title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Find 3 letter words
37,728,006
<p>I have the following code in Python:</p> <pre><code>import re string = "what are you doing you i just said hello guys" regexValue = re.compile(r'(\s\w\w\w\s)') mo = regexValue.findall(string) </code></pre> <p>My goal is to find any 3 letter word, but for some reason I seem to only be getting the "are" and not the ...
4
2016-06-09T13:55:51Z
37,728,157
<p>It's not regex, but you could do this:</p> <pre><code>words = [word for word in string.split() if len(word) == 3] </code></pre>
8
2016-06-09T14:01:56Z
[ "python" ]
Find 3 letter words
37,728,006
<p>I have the following code in Python:</p> <pre><code>import re string = "what are you doing you i just said hello guys" regexValue = re.compile(r'(\s\w\w\w\s)') mo = regexValue.findall(string) </code></pre> <p>My goal is to find any 3 letter word, but for some reason I seem to only be getting the "are" and not the ...
4
2016-06-09T13:55:51Z
37,728,209
<p>You should use word boundary <code>(\b\w{3}\b)</code> if you strictly want to use regex otherwise, answer suggested by Morgan Thrapp is good enough for this.</p> <p><a href="https://www.debuggex.com/r/7YnHc5L0_7VydOSJ" rel="nofollow">Demo</a></p>
6
2016-06-09T14:03:44Z
[ "python" ]
Find 3 letter words
37,728,006
<p>I have the following code in Python:</p> <pre><code>import re string = "what are you doing you i just said hello guys" regexValue = re.compile(r'(\s\w\w\w\s)') mo = regexValue.findall(string) </code></pre> <p>My goal is to find any 3 letter word, but for some reason I seem to only be getting the "are" and not the ...
4
2016-06-09T13:55:51Z
37,728,317
<p><code>findall</code> finds non-overlapping matches. An easy fix is to change the final <code>\s</code> to a lookahead; <code>(?=\s)</code> but you'll probably also want to extend the regex to cope with initial and final matches as well.</p> <pre><code>regexValue = re.compile(r'((?:^\s)\w\w\w(?: $|(?=\s))') </code><...
1
2016-06-09T14:08:06Z
[ "python" ]
Python Flask SQLalchemy Foreign key isn't saved in database - One to Many
37,728,047
<p>So I have a form where a user can submit a room, ofcourse a user should be able to submit multiple rooms, but the rooms all belong to this user, so we have a one-to-many relation here (for understanding):</p> <p>room1 - foreignkey(user1) room2 - foreignkey(user1)</p> <p><strong>The problem:</strong></p> <p>When s...
1
2016-06-09T13:57:10Z
37,728,192
<p>If I understand your problem correctly, you have not created a Zimmer object with a proper users_id: You need to do something like this:</p> <pre><code>new_zimmer = Zimmer(..., users_id=user_id) </code></pre> <p>And since you don't have access to the users_id, you need to get it. One option as you mentioned is put...
1
2016-06-09T14:03:07Z
[ "python", "python-2.7", "flask", "sqlalchemy", "foreign-key-relationship" ]
Django: How to access fields in chained queysets using for loop?
37,728,144
<p>I'm using <code>django v1.8</code></p> <p>I have to models in <code>models.py</code>:</p> <pre><code>class Demographic: patient_id = models.IntegerField(unique= True ,primary_key=True) age = models.IntegerField(null=True,blank=True) class MyTest: patient = models.ForeignKey(Demographic) date_vacci...
-1
2016-06-09T14:01:41Z
37,741,364
<p>Zinon, </p> <p>as I could understand what you want. You want to get all age of patients that were vacinated.</p> <p>I would not use this chain method, as the Django ORM is smart enough to get the data for you from the MyTest class.</p> <pre><code>vaccines = MyTest.objects.filter(date_vaccination__isnull = False) ...
1
2016-06-10T06:32:16Z
[ "python", "django", "django-views" ]
Packaging like jar for pyspark
37,728,174
<p>I have a pyspark project with a python script which runs spark-streaming. I've got some external dependencies which I run with <code>--packages</code> flag. </p> <p>However, in scala, we can use maven to download all required packages, make a jar file with the main spark program and have everything in one jar and t...
0
2016-06-09T14:02:36Z
37,728,672
<p>The documentation says you can use zip or egg. </p> <blockquote> <p>For Python applications, simply pass a .py file in the place of instead of a JAR, and add Python .zip, .egg or .py files to the search path with --py-files.</p> </blockquote> <p><a href="http://spark.apache.org/docs/latest/submitting-applicatio...
0
2016-06-09T14:22:46Z
[ "python", "apache-spark", "jar", "pyspark", "yarn" ]
Python - Writing to a file stops in the middle
37,728,236
<p>When I try to write to a text file in Python, using <code>file.write</code> and <code>numpy.savetext</code> Python stops to write in the middle of the text. </p> <p>I tried closing the file (<code>file.close</code>) and reopen it during run-time, it didn't help. I'm pretty clueless. </p>
0
2016-06-09T14:04:47Z
37,728,802
<p>Try closing out Python, close any instances of Python in your task manager, reopen and try again. Sometimes there are phantom instances... otherwise use Pandas <code>to_csv</code> after first converting to a <code>dataframe</code>, ie <code>import pandas as pd,. Dataset = pd.DataFrame(my data), Dataset.to_csv(filen...
1
2016-06-09T14:29:19Z
[ "python", "file", "numpy" ]
Regex Python Not Returning Desired Outcome
37,728,263
<p>Hi I have a script to go through a notepad of numbers with a series of regex's. My regex's are working with the exception of a few values that are not showing up properly. For instance some number examples such as 11111-C00 or 22222-X01 they are returned only as 11111 and 22222 and are not including "-" and what is...
3
2016-06-09T14:06:15Z
37,728,459
<p>It matches <code>11111</code> because in your alternation, the branch <code>\d{4,9}</code> is matching first. Change order to:</p> <pre><code>\d{4,5}-\d{2,3}|\w{3}\d-\d{2}|\d{4,5}-\w{1}\d{2}|\b|\d{4}-\w\d{1}\w|\d{4,9} </code></pre> <p>See <a href="https://regex101.com/r/wP3iE8/3" rel="nofollow">demo</a></p> <p>Yo...
0
2016-06-09T14:14:13Z
[ "python", "regex", "text", "expression", "notepad" ]
Graphs, edges and contextual information
37,728,377
<p>I'm new to graph and try to understand how contextual relations can be mapped into them. </p> <p>I've looked at examples which systematically introduce simple demos (1), for instance:</p> <pre><code># I want to organize the seating arrangement for my party # Bob does not like John, so I can say ----------- ...
2
2016-06-09T14:10:23Z
37,729,529
<p>If you don't restrict yourself to the set of people their relations, but to the <a href="https://en.wikipedia.org/wiki/Power_set" rel="nofollow">Power Set</a> of all people, you can also model relations between differently numbered groups - e.g. again by using a graph. The solution is clean in the sense of all node...
0
2016-06-09T14:57:14Z
[ "python", "graph" ]
Graphs, edges and contextual information
37,728,377
<p>I'm new to graph and try to understand how contextual relations can be mapped into them. </p> <p>I've looked at examples which systematically introduce simple demos (1), for instance:</p> <pre><code># I want to organize the seating arrangement for my party # Bob does not like John, so I can say ----------- ...
2
2016-06-09T14:10:23Z
37,729,925
<p>Two approaches came to my mind:</p> <ol> <li>Combine people pairs and so on into particular entities; so actually you will have relations Bob &lt;- John and Bob &lt;- John + Mary. But with a big amount of data, I guess it may look ugly.</li> <li>Create state machine: you will be able to track different states for d...
1
2016-06-09T15:14:18Z
[ "python", "graph" ]
What do SQL queries Parameterized with '%s' look like?
37,728,462
<p>Consider a particular SQL query in the form</p> <pre><code>cursor.execute(string, array) </code></pre> <p>Where string is some string containing <code>'%s'</code> and array is some array satisfying <code>len(array) == string.count("%s")</code>, not necessarily containing only strings. </p> <p>For example:</p> <p...
1
2016-06-09T14:14:19Z
37,728,877
<p>As you can read <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html" rel="nofollow">here</a>:</p> <blockquote> <p>Syntax:</p> <p><code>cursor.execute(operation, params=None, multi=False)</code></p> <p><code>iterator = cursor.execute(operation, params=None...
2
2016-06-09T14:32:26Z
[ "python", "mysql", "sql" ]
What do SQL queries Parameterized with '%s' look like?
37,728,462
<p>Consider a particular SQL query in the form</p> <pre><code>cursor.execute(string, array) </code></pre> <p>Where string is some string containing <code>'%s'</code> and array is some array satisfying <code>len(array) == string.count("%s")</code>, not necessarily containing only strings. </p> <p>For example:</p> <p...
1
2016-06-09T14:14:19Z
37,729,185
<p>Your <code>string</code> is actually your parameterized query, where you should pass your elements to match your <code>%s</code>.</p> <p>You can get examples in the <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html" rel="nofollow">mySql documentation</a> </p> <...
2
2016-06-09T14:45:47Z
[ "python", "mysql", "sql" ]
generic input images with labels in tensorflow
37,728,597
<p>I want to make a generic input images with labels in tensorflow. I checked the question <a href="http://stackoverflow.com/questions/34340489/tensorflow-read-images-with-labels">Tensorflow read images with labels</a> and write my test code, but there are some errors.</p> <pre><code> import tensorflow as tf f...
0
2016-06-09T14:19:39Z
37,801,770
<p>I would try removing the square brackets around input_queue in <code>result = sess.run([input_queue])</code>, since you want to specify the output feed there as a single tensor, not a list.</p>
0
2016-06-14T01:52:28Z
[ "python", "tensorflow", "deep-learning" ]
Example of building Bokeh panels with complex layouts?
37,728,598
<p>I am trying to make Bokeh Panels that have relatively complex layouts, so I tried moving half of my current layout into one <code>Panel</code> and half into another just to play around, like so:</p> <pre><code>selects = HBox(top_users_select, new_users_select, t1_users_select, t2_users_select, top_recent_users_sele...
0
2016-06-09T14:19:40Z
39,373,881
<p>I think you want to write <code>selects</code> instead of <code>inputs</code>, but there are basically some things wrong with your declaration.</p> <p>Look at the examples at <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#tab-panes" rel="nofollow">http://bokeh.pydata.org/en/late...
0
2016-09-07T15:25:23Z
[ "python", "bokeh" ]
Matplotlib overlap with alpha
37,728,660
<p>I'm running into an odd bug with matplotlib when plotting lines with transparency:</p> <pre><code>from matplotlib import pyplot as plt plt.plot(range(120), range(120), alpha=0.4, color='#0000FF', linewidth=3) plt.savefig('out.png') plt.show() plt.close() </code></pre> <p>The saved figure looks like this, which is...
0
2016-06-09T14:22:23Z
37,729,359
<p>a solution can be to use MPL 1.5.0 since I can't reproduce your bug there</p>
1
2016-06-09T14:51:45Z
[ "python", "matplotlib", "alpha" ]
How can I create plots before creating animation?
37,728,691
<p>I would like to plot data using multiprocessing and then creating animation with the plotted data. I mean something like this:</p> <pre><code>frames = [] def get_frames() ... [index, frame] = mp_queue.get() frames[index]=frame def get_frames_process(queue, index, x_vals, y_vals): frame...
2
2016-06-09T14:23:46Z
37,733,775
<p>From the <a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation" rel="nofollow"><code>FuncAnimation</code> documentation</a>:</p> <blockquote> <p><code>frames</code> can be a generator, an iterable, or a number of frames.</p> </blockquote> <p>I suggest you write a generator func...
1
2016-06-09T18:39:08Z
[ "python", "animation", "matplotlib", "multiprocessing" ]
Dictionary is not giving all elements - Python
37,728,733
<p>I want to make dictionary from lists.</p> <pre><code>import numpy as np a1 = [1,2,3,4,5,6,7,8,9] b1 = ['a','b','c','d','e','f','g','h','i'] c1 = ['A','B','C','D','E','F','G','H','I'] array2 = np.array([a1,b1,c1]).tolist() keys = ['name', 'type','description','logo'] print dict(zip(keys, zip(*array2))) </code></...
1
2016-06-09T14:26:04Z
37,728,823
<h2>Why am I getting only 4 elements?</h2> <p>According to the <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code> documentation</a>:</p> <blockquote> <p>The returned list is truncated in length to the length of the shortest argument sequence.</p> </blockquote> <p>Since <...
3
2016-06-09T14:30:16Z
[ "python", "numpy", "dictionary" ]
Google App Engine request logs are duplicated with small time difference
37,728,834
<p>Looking into GAE logs of a Python project I found out some amount of duplicated or even triplicated entries with very small difference in their timestamps.</p> <p>These are the requests triggered by an iPhone device which sends only unique data, so it seems <strong><em>extremely unlikely</em></strong> that this dup...
0
2016-06-09T14:30:42Z
37,735,831
<p>All data stored by Google is triplicated so that there is always a backup, even if one of the nodes goes down.</p> <blockquote> <p>This is a big factor, because as your data grows, the likelihood of losing the data becomes very real. Most companies deal with this by making multiple copies of the data in diffe...
-1
2016-06-09T20:45:25Z
[ "python", "google-app-engine", "https" ]
Google App Engine request logs are duplicated with small time difference
37,728,834
<p>Looking into GAE logs of a Python project I found out some amount of duplicated or even triplicated entries with very small difference in their timestamps.</p> <p>These are the requests triggered by an iPhone device which sends only unique data, so it seems <strong><em>extremely unlikely</em></strong> that this dup...
0
2016-06-09T14:30:42Z
38,207,664
<p>It happened because of asynchronous tasks: When the iPhone gets a location from its location manager, and when the OS has some free time to run our code, then the application fires an HTTP request to the <code>/logData</code> endpoint. At the same time user activity causes one more HTTP request. Data from local vari...
0
2016-07-05T15:47:42Z
[ "python", "google-app-engine", "https" ]
How do I send authenticated https requests using Python?
37,728,967
<p>What is the equivalent Python to the following <code>curl</code> command?</p> <pre><code>curl https://www.streak.com/api/v1/boxes/{Keyhere}/ -u passwordhere: </code></pre> <p>I tried this but I get 400 errors:</p> <pre><code>requests.get('https://www.streak.com/api/v1/boxes/{Key}/threads -u PASSWORD:', auth=HTTP...
1
2016-06-09T14:36:32Z
37,729,072
<p>This type of authentication is very common and the requests documentation <a href="http://docs.python-requests.org/en/master/user/authentication/#basic-authentication" rel="nofollow">covers</a> it. </p> <pre><code>requests.get('https://www.streak.com/api/v1/boxes/{Key}/threads', auth=(YOUR_API_KEY, '')) </code></pr...
0
2016-06-09T14:41:00Z
[ "python", "https", "http-authentication" ]
Altered Django model. I provided a one-off default = datetime.date for DateField. Found that it's invalid. Removed the field and still can't migrate
37,729,042
<p>Hi here's the specific line that I added in models.py</p> <p><code>billingMonth2 = models.DateTimeField()</code></p> <p>This is what happened in makemigrations, I figured I added a non nullable field so I tried to define a default value:</p> <pre><code> You are trying to add a non-nullable field 'billingMonth'...
1
2016-06-09T14:39:41Z
37,729,593
<pre><code>Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now() &gt;&gt;&gt; datetime.date </code></pre> <p>I guess it is asking for the return value of the method, not the method itself. So its <code>datetime.date()</code> ...
0
2016-06-09T14:59:43Z
[ "python", "linux", "django", "datetime", "models" ]
Testing the cache hits for Flask-Cache
37,729,077
<p>I am using <code>cache.memoize</code> to memoize a function with Flask-Cache. How can I get the cache key which got set in the decorated function? How can I test that the function is cached during testing?</p> <pre><code>from flask import Flask from flask.ext.cache import Cache app = Flask(__name__) cache = Cach...
0
2016-06-09T14:41:13Z
37,729,555
<p>When using <code>memoize</code>, the cache key is generated behind the scenes and should never need to be accessed manually. Flask-Cache is handling caching and retrieving the result of the function for you. But if you're interested in how Flask-Cache does it, you can <a href="https://github.com/thadeusb/flask-cac...
2
2016-06-09T14:58:19Z
[ "python", "caching", "flask", "flask-cache" ]
Split an array according to it's information
37,729,133
<p>I'm doing a project in python which has an array of 600 asteroid measurements (diameter, period, orbit radius). With that information I'd like to make new arrays according the diameter column, the resulting arrays would be diameter intervals of the first one.</p> <p>If i have this array, </p> <pre><code>diameter ...
3
2016-06-09T14:43:37Z
37,729,426
<p>Just use a list comprehension to filter it</p> <pre><code>filtered = [ ast for ast in arr if ast[0]&lt;=20 ] </code></pre>
3
2016-06-09T14:53:53Z
[ "python", "arrays", "python-2.7", "numpy" ]
Split an array according to it's information
37,729,133
<p>I'm doing a project in python which has an array of 600 asteroid measurements (diameter, period, orbit radius). With that information I'd like to make new arrays according the diameter column, the resulting arrays would be diameter intervals of the first one.</p> <p>If i have this array, </p> <pre><code>diameter ...
3
2016-06-09T14:43:37Z
37,729,762
<p>You can easily build new array using the indexing properties of numpy arrays, and that translates into that one liner :</p> <pre><code>filtered_arr = arr[(arr[:,0]&lt;=20)*(arr[:,0]&gt;=0),:] </code></pre> <p>or to develop:</p> <pre><code>#we separate the diameters from the rest diameter_column= arr[:,0] #we crea...
1
2016-06-09T15:06:36Z
[ "python", "arrays", "python-2.7", "numpy" ]
Split an array according to it's information
37,729,133
<p>I'm doing a project in python which has an array of 600 asteroid measurements (diameter, period, orbit radius). With that information I'd like to make new arrays according the diameter column, the resulting arrays would be diameter intervals of the first one.</p> <p>If i have this array, </p> <pre><code>diameter ...
3
2016-06-09T14:43:37Z
37,729,774
<p>Assuming you would like to achieve the required matrix using <code>numpy</code>, you may use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> to match the conditions and then apply a mask which can be used to index the array to get the ...
1
2016-06-09T15:07:10Z
[ "python", "arrays", "python-2.7", "numpy" ]
If condition in pandas dataframe
37,729,153
<p>I check whether each of there are any rows in df4 which meets the condition. But it throws the error "indices are out of bounds". Any help would be appreciated.</p> <pre><code>if (df4[df4['Occurences']] &gt;= 5).any(): df7 = df4[df4['Occurences'] &gt;= 5].reset_index() df8 = df7[['MachineName','DateTime','Occuren...
2
2016-06-09T14:44:29Z
37,729,203
<p>Your first line:</p> <pre><code>if (df4[df4['Occurences']] &gt;= 5).any(): </code></pre> <p>looks wrong, the closing square brace should include the condition:</p> <pre><code>if (df4[df4['Occurences'] &gt;= 5]).any(): </code></pre>
3
2016-06-09T14:46:33Z
[ "python", "pandas", "dataframe" ]
How to remove more than one space when reading text file
37,729,387
<p>Problem: I cannot seem to parse the information in a text file because python reads it as a full string not individual separate strings. The spaces between each variable is not a \t which is why it does not separate. Is there a way for python to flexibly remove the spaces and put a comma or \t instead?</p> <p>Examp...
4
2016-06-09T14:52:52Z
37,729,580
<p>You can instruct <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow"><code>csv.reader</code></a> to use space as delimiter and skip all the extra space:</p> <pre><code>reader = csv.reader(f, delimiter=" ", skipinitialspace=True) </code></pre> <p>For detailed information about available p...
2
2016-06-09T14:59:08Z
[ "python", "python-2.7", "csv" ]
How to remove more than one space when reading text file
37,729,387
<p>Problem: I cannot seem to parse the information in a text file because python reads it as a full string not individual separate strings. The spaces between each variable is not a \t which is why it does not separate. Is there a way for python to flexibly remove the spaces and put a comma or \t instead?</p> <p>Examp...
4
2016-06-09T14:52:52Z
37,729,614
<p>You can simply declare the delimiter to be a space, and ask csv to skip initial spaces after a delimiter. That way, your separator is in fact the regular expression <code>' +'</code>, that is one or more spaces.</p> <pre><code>rd = csv.reader(fd, delimiter=' ', skipinitialspace=True) for row in rd: print row </...
5
2016-06-09T15:00:26Z
[ "python", "python-2.7", "csv" ]
sort only dictionary values that are lists within a list
37,729,843
<p>I have this type of dict;</p> <pre><code>dict2 = {'value1': [ 2, ['get1', 3], ['post3', 4] ], 'value2' : [1, ['get1', 2], ['post2', 5] ], 'value3' : [7, ['get17', 6], ['post2', 2], ['post3', 3] ] } </code></pre> <p>I know how to order this based on the first value in the list (7, 2, 1). However once I've sorted it...
1
2016-06-09T15:10:07Z
37,730,001
<p>Since you already know how to sort based on the first value in the dict, let's focus on sorting the inner sequences. The important step is to use slicing to trim-off the initial value so you can sort the remaining pairs:</p> <pre><code>&gt;&gt;&gt; for key, seq in dict2.items(): dict2[key] = seq[:1] + sort...
0
2016-06-09T15:18:01Z
[ "python", "list", "sorting", "dictionary" ]
sort only dictionary values that are lists within a list
37,729,843
<p>I have this type of dict;</p> <pre><code>dict2 = {'value1': [ 2, ['get1', 3], ['post3', 4] ], 'value2' : [1, ['get1', 2], ['post2', 5] ], 'value3' : [7, ['get17', 6], ['post2', 2], ['post3', 3] ] } </code></pre> <p>I know how to order this based on the first value in the list (7, 2, 1). However once I've sorted it...
1
2016-06-09T15:10:07Z
37,730,047
<p>You should consider getting the items as a list or tuple and them sorting them with a function or lambda expression like so:</p> <pre><code>items = dict2.items() items.sort(key=lambda x:x[1][0]) </code></pre>
2
2016-06-09T15:19:52Z
[ "python", "list", "sorting", "dictionary" ]
PyQt5 how to destroy last widget when clicked 'OK' button on QMessageBox created by a button on that widget
37,729,921
<p>I have a QMainWindow that have a button, when clicked this button, another widget pops up. This widget have a button, when clicked this button an alert message pops up. When I press 'OK' on that message button, only QMessageBox is closing, small widget is still open. I want to close that widget when I press 'OK' on ...
-1
2016-06-09T15:14:09Z
37,730,448
<p>I figured out the solution by myself, just make a QMessageBox(no inherit), then find the result and check if the result is something you want, <code>close()</code> the widget.</p> <pre><code>self.result1 = QMessageBox(QMessageBox.Information,"Alert","Alert message",QMessageBox.Ok) self.result1.setGeometry(500,500,5...
0
2016-06-09T15:37:08Z
[ "python", "python-3.4", "qwidget", "pyqt5", "qmessagebox" ]
What characters can't a regex expression start with?
37,729,960
<p>I am writing a short script that will use a string either as a regex expression or as a dictionary key. I would like to keep all of this data in the string, though, without needing to specify in another variable which one of the two it is.</p> <p>I have decided to use the first character of the string to specify wh...
0
2016-06-09T15:16:08Z
37,730,139
<p>Any of the repetition characters (<code>?</code>, <code>*</code>, <code>+</code>) would be a good choice here, since they must be preceded by some other pattern. <code>$</code> can only be used at the end of a nontrivial regex, so it would also be a good choice. <code>}</code>, <code>]</code>, and <code>)</code> mus...
1
2016-06-09T15:24:06Z
[ "python", "regex" ]
String Replace for Multiple Lines In A CSV
37,729,969
<p>Below is a snippet from a csv file. The first column is the product number, 2 is the stock level, 3 is the target level, and 4 is the distance from target (target minus stock level.)</p> <pre><code>34512340,0,95,95 12395675,3,95,92 56756777,70,95,25 90673412,2,95,93 </code></pre> <p>When the stock level gets to 5 ...
1
2016-06-09T15:16:26Z
37,732,505
<p>The below code reads each line and checks the value of column 2. If it is less than or equal to 5, the value of column2 is changed to value of column3 and last column is changed to 0 else all the columns are left unchanged.</p> <pre><code>import sys import csv data=[] f=open("stockcontrol.csv") reader=csv.DictRead...
1
2016-06-09T17:22:37Z
[ "python", "csv" ]
urllib2 and BeautifulSoup not pulling the full webpage
37,730,017
<p>A friend and I are trying to calculate some comment metrics (how many users comment on certain posts, who comments, how many comments does each user add, etc.) at a baseball blog that we frequent. </p> <p>I know little to nothing about web programming or scraping, but I know a bit of Python so I volunteered to help...
1
2016-06-09T15:19:00Z
37,731,241
<p>Use Selenium or Dryscape. Selenium opens up a web browser and you can actually see it do stuff. Since a browser is used, it renders Javascript as well. </p> <p>I noticed a with the number of comments displayed in the page source.</p> <pre><code>&lt;span class="comments-count"&gt;80&lt;/span&gt; </code></pre> <p>...
0
2016-06-09T16:12:13Z
[ "python", "beautifulsoup", "urllib2" ]
urllib2 and BeautifulSoup not pulling the full webpage
37,730,017
<p>A friend and I are trying to calculate some comment metrics (how many users comment on certain posts, who comments, how many comments does each user add, etc.) at a baseball blog that we frequent. </p> <p>I know little to nothing about web programming or scraping, but I know a bit of Python so I volunteered to help...
1
2016-06-09T15:19:00Z
37,735,065
<p>What I ended up doing:</p> <pre><code>import sys,re,csv,glob,os from collections import Counter import dryscrape from bs4 import BeautifulSoup url = "http://www.royalsreview.com/2016/6/8/11881484/an-analysis-of-rr-game-threads#comments" session = dryscrape.Session() session.visit(url) f = session.body() soup = Be...
0
2016-06-09T19:54:53Z
[ "python", "beautifulsoup", "urllib2" ]
urllib2 and BeautifulSoup not pulling the full webpage
37,730,017
<p>A friend and I are trying to calculate some comment metrics (how many users comment on certain posts, who comments, how many comments does each user add, etc.) at a baseball blog that we frequent. </p> <p>I know little to nothing about web programming or scraping, but I know a bit of Python so I volunteered to help...
1
2016-06-09T15:19:00Z
37,737,251
<p>You can get the data in <em>json</em> format by making a get request to <code>http://www.royalsreview.com/comments/load_comments/11645525</code>:</p> <pre><code>import requests from collections import Counter from operator import itemgetter url = "http://www.royalsreview.com/comments/load_comments/11645525" js = r...
1
2016-06-09T22:32:17Z
[ "python", "beautifulsoup", "urllib2" ]
Filtering for empty string in SQLAlchemy + Oracle
37,730,030
<p>I have a weird problem with querying for strings using Oracle 11g backend for SQLAlchemy. First, class definition (for Oracle, for Postgres it is the same minus <code>Sequence</code>):</p> <pre><code>class Item(Base): __tablename__ = 'item' id = Column(Integer, Sequence('id_seq'), primary_key=True) ... ...
0
2016-06-09T15:19:20Z
37,734,607
<p>This has nothing to do with SQLAlchemy. Oracle treats empty string == null.</p> <p>See: <a href="http://stackoverflow.com/questions/203493/why-does-oracle-9i-treat-an-empty-string-as-null">Oracle treats an empty string as null</a></p>
0
2016-06-09T19:27:05Z
[ "python", "oracle", "postgresql", "oracle11g", "sqlalchemy" ]
QPainter::begin: Paint device returned engine == 0, type: 0
37,730,112
<p>I started watching some tutorials for Python and QT (<a href="https://www.youtube.com/watch?v=Eq7__6y0jwo&amp;index=3&amp;list=PL19DCiIwVefyQxlDTWlXQ4lnZDPW6_r-q" rel="nofollow">https://www.youtube.com/watch?v=Eq7__6y0jwo&amp;index=3&amp;list=PL19DCiIwVefyQxlDTWlXQ4lnZDPW6_r-q</a>) but I'm getting this error "QPaint...
-1
2016-06-09T15:22:37Z
37,731,676
<p>The only thing I see wrong with your code is you are inheriting from QAbstractListModel without implementing the abstract methods. </p> <p>From the documentation here: <a href="http://doc.qt.io/qt-5/qabstractlistmodel.html#details" rel="nofollow">http://doc.qt.io/qt-5/qabstractlistmodel.html#details</a></p> <block...
1
2016-06-09T16:36:50Z
[ "python", "qt", "pyside", "3dsmax" ]
Determine image in memory
37,730,119
<p>I want to determine if a buffer I have (downloaded it) is an image file, without saving it to the disk. I looked it up and found out that:</p> <ol> <li>imghdr can do it only for files.</li> <li>python-magic can give me the file type, but than I need to map it to image types.</li> </ol> <p>Is there a better way?</p...
0
2016-06-09T15:22:51Z
37,730,366
<p>You can identify the file type with imghdr via byte stream (which you should be able to get from your buffer)</p> <pre><code>import imghdr imghdr.what('', byteStream) </code></pre> <p>If you supply the second parameter the filename will be ignored.</p> <p>See <a href="https://docs.python.org/3.1/library/imghdr.ht...
0
2016-06-09T15:33:57Z
[ "python", "python-imaging-library", "python-magic" ]
Replace file contents in Python after specific match
37,730,144
<p>I am trying to replace file contents with new entry using 'replace' command but after execution command is truncating whole data in place of replace.Please help.</p> <p>File:</p> <pre><code>&lt;b&gt;&lt;center&gt;&lt;u&gt;S0 Outage Communication&lt;/u&gt;&lt;/center&gt;&lt;/b&gt; &lt;br&gt;&lt;br&gt; &lt;b&gt;Date...
0
2016-06-09T15:24:21Z
37,731,014
<p>You have a problem because you open the same file twice. It works like this (at least for me):</p> <pre><code>with open('/var/www/html/outage/Test.html', 'r') as f1: text = f1.read() text = text.replace("&lt;p style='color:red'&gt;&lt;b&gt;&lt;u&gt;Status:&lt;/u&gt;&lt;/b&gt;RED&lt;/p&gt;","Test") with open('...
1
2016-06-09T16:01:18Z
[ "python", "file-io", "replace" ]
Scraping hidden content from a javascript webpage with python
37,730,203
<p>I'm trying to scrape the content from the following website:</p> <p><a href="https://mobile.admiral.at/en/event/event/all#/event/15a822ab-84a1-e511-90a2-000c297013a7" rel="nofollow">https://mobile.admiral.at/en/event/event/all#/event/15a822ab-84a1-e511-90a2-000c297013a7</a></p> <p>I have previously scraped the con...
0
2016-06-09T15:26:42Z
37,731,015
<p>The content that you need is loaded using jQuery (Ajax). I don't know if dryscrape has been updated lately, but the last time I used it didn't support ajax content loaded from jQuery...</p> <p>Anyway.. just taking a look to the network inspector of chrome you will realize that the main content is loaded using an AP...
0
2016-06-09T16:01:24Z
[ "python", "web-scraping" ]
openpyxl loop through two spreadsheets match primary key and find differences
37,730,496
<p>Is there a way in python using openpyxl to loop through 2 spreadsheets and link them by a primary key and find the differences in a column. The example below uses "name" as a primary key and creates a new column with the differences </p> <p><strong>example</strong></p> <pre><code>new.xlsx: BOB, 1 JIM, 2 STEVE, 3 ...
-1
2016-06-09T15:39:00Z
37,730,889
<p>There are two possibilities:</p> <ol> <li>Create a third workbook to write the result</li> <li>When you want to insert a new row you have to shift down every value of every cells bellow, and it can take a lot of time ...</li> </ol>
0
2016-06-09T15:55:45Z
[ "python", "excel", "openpyxl" ]
openpyxl loop through two spreadsheets match primary key and find differences
37,730,496
<p>Is there a way in python using openpyxl to loop through 2 spreadsheets and link them by a primary key and find the differences in a column. The example below uses "name" as a primary key and creates a new column with the differences </p> <p><strong>example</strong></p> <pre><code>new.xlsx: BOB, 1 JIM, 2 STEVE, 3 ...
-1
2016-06-09T15:39:00Z
37,730,923
<p>No, there is no way to do this in openpyxl. Import into a database and save yourself a lot of headaches.</p>
0
2016-06-09T15:57:14Z
[ "python", "excel", "openpyxl" ]
Object has no attribute 'encode'
37,730,575
<p>I'm trying to attach an xlsx file to my email. I looked up solutions and it involves using email.encoders. But when I use this solution I get an error. I'm using a solution that someone else has working.</p> <pre><code>File "C:\Documents and Settings\Desktop\AppTera\dev\MTC_test\MTC_sender.py", line 41, in sendmail...
0
2016-06-09T15:41:58Z
37,731,084
<p><code>s</code> is a SMTP object which you created by <code>s = smtplib.SMTP(SERVER, 25)</code>. So the parameters for <code>s.sendmail(FROMADDR, TOADDR, message.as_string())</code> should be according to the <a href="https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail" rel="nofollow">documentation</...
1
2016-06-09T16:04:22Z
[ "python", "email", "encoder" ]
Python: Shorten If / Elif control flow tree (printing highest order string that is not None)
37,730,686
<p>In Python, I'm going to write a bunch of rules that prints out the "highest order" in a tree hierarchy.</p> <p><code>level_1</code> is the lowest and <code>level_3</code> is the highest order.</p> <p>The "highest order" available should be printed. Only if <code>level_3</code> is <code>None</code>, do we continue ...
0
2016-06-09T15:46:21Z
37,730,749
<p>Assuming no string is empty, you can use <code>or</code>:</p> <pre><code>print level_3 or level_2 or level_1 </code></pre> <p>This will work for any collection of none-empty strings since <code>or</code> returns the last truthy value.</p>
2
2016-06-09T15:49:11Z
[ "python" ]
Python: Shorten If / Elif control flow tree (printing highest order string that is not None)
37,730,686
<p>In Python, I'm going to write a bunch of rules that prints out the "highest order" in a tree hierarchy.</p> <p><code>level_1</code> is the lowest and <code>level_3</code> is the highest order.</p> <p>The "highest order" available should be printed. Only if <code>level_3</code> is <code>None</code>, do we continue ...
0
2016-06-09T15:46:21Z
37,730,809
<p>If you insert in correct order (something like a heap) the rules in an array, it would be easy to get the highest one.</p>
0
2016-06-09T15:52:02Z
[ "python" ]
Python: Shorten If / Elif control flow tree (printing highest order string that is not None)
37,730,686
<p>In Python, I'm going to write a bunch of rules that prints out the "highest order" in a tree hierarchy.</p> <p><code>level_1</code> is the lowest and <code>level_3</code> is the highest order.</p> <p>The "highest order" available should be printed. Only if <code>level_3</code> is <code>None</code>, do we continue ...
0
2016-06-09T15:46:21Z
37,731,173
<p>how about</p> <pre><code>for msj in (level_3,level_2,level_1): if msj: print msj break </code></pre> <p>or a variation to Reut solution</p> <pre><code>msj = level_3 or level_2 or level_1 if msj: print msj </code></pre> <p>both solution will print the first non-empty and non-None element t...
1
2016-06-09T16:08:48Z
[ "python" ]
Building a query optimization
37,730,751
<p>I'm doing this in my code:</p> <pre><code>programmes2 = [int(l) for l in g.getlist('programmes2')] if len(programmes2): q = q &amp; Q(personne__programmes2__in=programmes2) activites2 = [int(l) for l in g.getlist('activites2')] if len(activites2): q = q &amp; Q(personne__activites2__in=activites2) hobbies...
1
2016-06-09T15:49:14Z
37,732,172
<p>Sure:</p> <pre><code>q = Q() for field in ["hobbies2", "types_permis2", "and so on"]: values = [int(l) for l in g.getlist(field)] if values: field_query = "personne__{}__in".format(field) q = q &amp; Q(field_query=values) </code></pre> <p>Here's another approach:</p> <pre><code>fi...
1
2016-06-09T17:03:54Z
[ "python", "django", "django-queryset" ]
np.gradient - correct use?
37,730,760
<p>I'm trying to use np.gradient to calculate a derivative, but I'm getting strange results and want to check that I'm using it correctly to eliminate that as a possible error.</p> <p>A have a function y(x) over a range of equally spaced (but not unity) x-value data points. I compute the derivative by </p> <pre><code...
1
2016-06-09T15:49:43Z
37,732,440
<p>Looks right to me. Derivative of sin is cos. When I plot <code>np.gradient</code> of my sin function, it looks identical to when I plot cos directly.</p> <p>An example:</p> <pre><code>import numpy as np import pandas as pd x = np.arange(-2 * np.pi, 2 * np.pi, 0.01) y = np.sin(x) pd.Series(y).plot() </code></pre...
0
2016-06-09T17:19:16Z
[ "python", "numpy", "derivative" ]
Encode "k out of n labels" feature in sklearn/pandas
37,730,816
<p>I have a feature that is a subset of a set of labels. </p> <pre><code>&gt;&gt;&gt; labels = ['ini', '', 'pdf', 'flac', 'php'] &gt;&gt;&gt; data = [random.sample(labels, random.randint(0, len(labels))) for _ in range(20)] &gt;&gt;&gt; data[:5] [['pdf'], [], ['pdf', 'flac'], ['php', 'pdf', 'ini'], ['', 'php', 'ini']]...
1
2016-06-09T15:52:19Z
37,730,941
<p>Use a pandas series to track your labels in its index. Then access the values of <code>1</code> via the <code>.loc</code> method. Fill in the missing values with <code>0</code>.</p> <pre><code>import pandas as pd import numpy as np s1 = pd.Series(np.ones(len(labels)), labels) s0 = pd.Series(np.zeros(len(labels))...
2
2016-06-09T15:58:08Z
[ "python", "pandas", "scikit-learn" ]
How to open socket in Python with Active/Passive host?
37,731,068
<p>My goal is to open the socket with a host who is Up.</p> <p>My initial code with a single host:</p> <pre><code>!/usr/bin/python import socket def Socket(host, port): # create socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((str(host), port)) except Exc...
1
2016-06-09T16:03:45Z
37,731,426
<p>A simple solution would be to simply loop the hosts, and use the first connection that is successful.</p> <pre><code>def Socket(hosts, port): # create socket sock = connect(hosts, port) # Send Request = "GET services\n" sock.sendall(Request) sock.shutdown(socket.SHUT_WR) data = "" w...
1
2016-06-09T16:22:27Z
[ "python", "sockets" ]
How to increment a date using Arrow?
37,731,106
<p>I'm using the <a href="http://crsmithdev.com/arrow/" rel="nofollow">arrow</a> module to handle <code>datetime</code> objects in Python. If I get current time like this:</p> <pre><code>now = arrow.now() </code></pre> <p>...how do I increment it by one day?</p>
0
2016-06-09T16:05:28Z
37,731,166
<p><strong>Increment the day</strong></p> <pre><code>now.replace(days=1) </code></pre> <p><strong>Decrement the day</strong></p> <pre><code>now.replace(days=-1) </code></pre> <p><a href="http://crsmithdev.com/arrow/#replace-shift" rel="nofollow">I highly recommend the docs.</a></p>
1
2016-06-09T16:08:25Z
[ "python", "datetime", "arrow" ]
How to increment a date using Arrow?
37,731,106
<p>I'm using the <a href="http://crsmithdev.com/arrow/" rel="nofollow">arrow</a> module to handle <code>datetime</code> objects in Python. If I get current time like this:</p> <pre><code>now = arrow.now() </code></pre> <p>...how do I increment it by one day?</p>
0
2016-06-09T16:05:28Z
37,731,245
<p>See <a href="http://crsmithdev.com/arrow/#replace-shift" rel="nofollow">documentation</a></p> <pre><code>now = arrow.now() oneDayFromNow = now.replace(days+=1) </code></pre>
0
2016-06-09T16:12:23Z
[ "python", "datetime", "arrow" ]
Getting python 3+ comparison on return value and inputted value
37,731,175
<p>Its been several months since I have worked with python. Im not getting an error, but im also not receiving the desired output too.</p> <p>I have a function:</p> <pre><code>def set_account(gather_accounts): print("gather_accounts():\n") for a in gather_accounts: print('Value: {}'.format(a[1])) ...
1
2016-06-09T16:08:52Z
37,731,372
<p>I'm guessing you are running in Python2, If in Python2, you need to use <code>prompt_account_name = raw_input('\nWhat is the account name? \n')</code> instead of <code>prompt_account_name = input('\nWhat is the account name? \n')</code> in this case.</p> <p>Actually, in Python3, the <code>input()</code> is equivale...
0
2016-06-09T16:19:14Z
[ "python", "string-comparison" ]
Python HTTP Request to replace bash curl
37,731,368
<p>I'm porting some automation scripts from bash to python, and they're almost ll curl commands of the following format:</p> <pre><code>curl -k -H "Content-Type: application/json" -X POST -d '{ "Request": { "MessageID": "xxxx", "MessageDateTime": "xxxxx...
1
2016-06-09T16:19:06Z
37,731,579
<p>You can use <code>requests.post</code> directly. <code>-k</code> corresponds to <code>verify=False</code>:</p> <pre><code>from datetime import datetime as DateTime import requests import json URL = "https://myUrl.xxx" message = { "Request": { "MessageID": "xxxx", "MessageDateTime": DateTime.no...
2
2016-06-09T16:30:58Z
[ "python", "bash", "curl" ]
Is there a proper way to set compound greek letters as a symbol in SymPy?
37,731,381
<p>As silly as it may sound, I would like to use compound greek letters as a single symbol in SymPy. For example, if the following is entered in a Jupyter notebook:</p> <pre><code>import sympy as sp ab = sp.Symbol("alpha beta") sp.pprint(ab) </code></pre> <p><code>ab</code> behaves as desired when used in symbolic ma...
2
2016-06-09T16:19:36Z
37,754,510
<p>Symbol names can be any string, but the automatic conversion of greek letter names to greek letters for printing doesn't work for all input. I guess it doesn't try to split the string in spaces.</p> <p>If you are using the Jupyter notebook, you can just set the symbol name to be the LaTeX of what you want</p> <pre...
1
2016-06-10T17:57:42Z
[ "python", "sympy", "jupyter" ]
Blank search does not return error in Django
37,731,554
<p>I need some help with a problem i am facing, where I cannot seem to figure out the problem. Basically, I have a search function that is supposed to return an a message 'nothing entered!' if the entry is blank. However, it does not work.</p> <p>fyi this is an example from the book masteringDjango - similar, but not ...
1
2016-06-09T16:29:25Z
37,731,891
<p>Since your input is of type <code>text</code>, the <code>title</code> input is always sent, even if empty. Therefore, your view receive the content like this :</p> <pre><code>request.GET['title'] = '' </code></pre> <p>You have to check the content of the input, here's a bit of code :</p> <pre><code>def search(req...
3
2016-06-09T16:47:45Z
[ "python", "django" ]
For loop running infinite python
37,731,695
<p>It's been 5 hours trying to find the issue but unable to identify why for loop <code>for fn in L</code> running infinite.</p> <pre><code>L=[] N=int(raw_input()) for i in range(0,N): L.append(list(raw_input().split())) print L for fn in L: if 'insert'==fn[0]: L.insert(int(fn[1]),int(fn[2])) eli...
1
2016-06-09T16:37:46Z
37,731,748
<p>You're <em>mutating</em> your list in the loop. Outcomes will be very unpredictable. You can instead iterate on a slice of the list:</p> <pre><code>for fn in L[:]: # your code here pass </code></pre> <p>In this way, the loop terminates when the items in the shallow copy (the slice) are exhausted.</p>
7
2016-06-09T16:40:37Z
[ "python" ]
For loop running infinite python
37,731,695
<p>It's been 5 hours trying to find the issue but unable to identify why for loop <code>for fn in L</code> running infinite.</p> <pre><code>L=[] N=int(raw_input()) for i in range(0,N): L.append(list(raw_input().split())) print L for fn in L: if 'insert'==fn[0]: L.insert(int(fn[1]),int(fn[2])) eli...
1
2016-06-09T16:37:46Z
37,731,757
<p>You insert/remove elements while iterating the elements of a list. You also change the list by reversing the list. Both are mutation operations to the list which are not allowed during iteration. The behavior is unspecified in this case.</p> <pre><code>for fn in L: if ...: L.insert(...) </code></pre>
2
2016-06-09T16:41:15Z
[ "python" ]
For loop running infinite python
37,731,695
<p>It's been 5 hours trying to find the issue but unable to identify why for loop <code>for fn in L</code> running infinite.</p> <pre><code>L=[] N=int(raw_input()) for i in range(0,N): L.append(list(raw_input().split())) print L for fn in L: if 'insert'==fn[0]: L.insert(int(fn[1]),int(fn[2])) eli...
1
2016-06-09T16:37:46Z
37,731,859
<p>You mutate the object used for looping ... and better you reverse it :p reverse &lt;-- reverse --> reverse &lt;-- reverse --></p> <p>:p</p>
1
2016-06-09T16:46:30Z
[ "python" ]
How can I add/change the parent of an entity after it has been created but before it is put in the Datastore?
37,731,767
<p>From what I've read in the docs, it's impossible to change the parent of an entity after it has been put in the datastore. But I am looking for a way to change the parent before that happens (but after it is created). So instead of having this:</p> <pre class="lang-py prettyprint-override"><code>John = Student(pa...
1
2016-06-09T16:41:49Z
37,734,068
<p>According to the <a href="https://cloud.google.com/appengine/docs/python/ndb/modelclass#Constructor" rel="nofollow">NDB Model Class Constructor</a> docs:</p> <blockquote> <p>You cannot easily define a property named "key", "id", "parent", or "namespace". If you pass, for example, key="foo" in a constructor or ...
0
2016-06-09T18:55:30Z
[ "python", "google-app-engine", "app-engine-ndb" ]
Compile and use python-openzwave with open-zwave in non-standard location
37,731,787
<p>I manually compiled <a href="https://github.com/OpenZWave/python-openzwave">python-openzwave</a> to work with <a href="https://github.com/OpenZWave/open-zwave">C++ library</a>.</p> <p>I would like to use it as Kodi addon (OpenELEC running on Pi 3), so can not use standard installation. I've compiled everything, dow...
11
2016-06-09T16:42:51Z
37,897,891
<p>In general the steps required consist of calls to <code>make build</code> which handles building the <code>.cpp</code> files for openzwave and downloading all dependencies (including <code>Cython</code>); and <code>make install</code> which runs the <code>setup-api</code>, <code>setup-lib.py</code> (this setup scrip...
1
2016-06-18T14:11:13Z
[ "python", "c++", "z-wave" ]
Compile and use python-openzwave with open-zwave in non-standard location
37,731,787
<p>I manually compiled <a href="https://github.com/OpenZWave/python-openzwave">python-openzwave</a> to work with <a href="https://github.com/OpenZWave/open-zwave">C++ library</a>.</p> <p>I would like to use it as Kodi addon (OpenELEC running on Pi 3), so can not use standard installation. I've compiled everything, dow...
11
2016-06-09T16:42:51Z
37,934,574
<p>Here's the description of the <code>python-openzwave</code>'s build from the question's perspective. Almost all the steps correspond to the root <code>Makefile</code>'s targets.</p> <ul> <li><strong>Prerequisites.</strong> There are several independent targets with little to no organization. Most use Debian-specifi...
1
2016-06-21T02:20:37Z
[ "python", "c++", "z-wave" ]
Assistance needed to understand how exception handling is working
37,731,790
<p>I have been fiddling around with raising exceptions for Google Big Query for 2 days straight. I finally figured out how to make it work in the way it should work, but I don't really understand why it works. I am looking for assistance in gaining a better understanding what is going on in my code. I have already scou...
0
2016-06-09T16:42:55Z
37,733,760
<p>As the code is, there is no real reason for the <code>try</code> because at the end of the <code>try</code> block you <strong><em>always</em></strong> raise an exception, so you always go to the <code>except</code> block. So each time the code runs, it goes through the <code>try</code>, then hits the exception so g...
1
2016-06-09T18:38:09Z
[ "python", "django", "exception-handling", "google-api", "google-bigquery" ]
using FIFOs for input and output in python
37,731,797
<p>To communicate with a shell, which is started once and runs in a separate process, I used <code>Popen</code> <code>from subprocess</code>.</p> <pre><code>import os from subprocess import Popen, PIPE def server(): FIFO_PATH = '/tmp/my_fifo' FIFO_PATH2 = '/tmp/in_fifo' if os.path.exists(FIFO_PATH): ...
1
2016-06-09T16:43:14Z
37,735,689
<p>From the man page for <code>mkfifo</code>:</p> <blockquote> <p>Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa. See fifo(7) for nonblocking handling of FIFO special files.</p> </blockquote> <p>So the second time you open the FIFO for reading, t...
0
2016-06-09T20:36:31Z
[ "python", "fifo", "mkfifo" ]
Python Java forEach equivalent
37,731,895
<p>I am Java programmer. I started learning Python few days ago. I'm wondering: are there any equivalents to </p> <p><br/> <code>map.forEach(System.out::println)</code></p> <p><br/> in Python with lambdas? Or only with for loop:</p> <p><br/> <code>for e in map: print(e)</code></p> <p><br/></p>
0
2016-06-09T16:47:59Z
37,731,929
<p>Python also has a <code>map</code> function and it uses the syntax <code>map(function, iterable, ...)</code></p> <p>See Python docs: <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">https://docs.python.org/2/library/functions.html#map</a></p>
0
2016-06-09T16:50:07Z
[ "java", "python", "python-3.x", "lambda" ]
Python Java forEach equivalent
37,731,895
<p>I am Java programmer. I started learning Python few days ago. I'm wondering: are there any equivalents to </p> <p><br/> <code>map.forEach(System.out::println)</code></p> <p><br/> in Python with lambdas? Or only with for loop:</p> <p><br/> <code>for e in map: print(e)</code></p> <p><br/></p>
0
2016-06-09T16:47:59Z
37,732,102
<p>There is no equivalent to Java's imperative <code>Iterable.forEach</code> or <code>Stream.forEach</code> method. There's a <code>map</code> function, analogous to Java's <code>Stream.map</code>, but it's for applying transformations to an iterable. Like Java's <code>Stream.map</code>, it doesn't actually apply the f...
3
2016-06-09T17:00:56Z
[ "java", "python", "python-3.x", "lambda" ]
Concatenating numpy arrays of different shapes
37,732,024
<p>I have several <strong>N</strong>-dimensional arrays of different shapes and want to combine them into a new <strong>(N+1)</strong>-dimensional array, where the new axis has a length corresponding to the number of initial N-d arrays. </p> <p><a href="http://stackoverflow.com/questions/8898471/concatenate-two-numpy-...
1
2016-06-09T16:56:41Z
37,732,237
<p>While I was writing this, Sven gave the same answer in the comments...</p> <p>Put the arrays in a python list in the following manner:</p> <pre><code>5d_list = [] 5d_list.append(4D_array_1) 5d_list.append(4D_array_2) ... </code></pre> <p>Then you can unpack them:</p> <pre><code>for 4d_array in 5d_list: #plot...
2
2016-06-09T17:07:47Z
[ "python", "arrays", "numpy", "multidimensional-array", "concatenation" ]
Can I explicitly specify multiple tests in PyTest?
37,732,032
<p>I know I can specify a single test to run in PyTest with the following command:</p> <p><code>py.test test.py::my_test_class::my_test_function</code>.</p> <p>Is there a way to explicitly specify multiple tests to run, without running ALL the tests?</p> <p>I could run the <code>py.test</code> command in a for loop ...
1
2016-06-09T16:56:54Z
37,855,199
<p>You can put your tests in a file, implement the modifier hook to filter the tests to execute based on whether or not they are present in the file. Here's an example:</p> <p><strong>Test file# 1</strong></p> <pre><code>$ cat test_foo.py def test_001(): pass def test_002(): pass $ </code></pre> <p><strong...
2
2016-06-16T09:31:12Z
[ "python", "unit-testing", "automated-tests", "py.test" ]
return an unpacked list in python
37,732,050
<p>I'm trying to do something like this in python:</p> <pre><code>def f(): b = ['c', 8] return 1, 2, b*, 3 </code></pre> <p>Where I want f to return the tuple (1, 2, 'c', 8, 3). I found a way to do this using itertools followed by tuple, but this is not very nice and I was wondering whether there exists an el...
0
2016-06-09T16:57:49Z
37,732,122
<p>The unpacking operator <code>*</code> appears before the <code>b</code>, not after it.</p> <pre><code>return 1, 2, *b, 3 # ^^ </code></pre> <p>However, this will only work on Python 3.5+ (<a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>). In the older versions, use <code>+<...
4
2016-06-09T17:01:52Z
[ "python", "return", "tuples", "unpack" ]
Python in OS X: Detect multiple monitors and move application window to specific monitor
37,732,063
<p><strong>Question</strong>: Is there a way to have Python detect when running the code in OS X, if there is more than one monitor active? Is it then, possible to move a specific OS X application window to one of those monitors by choosing?</p> <hr> <p><em>FYI:</em> I have previously been able to utilize <code>Carbo...
1
2016-06-09T16:58:35Z
37,916,490
<p>To detect monitors, you can use <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSScreen_Class/#//apple_ref/occ/clm/NSScreen/screens" rel="nofollow"><code>NSScreen.screens()</code></a>. You can then probably just position your <code>NSWindow</code> within the des...
1
2016-06-20T07:10:43Z
[ "python", "osx", "monitor", "pyobjc", "appleevents" ]
Django queryset.query and query run in mysql console doesn't give the same result
37,732,091
<p>I have 2 Models: Project and ProjectTweet.</p> <p>Project has a relation OneToMany with ProjectTweet (related name: "tweets")</p> <p>Here is my queryset:</p> <pre><code>current_pledge = 1000000 projects = Project.objects.filter(state = "live").filter(pledged__gt=current_pledge).exclude(tweets__step__gte=current_p...
0
2016-06-09T17:00:19Z
37,743,267
<p>I don't know how i could miss that but my "step" field that i compare using <code>.exclude(tweets__step__gte=current_pledge)</code></p> <p>is a CharField instead of FloatField... i've change that and now the query in mysql console and queryset give me same result. However i would have liked an error instead of giv...
0
2016-06-10T08:17:46Z
[ "python", "mysql", "django", "django-queryset" ]
Putting an int and str into one output in an input(python)
37,732,137
<p>E.g "input("what is",a,b,c,"?")"</p> <p>However this doesn't work</p> <p>a is a random number</p> <p>b is a + sign </p> <p>c is another random number</p> <p>When i try and run the code it says: :TypeError: input expected at most 1 arguments, got 5</p> <p>p.s im am new to coding so please use simple language so...
-1
2016-06-09T17:02:32Z
37,732,266
<p>You need to provide a single string argument when calling input, i.e. <code>input("enter input now")</code>. If <code>b</code> is always a <code>+</code>, try <code>input("what is {}+{}".format(a,c))</code>. The first argument in <code>format</code> will replace the first <code>{}</code> in the string, the second ar...
0
2016-06-09T17:09:10Z
[ "python", "input" ]
Putting an int and str into one output in an input(python)
37,732,137
<p>E.g "input("what is",a,b,c,"?")"</p> <p>However this doesn't work</p> <p>a is a random number</p> <p>b is a + sign </p> <p>c is another random number</p> <p>When i try and run the code it says: :TypeError: input expected at most 1 arguments, got 5</p> <p>p.s im am new to coding so please use simple language so...
-1
2016-06-09T17:02:32Z
37,732,300
<pre><code>import numpy as np a= np.random.randint(0,10) b = "+" c = np.random.randint(0,10) print("what is 'a,b,c'", eval(str(a)+str(b)+str(c))) </code></pre> <p>If you want to input a random number and assign it to <code>a</code> and <code>b</code>. You should use following:</p> <pre><code>a = input("Value of ...
0
2016-06-09T17:11:10Z
[ "python", "input" ]
Putting an int and str into one output in an input(python)
37,732,137
<p>E.g "input("what is",a,b,c,"?")"</p> <p>However this doesn't work</p> <p>a is a random number</p> <p>b is a + sign </p> <p>c is another random number</p> <p>When i try and run the code it says: :TypeError: input expected at most 1 arguments, got 5</p> <p>p.s im am new to coding so please use simple language so...
-1
2016-06-09T17:02:32Z
37,732,325
<p>I think your issue is a fundamental misunderstanding of how input works. It's really difficult to parse out what you're trying to do with the input, but I'll give it a shot.</p> <p>The 'input' function asks the user for exactly that, input. It will then store that input somehow. Usually you'll want to assign it to ...
1
2016-06-09T17:13:17Z
[ "python", "input" ]
Python Fabric perform remote database task
37,732,177
<p>I need to ssh to a remote Ubuntu server to do some routine job, in following steps:</p> <ol> <li>ssh in as userA</li> <li>sudo su - userB</li> <li>run daliy_python.py script with use psycopg2 to read some info from the database (via local connection (non-TCP/IP)) </li> <li>scp readings to my local machine</li> </ol...
0
2016-06-09T17:04:08Z
37,732,419
<p>This is what I do to read my root accessible logfiles without extra login</p> <pre><code>ssh usera@12.34.56.78 "echo hunter2 | sudo -S tail -f /var/log/nginx/access.log" </code></pre> <p>That is: <code>ssh usera@12.34.56.78 "..run this code on the remote.."</code></p> <p>Then on the remote, you pipe the sudo pass...
0
2016-06-09T17:18:11Z
[ "python", "postgresql", "ssh", "ubuntu-14.04", "fabric" ]
Python Fabric perform remote database task
37,732,177
<p>I need to ssh to a remote Ubuntu server to do some routine job, in following steps:</p> <ol> <li>ssh in as userA</li> <li>sudo su - userB</li> <li>run daliy_python.py script with use psycopg2 to read some info from the database (via local connection (non-TCP/IP)) </li> <li>scp readings to my local machine</li> </ol...
0
2016-06-09T17:04:08Z
37,743,305
<p>I finally find out where my problem is. Thanks @chishake and @C14L, I look at the problem in another way. After inspired by this posts <a href="http://stackoverflow.com/a/13801188/4627539">link1</a> <a href="http://stackoverflow.com/q/13080643">link2</a>, I start to think this problem is related to environmental var...
0
2016-06-10T08:20:09Z
[ "python", "postgresql", "ssh", "ubuntu-14.04", "fabric" ]
python ldap3 search LDAPOperationsErrorResult
37,732,180
<p>I would like to get all PCs in the local network from ldap, so I tried (variations of) this:</p> <pre><code>import ldap3 from ldap3 import ALL_ATTRIBUTES, SUBTREE, ALL import dns.resolver import socket def get_ldap_server(): domain_name = socket.getfqdn().lstrip( socket.gethostname() ) answers = dns.re...
1
2016-06-09T17:04:15Z
37,736,222
<p>You didn't provide any username or password in the connection object, so an anonymous bind is performed.</p> <p>Try adding username=xxx and password=yyy to the Connection definition in the "with" statement.</p>
2
2016-06-09T21:09:24Z
[ "python", "ldap" ]
how scipy.signal.step compute the time
37,732,216
<p>scipy.signal.step the documentation states that the simulation time is deducted if it is not specified. How is this time determined if the function converges?</p> <p>How come if it does not converge?</p>
1
2016-06-09T17:06:36Z
37,770,342
<p><code>scipy</code> is open source. Currently the code resides on github at <a href="https://github.com/scipy/scipy" rel="nofollow">https://github.com/scipy/scipy</a>. The definition of <code>step</code> is currently in <a href="https://github.com/scipy/scipy/blob/master/scipy/signal/ltisys.py" rel="nofollow">https...
1
2016-06-12T03:05:29Z
[ "python", "scipy", "signals" ]
I am having trouble adding a number to a previous number and so on
37,732,234
<p>So I have a text file which contains a list of numbers which I want to create a running total of. I need the first number to add to the second number and then the third number to add to the newly created second value and so on...<br> Like this:<br> <strong>Old List</strong><br> 0.1<br> 0.25<br> 0.35<br> 0.2<br> 0.3<...
0
2016-06-09T17:07:24Z
37,732,348
<p>The answer is right in the error message:</p> <pre><code>total = sum([int(num) for num in value]) ValueError: invalid literal for int() with base 10: ' ' </code></pre> <p><code>num</code> has a value of <code>' '</code>, and you're trying to convert it to an integer with <code>int()</code>. Obviously <code>int(' '...
0
2016-06-09T17:14:38Z
[ "python", "running-total" ]
I am having trouble adding a number to a previous number and so on
37,732,234
<p>So I have a text file which contains a list of numbers which I want to create a running total of. I need the first number to add to the second number and then the third number to add to the newly created second value and so on...<br> Like this:<br> <strong>Old List</strong><br> 0.1<br> 0.25<br> 0.35<br> 0.2<br> 0.3<...
0
2016-06-09T17:07:24Z
37,732,475
<p>There is a number of things wrong, so that it's hard to understand what you want &amp; what's going on.</p> <p>Firstly, I suggest that instead of complicated file operations, just paste the first 5 lines or so of your 'compiled.txt' in here as </p> <pre><code>numbers_string = """ 1 2 3 whate...
0
2016-06-09T17:21:35Z
[ "python", "running-total" ]
I am having trouble adding a number to a previous number and so on
37,732,234
<p>So I have a text file which contains a list of numbers which I want to create a running total of. I need the first number to add to the second number and then the third number to add to the newly created second value and so on...<br> Like this:<br> <strong>Old List</strong><br> 0.1<br> 0.25<br> 0.35<br> 0.2<br> 0.3<...
0
2016-06-09T17:07:24Z
37,732,906
<p>The rest of the code you posted is a bit convoluted and it's hard to figure out what you're trying to, especially since we don't have the full data you're working with. But the answer to your specific question about just adding up the numbers from one file and writing them to another one is as follows:</p> <pre><co...
0
2016-06-09T17:47:27Z
[ "python", "running-total" ]
How to get the Hometown and Gender of Users from Facebook
37,732,263
<p>Is there a way to get the hometown and gender of users who comment on a specific Page Post, using the facebook graph API or any other?</p> <p>More precisely, when I do extract comments on a Page Post with Graph API, it shows me all the IDs of Users who had posted comments. But I need also hometown where they live i...
0
2016-06-09T17:09:02Z
37,733,007
<p>That´s not possible, you even need an extra permission to authorize a user in order to get his hometown, and you can´t get the gender without authorization either.</p>
0
2016-06-09T17:52:49Z
[ "python", "facebook-graph-api" ]
How can I merge two dataframes with 'wildcards'?
37,732,276
<p>I have a simple dataframe like so:</p> <pre><code> p b 0 a buy 1 b buy 2 a sell 3 b sell </code></pre> <p>and a lookup table like this:</p> <pre><code> p b v 0 a buy 123 1 a sell 456 2 a * 888 4 b * 789 </code></pre> <p>How can I merge (join) the two dataframes, but re...
4
2016-06-09T17:09:57Z
37,733,128
<p>I think a little cleaner is to clean up the <code>wildcards</code> first:</p> <pre><code>In [11]: wildcards = lookup[lookup["b"] == "*"] In [12]: wildcards.pop("b") # ditch the * column, it'll confuse the later merge </code></pre> <p>Now you can combine the two merges (without needing <code>set_index</code>) wit...
5
2016-06-09T18:01:03Z
[ "python", "pandas" ]
How can I merge two dataframes with 'wildcards'?
37,732,276
<p>I have a simple dataframe like so:</p> <pre><code> p b 0 a buy 1 b buy 2 a sell 3 b sell </code></pre> <p>and a lookup table like this:</p> <pre><code> p b v 0 a buy 123 1 a sell 456 2 a * 888 4 b * 789 </code></pre> <p>How can I merge (join) the two dataframes, but re...
4
2016-06-09T17:09:57Z
37,733,267
<p>I find this intuitive:</p> <pre><code>def find_lookup(lookup, p, b): ps = lookup.p == p bs = lookup.b.isin([b, '*']) return lookup.loc[ps &amp; bs].iloc[0].replace('*', b) data.apply(lambda x: find_lookup(lookup, x.loc['p'], x.loc['b']), axis=1) p b v 0 a buy 123 1 b buy 789 2 a se...
1
2016-06-09T18:08:48Z
[ "python", "pandas" ]
How can I merge two dataframes with 'wildcards'?
37,732,276
<p>I have a simple dataframe like so:</p> <pre><code> p b 0 a buy 1 b buy 2 a sell 3 b sell </code></pre> <p>and a lookup table like this:</p> <pre><code> p b v 0 a buy 123 1 a sell 456 2 a * 888 4 b * 789 </code></pre> <p>How can I merge (join) the two dataframes, but re...
4
2016-06-09T17:09:57Z
37,743,006
<p>I've found another solution, inspired by some of the ideas above (thanks all!). It's neater than my first attempt so I'll put it here, though I'm sure there's room for improvement. This solution assumes lookup is sorted so that wildcards are at the bottom of the table:</p> <pre><code>x = data.reset_index().merge(lo...
1
2016-06-10T08:01:07Z
[ "python", "pandas" ]
How to successfully implement my own __contains__ method for an ArrayList class?
37,732,291
<p>I'm a relatively new python programmer and am trying to fix my <strong>contains</strong> method in my ArrayList class. I want to check if an input value is actually contained in the stored list.</p> <pre><code>def __contains__(self, value): """Implements `val in self`. Returns true if value is found in this...
0
2016-06-09T17:10:49Z
37,732,354
<p>This tests if <code>num</code> is equal to the first value in <code>self</code>. You should only <code>return False</code> after the whole loop ends and you've shown that <code>num</code> wasn't equal to anything in the list since you haven't returned <code>True</code> yet.</p> <p>Also note that the <code>iter</cod...
1
2016-06-09T17:15:04Z
[ "python", "class", "arraylist", "contains" ]
How to remove utf format in a dataframe in Pyspark and convert column from string to Integer
37,732,301
<p>I need to remove utf formatting and convert a column to Integer type.</p> <p>Below is what I have done to remove the utf format</p> <pre><code>&gt;&gt;auction_data = auction_raw_data.map(lambda line: line.encode("ascii","ignore").split(",")) &gt;&gt;auction_Data.take(2) &gt;&gt;[['8211480551', '52.99', '1.201505',...
0
2016-06-09T17:11:10Z
39,664,461
<p>I am loading a JSON and not using a schema, so I don't know if there's a difference. I have no issues when converting fields to int when using <code>select</code>. This is what I do:</p> <pre><code>from pyspark.sql.functions import * ... df = df.select(col('intField').cast('int')) df.show() # prints Row(intField=12...
0
2016-09-23T15:27:44Z
[ "python", "utf-8", "pyspark", "spark-dataframe" ]
Apache server in Linux error forbidden access
37,732,395
<p>I'm a beginner in web development. When I run Apache server give me this error in web page:</p> <pre><code>Access forbidden! You don't have permission to access the requested object. It is either read-protected or not readable by the server. If you think this is a server error, please contact the webmaster. Error...
-2
2016-06-09T17:16:58Z
37,762,592
<p>thanks guys'<br> im succeed to run the server truely .<br> just change target directory permission to 775 and change the user and group in httpd.conf to my current user .<br> and for custom folder for sites root , change "DocumentRoot" of httpd.conf and set permission. <br><br><br> sory for my english.<br> thanks ag...
0
2016-06-11T10:21:35Z
[ "python", "django", "apache", "web", "wsgi" ]
Pandas DataFrame from MultiIndex and NumPy structured array (recarray)
37,732,403
<p>First I create a two-level <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#hierarchical-indexing-multiindex" rel="nofollow">MultiIndex</a>:</p> <pre><code>import numpy as np import pandas as pd ind = pd.MultiIndex.from_product([('X','Y'), ('a','b')]) </code></pre> <p>I can use it like this:</p>...
2
2016-06-09T17:17:23Z
37,732,964
<p>This looks like a bug, and worth reporting <a href="https://github.com/pydata/pandas/issues" rel="nofollow">as an issue github</a>.</p> <p>A workaround is to set the columns manually after construction:</p> <pre><code>In [11]: df1 = pd.DataFrame(np.zeros(3, dtype)) In [12]: df1.columns = ind In [13]: df1 Out[13]...
2
2016-06-09T17:50:14Z
[ "python", "numpy", "pandas", "dataframe", "multi-index" ]
Pandas DataFrame from MultiIndex and NumPy structured array (recarray)
37,732,403
<p>First I create a two-level <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#hierarchical-indexing-multiindex" rel="nofollow">MultiIndex</a>:</p> <pre><code>import numpy as np import pandas as pd ind = pd.MultiIndex.from_product([('X','Y'), ('a','b')]) </code></pre> <p>I can use it like this:</p>...
2
2016-06-09T17:17:23Z
37,732,981
<pre><code>pd.DataFrame(np.zeros(3, dtype), columns=ind) Empty DataFrame Columns: [(X, a), (X, b), (Y, a), (Y, b)] Index: [] </code></pre> <p>is just showing the textual representation of the dataframe output.</p> <pre><code>Columns: [(X, a), (X, b), (Y, a), (Y, b)] </code></pre> <p>is then just the text representa...
1
2016-06-09T17:51:19Z
[ "python", "numpy", "pandas", "dataframe", "multi-index" ]
Python CSV - optimizing CSV Read and Write
37,732,466
<p>I am currently fiddling around with Python when my boss assigned me with a quite daunting task.</p> <p>He gave me a CSV file with around 14GB in size, and ask me if I can <em>inflate</em> that CSV to a delimited file with 4TB of size, by replicating itself several times.</p> <p>For example, take this CSV:</p> <pr...
1
2016-06-09T17:21:03Z
37,733,235
<p>I don't have a 14GB file to try this with, so memory footprint is a concern. Someone who knows regex better than myself might have some performance tweaking suggestions.</p> <p>The main concept is don't iterate through each line when avoidable. Let <code>re</code> do it's magic on the whole body of text then write...
1
2016-06-09T18:07:17Z
[ "python", "algorithm", "csv" ]
Python CSV - optimizing CSV Read and Write
37,732,466
<p>I am currently fiddling around with Python when my boss assigned me with a quite daunting task.</p> <p>He gave me a CSV file with around 14GB in size, and ask me if I can <em>inflate</em> that CSV to a delimited file with 4TB of size, by replicating itself several times.</p> <p>For example, take this CSV:</p> <pr...
1
2016-06-09T17:21:03Z
37,733,320
<p>Batch writing your rows isn't really going to be an improvement because your write IO's are still going to be the same size. Batching up writes only gives you an improvement if you can increase your IO size, which reduces the number of system calls and allows the IO system to deal with fewer but larger writes.</p> ...
1
2016-06-09T18:11:55Z
[ "python", "algorithm", "csv" ]
Python CSV - optimizing CSV Read and Write
37,732,466
<p>I am currently fiddling around with Python when my boss assigned me with a quite daunting task.</p> <p>He gave me a CSV file with around 14GB in size, and ask me if I can <em>inflate</em> that CSV to a delimited file with 4TB of size, by replicating itself several times.</p> <p>For example, take this CSV:</p> <pr...
1
2016-06-09T17:21:03Z
37,814,647
<p>First of all, you're going to be limited by the write speed. Typical write speed for a desktop machine is on the order of about 40 seconds per gigabyte. You need to write 4,000 gigabytes, so it's going to take on the order of 160,000 seconds (44.5 hours) just to write the output. The only way to reduce that time is ...
1
2016-06-14T14:17:57Z
[ "python", "algorithm", "csv" ]
Matplotlib doesn't show last figure
37,732,495
<p>I use matplotlib to show figures but when it comes to the last figure, it doesn't show its content (just creates the window). I use it to depicture maximal independent sets of a graph. So, sets is actually a list which contains lists of nodes.</p> <pre><code>pos=nx.spring_layout(G) # positions for all nodes for i...
1
2016-06-09T17:22:16Z
37,733,598
<p>Try this :</p> <pre><code>pos=nx.spring_layout(G) # positions for all nodes for i in range(0, len(sets)): nx.draw_networkx_nodes(G,pos, sets[i], node_color='r', node_size=500, alpha=0.8) rest = [] for j in nodes: if j not in sets[i]: rest.append(j) nx.draw_networ...
0
2016-06-09T18:28:14Z
[ "python", "matplotlib" ]
Python decorator access argument by name
37,732,639
<p>I want to make a Python decorator that can take an argument (the name of an argument in the function it is decorating) and use that argument to find the value of the argument in the function. I know that sounds super confusing, ha! But what I want to do would look like this (it's for a Flask web application):</p> <...
2
2016-06-09T17:30:38Z
37,733,001
<p>You can use the <a href="https://docs.python.org/2/library/inspect.html#inspect.getargspec" rel="nofollow"><code>inspect.getargspec()</code> function</a> to access the names used in a function:</p> <pre><code>def access_course_permission(argument_name): def decorator(f): argspec = inspect.getargspec(f) ...
2
2016-06-09T17:52:22Z
[ "python", "flask", "python-decorators" ]
Scrapy loop - xpath selector escaping object it is applied to and returning all records?
37,732,649
<p>I'll start with the scrapy code I'm trying to use to iterate through a collection of vehicles and extract the model and price:</p> <pre><code> def parse(self, response): hxs = Selector(response) split_url = response.url.split("/") listings = hxs.xpath("//div[contains(@class,'listing-item'...
0
2016-06-09T17:31:07Z
37,734,020
<p>I was able to solve the problem with the aid of the manual, <a href="http://doc.scrapy.org/en/latest/topics/selectors.html" rel="nofollow">here</a>. In summary, the xpath was indeed escaping the iteration because I neglected to put a period in front of the <code>//</code> which meant that it was escaping to the root...
0
2016-06-09T18:53:06Z
[ "python", "xpath", "scrapy", "scrapy-spider" ]
Where to store global data in Django
37,732,658
<p>Where should I store information like admin's email, telephone number? I want admin to be able to change this data anytime they want.</p> <p>Now, I have one model for this. It's called <code>AdminContact</code> and it allows only one row. I think it's not an appropriate way to do this. Moreover, it causes circular ...
1
2016-06-09T17:31:58Z
37,734,657
<p>One fine way to do this is to put it inside your <code>settings.py</code> file like so :</p> <p><code>ADMIN_CONTACT = {email: 'foo@bar.com', phone: '0585522002'}</code></p> <p>Then you can access it anywhere by importing django settings :</p> <pre><code>from django.conf import settings from django.core.mail impo...
1
2016-06-09T19:29:10Z
[ "python", "django", "django-models" ]
Python regular expression: how to return search value?
37,732,668
<p>I'm sure that this is a very elementary question, so thank you in advance for your patience. </p> <p>I'm using a simple regular expression to identify whether a year is present in a line of text (line is a dictionary so I'm calling the particular field I want to search). Then I want to do something with the year. M...
0
2016-06-09T17:32:25Z
37,732,756
<p>You just need to put the matched object in a variable, then use <a href="https://docs.python.org/3/library/re.html#re.match.group" rel="nofollow"><code>group()</code> attribute</a> in order to return the matched string.</p> <pre><code>p = re.compile('\d{4}') matched_obj = p.search(line['productionStartYear']) if ma...
2
2016-06-09T17:37:29Z
[ "python", "regex" ]
Python3.5 ImportError: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory
37,732,748
<p>I am using Ubuntu 14.04 LTS, 64-bit. I downloaded Python3.5.1 Gzipped tarball source from <a href="https://www.python.org/downloads/release/python-351/" rel="nofollow">https://www.python.org/downloads/release/python-351/</a>. </p> <p>Then installed using</p> <pre><code>./configure sudo make install </code></pre> ...
0
2016-06-09T17:36:53Z
37,732,994
<p>Most people installed matlibplot through <code>Anaconda</code> or <code>Canopy</code> instead of installing it as an individual module. Usually if you have an error from <code>_path</code>, it means something wrong with your installation or compilation. <code>_path</code> is related to compiled c extentions. You can...
1
2016-06-09T17:51:58Z
[ "python", "linux", "matplotlib", "importerror" ]