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
How to define class variables using the functions and variables of an instance in Python
39,856,861
<p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p> <p>The simplified code looks like this:</p> <pre><code>def ClassA(): X = self.func(self.a) def __init__(self, avalue): self.a = avalue def func(self): return self.a + 5 </code></pre> <p>NameError: name 'self' is not defined</p>
-3
2016-10-04T15:57:17Z
39,857,029
<p>I guess what you tried to do was:</p> <pre><code>class ClassA(): def __init__(self,avalue): self.a = avalue self.X = self.func def func(self): return self.a + 5 b = ClassA(43) b.X() </code></pre> <p>outputs </p> <pre><code>48 </code></pre>
0
2016-10-04T16:06:10Z
[ "python", "class", "scope" ]
How to define class variables using the functions and variables of an instance in Python
39,856,861
<p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p> <p>The simplified code looks like this:</p> <pre><code>def ClassA(): X = self.func(self.a) def __init__(self, avalue): self.a = avalue def func(self): return self.a + 5 </code></pre> <p>NameError: name 'self' is not defined</p>
-3
2016-10-04T15:57:17Z
39,857,055
<pre><code>class A(): def __init__(self): self.y = 0 def m(self): A.x = 1 b = A() #print(b.x) doesn't work here since we haven't made it yet. b.m() print(b.x) #1 c = A() print(c.x) #1 A.x = 2 print(c.x) #2 print(b.x) #2 print(vars(A)) #{'__dict__': &lt;attribute '__dict__' of 'A' objects&gt;, '__module__': 'builtins', 'x': 2, '__init__': &lt;function A.__init__ at 0x7f15f800d730&gt;, '__weakref__': &lt;attribute '__weakref__' of 'A' objects&gt;, '__doc__': None, 'm': &lt;function A.m at 0x7f15f800d7b8&gt;} </code></pre> <p>Would you be looking for something like this?</p>
0
2016-10-04T16:07:58Z
[ "python", "class", "scope" ]
How to use matplotlib quiver using an external file
39,856,867
<p>I am trying to write a very simple code (should be):</p> <p>I want to plot arrows from an external data file which gives me the vector dimensions in x and y, given in two columns sx and sy.</p> <p>For example, I have two columns of 36 numbers each but they are the dimension of a vector having 6x6 grid. however when I do the following it gives me an error, I suppose I need an extra step to convert this data from two columns to a grid?! But I have no idea what this step could be. Any insights?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl data=np.loadtxt(r'text.dat') x,y = np.meshgrid(np.arange(0, 6, 1), np.arange(0, 6, 1)) u = data[:,1] v = data[:,2] plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1) </code></pre>
0
2016-10-04T15:57:56Z
39,857,142
<p>You would benefit from a quick sanity check.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl data=np.loadtxt(r'text.dat') x,y = np.meshgrid(np.arange(0, 6, 1), np.arange(0, 6, 1)) print x # 6x6 array, 2D! print y # 6x6 array, 2D! u = data[:,1] # 36 array, 1D! v = data[:,2] # 36 array, 1D! plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1) </code></pre> <p>Presumably your text.dat file holds records for points [(0,0), (1,0), (2,0), ... (0,1), (1,1), (2,1)... (4,5), (5,5)] in that order.</p> <p>In such a case, you just need to flatten <code>x</code> and <code>y</code> to make them 1-dimensional. You can't mix 1D and 2D arrays in quiver.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl data=np.loadtxt(r'text.dat') x,y = np.meshgrid(np.arange(0, 6, 1), np.arange(0, 6, 1)) x = x.flatten() y = y.flatten() print x # 36 array, 1D! print y # 36 array, 1D! u = data[:,1] # 36 array, 1D! v = data[:,2] # 36 array, 1D! plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1) </code></pre> <p><strong>EDIT:</strong> If you continue having problems, run your commands in an interactive terminal or command prompt. Check each variable and its dimensions (array.shape) to make sure the variables are what you think they are. Are each of the dimensions actually 36? </p>
1
2016-10-04T16:11:31Z
[ "python", "matplotlib", "plot", "vector-graphics" ]
How to extract a specific part from a JSON response?
39,856,978
<p>I have code like</p> <pre><code>import requests dict_api = "http://api.pearson.com/v2/dictionaries/entries?headword=" r = requests.get(dict_api + word) results = r.json()["results"] </code></pre> <p>and this gives me this:</p> <pre><code>[ { "senses": [ { "translation": "\\u6c99\\u62c9\\uff0c\\u8272\\u62c9\\uff0c\\u6c99\\u5f8b\\u3014\\u7528\\u751f\\u83dc\\u3001\\u9ec3\\u74dc\\u3001\\u756a\\u8304\\u7b49\\u751f\\u7684\\u852c\\u83dc\\u4f5c\\u539f\\u6599\\u7684\\u6dbc\\u62cc\\u83dc\\u3015" } ], "url": "/v2/dictionaries/entries/cqAJbKG6Bx", "part_of_speech": "noun", "datasets": [ "ldec", "dictionary" ], "headword": "salad", "id": "cqAJbKG6Bx" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d", "audio": [ { "url": "/v2/dictionaries/assets/ldoce/gb_pron/salad_las2_br.mp3", "lang": "British English", "type": "pronunciation" }, { "url": "/v2/dictionaries/assets/ldoce/us_pron/salad.mp3", "lang": "American English", "type": "pronunciation" } ] } ], "senses": [ { "definition": [ "a mixture of raw vegetables, especially lettuce, cucumber, and tomato" ], "collocation_examples": [ { "collocation": "toss a salad", "example": { "audio": [ { "url": "/v2/dictionaries", "type": "example" } ] } } ], "examples": [ { "text": "Would you like some salad with your pasta?", "audio": [ { "url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-000741011.mp3", "type": "example" } ] } ] } ], "url": "/v2/dictionaries/entries/cqAFq6n9JR", "part_of_speech": "noun", "datasets": [ "ldoce5", "dictionary" ], "headword": "salad", "id": "cqAFq6n9JR" }, { "senses": [ { "definition": "a mixture of vegetables, eaten cold", "examples": [ { "text": "a tomato salad" } ] } ], "url": "/v2/dictionaries/entries/cqARFW4JGH", "part_of_speech": "noun", "datasets": [ "wordwise", "dictionary" ], "headword": "salad", "id": "cqARFW4JGH" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ {} ], "url": "/v2/dictionaries/entries/csTMd1V83W", "part_of_speech": "noun", "datasets": [ "laes", "dictionary" ], "headword": "salad", "id": "csTMd1V83W" }, { "senses": [ { "definition": "rou groentemengsel", "translations": [ { "text": "slaai" } ] } ], "url": "/v2/dictionaries/entries/cqAG06X6Kc", "part_of_speech": "noun", "datasets": [ "leasd", "dictionary" ], "headword": "salad", "id": "cqAG06X6Kc" }, { "senses": [ { "definition": "a mixture of raw vegetables, usually including lettuce", "examples": [ { "text": "a tomato and cucumber salad" } ] } ], "url": "/v2/dictionaries/entries/cs1tApKyAq", "part_of_speech": "noun", "datasets": [ "laad3", "dictionary" ], "headword": "salad", "id": "cs1tApKyAq" }, { "pronunciations": [ { "lang": "American English", "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ { "definition": [ "dish of mixed raw vegetables" ], "translations": [ { "text": [ "salada" ], "example": [ { "text": "a salad of tomatoes, lettuce and cucumber", "translation": { "text": [ "uma salada de tomate, alface e pepino" ] } } ] } ] } ], "url": "/v2/dictionaries/entries/ct59xTBDRn", "part_of_speech": "noun", "datasets": [ "brep", "dictionary" ], "headword": "salad", "id": "ct59xTBDRn" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ { "definition": [ "a mixture of vegetables eaten cold and usually raw" ], "examples": [ { "text": "a salad of lettuce, tomatoes, and cucumber" } ] } ], "url": "/v2/dictionaries/entries/cvfdktDye8", "part_of_speech": "noun", "datasets": [ "lasde", "dictionary" ], "headword": "salad", "id": "cvfdktDye8" }, { "senses": [ { "definition": "a salad made with lettuce and other raw green vegetables" } ], "url": "/v2/dictionaries/entries/cs1saJp1NK", "part_of_speech": "noun", "datasets": [ "laad3", "dictionary" ], "headword": "green salad", "id": "cs1saJp1NK" }, { "senses": [ { "translation": "\\u8a00\\u8a9e\\u96dc\\u4e82\\uff0c\\u8a00\\u8a9e\\u856a\\u96dc" } ], "url": "/v2/dictionaries/entries/cqAJqE3gvE", "part_of_speech": "noun", "datasets": [ "ldec", "dictionary" ], "headword": "word salad", "id": "cqAJqE3gvE" } ] </code></pre> <p>All I want to do is get each 'part_of_speech' value from the response and push it into a list, but I can't figure out how to do this.</p> <p>I have unsuccessfully tried parsing and python insists that this is actually a list.</p>
0
2016-10-04T16:03:37Z
39,857,083
<pre><code>print(results[0]['part_of_speech']) #prints 'noun' </code></pre>
3
2016-10-04T16:09:02Z
[ "python", "json", "python-requests" ]
How to extract a specific part from a JSON response?
39,856,978
<p>I have code like</p> <pre><code>import requests dict_api = "http://api.pearson.com/v2/dictionaries/entries?headword=" r = requests.get(dict_api + word) results = r.json()["results"] </code></pre> <p>and this gives me this:</p> <pre><code>[ { "senses": [ { "translation": "\\u6c99\\u62c9\\uff0c\\u8272\\u62c9\\uff0c\\u6c99\\u5f8b\\u3014\\u7528\\u751f\\u83dc\\u3001\\u9ec3\\u74dc\\u3001\\u756a\\u8304\\u7b49\\u751f\\u7684\\u852c\\u83dc\\u4f5c\\u539f\\u6599\\u7684\\u6dbc\\u62cc\\u83dc\\u3015" } ], "url": "/v2/dictionaries/entries/cqAJbKG6Bx", "part_of_speech": "noun", "datasets": [ "ldec", "dictionary" ], "headword": "salad", "id": "cqAJbKG6Bx" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d", "audio": [ { "url": "/v2/dictionaries/assets/ldoce/gb_pron/salad_las2_br.mp3", "lang": "British English", "type": "pronunciation" }, { "url": "/v2/dictionaries/assets/ldoce/us_pron/salad.mp3", "lang": "American English", "type": "pronunciation" } ] } ], "senses": [ { "definition": [ "a mixture of raw vegetables, especially lettuce, cucumber, and tomato" ], "collocation_examples": [ { "collocation": "toss a salad", "example": { "audio": [ { "url": "/v2/dictionaries", "type": "example" } ] } } ], "examples": [ { "text": "Would you like some salad with your pasta?", "audio": [ { "url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-000741011.mp3", "type": "example" } ] } ] } ], "url": "/v2/dictionaries/entries/cqAFq6n9JR", "part_of_speech": "noun", "datasets": [ "ldoce5", "dictionary" ], "headword": "salad", "id": "cqAFq6n9JR" }, { "senses": [ { "definition": "a mixture of vegetables, eaten cold", "examples": [ { "text": "a tomato salad" } ] } ], "url": "/v2/dictionaries/entries/cqARFW4JGH", "part_of_speech": "noun", "datasets": [ "wordwise", "dictionary" ], "headword": "salad", "id": "cqARFW4JGH" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ {} ], "url": "/v2/dictionaries/entries/csTMd1V83W", "part_of_speech": "noun", "datasets": [ "laes", "dictionary" ], "headword": "salad", "id": "csTMd1V83W" }, { "senses": [ { "definition": "rou groentemengsel", "translations": [ { "text": "slaai" } ] } ], "url": "/v2/dictionaries/entries/cqAG06X6Kc", "part_of_speech": "noun", "datasets": [ "leasd", "dictionary" ], "headword": "salad", "id": "cqAG06X6Kc" }, { "senses": [ { "definition": "a mixture of raw vegetables, usually including lettuce", "examples": [ { "text": "a tomato and cucumber salad" } ] } ], "url": "/v2/dictionaries/entries/cs1tApKyAq", "part_of_speech": "noun", "datasets": [ "laad3", "dictionary" ], "headword": "salad", "id": "cs1tApKyAq" }, { "pronunciations": [ { "lang": "American English", "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ { "definition": [ "dish of mixed raw vegetables" ], "translations": [ { "text": [ "salada" ], "example": [ { "text": "a salad of tomatoes, lettuce and cucumber", "translation": { "text": [ "uma salada de tomate, alface e pepino" ] } } ] } ] } ], "url": "/v2/dictionaries/entries/ct59xTBDRn", "part_of_speech": "noun", "datasets": [ "brep", "dictionary" ], "headword": "salad", "id": "ct59xTBDRn" }, { "pronunciations": [ { "ipa": "\\u02c8s\u5adcu0259d" } ], "senses": [ { "definition": [ "a mixture of vegetables eaten cold and usually raw" ], "examples": [ { "text": "a salad of lettuce, tomatoes, and cucumber" } ] } ], "url": "/v2/dictionaries/entries/cvfdktDye8", "part_of_speech": "noun", "datasets": [ "lasde", "dictionary" ], "headword": "salad", "id": "cvfdktDye8" }, { "senses": [ { "definition": "a salad made with lettuce and other raw green vegetables" } ], "url": "/v2/dictionaries/entries/cs1saJp1NK", "part_of_speech": "noun", "datasets": [ "laad3", "dictionary" ], "headword": "green salad", "id": "cs1saJp1NK" }, { "senses": [ { "translation": "\\u8a00\\u8a9e\\u96dc\\u4e82\\uff0c\\u8a00\\u8a9e\\u856a\\u96dc" } ], "url": "/v2/dictionaries/entries/cqAJqE3gvE", "part_of_speech": "noun", "datasets": [ "ldec", "dictionary" ], "headword": "word salad", "id": "cqAJqE3gvE" } ] </code></pre> <p>All I want to do is get each 'part_of_speech' value from the response and push it into a list, but I can't figure out how to do this.</p> <p>I have unsuccessfully tried parsing and python insists that this is actually a list.</p>
0
2016-10-04T16:03:37Z
39,857,151
<pre><code>for i in range(len(results)): print(results[i]['part_of_speech']) noun noun noun noun noun noun noun noun noun noun </code></pre>
1
2016-10-04T16:12:02Z
[ "python", "json", "python-requests" ]
Dropping multilevel columns from lists of dictionaries in pandas
39,857,148
<p>I have a dataframe with multilevel columns, like the one in the following MWE:</p> <pre><code>df = pd.DataFrame([[1,2],[3,4]], columns=[['a','c'],['b','d']], index=['one','two']) df.columns.names = ['aa', 'bb'] </code></pre> <p>Which looks like this:</p> <pre><code>In [267]: df Out[267]: aa a c bb b d one 1 2 two 3 4 </code></pre> <p>I also have a list of dictionaries like the following:</p> <pre><code>to_keep = [{'aa':'a', 'bb':'b'}, {'aa':'q', 'bb':'d'}] </code></pre> <p>What I'm looking to do:</p> <p>If the multilevel column labels are in the <code>to_keep</code> list then keep them in <code>df</code>, otherwise drop them from the df.</p> <p>So for <code>df</code> and <code>to_keep</code> above the resulting dataframe would look like:</p> <pre><code>aa a bb b one 1 two 3 </code></pre> <p>as <code>{'aa':'c', 'bb':'d'}</code> is not contained within <code>to_keep</code>. Is this possible?</p>
2
2016-10-04T16:11:55Z
39,859,358
<p>Create a <code>DF</code> mapping the column names to it's levels of the multi-index <code>DF</code>:</p> <pre><code>level_df = pd.DataFrame(df.columns.values.tolist(), columns=np.array(df.columns.names)) level_df </code></pre> <p><a href="http://i.stack.imgur.com/55E5e.png" rel="nofollow"><img src="http://i.stack.imgur.com/55E5e.png" alt="Image"></a></p> <p>Create another <code>DF</code> which keeps our required mapping containing list of dicts:</p> <pre><code>keep = pd.DataFrame(to_keep) keep </code></pre> <p><a href="http://i.stack.imgur.com/rUQrD.png" rel="nofollow"><img src="http://i.stack.imgur.com/rUQrD.png" alt="Image"></a></p> <p>Concatenate both <code>DFs</code> row-wise:</p> <pre><code>df_concat = pd.concat([level_df, keep], ignore_index=True) df_concat </code></pre> <p><a href="http://i.stack.imgur.com/0gFSj.png" rel="nofollow"><img src="http://i.stack.imgur.com/0gFSj.png" alt="Image"></a></p> <p>Remove all duplicates from concatenated <code>DF</code>. Drop off the level after checking if the remaining values in the concatenated <code>DF</code> is present in <code>level_df</code>:</p> <pre><code>cond = df_concat[~df_concat.duplicated(keep=False)] df.drop([tuple(x) for x in cond[cond.isin(level_df).all(axis=1)].values], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/i3pfE.png" rel="nofollow"><img src="http://i.stack.imgur.com/i3pfE.png" alt="Image"></a></p> <p>Note: Here it is assumed that the keys of the dictionaries match the multi-index column names.</p>
1
2016-10-04T18:30:38Z
[ "python", "pandas", "multi-index" ]
plot differently colored background rectangles on plot over several axes
39,857,170
<p>The following code is a snippet from a much larger function that plots several financial indicators over 3 axis:</p> <pre><code>left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axes background color ax1 = fig.add_axes(rect1)#, axisbg=axescolor) # left, bottom, width, height ax2 = fig.add_axes(rect2,sharex=ax1)#, axisbg=axescolor) ax3 = fig.add_axes(rect3,sharex=ax1)#, axisbg=axescolor </code></pre> <p>The final plot looks like that: </p> <p><a href="http://i.stack.imgur.com/AGRiF.png" rel="nofollow"><img src="http://i.stack.imgur.com/AGRiF.png" alt="enter image description here"></a></p> <p>Now I want to add background rectangles with a height that covers the complete x-axis (i.e. over all axis) and a width of several minutes, like that:</p> <p><a href="http://i.stack.imgur.com/WnqaK.png" rel="nofollow"><img src="http://i.stack.imgur.com/WnqaK.png" alt="enter image description here"></a></p> <p>How can I do that?</p>
0
2016-10-04T16:13:16Z
39,857,214
<p>This works :</p> <pre><code>ax1.axvspan(start, end, facecolor='g', alpha=0.25, label=my_label) </code></pre>
1
2016-10-04T16:15:56Z
[ "python", "matplotlib" ]
plot differently colored background rectangles on plot over several axes
39,857,170
<p>The following code is a snippet from a much larger function that plots several financial indicators over 3 axis:</p> <pre><code>left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axes background color ax1 = fig.add_axes(rect1)#, axisbg=axescolor) # left, bottom, width, height ax2 = fig.add_axes(rect2,sharex=ax1)#, axisbg=axescolor) ax3 = fig.add_axes(rect3,sharex=ax1)#, axisbg=axescolor </code></pre> <p>The final plot looks like that: </p> <p><a href="http://i.stack.imgur.com/AGRiF.png" rel="nofollow"><img src="http://i.stack.imgur.com/AGRiF.png" alt="enter image description here"></a></p> <p>Now I want to add background rectangles with a height that covers the complete x-axis (i.e. over all axis) and a width of several minutes, like that:</p> <p><a href="http://i.stack.imgur.com/WnqaK.png" rel="nofollow"><img src="http://i.stack.imgur.com/WnqaK.png" alt="enter image description here"></a></p> <p>How can I do that?</p>
0
2016-10-04T16:13:16Z
39,857,261
<p>You can use the <code>patches</code> from <code>matplotlib</code></p> <pre><code>import matplotlib.patches as patches left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axes background color ax1 = fig.add_axes(rect1)#, axisbg=axescolor) # left, bottom, width, height ax2 = fig.add_axes(rect2,sharex=ax1)#, axisbg=axescolor) ax3 = fig.add_axes(rect3,sharex=ax1)#, axisbg=axescolor ax1.add_patch(patches.Rectangle( (0.1, 0.1), # (x,y) 0.5, # width 0.5, # height alpha = 0.5)) #transparency </code></pre>
2
2016-10-04T16:18:17Z
[ "python", "matplotlib" ]
Use OrderedDict for SQLAlchemy relationship()?
39,857,194
<p>Is it possible to tell SQLAlchemy to use <code>OrderedDict</code> for the <code>relationship</code> storage? I'm only familiar with <code>attribute_mapped_collection</code>, but that's unordered.</p>
1
2016-10-04T16:14:53Z
39,859,765
<p>There's an <a href="http://docs.sqlalchemy.org/en/latest/orm/collections.html#custom-dictionary-based-collections" rel="nofollow">example</a> of this in the docs:</p> <pre><code>from sqlalchemy.util import OrderedDict from sqlalchemy.orm.collections import MappedCollection class NodeMap(OrderedDict, MappedCollection): """Holds 'Node' objects, keyed by the 'name' attribute with insert order maintained.""" def __init__(self, *args, **kw): MappedCollection.__init__(self, keyfunc=lambda node: node.name) OrderedDict.__init__(self, *args, **kw) </code></pre> <p>Usage is simply:</p> <pre><code>foo = relationship(..., collection_class=NodeMap) </code></pre>
3
2016-10-04T18:56:07Z
[ "python", "python-3.x", "sqlalchemy" ]
Email as Username in an existing django app
39,857,213
<p>I created an app where I used to require an <code>email</code> and a <code>username</code> for signup. </p> <p>Now I would like to change this so that any existing users have their username changed to their email. Any new users will not see the username field upon signup, but in the backend they'd be the same. </p> <p>I was thinking that I could just set the <code>max_length</code> to the length of email? Then in the backend, I could just set the username to the email when the user signs up. What am I missing here?</p>
0
2016-10-04T16:15:55Z
39,861,387
<p>You probably need to change the authentication backend and then change your models. More information can be found on the django documentation website: </p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/auth/customizing/</a></p>
4
2016-10-04T20:41:31Z
[ "python", "django" ]
sqlite3 update database with "?" - python
39,857,219
<p>I have: </p> <p>database testing.db3 table: mytable columns: 'name', 'status'</p> <p>I do:</p> <pre><code>con = sqlite3.connect('testing.db3') cur = con.cursor() cur.execute('select * from mytable where status is null') data = cur.fetchone() print(data[0]) </code></pre> <p>as wanted I receive following result:</p> <pre><code>('Johnny', 'None') </code></pre> <p>Now I am trying to update this line, it works if I do:</p> <pre><code>cur.execute('UPDATE mytable SET status = "Online" WHERE name is "Johnny"') </code></pre> <p>However if I want to update it with '?', it just doesn't work. Any idea why?</p> <pre><code>cur.execute('UPDATE mytable SET status = "Online" WHERE name is ?', data[0]) con.commit() con.close() </code></pre> <p>Would appreciate any help. Thank you.</p>
0
2016-10-04T16:16:05Z
39,857,448
<pre><code>cur.execute('UPDATE mytable SET status = "Online" WHERE name is ?', (data[0], )) </code></pre> <p><code>execute</code> expects a tuple as an input parameter. Therefore, even if you insert only a single value, you should format it as a tuple. </p> <p>Although in your question you say that <code>data[0] = ('Johnny', 'None')</code>, in the comments you indicate that <code>data[0]</code> is the first value of the tuple. So I assume the latter one is the case.</p>
2
2016-10-04T16:28:44Z
[ "python", "sql", "sqlite3", "insert" ]
Deleting a row if it contains a string in a CSV file
39,857,223
<p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p> <p>This is what the values in that column looks like:</p> <pre class="lang-none prettyprint-override"><code>Ship To or Bill To ------------------ 3000000092-BILL_TO 3000000092-SHIP_TO 3000004000_SHIP_TO-INAC-EIM </code></pre> <p>And there are 20 more columns and 50,000k plus rows. So essentially I'm trying to delete <strong>all</strong> the rows that contain strings <code>'INAC'</code> or <code>'EIM'</code>.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" remove_words = ['INAC','EIM'] with open(my_file_name, 'r', newline='') as infile, \ open(cleaned_file, 'w',newline='') as outfile: writer = csv.writer(outfile) for line in csv.reader(infile, delimiter='|'): if not any(remove_word in line for remove_word in remove_words): writer.writerow(line) </code></pre>
1
2016-10-04T16:16:17Z
39,857,616
<p>Each line output by the csv reader is a list of strings, not a string, so your list comprehension is checking if 'INAC' or 'EIM' is one of the members of the list, i.e:</p> <pre><code>'INAC' in ['3000004000_SHIP_TO-INAC-EIM', ...] </code></pre> <p>Which is always false, since 'in' looks for exact matches when called on a list. If you want to check whether the string is present anywhere in the line, you don't need a csv reader, and can instead use a normal open():</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" remove_words = ['INAC','EIM'] with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile: writer = csv.writer(outfile) for line in infile: if not any(remove_word in line for remove_word in remove_words): writer.writerow(line) </code></pre>
1
2016-10-04T16:39:58Z
[ "python", "python-3.x" ]
Deleting a row if it contains a string in a CSV file
39,857,223
<p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p> <p>This is what the values in that column looks like:</p> <pre class="lang-none prettyprint-override"><code>Ship To or Bill To ------------------ 3000000092-BILL_TO 3000000092-SHIP_TO 3000004000_SHIP_TO-INAC-EIM </code></pre> <p>And there are 20 more columns and 50,000k plus rows. So essentially I'm trying to delete <strong>all</strong> the rows that contain strings <code>'INAC'</code> or <code>'EIM'</code>.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" remove_words = ['INAC','EIM'] with open(my_file_name, 'r', newline='') as infile, \ open(cleaned_file, 'w',newline='') as outfile: writer = csv.writer(outfile) for line in csv.reader(infile, delimiter='|'): if not any(remove_word in line for remove_word in remove_words): writer.writerow(line) </code></pre>
1
2016-10-04T16:16:17Z
39,857,619
<p>The problem here is that the <code>csv.reader</code> object returns the rows of the file as lists of individual column values, so the "in" test is checking to see whether any of the individual values in that list is equal to a <code>remove_word</code>.</p> <p>A quick fix would be to try</p> <pre><code> if not any(remove_word in element for element in line for remove_word in remove_words): </code></pre> <p>because this will be true if any field in the line contains any of the <code>remove_words</code>.</p>
1
2016-10-04T16:40:16Z
[ "python", "python-3.x" ]
Deleting a row if it contains a string in a CSV file
39,857,223
<p>I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.</p> <p>This is what the values in that column looks like:</p> <pre class="lang-none prettyprint-override"><code>Ship To or Bill To ------------------ 3000000092-BILL_TO 3000000092-SHIP_TO 3000004000_SHIP_TO-INAC-EIM </code></pre> <p>And there are 20 more columns and 50,000k plus rows. So essentially I'm trying to delete <strong>all</strong> the rows that contain strings <code>'INAC'</code> or <code>'EIM'</code>.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file = "cleanNVG.csv" remove_words = ['INAC','EIM'] with open(my_file_name, 'r', newline='') as infile, \ open(cleaned_file, 'w',newline='') as outfile: writer = csv.writer(outfile) for line in csv.reader(infile, delimiter='|'): if not any(remove_word in line for remove_word in remove_words): writer.writerow(line) </code></pre>
1
2016-10-04T16:16:17Z
39,859,748
<p>As other answers have pointed out, the reason your code doesn't work is because each <code>line in csv.reader</code> is actually a list of column values, so the <code>remove_word in line</code> checks to see if any of them is exactly equal to one of the <code>remove_words</code> — which is apparently never <code>True</code>.</p> <p>If you only need to check for the words in one column there's no reason to check all of them. The following will only check one column's value and so should be significantly faster than checking all 20 or more of them in every row of your file.</p> <pre><code>import csv my_file_name = "NVG.txt" cleaned_file_name = "cleanNVG.csv" ONE_COLUMN = 1 remove_words = ['INAC', 'EIM'] with open(my_file_name, 'r', newline='') as infile, \ open(cleaned_file_name, 'w',newline='') as outfile: writer = csv.writer(outfile) for row in csv.reader(infile, delimiter='|'): column = row[ONE_COLUMN] if not any(remove_word in column for remove_word in remove_words): writer.writerow(row) </code></pre>
1
2016-10-04T18:55:08Z
[ "python", "python-3.x" ]
how to create a new variable in a loop
39,857,224
<p>I'm trying to make a function that prints n number of rows of the following sequence </p> <pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... </code></pre> <p>this is what I have so far:</p> <pre><code>def numTriangle(n): #n = number of rows integers = range(0,n-1) val = 1 places = 1 for num in integers: print val val = val + 1 </code></pre> <p>I've realized that I need to make a loop in which it prints the value, then adds one, but also creates a new variable that is one greater than the previous and prints the original value + 1 and the new variable and so on. How would I create a new variable for each line, or are there any other alternatives to this function, such as printing an additional part of the index for each row?</p>
0
2016-10-04T16:16:17Z
39,857,457
<p>Not trying to do your homework for you, but you at least have a basic description of your plan. Here is a pretty minimal version.</p> <pre><code>def pyramid(n): k = 1 for i in range(n): print ' '.join(map(str, range(k, k+i+1))) k += i + 1 </code></pre> <p>Here is a version that is more verbose.</p> <pre><code>def pyramid(n): k = 1 for i in range(1, n +1): first_number = k next_row_first_number = k + i numbers = range(first_number, next_row_first_number) numbers_as_strings = map(str, numbers) line = ' '.join(numbers_as_strings) print line k = next_row_first_number </code></pre> <p>And multiple loops!</p> <pre><code>def pyramid(n): k = 1 for i in range(1, n +1): first_number = k next_row_first_number = k + i numbers = range(first_number, next_row_first_number) line = "" for num in numbers: line = line + str(num) + ' ' print line k = next_row_first_number </code></pre>
1
2016-10-04T16:29:27Z
[ "python", "jes" ]
how to create a new variable in a loop
39,857,224
<p>I'm trying to make a function that prints n number of rows of the following sequence </p> <pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... </code></pre> <p>this is what I have so far:</p> <pre><code>def numTriangle(n): #n = number of rows integers = range(0,n-1) val = 1 places = 1 for num in integers: print val val = val + 1 </code></pre> <p>I've realized that I need to make a loop in which it prints the value, then adds one, but also creates a new variable that is one greater than the previous and prints the original value + 1 and the new variable and so on. How would I create a new variable for each line, or are there any other alternatives to this function, such as printing an additional part of the index for each row?</p>
0
2016-10-04T16:16:17Z
39,857,712
<p>This produces your output:</p> <pre><code>n = 6; y= 1; for i in range(0,n): for j in range (0,i): print y, y = y+1; print "\n" </code></pre> <p>Note the indentation, indentation defines the scopes.</p>
0
2016-10-04T16:45:48Z
[ "python", "jes" ]
How to remove a random element from a list and add it to another list in python
39,857,231
<p><code>list = ['john','james','michael','david','william']</code></p> <p><code>winner = []</code></p> <p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
0
2016-10-04T16:16:48Z
39,857,313
<p>This selects a random item from a list of names <code>names</code> and adds it to another list <code>winner</code>. The chosen winner is then removed from the <code>names</code>.</p> <pre><code>import random winner = [] names = ['john','james','michael','david','william'] winnerindex = random.randint(0,len(names)-1) winner.append(names[winnerindex]) del names[winnerindex] print winner, names </code></pre>
0
2016-10-04T16:21:05Z
[ "python", "list", "random-access" ]
How to remove a random element from a list and add it to another list in python
39,857,231
<p><code>list = ['john','james','michael','david','william']</code></p> <p><code>winner = []</code></p> <p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
0
2016-10-04T16:16:48Z
39,857,337
<p>Simply use random.randint from index 0 to len(list) to get the index of the element of list and append it to winner.</p> <pre><code>import random index = random.randomint(0, len(list)-1) winner.append(list[index]) del list[index] </code></pre>
-1
2016-10-04T16:22:42Z
[ "python", "list", "random-access" ]
How to remove a random element from a list and add it to another list in python
39,857,231
<p><code>list = ['john','james','michael','david','william']</code></p> <p><code>winner = []</code></p> <p>How can I remove a random item from <code>list</code> and add it to <code>winner</code>?</p>
0
2016-10-04T16:16:48Z
39,857,461
<pre><code>winner.append(list.pop(random.randrange(0,len(list)))) </code></pre> <p>To break this down:</p> <pre><code>random.randrange(0,len(list)) </code></pre> <p>will generate a random number between zero and the length of your list inclusive. This will generate a random index in your list that you can reference.</p> <pre><code>list.pop(i) </code></pre> <p>This will remove the item at the specified index (i) from your list.</p> <pre><code>winner.append(x) </code></pre> <p>This will add an item (x) to the end of the winner list. If you want to add the item at a specific index, you can use</p> <pre><code>winner.insert(i,x) </code></pre> <p>with i being the index to insert at and x being the value to insert.</p> <p>If you want more information, a good reference is the python docs on data structures: <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/2/tutorial/datastructures.html</a></p>
3
2016-10-04T16:29:38Z
[ "python", "list", "random-access" ]
Should I use Conda or Conda Forge when creating Anaconda Python environments?
39,857,289
<p>I understand that conda-forge was initiated to build and maintain packages. </p> <p>But when building Anaconda Python environments, how do we know when to use 'conda-forge' verses 'conda install' if a package exists in both repositories? Django for example can be installed with both 'conda install' and 'conda-forge'.</p> <p>Which one should we use? Does it matter?</p> <p>Can someone give me a very brief 'conda-forge for dummies' lesson? The docs are very scant.</p> <p>Thanks</p>
0
2016-10-04T16:19:58Z
39,862,730
<p>The short answer is that, in my experience generally, it doesn't matter which you use.</p> <p>The long answer:</p> <p>So <code>conda-forge</code> is an additional channel from which packages may be installed. In this sense, it is not any more special than the default channel, or any of the other hundreds (thousands?) of channels that people have posted packages to. You can add your own channel if you sign up at <a href="https://anaconda.org" rel="nofollow">https://anaconda.org</a> and upload your own Conda packages.</p> <p>Here we need to make the distinction, which I think you're not clear about from your phrasing in the question, between <code>conda</code>, the cross-platform package manager, and <code>conda-forge</code>, the package channel. Continuum IO, the main developers of the <code>conda</code> software also maintain a separate channel of packages, which is the default when you type <code>conda install packagename</code> without changing any options.</p> <p>There are two ways to change the options for channels. One is to specify a channel every time you install a package:</p> <pre><code>conda install -c some-channel packagename </code></pre> <p>Of course, the package has to exist on that channel. If you find yourself using the same channel often, then you might want to add it to your configuration. You can write</p> <pre><code>conda config --add channels some-channel </code></pre> <p>to add the channel <code>some-channel</code> to the top of the <code>channels</code> configuration list. This gives <code>some-channel</code> the highest priority (priority determines (<a href="http://conda.pydata.org/docs/channels.html" rel="nofollow">in part</a>) which channel is selected when more than one channel has a particular package). To add the channel to the end of the list and give it the lowest priority, type</p> <pre><code>conda config --append channels some-channel </code></pre> <p>With all of that said, there are three main reasons to use the <code>conda-forge</code> channel instead of the <code>defaults</code> channel maintained by Continuum:</p> <ol> <li>Packages on <code>conda-forge</code> <em>may</em> be more up-to-date than those on the <code>defaults</code> channel</li> <li>There are packages on the <code>conda-forge</code> channel that aren't available from <code>defaults</code></li> <li>You would prefer to use a dependency such as <code>openblas</code> (from <code>conda-forge</code>) instead of <code>mkl</code> (from <code>defaults</code>).</li> </ol>
1
2016-10-04T22:28:14Z
[ "python", "conda" ]
How save an string output after a for loop in python with pandas and csv modules?
39,857,297
<p>I have the following for loop:</p> <pre><code> for titles in titles: title = titles.xpath("a/text()").extract() link = titles.xpath("a/@href").extract() print(title, link) </code></pre> <p>How can I dump the title and link into a formmated .csv file?</p>
0
2016-10-04T16:20:14Z
39,857,380
<p>Use a <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv writer</a>.</p> <p>Basic usage:</p> <pre><code>import csv with open('file.csv') as f: writer = csv.writer(f) writer.writerow(["title", "link"]) </code></pre>
1
2016-10-04T16:25:00Z
[ "python", "python-3.x", "csv", "pandas" ]
How save an string output after a for loop in python with pandas and csv modules?
39,857,297
<p>I have the following for loop:</p> <pre><code> for titles in titles: title = titles.xpath("a/text()").extract() link = titles.xpath("a/@href").extract() print(title, link) </code></pre> <p>How can I dump the title and link into a formmated .csv file?</p>
0
2016-10-04T16:20:14Z
39,857,488
<p>You should use the python CSV module. Look here for more infromation, <a href="http://stackoverflow.com/questions/6916542/writing-list-of-strings-to-excel-csv-file-in-python">Writing List of Strings to Excel CSV File in Python</a>. Here is some example for your problem. </p> <pre><code>import csv results = [] # your code... also add this to your for loop. results.append([title, link]) csv_file = open("csv_file.csv",'wb') wr = csv.writer(csv_file) for row in results: wr.writerow(row) </code></pre>
3
2016-10-04T16:31:07Z
[ "python", "python-3.x", "csv", "pandas" ]
How save an string output after a for loop in python with pandas and csv modules?
39,857,297
<p>I have the following for loop:</p> <pre><code> for titles in titles: title = titles.xpath("a/text()").extract() link = titles.xpath("a/@href").extract() print(title, link) </code></pre> <p>How can I dump the title and link into a formmated .csv file?</p>
0
2016-10-04T16:20:14Z
39,857,501
<p>Something like this (<a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">documentation</a>): </p> <pre><code>... doc_path = "path/to/doc.csv" # must exist, first folder on the place # where you are running the script! with open(doc_path, 'a') as doc: for entry in titles: title = entry.xpath("a/text()").extract() link = entry.xpath("a/@href").extract() print(title, link) doc.write(str(title)+','+str(link)+'\n') </code></pre>
2
2016-10-04T16:31:47Z
[ "python", "python-3.x", "csv", "pandas" ]
How save an string output after a for loop in python with pandas and csv modules?
39,857,297
<p>I have the following for loop:</p> <pre><code> for titles in titles: title = titles.xpath("a/text()").extract() link = titles.xpath("a/@href").extract() print(title, link) </code></pre> <p>How can I dump the title and link into a formmated .csv file?</p>
0
2016-10-04T16:20:14Z
39,857,561
<pre><code>result = [] for titles in titles: title = titles.xpath("a/text()").extract() link = titles.xpath("a/@href").extract() print(title, link) result += [title + ',' + link + '\n'] with open("result.csv" "w+") as f: f.writelines(result) </code></pre>
1
2016-10-04T16:36:35Z
[ "python", "python-3.x", "csv", "pandas" ]
Creating pattern using simple loops?
39,857,341
<p>I am trying to create this pattern in python:</p> <pre><code> * * * * * * * * * </code></pre> <p>This is my program so far that I've come up with:</p> <pre><code>ster = "*" space = " " lines = 0 n = 3 x = 1 while lines &lt;= 5: print space*n, ster*x n-= 1 x+= 1 lines += 1 </code></pre> <p>What am I doing wrong?</p>
-2
2016-10-04T16:22:52Z
39,857,587
<p>Okay, first of all you can create a list of numbers which represents the number of stars in each line.</p> <pre><code>number_of_stars = 5 i_list = list(range(number_of_stars)) # extend the list by its inverse i_list[::-1] # but exclude the first item i_list.extend(i_list[::-1][1:]) print(i_list) # prints: [0, 1, 2, 3, 4, 3, 2, 1, 0] </code></pre> <p>Now you can go thru the list and print a multiple of <code>*</code></p> <pre><code>for i in i_list: print('* ' * i) </code></pre> <p>But this is not aligned properly. By adding multiple empty spaces to the left one can archive a solution:</p> <pre><code>for i in i_list: print(' ' * (number_of_stars - i) + '* ' * i) </code></pre> <p>Note that in python one can repeat a string by using the multiplication symbol:</p> <pre><code>print('a'*5) # prints: aaaaa </code></pre>
2
2016-10-04T16:38:20Z
[ "python", "python-2.7", "loops" ]
Creating pattern using simple loops?
39,857,341
<p>I am trying to create this pattern in python:</p> <pre><code> * * * * * * * * * </code></pre> <p>This is my program so far that I've come up with:</p> <pre><code>ster = "*" space = " " lines = 0 n = 3 x = 1 while lines &lt;= 5: print space*n, ster*x n-= 1 x+= 1 lines += 1 </code></pre> <p>What am I doing wrong?</p>
-2
2016-10-04T16:22:52Z
39,857,626
<p>Notice you have</p> <ul> <li>3 spaces for 1 star</li> <li>2 spaces for 2 stars</li> <li>1 space for 3 stars.</li> </ul> <p>For the upright triangle part of your diamond (including the large part). Then you have</p> <ul> <li>2 spaces for 2 stars</li> <li>3 spaces for 1 star</li> </ul> <p>Without throwing out the answer, try analysing a certain pattern in what i've just pointed out. It can be achieved with 2 loops ( for or while, depending on your preference).</p>
1
2016-10-04T16:40:43Z
[ "python", "python-2.7", "loops" ]
Creating pattern using simple loops?
39,857,341
<p>I am trying to create this pattern in python:</p> <pre><code> * * * * * * * * * </code></pre> <p>This is my program so far that I've come up with:</p> <pre><code>ster = "*" space = " " lines = 0 n = 3 x = 1 while lines &lt;= 5: print space*n, ster*x n-= 1 x+= 1 lines += 1 </code></pre> <p>What am I doing wrong?</p>
-2
2016-10-04T16:22:52Z
39,857,692
<p>Thank you for the help, I wrote a functional code for the problem. It was supposed to made using while loop(s). This is what I did:</p> <pre><code>width = int(input("Width: ")) i = 1 while i &lt; width*2: if i &lt; width: print " " * (width-i) + "* " * i else: print " " * (i-width) + "* " * (2*width-i) i = i + 1 </code></pre>
2
2016-10-04T16:44:48Z
[ "python", "python-2.7", "loops" ]
Pandas - Selecting multiple dataframe criteria
39,857,428
<p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete'] </code></pre> <p>But I'm struggling to specify values from two columns. I've tried something like this but get errors:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete' and df['READY TO INVOICE'] == 'No'] </code></pre> <p>It may be a simple answer, but any help is appreciated.</p>
1
2016-10-04T16:28:05Z
39,857,462
<pre><code>status_filter = df.ix[(df['STATUS'] == 'Complete') &amp; (df['READY TO INVOICE'] == 'No'),] </code></pre> <p>ur welcome</p>
1
2016-10-04T16:29:41Z
[ "python", "pandas", "dataframe" ]
Pandas - Selecting multiple dataframe criteria
39,857,428
<p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete'] </code></pre> <p>But I'm struggling to specify values from two columns. I've tried something like this but get errors:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete' and df['READY TO INVOICE'] == 'No'] </code></pre> <p>It may be a simple answer, but any help is appreciated.</p>
1
2016-10-04T16:28:05Z
39,857,531
<p>you can use:</p> <pre><code>status_filter = df[(df['STATUS'] == 'Complete') &amp; (df['READY TO INVOICE'] == 'No')] </code></pre>
0
2016-10-04T16:34:07Z
[ "python", "pandas", "dataframe" ]
Pandas - Selecting multiple dataframe criteria
39,857,428
<p>I have a DataFrame with multiple columns and I need to set the criteria to access specific values from two different columns. I'm able to do it successfully on one column as shown here:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete'] </code></pre> <p>But I'm struggling to specify values from two columns. I've tried something like this but get errors:</p> <pre><code>status_filter = df[df['STATUS'] == 'Complete' and df['READY TO INVOICE'] == 'No'] </code></pre> <p>It may be a simple answer, but any help is appreciated.</p>
1
2016-10-04T16:28:05Z
39,857,722
<p>Your code has two very small errors: 1) need parentheses for two or more criteria and 2) you need to use the ampersand between your criteria:</p> <pre><code>status_filter = df[(df['STATUS'] == 'Complete') &amp; (df['READY TO INVOICE'] == 'No')] </code></pre>
4
2016-10-04T16:46:28Z
[ "python", "pandas", "dataframe" ]
Repeated regex groups of arbitrary number
39,857,497
<p>I have this example text snippet</p> <pre><code>headline: Status[apphmi]: blubb, 'Statustext1' Main[apphmi]: bla, 'Maintext1'Main[apphmi]: blaa, 'Maintext2' Popup[apphmi]: blaaa, 'Popuptext1' </code></pre> <p>and I want to extract the words within '', but sorted with the context (status, main, popup). </p> <p>My current regex is (<a href="http://pythex.org/?regex=headline%3A(%3F%3A%5Cn%20%2BStatus%5C%5Bapphmi%5C%5D%3A.*%20%27(.*)%27)*(%3F%3A%5Cn%20%2BMain%5C%5Bapphmi%5C%5D%3A.*%20%27(.*)%27)*(%3F%3A%5Cn%20%2BPopup%5C%5Bapphmi%5C%5D%3A.*%20%27(.*)%27)*&amp;test_string=headline%3A%0A%20%20%20%20Status%5Bapphmi%5D%3A%20blubb%2C%20%27Statustext%27%0A%20%20%20%20Main%5Bapphmi%5D%3A%20bla%2C%20%27Maintext1%27Main%5Bapphmi%5D%3A%20blaa%2C%20%27Maintext2%27%0A%20%20%20%20Popup%5Bapphmi%5D%3A%20blaaa%2C%20%27Popuptext%27%20%5Bpuff%5D%0A&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofollow">example at pythex.org</a>):</p> <pre><code>headline:(?:\n +Status\[apphmi\]:.* '(.*)')*(?:\n +Main\[apphmi\]:.* '(.*)')*(?:\n +Popup\[apphmi\]:.* '(.*)')* </code></pre> <p>but with this I only get 'Maintext2' and not both. I don't know how to repeat the groups to an arbitrary number. </p>
0
2016-10-04T16:31:42Z
39,857,790
<p>You can try with this:</p> <pre><code>r"(.*?]):(?:[^']*)'([^']*)'"g </code></pre> <p><a href="http://pythex.org/?regex=(.*%3F%5D)%3A(%3F%3A%5B%5E%27%5D*)%27(%5B%5E%27%5D*)%27&amp;test_string=headline%3A%0A%20%20%20%20Status%5Bapphmi%5D%3A%20blubb%2C%20%27Statustext%27%0A%20%20%20%20Main%5Bapphmi%5D%3A%20bla%2C%20%27Maintext1%27Main%5Bapphmi%5D%3A%20blaa%2C%20%27Maintext2%27%0A%20%20%20%20Popup%5Bapphmi%5D%3A%20blaaa%2C%20%27Popuptext%27%20%5Bpuff%5D%0A&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofollow">Look here</a> Group1 and Group 2 for each match contains your key value pair</p> <p>You can not merge the second match as one by using regex, once you get all the pairs... you can apply some programming here to merge duplicate keys as one.</p> <p>Here I have used dictionary of list, if a key already exists in the dictionary then you should append the value to the list , otherwise insert a new key with a new list having the value.</p> <p><a href="https://repl.it/DoHw" rel="nofollow">This is how it should be done (tested in python 3+)</a></p> <pre><code>import re d = dict() regex = r"(.*?]):(?:[^']*)'([^']*)'" test_str = ("headline: \n" "Status[apphmi]: blubb, 'Statustext1'\n" "Main[apphmi]: bla, 'Maintext1'Main[apphmi]: blaa, 'Maintext2'\n" "Popup[apphmi]: blaaa, 'Popuptext1'") matches = re.finditer(regex, test_str) for matchNum, match in enumerate(matches): if match.group(1) in d: d[match.group(1)].append(match.group(2)) else: d[match.group(1)] = [match.group(2),] print(d) </code></pre> <p><strong>Output:</strong></p> <pre><code>{ 'Popup[apphmi]': ['Popuptext1'], 'Main[apphmi]': ['Maintext1', 'Maintext2'], 'Status[apphmi]': ['Statustext1'] } </code></pre>
0
2016-10-04T16:51:13Z
[ "python", "regex" ]
Google App Engine urlfetch DeadlineExceededError in push task handler running apiclient batch request
39,857,515
<p>I have a task handler that is making a batch request to the Google Calendar API. After 5 seconds, the request fails with <em>DeadlineExceededError: The API call urlfetch.Fetch() took too long to respond and was cancelled.</em> I have changed <code>urlfetch.set_default_fetch_deadline(60)</code> near where I make the batch request, as suggested <a href="http://stackoverflow.com/questions/13051628/gae-appengine-deadlineexceedederror-deadline-exceeded-while-waiting-for-htt">here</a> but it does not seem to make a difference: the deadline seems to remain 5 seconds.</p> <p>I am using the Python Google API Client library which sits on top of oauth2client and httplib2. But my understanding is that GAE intercepts the underlying calls to use urlfetch.Fetch. This is what the stack trace seems to show as well. </p> <p>Can you see any reason why <code>urlfetch.set_default_fetch_deadline</code> does not seem to be working?</p> <h2>EDIT:</h2> <p>This is the code used to build the batch request:</p> <pre><code># note `http` is a oauth2client authorized http client cal = apiclient.discovery.build('calendar','v3',http=http) req = cal.new_batch_http_request(callback=_callback) for event in events: # anything larger than ~5 events in batch takes &gt;5 secs req.add( cal.events().patch(calendarId=calid, eventId=event["id"], body=self._value) ) urlfetch.set_default_fetch_deadline(60) # has no effect req.execute() </code></pre>
2
2016-10-04T16:32:42Z
39,860,394
<p>Try adding the <code>deadline</code> parameter:</p> <p><code>my_result = urlfetch.fetch(my_url, deadline=15)</code></p>
0
2016-10-04T19:35:36Z
[ "python", "google-app-engine", "google-api", "google-calendar", "task-queue" ]
Google App Engine urlfetch DeadlineExceededError in push task handler running apiclient batch request
39,857,515
<p>I have a task handler that is making a batch request to the Google Calendar API. After 5 seconds, the request fails with <em>DeadlineExceededError: The API call urlfetch.Fetch() took too long to respond and was cancelled.</em> I have changed <code>urlfetch.set_default_fetch_deadline(60)</code> near where I make the batch request, as suggested <a href="http://stackoverflow.com/questions/13051628/gae-appengine-deadlineexceedederror-deadline-exceeded-while-waiting-for-htt">here</a> but it does not seem to make a difference: the deadline seems to remain 5 seconds.</p> <p>I am using the Python Google API Client library which sits on top of oauth2client and httplib2. But my understanding is that GAE intercepts the underlying calls to use urlfetch.Fetch. This is what the stack trace seems to show as well. </p> <p>Can you see any reason why <code>urlfetch.set_default_fetch_deadline</code> does not seem to be working?</p> <h2>EDIT:</h2> <p>This is the code used to build the batch request:</p> <pre><code># note `http` is a oauth2client authorized http client cal = apiclient.discovery.build('calendar','v3',http=http) req = cal.new_batch_http_request(callback=_callback) for event in events: # anything larger than ~5 events in batch takes &gt;5 secs req.add( cal.events().patch(calendarId=calid, eventId=event["id"], body=self._value) ) urlfetch.set_default_fetch_deadline(60) # has no effect req.execute() </code></pre>
2
2016-10-04T16:32:42Z
39,865,233
<p>So, <code>urlfetch.set_default_fetch_deadline()</code> did eventually work for me. The problem was my underlying http client (oauth2client / httplib2) was essentially stored in a global. Once I created it in the task handler thread the <code>set_default_fetch_deadline</code> worked.</p>
1
2016-10-05T04:01:53Z
[ "python", "google-app-engine", "google-api", "google-calendar", "task-queue" ]
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error
39,857,608
<p>Everytime I enter a value such as 002 the length comes out as 1 however it should come out as 3 My code is:</p> <pre><code>list1 = int(input("Enter a number")) list1 = [int(x) for x in str(list1)] print (len(list1)) </code></pre> <p>If I type in a number after a space I get an error saying:</p> <pre><code>File "C:\\practice11.py", line 2, in &lt;module&gt; list1 = [int(x) for x in text] File "C:\\practice11.py", line 2, in &lt;listcomp&gt; list1 = [int(x) for x in text] </code></pre> <p>ValueError: invalid literal for int() with base 10: ' '</p>
1
2016-10-04T16:39:17Z
39,857,647
<p>Don't convert your input to a int. If you convert your the string <code>002</code> to a int, the leading zeros are gone, because <code>002</code> is the same number as <code>2</code>. Converting to string again leads to <code>2</code>, which only has a length of 1.</p> <pre><code>text = input("Enter a number") list1 = [int(x) for x in text] print(len(list1)) </code></pre>
3
2016-10-04T16:41:38Z
[ "python" ]
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error
39,857,608
<p>Everytime I enter a value such as 002 the length comes out as 1 however it should come out as 3 My code is:</p> <pre><code>list1 = int(input("Enter a number")) list1 = [int(x) for x in str(list1)] print (len(list1)) </code></pre> <p>If I type in a number after a space I get an error saying:</p> <pre><code>File "C:\\practice11.py", line 2, in &lt;module&gt; list1 = [int(x) for x in text] File "C:\\practice11.py", line 2, in &lt;listcomp&gt; list1 = [int(x) for x in text] </code></pre> <p>ValueError: invalid literal for int() with base 10: ' '</p>
1
2016-10-04T16:39:17Z
39,857,673
<p>You're casting the input to an integer with <code>int</code>, so you're removing trailing zeroes. Integers don't preserve their trailing zeroes, so when converted it becomes a single digit:</p> <pre><code>int("002") # 2 </code></pre> <p>You should remove the first int call, save it as a string until you split it up in the list comprehension:</p> <pre><code>list1 = input("Enter a number") list1 = [int(x) for x in str(list1)] print (len(list1)) # 3 </code></pre>
0
2016-10-04T16:43:51Z
[ "python" ]
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error
39,857,608
<p>Everytime I enter a value such as 002 the length comes out as 1 however it should come out as 3 My code is:</p> <pre><code>list1 = int(input("Enter a number")) list1 = [int(x) for x in str(list1)] print (len(list1)) </code></pre> <p>If I type in a number after a space I get an error saying:</p> <pre><code>File "C:\\practice11.py", line 2, in &lt;module&gt; list1 = [int(x) for x in text] File "C:\\practice11.py", line 2, in &lt;listcomp&gt; list1 = [int(x) for x in text] </code></pre> <p>ValueError: invalid literal for int() with base 10: ' '</p>
1
2016-10-04T16:39:17Z
39,857,675
<p>Because you cast the user input <code>"002"</code> to an int with value <code>2</code>. Then, in your list comprehension you cast it back to a string <code>"2"</code>, over which you iterate (once). </p> <p>The result of your list comprehension is thus <code>["2"]</code>, a list of length 1.</p> <p>So instead of casting back and forth you could:</p> <pre><code>list1 = [int(x) for x in input("Enter a number")] </code></pre> <p>Which will give you <code>list1 = [0, 0, 2]</code>, a list of integers with a total length of 3. </p>
0
2016-10-04T16:43:54Z
[ "python" ]
How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error
39,857,608
<p>Everytime I enter a value such as 002 the length comes out as 1 however it should come out as 3 My code is:</p> <pre><code>list1 = int(input("Enter a number")) list1 = [int(x) for x in str(list1)] print (len(list1)) </code></pre> <p>If I type in a number after a space I get an error saying:</p> <pre><code>File "C:\\practice11.py", line 2, in &lt;module&gt; list1 = [int(x) for x in text] File "C:\\practice11.py", line 2, in &lt;listcomp&gt; list1 = [int(x) for x in text] </code></pre> <p>ValueError: invalid literal for int() with base 10: ' '</p>
1
2016-10-04T16:39:17Z
39,857,685
<p>If you do:</p> <pre><code>s = "002" i = int(s) print(i) </code></pre> <p>outputs</p> <pre><code>2 </code></pre> <p>because leading 0 are dropped during the casting to int. As a matter of fact,</p> <pre><code>i = 002 </code></pre> <p>is illegal and yields</p> <pre><code>SyntaxError: invalid token </code></pre> <p>So you can't go <code>string &gt; int &gt; string</code> to count the characters, why not doing this instead:</p> <pre><code>s = input("Enter a number") print (len(s)) </code></pre>
0
2016-10-04T16:44:13Z
[ "python" ]
Fastest Method To Read Thousands of JSON Files in Python
39,857,632
<p>I have a number of JSON files I need to analyze. I am using iPython (<code>Python 3.5.2 | IPython 5.0.0</code>), reading in the files to a dictionary and appending each dictionary to a list.</p> <p>My main bottleneck is reading in the files. Some files are smaller, and are read quickly, but the larger files are slowing me down.</p> <p>Here is some example code (sorry, I cannot provide the actual data files):</p> <pre><code>import json import glob def read_json_files(path_to_file): with open(path_to_file) as p: data = json.load(p) p.close() return data def giant_list(json_files): data_list = [] for f in json_files: data_list.append(read_json_files(f)) return data_list support_files = glob.glob('/Users/path/to/support_tickets_*.json') small_file_test = giant_list(support_files) event_files = glob.glob('/Users/path/to/google_analytics_data_*.json') large_file_test = giant_list(event_files) </code></pre> <p>The support tickets are very small in size--largest I've seen is 6KB. So, this code runs pretty fast:</p> <pre><code>In [3]: len(support_files) Out[3]: 5278 In [5]: %timeit giant_list(support_files) 1 loop, best of 3: 557 ms per loop </code></pre> <p>But larger files definitely are slowing me down...these event files can reach ~2.5MB each:</p> <pre><code>In [7]: len(event_files) # there will be a lot more of these soon :-/ Out[7]: 397 In [8]: %timeit giant_list(event_files) 1 loop, best of 3: 14.2 s per loop </code></pre> <p>I've researched how to speed up the process and came across <a href="http://stackoverflow.com/questions/706101/python-json-decoding-performance">this post</a>, however, when using UltraJSON the timing was just slightly worse:</p> <pre><code>In [3]: %timeit giant_list(traffic_files) 1 loop, best of 3: 16.3 s per loop </code></pre> <p>SimpleJSON did not do much better: </p> <pre><code>In [4]: %timeit giant_list(traffic_files) 1 loop, best of 3: 16.3 s per loop </code></pre> <p>Any tips on how to optimize this code and more efficiently read a lot of JSON files into Python is much appreciated.</p> <p>Finally, <a href="http://stackoverflow.com/questions/39781716/loading-large-twitter-json-data-7gb-into-python">this post</a> is the closest I've found to my question, but deals with one giant JSON file, not many smaller sized ones.</p>
1
2016-10-04T16:41:00Z
39,857,750
<p>Use list comprehension to avoid resizing list multiple times.</p> <pre><code>def giant_list(json_files): return [read_json_file(path) for path in json_files] </code></pre> <p>You are closing file object twice, simply do it once (on exiting <code>with</code> file would be closed automatically)</p> <pre><code>def read_json_file(path_to_file): with open(path_to_file) as p: return json.load(p) </code></pre> <p>At the end of the day, your problem is I/O bound, but these changes will help a little bit. Also, I have to ask - do you really have to have all these dictionaries in the memory at the same time?</p>
1
2016-10-04T16:48:40Z
[ "python", "json", "python-3.x", "ipython" ]
Python array_flip analogue or best way to do this?
39,857,691
<p>Is there array_flip (php) analogue for Python 3.x? </p> <p>from</p> <pre><code>obj = ['a', 'c', 'b' ] </code></pre> <p>to </p> <pre><code>{'a': 1, 'c':2, 'b': 3} </code></pre>
2
2016-10-04T16:44:48Z
39,857,729
<p>You can use a list comprehension along with the <code>dict</code> constructor, as follows:</p> <pre><code>&gt;&gt;&gt; obj = [ 'a', 'c', 'b' ] &gt;&gt;&gt; dict((x, i + 1) for i, x in enumerate(obj)) {'a': 1, 'c': 2, 'b': 3} </code></pre> <p>As noted in the comments, you can also use a simple dict comprehension:</p> <pre><code>&gt;&gt;&gt; { x: i + 1 for i, x in enumerate(obj) } {'a': 1, 'c': 2, 'b': 3} </code></pre>
1
2016-10-04T16:47:07Z
[ "python", "sorting" ]
error: list indices must be indtegers, not str
39,857,717
<pre><code>fields = ["date", "time", "a_x", "a_y", "a_z", "roll", "pitch", "yaw", "ug_x", "ug_y", "ug_z", "o2", "hyd", "bpm"] import csv f = open("data.TXT") dialect = csv.Sniffer().sniff(f.read(), delimiters=' ') f.seek(0) reader = csv.reader(f, dialect) rows = [] obj = {} for row in reader: for i, field in enumerate(fields): obj[field] = row[i] if field == "a_x": obj[field] = float(row[i]) elif field == "a_y": obj[field] = float(row[i]) elif field == "a_z": obj[field] = float(row[i]) elif field == "roll": obj[field] = float(row[i]) elif field == "pitch": obj[field] = float(row[i]) elif field == "yaw": obj[field] = float(row[i]) elif field == "ug_x": obj[field] = float(row[i]) elif field == "ug_y": obj[field] = float(row[i]) elif field == "ug_z": obj[field] = float(row[i]) elif field == "o2": obj[field] = int(row[i]) elif field == "hyd": obj[field] = int(row[i]) elif field == "bpm": obj[field] = int(row[i]) else: obj[field] = str(row[i]) rows.append(obj) import requests requests.get("http://localhost:5000/api/players") for obj in rows: # *** Here is the error *** row["player_id"] = ['03fd6907-64fc-46e7-b1f2-38af96c48037'] requests.post("http://localhost:5000/api/impact") </code></pre> <p>The error occurs in the second to last line of code, as indicated by a comment. The code is intended to upload information from a text file to a database, changing the data types match a schema written in a separate file.</p> <p>I am not sure of the source of the error in line 56, that the list indices must be integers, not str, or how to fix it.</p>
-1
2016-10-04T16:46:19Z
39,857,813
<pre><code>for obj in rows: row["player_id"] = ['03fd6907-64fc-46e7-b1f2-38af96c48037'] </code></pre> <p>The loop variable is called <code>obj</code> but you are trying to access <code>row</code>. <code>row</code> is a list left over from a previous loop (<code>for row in reader:</code>). Change <code>row</code> to <code>obj</code> and the problem should go away:</p> <pre><code>for obj in rows: obj["player_id"] = ['03fd6907-64fc-46e7-b1f2-38af96c48037'] </code></pre> <p>Also, it is a bug to define <code>obj = {}</code> outside of the <code>for row in reader</code> loop. You will keep mutating the same dictionary and all <code>obj</code> in <code>rows</code> will be identical because they will all be references to the same object. </p> <p>I would rewrite that loop as:</p> <pre><code>float_fields = {'a_x', 'a_y', 'a_z', 'roll', 'pitch', 'yaw', 'ug_x', 'ug_y', 'ug_z'} int_fields = {'o2', 'hyd', 'bpm'} for row in reader: obj = {} # moved inside loop for item, fieldname in zip(row, fields): if fieldname in float_fields: obj[fieldname] = float(item) elif fieldname in int_fields: obj[fieldname] = int(item) else: obj[fieldname] = str(item) rows.append(obj) </code></pre>
2
2016-10-04T16:52:27Z
[ "python", "database", "mongodb", "csv" ]
Fetch HTML From URL in Python
39,857,757
<p>I am trying to read the <code>HTML</code> contents of a <code>URL</code> with <code>Python</code>. To fetch the <code>HTML</code> contents of a <code>URL</code>, would I use the module <code>wget</code>, <code>urllib</code> or a different module entirely? </p> <p>After Answers: I will use the <code>urllib</code> module since that comes with the default Python 2.7 build, and I can't download external modules from this computer.</p> <p>List of Modules That Fetch URL Contents:</p> <pre><code>Wget Beautiful Soup Urllib Requests </code></pre>
-1
2016-10-04T16:48:58Z
39,857,894
<p>Here is a sample to get you started with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p> <pre><code>import requests resp = requests.get('http://httpbin.org/get') if resp.ok: print (resp.text) else: print ("Boo! {}".format(resp.status_code)) print (resp.text) </code></pre>
2
2016-10-04T16:57:42Z
[ "python", "html", "url" ]
use asyncio update some data timely and present via aiohttp?
39,857,796
<p>I am in trying to write a snippet to study Python asyncio. The basic idea is:</p> <ol> <li><p>use a "simple" web server (aiohttp) to present some data to user </p></li> <li><p>the data return to user will change promptly</p></li> </ol> <p>here is the code:</p> <pre><code>import asyncio import random from aiohttp import web userfeed = [] # the data suppose to return to the user via web browsers async def data_updater(): #to simulate data change promptly while True: await asyncio.sleep(3) userfeed = [x for x in range(random.randint(1, 20))] print('user date updated: ', userfeed) async def web_handle(request): text = str(userfeed) #print('in handler:', text) # why text is empty? return web.Response(text=text) async def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/', web_handle) srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000) print('Server started @ http://127.0.0.1:8000...') return srv loop = asyncio.get_event_loop() asyncio.ensure_future(data_updater()) asyncio.ensure_future(init(loop)) loop.run_forever() </code></pre> <p>the problem is, the code is running (python 3.5), but the <code>userfeed</code> is always empty in browsers and also in <code>web_handler()</code> :-(</p> <ol> <li>why <code>userfeed</code> is not been updated?</li> <li>regarding this <code>timely date update</code> function, because the update mechanism might be more complex later say async IO wait may be involved, is there a better way instead of using <code>while True: await asyncio.sleep(3)</code> in <code>data_updater()</code> to get "more roughly precise" timer? </li> </ol>
2
2016-10-04T16:51:40Z
39,859,949
<p>The main problem is that you forget the statement <code>global userfeed</code> in both <code>data_updater</code> and <code>web_handle</code> functions. So, according to <a href="http://stackoverflow.com/a/292502/5050917">how python resolves scopes</a>, in <code>web_handle</code> it was referring to the global variable you defined and in <code>data_updater</code> to a local one, created by the statement <code>userfeed = [x for x ...</code>. Using global variables in this context is explicitly <a href="http://aiohttp.readthedocs.io/en/stable/web.html#data-sharing-aka-no-singletons-please" rel="nofollow">discouraged</a> so there is an example using the <code>dict</code> interface of the <code>aiohttp.web.Application</code> object to safely refer to your variable between the functions.</p> <pre><code>import asyncio import random from aiohttp import web async def data_updater(app): while True: await asyncio.sleep(3) app["userfeed"] = [x for x in range(random.randint(1, 20))] async def web_handle(request): userfeed = request.app["userfeed"] return web.Response(text=str(userfeed)) async def init(loop, port=8000): app = web.Application(loop=loop) app.router.add_route('GET', '/', web_handle) handler = app.make_handler() srv = await loop.create_server( handler, '127.0.0.1', port=port) return srv, app, handler if __name__ == "__main__": loop = asyncio.get_event_loop() srv, app, handler = loop.run_until_complete(init(loop, 8000)) app['userfeed'] = [] asyncio.ensure_future(data_updater(app)) try: loop.run_forever() except KeyboardInterrupt: pass finally: srv.close() loop.run_until_complete(srv.wait_closed()) loop.run_until_complete(app.shutdown()) loop.run_until_complete(handler.finish_connections(60.0)) loop.run_until_complete(app.cleanup()) loop.close() </code></pre> <p>When you refresh the page on <code>127.0.0.1:8000</code> you should have some new random numbers as they are updated every 3 seconds server-side (you can put back the <code>print</code> statement in <code>data_updater</code> to verify it).</p>
1
2016-10-04T19:08:17Z
[ "python", "python-asyncio", "aiohttp" ]
how to pass elements in a list to a function in a for-loop
39,857,807
<p>I'm trying to print the pressure of each city. </p> <p>Instead of using the cities in the list, it is returning the pressure of a city called 'city'. </p> <p>Super new to this and can't find an answer to something this specific. thanks!!!!!!</p> <pre><code>import pyowm owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff') city = ["tokyo", "jakarta"] for i in city: city = owm.weather_at_place('city') city = city.get_weather() print (city.get_pressure()['press']) </code></pre>
0
2016-10-04T16:52:19Z
39,857,939
<p>Use better names and things will become clearer:</p> <pre><code>import pyowm owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff') cities = ["tokyo", "jakarta"] for city in cities: weather = owm.weather_at_place(city).get_weather() print (weather.get_pressure()['press']) </code></pre> <p>Changes and rationales:</p> <ul> <li>Changed the list of cities from <code>city</code> to <code>cities</code>. A variable named <code>city</code> should contain a city. Not a list of them.</li> <li>Changed the iteration variable used by the <code>for</code> loop to <code>city</code> because that is what will be in the variable: the name of one city. <code>i</code> is a poor name because you'd expect it to be an index, not the item, and Python <code>for</code> loops don't work that way. See how nicely <code>for city in cities</code> expresses what is actually happening?</li> <li>Changed the call to <code>weather_at_place()</code> to use the <em>variable</em> <code>city</code> (a city from the list) rather than the constant string <code>"city"</code>, as the latter would search for a city <em>named City.</em></li> <li>Chained the calls to <code>weather_at_place()</code> and <code>get_weather()</code> rather than using <code>city</code> to hold the value returned by the former, because the intermediate value is never used. Also eliminates the use of the variable <code>city</code> for something else that is not a city.</li> <li>Changed the variable that contains the result of <code>get_weather()</code> to <code>weather</code> from <code>city</code> because it contains the weather, not the city.</li> </ul> <p>Readability is important, even (especially!) when the person reading the code is the one who wrote it. If you're getting confused <em>now,</em> writing the code for the first time, imagine how confused you'll be when you try to modify the code in six months!</p>
2
2016-10-04T17:00:39Z
[ "python", "for-loop" ]
how to pass elements in a list to a function in a for-loop
39,857,807
<p>I'm trying to print the pressure of each city. </p> <p>Instead of using the cities in the list, it is returning the pressure of a city called 'city'. </p> <p>Super new to this and can't find an answer to something this specific. thanks!!!!!!</p> <pre><code>import pyowm owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff') city = ["tokyo", "jakarta"] for i in city: city = owm.weather_at_place('city') city = city.get_weather() print (city.get_pressure()['press']) </code></pre>
0
2016-10-04T16:52:19Z
39,858,097
<p>Hanley, I hope you don't mind I rewrote your code.</p> <pre><code>import pyowm owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff') cities = ["tokyo", "jakarta"] for city in cities: city_weather = owm.weather_at_place(city) weather = city_weather.get_weather() print(weather.get_pressure()['press']) </code></pre>
0
2016-10-04T17:11:06Z
[ "python", "for-loop" ]
Combine multiple json merging duplicates and adding values for a specific key in python
39,857,854
<p>I've looked around for a method to do this, but I can only find bits and pieces and keep getting stuck. I want to add two sets of json, retaining all properties but adding the <code>total</code> value if a duplicate <code>owner</code> value exists.</p> <pre><code>json1 = [{"total":101,"owner":"User1","type":8,"team":"Team1"}, {"total":44,"owner":"User2","type":8,"team":"Team1"}, {"total":22,"owner":"User3","type":8,"team":"Team2"}] json2 = [{"total":12,"owner":"User1","type":8,"team":"Team1"}, {"total":33,"owner":"User3","type":8,"team":"Team2"}, {"total":18,"owner":"User4","type":8,"team":"Team1"}] </code></pre> <p>I want to have the output look like this</p> <pre><code>finaljson = [{"total":113,"owner":"User1","type":8,"team":"Team1"}, {"total":44,"owner":"User2","type":8,"team":"Team1"}, {"total":55,"owner":"User3","type":8,"team":"Team2"}, {"total":18,"owner":"User4","type":8,"team":"Team1"}] </code></pre> <p>Alternatively, how would I reach my final <code>finaljson</code> if I had a single json set and wanted to find duplicate <code>owner</code> and merge <code>total</code> the same as above.</p> <p><code>mergedjson = json1.extend(json2)</code> becomes <code>finaljson</code></p> <p>Thanks!</p>
0
2016-10-04T16:54:49Z
39,859,286
<p>Try this, although this wont be the best solution.</p> <pre><code>def merge_json(json1, json2): data = {} for val in json1+json2: key = val["owner"] if key in data: data[key]['total'] = data[key]['total']+val['total'] else: data[key] = val return list(data.values()) </code></pre> <p><strong><a href="https://repl.it/DoKf" rel="nofollow">DEMO</a></strong></p>
0
2016-10-04T18:25:52Z
[ "python", "json", "merge" ]
Get Deferred from dbpool.runQuery instead of data with Twisted and Oracle
39,857,898
<p>I am trying to get some data from Oracle, using Twisted and runQuery and keep getting Deferred instead of actual data. How can this be solved? Some code (I excluded some unnecessary parts, but the idea should be clear):</p> <pre><code>from twisted.enterprise import adbapi from twisted.internet import defer import service_config ORACLE_DSN = service_config.oracle_dsn ORACLE_USER = service_config.oracle_user ORACLE_PASSWORD = service_config.oracle_password dbpool = adbapi.ConnectionPool('cx_Oracle', user=ORACLE_USER, password=ORACLE_PASSWORD, dsn=ORACLE_DSN, port='49161') @defer.inlineCallbacks def ask_db(): data = yield dbpool.runQuery("SELECT * FROM customer") a = ask_db() print(a) </code></pre> <p>I got reactor running in other module, if that is important. Thank you in advance.</p> <p>UPDATE: With help of @notorious.no got working code, returning data instead of Deferred with Python 3.5:</p> <pre><code>@defer.inlineCallbacks def ask_db(request): data = yield dbpool.runQuery(request) return defer.returnValue(data) </code></pre>
0
2016-10-04T16:57:56Z
39,862,455
<p>You get a Deferred because you're calling an <code>inlineCallback</code> which always returns a Deferred. You're also misinterpreting what <code>yield</code> does. It doesn't actually return a value from an <code>inlinceCallback</code> it just wait's for a result. Use <code>defer.returnValue()</code> to return a value (you can use a simple <code>return</code> if you're using Python 3.4+). This is what your code should look like:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import print_function #... @defer.inlineCallbacks def ask_db(): data = yield dbpool.runQuery("SELECT * FROM customer") defer.returnValue(data) # actually return a value a = ask_db() # this returns a Deferred so add callbacks! a.addCallback(print) # add a useful callback to processes query list reactor.run() </code></pre> <p>The difference between what you had previously and this answer is that a callback is added so when the <code>runQuery()</code> returns with a value, the callback is executed and <code>ask_db()</code> actually returns a value you care about.</p> <h1>References</h1> <ul> <li><a href="https://notoriousno.blogspot.com/2016/08/twisted-klein-database-usage.html" rel="nofollow">Database Usage with Klein/Twisted</a></li> </ul>
0
2016-10-04T22:02:06Z
[ "python", "oracle", "twisted", "deferred" ]
Applying a function to a DataFrame column returns NoneType
39,857,949
<p>I have a DataFrame with source IP addresses and I want to check if they belong to a documented CIDR range. </p> <pre><code>netflow_df2["sip"].head(10) timestamp 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 40.101.X.X 2016-10-04 16:24:58 67.X.X.X 2016-10-04 16:24:58 10.1.1.X 2016-10-04 16:24:58 10.1.Y.Y import ipaddress import numpy from collections import defaultdict from pandas.util.testing import test_parallel </code></pre> <p>I put all the documented CIDRs I know of in a dict:</p> <pre><code># dict to key (vlan, designation) nets = defaultdict(str) nets["10.1.0.0/24"] = "13, web" net["10.2.0.0/24"] = "14, department X" net["10.3.55.0/24"] = "601, wifi" ... net["10.1.243.0/24"] = "1337, IT" </code></pre> <p>I define my function:</p> <pre><code>def netmap(ip, network_lookup_dict): for key, value in network_lookup_dict.iteritems() : if ipaddress.ip_address(unicode(ip)) in ipaddress.ip_network(unicode(key)): return value # print "VLAN: " + infos[0].strip() + ", Network designation: " + infos[1].strip() else: return numpy.NAN </code></pre> <p>And now I map it:</p> <pre><code>@test_parallel(num_threads=4) def apply_netmap(netflow_df2, location="ABC"): % time netflow_df2["sip_infos"] = netflow_df2["sip"].map(lambda ip: netmap(ip, nets)) return netflow_df2 CPU times: user 3min 14s, sys: 21.2 s, total: 3min 36s Wall time: 3min 5s netflow_df3 = apply_netmap(netflow_df2) </code></pre> <p>My error is:</p> <pre><code>netflow_df3.head(10) </code></pre> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'head'</p> </blockquote> <p>I was under the impression this function would map the return value of <code>netmap()</code> to the DataFrame column. That is the reason why I also return <code>NAN</code>. This does not appear to be the case. Also it's super slow.</p>
0
2016-10-04T17:01:21Z
39,860,011
<p>The problem is that I use the <code>defaultdict</code> in the <code>netmap</code> function wrong. This yields the corrects results:</p> <pre><code>def netmap(ip, network_lookup_dict): for key, value in network_lookup_dict.iteritems(): try: if ipaddress.ip_address(unicode(ip)) in ipaddress.ip_network(unicode(key)): return network_lookup_dict.get(key) except KeyError: print "duh" return numpy.NaN </code></pre> <p>The <code>return</code> statement was broken. It's confusing to me why this would corrupt the <code>DataFrame</code> object, but I suppose everything has bugs.</p>
0
2016-10-04T19:11:31Z
[ "python", "pandas", "networking" ]
OAuth and redirect_uri in offline Python script
39,858,027
<p>I'm currently trying to write a Python script that will use Deviantart's API to automatically shuffle my favourites. To do that I need to first log in in my script. Deviantart uses OAuth2 authentication, which requires a redirect_uri, which as I understand it is supposed to be the server where my application is running.</p> <p>However I'm running the script locally on my computer (not on a server) and just sending http requests via Python's <code>Requests</code> library. How do I then authenticate, when the OAuth procedure sends the code required for the authentication token as a parameter of a <code>GET</code> call to the redirect_uri, which points to nowhere in particular for me? Is there no way to authenticate without running a server?</p> <h2>EDIT</h2> <p>My problem is still that I'm running a simple offline script, and I'm not sure how to authenticate from it.</p> <p>This is my authentication code so far:</p> <pre><code>import binascii, os, requests def auth(): request = 'https://www.deviantart.com/oauth2/authorize' state = binascii.hexlify(os.urandom(160)) params = { 'response_type': 'token', 'client_id': 1, 'redirect_uri': 'https://localhost:8080', 'state': state, 'scope': 'user' } r = requests.get(request, params) print(r) </code></pre> <p>The printed response is simply a 200 HTTP code, rather than an access token (obviously, since the username and password haven't been entered anywhere). The request is sent to DA's authorisation page, but since the page itself doesn't actually open in my script, I can't enter my username and password to log in anywhere. And I can't directly send the username and password in the <code>GET</code> request to authenticate that way either (again obviously, since it would be a terrible idea to send the password like that).</p> <p>Preferably I'd like a way to simply have the user (me) prompted for the username and password in the console that the script is running in and then have the script continue executing after the user has successfully logged in.</p> <p>Alternatively, if the above is not possible, the script should open the authorisation webpage in a browser, and then continue execution once the user logs in. </p> <p>How would I go about realising either of these two solutions in Python?</p>
0
2016-10-04T17:06:00Z
39,858,388
<p>You are supposed to get authorization token using received code. This token will be used to access DeviantArt afterwards. </p> <p>Refer to <a href="https://www.deviantart.com/developers/authentication" rel="nofollow">https://www.deviantart.com/developers/authentication</a> (section "Using The Authorization Code Grant").</p>
1
2016-10-04T17:29:50Z
[ "python", "oauth", "oauth-2.0", "deviantart-api" ]
OAuth and redirect_uri in offline Python script
39,858,027
<p>I'm currently trying to write a Python script that will use Deviantart's API to automatically shuffle my favourites. To do that I need to first log in in my script. Deviantart uses OAuth2 authentication, which requires a redirect_uri, which as I understand it is supposed to be the server where my application is running.</p> <p>However I'm running the script locally on my computer (not on a server) and just sending http requests via Python's <code>Requests</code> library. How do I then authenticate, when the OAuth procedure sends the code required for the authentication token as a parameter of a <code>GET</code> call to the redirect_uri, which points to nowhere in particular for me? Is there no way to authenticate without running a server?</p> <h2>EDIT</h2> <p>My problem is still that I'm running a simple offline script, and I'm not sure how to authenticate from it.</p> <p>This is my authentication code so far:</p> <pre><code>import binascii, os, requests def auth(): request = 'https://www.deviantart.com/oauth2/authorize' state = binascii.hexlify(os.urandom(160)) params = { 'response_type': 'token', 'client_id': 1, 'redirect_uri': 'https://localhost:8080', 'state': state, 'scope': 'user' } r = requests.get(request, params) print(r) </code></pre> <p>The printed response is simply a 200 HTTP code, rather than an access token (obviously, since the username and password haven't been entered anywhere). The request is sent to DA's authorisation page, but since the page itself doesn't actually open in my script, I can't enter my username and password to log in anywhere. And I can't directly send the username and password in the <code>GET</code> request to authenticate that way either (again obviously, since it would be a terrible idea to send the password like that).</p> <p>Preferably I'd like a way to simply have the user (me) prompted for the username and password in the console that the script is running in and then have the script continue executing after the user has successfully logged in.</p> <p>Alternatively, if the above is not possible, the script should open the authorisation webpage in a browser, and then continue execution once the user logs in. </p> <p>How would I go about realising either of these two solutions in Python?</p>
0
2016-10-04T17:06:00Z
39,865,646
<p>If your application is offline, you cannot use the Authorization Code nor the Implicit grant type: both flows require a redirection URI. </p> <p>As your python script cannot be reached from the Internet and because Deviantart does not allow the use of another grant type (except Client Credentials, but not relevant in you case), then you won't be able to issue any access token.</p> <p>Your application must be accessible from the Internet.</p>
1
2016-10-05T04:50:25Z
[ "python", "oauth", "oauth-2.0", "deviantart-api" ]
Why am I getting an infinite for loop?
39,858,118
<p>For this python problem I am taking in one argument an int, this is the max length of a list I am going to be appending to. Starting with an int value of 1, I want to iterate through the list appending two more linear values until the max length is reached. </p> <p>I am getting an infinite loop or something similar; I am not receiving any values but python is still processing. </p> <p>This is the code where the infinite loop is occurring, wondering why? Code:</p> <pre><code> def dbl_linear(n): lst_u =[1] while len(lst_u)&lt;=n: for i in lst_u: lst_u.append(2*i+1) lst_u.append(3*i+1) return sorted(lst_u) dbl_linear(10) </code></pre> <p>I looked up this example user had set a variable to another variable that contained a list before the for loop and then changed it back after the loop. Wondering why this is done and why it is useful? other code: d</p> <pre><code>ef dbl_linear(n): lst_u =[1] while len(lst_u)&lt;=n: new_u = lst_u for i in lst_u: new_u.append(2*i+1) new_u.append(3*i+1) new_u=lst_u return sorted(lst_u) dbl_linear(10) </code></pre>
0
2016-10-04T17:12:15Z
39,858,313
<p>You are adding to the list as you loop over it. A list iterator simply increments a position counter and returns the value at that index until the index doesn't exist. It doesn't keep track of the length of the list up-front. In your case, by adding more elements to the end, the iterator never reaches an index that doesn't exist.</p> <p>You have several options:</p> <ul> <li><p>Create a copy of the list first to iterate over; that copy won't grow:</p> <pre><code>def dbl_linear(n): lst_u = [1] while len(lst_u)&lt;=n: for i in lst_u[:]: # [:] returns a shallow copy lst_u.append(2*i+1) lst_u.append(3*i+1) return sorted(lst_u) </code></pre></li> <li><p>Append to a <em>separate, new</em> list and extend the original after the loop:</p> <pre><code>def dbl_linear(n): lst_u = [1] while len(lst_u)&lt;=n: new_values = [] for i in lst_u: new_values.append(2*i+1) new_values.append(3*i+1) lst_u.extend(new_values) return sorted(lst_u) </code></pre></li> <li><p>Use a <code>range()</code> to produce indices; this is based on taking the length <em>once</em>:</p> <pre><code>def dbl_linear(n): lst_u = [1] while len(lst_u)&lt;=n: for idx in range(len(lst_u)): i = lst_u[idx] lst_u.append(2*i+1) lst_u.append(3*i+1) return sorted(lst_u) </code></pre></li> </ul>
1
2016-10-04T17:25:10Z
[ "python", "loops" ]
Python multiprocessing dies in the middle
39,858,119
<p>I run a <code>python</code> program on <strong>CentOS VPS Server</strong>. I am running this program for last few months &amp; I am facing this problem from the beginning. </p> <p>I usually run this python program from crontab. The program does the following things everyday sequentially. </p> <ol> <li>Connect to a <code>MySQL</code> Database &amp; Update some specific info.</li> <li>Divide into 8-10 python instances using <code>multiprocessing</code>.</li> <li>Each instance run virtual display using <code>Xvfb</code> (which is required to run firefox).</li> <li>Each instance run individual firefox browser. </li> <li>Every instance visit one website to check update (using <code>selenium</code>) for some data and if it get any changes it update to database.</li> <li>After checking each instance close <code>firefox</code></li> </ol> <p>All these processes usually take 60 min to 90 min if it runs properly. But problem is that it is not running fine every time. Sometime it runs sometimes it dies in the middle. Also I never found any specific reason, why these program dies and what should I do. When I checked <code>top</code> or <code>ps</code>, I found <code>python</code> program is absent and <code>firefox</code> &amp; <code>Xvfb</code> is still there waiting for the python command like a fool. </p> <p>Probably killed by system due to overload or some other reason. Sometime rebooting system helps. But, I know that is not a good solution. That is why I tried to run the program reducing the niceness value at the lowest level. But, program probably cannot run with negative <code>niceness</code> value, so still the same problem persist.</p> <pre><code>F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 S 500 12673 12655 0 80 0 - 54957 wait ? 00:00:00 python 1 S 500 12683 12673 0 80 0 - 62766 sk_wai ? 00:00:18 python 1 S 500 12704 12673 0 80 0 - 59295 sk_wai ? 00:00:17 python 1 S 500 12816 12673 0 80 0 - 59230 sk_wai ? 00:00:16 python 1 S 500 12898 12673 0 80 0 - 59400 sk_wai ? 00:00:16 python 1 S 500 12988 12673 0 80 0 - 59491 sk_wai ? 00:00:17 python 1 S 500 13072 12673 0 80 0 - 59151 sk_wai ? 00:00:17 python </code></pre> <p>Again, I have run this program on my <strong>Windows 8</strong> desktop and it runs fine with up to 26 instances (I never tried more :) ). As it is running so many instances at a time page loading become slow. That is why I tried to run this program on 3 VPS server by splitting the job.</p> <p>Also, I run another program using <code>python</code>, <code>firefox</code>, <code>selenium</code>, <code>Xvfb</code> with single process and it runs fine 10-12 hours without any hiccup. Also this program does almost same thing like first one but only difference is it is running only single process. And, it never create any trouble like first one.</p> <p>Is there any way, which will confirm that it will run the program properly every time?</p>
0
2016-10-04T17:12:17Z
39,858,860
<p>I have also faced the same problem. After doing a lot of research I concluded, Firefox is not good option for multiprocessing. Better use <strong>PhantomJS</strong> or <strong>Chrome Driver</strong>. In my case when I was saw ps or top, I was getting Zombie Firefox process. </p>
0
2016-10-04T17:58:43Z
[ "python", "linux", "selenium", "firefox", "multiprocessing" ]
I need help making a triangle that generates using user input by making the user enter the number of rows
39,858,146
<p>It should look like this but reversed and the first column indented</p> <pre><code>OOOOOOO OOOOOO OOOOO OOOO OOO OO O </code></pre> <p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p> <p>Here is what I got so far</p> <pre><code>row = int(input('Please enter how many rows you want: ')) for r in range(row,0,-1): for c in range(r): print('o', end='') print('') </code></pre>
-1
2016-10-04T17:13:57Z
39,858,297
<p>You can do in this way:</p> <pre><code>line = int(input('Please enter how many lines you want: ')) vec = [i for i in range(1,line+1)] for elem in vec: print("\t"+"O"*elem) </code></pre> <p>Output example:</p> <p><a href="http://i.stack.imgur.com/l1Vx6.png" rel="nofollow"><img src="http://i.stack.imgur.com/l1Vx6.png" alt="enter image description here"></a></p>
1
2016-10-04T17:24:26Z
[ "python", "for-loop", "nested-loops" ]
I need help making a triangle that generates using user input by making the user enter the number of rows
39,858,146
<p>It should look like this but reversed and the first column indented</p> <pre><code>OOOOOOO OOOOOO OOOOO OOOO OOO OO O </code></pre> <p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p> <p>Here is what I got so far</p> <pre><code>row = int(input('Please enter how many rows you want: ')) for r in range(row,0,-1): for c in range(r): print('o', end='') print('') </code></pre>
-1
2016-10-04T17:13:57Z
39,858,328
<pre><code>line = int(input('number of lines')) for i in range(1, line + 1): a = 'O' * ((line + 1) - i) b = " "*(i) print(b + a) </code></pre> <p>I don't understand what 'first column indented' means but this posts what you want I believe. </p> <p>for <code>line = 5</code> this prints </p> <pre><code> OOOOO OOOO OOO OO O </code></pre> <p>Unless you mean reversed as to be like this? </p> <pre><code> O OO OOO OOOO OOOOO </code></pre> <p>In which case the code is: </p> <pre><code>line = int(input('number of lines')) for i in range(line , 0, -1): a = 'O' * ((line + 1) - i) b = " "*(i) print(b + a) </code></pre> <p>Or perhaps you mean reversed like this?</p> <pre><code>O OO OOO OOOO OOOOO </code></pre> <p>In which case, this code is your friend:</p> <pre><code>line = int(input('number of lines')) for i in range(line , 0, -1): a = 'O' * ((line + 1) - i) print(a) </code></pre> <p>As you can see specific questions help. </p>
0
2016-10-04T17:26:01Z
[ "python", "for-loop", "nested-loops" ]
I need help making a triangle that generates using user input by making the user enter the number of rows
39,858,146
<p>It should look like this but reversed and the first column indented</p> <pre><code>OOOOOOO OOOOOO OOOOO OOOO OOO OO O </code></pre> <p>Every time I attempt to do it I always get this code iteration and I don't know where I am going wrong.</p> <p>Here is what I got so far</p> <pre><code>row = int(input('Please enter how many rows you want: ')) for r in range(row,0,-1): for c in range(r): print('o', end='') print('') </code></pre>
-1
2016-10-04T17:13:57Z
39,858,390
<p>Well here goes my version of the solution</p> <pre><code>line = int(raw_input('Please enter how many lines you want: ')) k='' for r in range(line): k=k+'0' for r in range(line): print k k=k[0:len(k)-1] k=' '+k </code></pre> <p>The terminal output looks like this</p> <pre><code>Please enter how many lines you want: 7 0000000 000000 00000 0000 000 00 0 </code></pre>
0
2016-10-04T17:29:52Z
[ "python", "for-loop", "nested-loops" ]
Basic Python function
39,858,150
<p>I am trying to complete two different questions but cannot get them to work. Please help me understand where I went wrong.</p> <p>1) For each number between 1 and 100, odds should be normal and even numbers should print out the word "Billy". Must start at 1 not 0 and include the number 100. Here's my answer (I know I'm way off)</p> <pre><code>for i in range(1,101): if i % 2 == 0: print(Billy) else: print(i) </code></pre> <p>2) Ask the user: "What is your name?". Response should look like "Hello Billy" for all names except Joe and Susie. For Joe it should say "Hi Joe :)" and for susie it should say "Ahoy Susie :D". Here is where I'm at:</p> <pre><code>name = input("What is your name?") if name == "Joe": print("Hi Joe :)") if name == "Susie": print("Ahoy Susie :D) else: print("Hello", name) </code></pre>
-2
2016-10-04T17:14:14Z
39,858,177
<p>try this</p> <pre><code>for i in range(1,101): if i % 2 == 0: print('Billy') #you missed quote marks here else: print(i) </code></pre> <p>(bad indentation, and missing quote marks)</p> <p>and </p> <pre><code>name = input("What is your name?") if name == "Joe": print("Hi Joe :)") elif name == "Susie": print("Ahoy Susie :D") #and you missed quote marks here else: print("Hello" + name) </code></pre> <p>...same issues.</p>
0
2016-10-04T17:16:30Z
[ "python" ]
TypeError: Expected bytes in Flask app
39,858,161
<p>I am trying to implement a simple flask app which will pass a json file to the front end, but got an error as following:</p> <pre><code>&gt; 127.0.0.1 - - [04/Oct/2016 17:53:02] "GET /test HTTP/1.1" 500 - Traceback (most recent call last): File &gt; "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/flask/app.py", &gt; line 2000, in __call__ &gt; return self.wsgi_app(environ, start_response) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/flask/app.py", &gt; line 1992, in wsgi_app &gt; return response(environ, start_response) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py", &gt; line 1228, in __call__ &gt; app_iter, status, headers = self.get_wsgi_response(environ) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py", &gt; line 1216, in get_wsgi_response &gt; headers = self.get_wsgi_headers(environ) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py", &gt; line 1167, in get_wsgi_headers &gt; for x in self.response) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py", &gt; line 1167, in &lt;genexpr&gt; &gt; for x in self.response) File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/_compat.py", &gt; line 112, in to_bytes &gt; raise TypeError('Expected bytes') TypeError: Expected bytes &gt; 127.0.0.1 - - [04/Oct/2016 17:53:03] "GET /favicon.ico HTTP/1.1" 404 </code></pre> <p>The coding related to the url '/test' is:</p> <pre><code>@app.route("/test",methods=['GET']) def get_local_json(): SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) json_url = os.path.join(SITE_ROOT, "static/data","predict.json") #console.log("url is all right") data = json.load(open(json_url)) return app.response_class(data, content_type='application/json') </code></pre> <p>And the coresponding code for front-end:</p> <pre><code>$.getJSON('/test', function(data){ var myData = []; for(var i in data){ var item = data[i]; var myItem = []; myItem.push(new Date(item.time).getTime()); myItem.push(item.occupancy); myData.push(myItem); } console.log(myData); </code></pre> <p>Any hints are appreciated!!</p>
0
2016-10-04T17:14:58Z
39,858,612
<p>You are returning a Python object other than a <code>bytes</code> object here:</p> <pre><code>return app.response_class(data, content_type='application/json') </code></pre> <p>That's not a JSON response, that's an <em>unencoded</em> Python list or dictionary.</p> <p>Just return the JSON data <em>without</em> decoding it:</p> <pre><code> with open(json_url, 'rb') as json_file: return app.response_class(json_file.read(), content_type='application/json') </code></pre> <p>or if you must do something with the data structure first, re-encode it back to JSON. Use the <code>jsonify()</code> utility function for that:</p> <pre><code>with open(json_url) as json_file: data = json.load(json_file) # manipulate data as needed return jsonify(data) </code></pre>
0
2016-10-04T17:42:44Z
[ "python", "json", "flask" ]
Do statement not working in jinja
39,858,191
<p>I'm altering an existing web interface to view ROBOT doc libraries, which uses a mixture of jinja (Python inside HTML) and HTML. I have never worked with jinja or HTML before and am having issues getting even a simple test case to work. When the browser loads the docs, I want our project's directory structure for the docs to be preserved to make finding things easier, and so I want to use jinja to create the dir structure. Here is a snippet of the code I'm working with:</p> <pre><code>{% extends "base.html" %} {% block body %} &lt;div class="well" id="left"&gt; &lt;ul class="list-group list-unstyled"&gt; {% set collection_list = [] %} {% for collection in data.hierarchy %} {% if collection.collection_id|string == data.collection_id|string %} {% do collection_list.append(collection.path) %} {% else %} {% for link in collection.path_chain %} &lt;li&gt; &lt;label class="tree-toggler nav-header" title="file path: {{collection.path}}"&gt;{{link}}&lt;/label&gt; &lt;ul class="list-group tree collapse" id={{link}}&gt; &lt;/ul&gt; {% endfor %} &lt;/li&gt; {% endif %} </code></pre> <p>...there's more after that, but this is where I hit the error. It sets the collection_list var fine, and the if statements work, but when it goes to execute the 'do' statement it fails with:</p> <p><strong>TemplateSyntaxError: Encountered unknown tag 'do'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.</strong></p> <p>I don't believe this is an unclosed loop or something because if I replace the do statement with a simple test print statement, it works. Does anyone know what I'm doing wrong?</p>
1
2016-10-04T17:17:38Z
39,858,522
<p>From the <a href="http://jinja.pocoo.org/docs/dev/templates/#expression-statement" rel="nofollow">template documentation</a>:</p> <blockquote> <h3>Expression Statement</h3> <p>If the expression-statement extension is loaded, a tag called <code>do</code> is available that works exactly like the regular variable expression (<code>{{ ... }}</code>); except it doesn’t print anything. This can be used to modify lists:</p> <pre><code>{% do navigation.append('a string') %} </code></pre> </blockquote> <p>You need to enable the <a href="http://jinja.pocoo.org/docs/dev/extensions/#expression-statement" rel="nofollow">Expression statement extension</a> for this to work.</p> <p>You didn't show how you load the Jinja2 environment, but loading extensions takes place via the <code>extensions</code> argument to the <a href="http://jinja.pocoo.org/docs/dev/api/#jinja2.Environment" rel="nofollow"><code>Environment()</code> class</a>:</p> <pre><code>jinja_env = Environment(extensions=['jinja2.ext.do']) </code></pre>
0
2016-10-04T17:38:10Z
[ "python", "html", "jinja2" ]
Python 3.5: NLTK Download Default URL will not change
39,858,195
<p>I've updated the DEFAULT_URL in downloader.py and I'm still getting the following error. I originally tried just nltk.downloader() and the file browser updated but when I tried to download, it still reverted back to the github site.</p> <pre><code>DEFAULT_URL = 'http://nltk.org/nltk_data/' </code></pre> <p>.</p> <pre><code>import nltk nltk.set_proxy('proxyaddress',user=None) dl = nltk.downloader.Downloader("http://nltk.org/nltk_data/") dl.download('all') [nltk_data] Downloading collection 'all' [nltk_data] | [nltk_data] | Downloading package abc to C:\nltk_data... [nltk_data] | Error downloading 'abc' from [nltk_data] | &lt;https://raw.githubusercontent.com/nltk/nltk_data [nltk_data] | /gh-pages/packages/corpora/abc.zip&gt;: &lt;urlopen [nltk_data] | error [Errno 11004] getaddrinfo failed&gt; </code></pre> <p>Why is this still defaulting to raw.githubusercontent.com/nltk/nltk_data?</p>
0
2016-10-04T17:17:57Z
39,875,376
<p>The problem comes from your proxy. I can't say what's wrong with your proxy configuration, but initializing a downloader with a custom download url works as intended (there is no need to modify the nltk source in <code>nltk/downloader.py</code>):</p> <pre><code>dl = nltk.downloader.Downloader("http://example.com/my_corpus_data/index.xml") </code></pre> <p>Note that the custom url must resolve to an XML document describing the downloadable resources, in the format expected by the <code>nltk</code>; the code in your question points to the human-readable list at <code>http://nltk.org/nltk_data</code>, which will just result in an error. (Presumably your real code uses a different URL, and different code around the proxy settings.)</p> <p>Anyway the problem has to be in your proxy, or the way you use it. The nltk's <code>set_proxy</code> function just calls a couple of functions from <code>urllib.request</code> to declare the proxy. It never comes near the nltk's <code>downloader</code> module, so there's no way it could affect the downloader's defaults.</p>
1
2016-10-05T13:30:51Z
[ "python", "nltk" ]
Python Sounddevice.play() on Threads
39,858,212
<p>I am having some problems to play the sounddevice on a Thread. I import the sounddevice as sd at the beginning. Then during running I want to play a tone on a thread using the ASIO sound card. All the configurations I need to do on the thread works well. However, when I want to play the tone I got the following Error: </p> <p><strong>sounddevice.PortAudioError: Error opening OutputStream: Unanticipated host API 2 error 0: u'Failed to load ASIO driver'</strong></p> <p>If I initialize the import at the thread everytime I need it, it work. But of course I do not want to do that. Any Idea hot to solve it? </p> <p>Thanks!</p> <p>Here a simple code example:</p> <pre><code>from threading import Thread import numpy as np import sounddevice as sd class Test(Thread): def __init__(self): Thread.__init__(self) #-- Configuration of the Tone to be played self.fs = 44100 # sampling rate, in Hz, 44100 or 48000 duration = 1.05 # in seconds, may be float f = 200.0 # sine frequency, Hz, may be float self.tone_data = (np.sin(2*np.pi*np.arange(self.fs*duration)*f/self.fs)).astype(np.float32) def run(self): #-- Configuration of the ASIO sound card #import sounddevice as sd sd.default.channels = 2 sd.default.device = 14 print sd.query_devices(sd.default.device)['name'] #sd.default.latency = ('low','low') #asio_out = sd.AsioSettings(channel_selectors=[1, 2]) #sd.default.extra_settings = asio_out sd.default.samplerate = self.fs sd.play(self.tone_data) sd.wait() w = Test() w.start() </code></pre>
0
2016-10-04T17:18:52Z
40,045,505
<p>This seems to be a platform-specific problem. I just tried it with ALSA/Linux and it works fine. With ASIO, you probably have to do the library initialization (which happens during <code>import</code> time) in the same thread you are using later to create the stream (which <code>play()</code> does for you)?</p> <blockquote> <p>If I initialize the import at the thread everytime I need it, it work. But of course I do not want to do that.</p> </blockquote> <p>Why do you not want to do that? Are you aware that the use of <code>import</code> in Python is cached automatically? The second time you use <code>import</code>, only a <code>dict</code> lookup is done and nothing else.</p> <p>But you are right, the repeated <code>import</code> still <em>looks</em> a bit strange. Did you try to do the <code>import</code> only once in <code>Test.__init__()</code>? There you could also do all the <code>sd.default</code> stuff.</p> <p>If you still have problems during the initialization (or if you insist on having all imports at the top), you can try to use the undocumented <code>_initialize()</code> and <code>_terminate()</code> functions, see <a href="https://github.com/spatialaudio/python-sounddevice/issues/3" rel="nofollow">issue #3</a>.</p> <p>If you want to use multiple <code>Thread</code> instances, you'll get problems with the <code>play()</code> function, which is meant for single-threaded use. But it probably makes more sense anyway to have only one Python thread that does the audio I/O. See also <a href="https://app.assembla.com/spaces/portaudio/wiki/Tips_Threading" rel="nofollow">PortAudio Tips – Threading</a>.</p> <p>BTW, you don't need <code>(...).astype(np.float32)</code>, this conversion is done automatically for you.</p> <p>And while I'm at it, your line <code>sd.query_devices(sd.default.device)['name']</code> will break if the default input and output devices are different.</p>
0
2016-10-14T14:21:10Z
[ "python", "multithreading", "python-sounddevice" ]
How can i save RDD to a single parquet file?
39,858,238
<p>I work with pyspark 2.0, hadoop 2.7.2. And here is my code:</p> <pre><code>def func(df): new_df = pd.DataFrame(df['id']) new_df['num'] = new_df['num'] * 12 return new_df set = sqlContext.read.parquet("data_set.parquet") columns = set.columns map_res = set.rdd.mapPartitions(lambda iter_: func(pd.DataFrame(list(iter_), columns=columns))) </code></pre> <p>Now, I need to save <strong>map_res</strong> RDD as a parquet file <em>new.parquet</em>. Is there any way i can do it without creating a large dataframe before the saving? Or may be there is a possibility of saving each partition of RDD separately and then merge all saved files?</p> <p>P.s. I want to manage without creating a dataframe due to its realy large size.</p>
2
2016-10-04T17:20:43Z
39,859,509
<p>There are only 2 ways to do this: </p> <p>One is use <code>"coalesce(1)"</code> This will make sure that all the data is saved into 1 file rather than multiple files (200 is the spark default no of partitions) use <code>dataframe.write.save("/this/is/path")</code>. </p> <p>The other option is write the output to a hive table and then use <code>hive -e "select * from table" &gt; data.tsv</code> which will be tab separated.</p>
0
2016-10-04T18:40:42Z
[ "python", "hadoop", "apache-spark", "pyspark", "rdd" ]
How can i save RDD to a single parquet file?
39,858,238
<p>I work with pyspark 2.0, hadoop 2.7.2. And here is my code:</p> <pre><code>def func(df): new_df = pd.DataFrame(df['id']) new_df['num'] = new_df['num'] * 12 return new_df set = sqlContext.read.parquet("data_set.parquet") columns = set.columns map_res = set.rdd.mapPartitions(lambda iter_: func(pd.DataFrame(list(iter_), columns=columns))) </code></pre> <p>Now, I need to save <strong>map_res</strong> RDD as a parquet file <em>new.parquet</em>. Is there any way i can do it without creating a large dataframe before the saving? Or may be there is a possibility of saving each partition of RDD separately and then merge all saved files?</p> <p>P.s. I want to manage without creating a dataframe due to its realy large size.</p>
2
2016-10-04T17:20:43Z
39,876,160
<p>I suggest this:</p> <pre><code>dataframes = [] #creating index map_res = map_res.zipWithIndex() # setting index as key map_res = map_res.map(lambda x: (x[1],x[0])) # creating one spark df per element for i in range(0, map_res.count()): partial_dataframe_pd = map_res.lookup(i) partial_dataframe = sqlContext.createDataFrame(partial_dataframe_pd) dataframes.append(partial_dataframe) # concatination result_df = dataframes.pop() for df in dataframes: result_df.union(df) #saving result_df.write.parquet("...") </code></pre> <p>If you have small number of partitions (2-100) then it should work rather fast. </p>
1
2016-10-05T14:05:33Z
[ "python", "hadoop", "apache-spark", "pyspark", "rdd" ]
Multiple functions on class-based views flask
39,858,256
<p>maybe I'm misunderstanding class-based views on Flask. I come from a PHP/Laravel background. On Laravel I can define a controller class where I can response different json data, views (templates on Flask), etc. So the only thing I do is define a route and associate that route to a specific method on a controller class.</p> <p>A pseudo-code like this:</p> <pre><code>On POST associate /path to MyControllerClass@doPostMethod On GET associate /path to MyControllerClass@someGetMethod On GET associate /path/extra to MyControllerClass@someOtherGetMethod ... </code></pre> <p>On Flask I would have them as separated functions. Something like:</p> <pre><code>def doPostFunction()... def someGetFunction()... def someOtherGetFunction()... </code></pre> <p>So googling a bit, there are class-based views but as I saw it, insted of defining a function I define a class and put the content of the old view function inside <em>dispatch_request</em> class-based view's method.</p> <pre><code>class DoPostClass(View): dispatch_request() ... class DoGetClass(View): dispatch_request() ... class DoSomeOtherGetClass(View): dispatch_request() ... </code></pre> <p>Is there a way to have these functions inside a single class? am I misunderstading Flask's class-based views? I know there's a MethodView class that has get, post, put, delete methods but as I'm not createing a RESTful API neither I use nice-RESTful urls, MethodView class seems not to be useful for my case.</p> <p>Thanks in advance.</p>
1
2016-10-04T17:22:12Z
39,859,447
<p>Based on my laravel/flask project experience, the classy code of controller/view are same. You can try <a href="https://github.com/apiguy/flask-classy" rel="nofollow">flask-classy</a> extension</p> <p>Below is an example based on <code>flask-classy</code>.</p> <p><strong>Directory</strong></p> <pre><code>. ├── index.py └── views ├── __init__.py └── myView.py </code></pre> <p><strong>myView.py</strong></p> <pre><code>from flask_classy import FlaskView class myView(FlaskView): def index(self): return "this is index" def get(self, id): return "this is page " + str(id) </code></pre> <p><strong>index.py</strong></p> <pre><code>from flask import Flask from views.myView import myView app = Flask(__name__) myView.register(app) </code></pre> <p><strong>Run</strong></p> <pre><code>$ export FLASK_APP=index.py $ flask run # Index: http://127.0.0.1:5000/my # Get: http://127.0.0.1:5000/my/&lt;id&gt; </code></pre>
1
2016-10-04T18:36:24Z
[ "python", "flask" ]
Fail to map the output of a generator to a function in multiprocessing with python-2.7
39,858,279
<p>Here is my code:</p> <pre><code>from multiprocessing import Pool user_list = [1, 2, 3, 4, 5] def gen_pair(): for u1 in reversed(user_list): for u2 in reversed(list(range(1, u1))): yield (u1, u2) def cal_sim(u_pair): u1, u2 = u_pair sim = sim_f(df[u1], df[u2]) return sim pool = Pool(processes=6) vals = pool.map(cal_sim, gen_pair()) df2record = pd.DataFrame(columns=['u1', 'u2', 'js']) for v in vals: print (v) pool.terminate() </code></pre> <p>But when I run the code, I got such an error: <code>TypeError: unsupported operand type(s) for +: 'set' and 'set'</code>. The full TraceBack is as below:</p> <pre><code>Traceback (most recent call last): File "b.py", line 57, in &lt;module&gt; main() File "b.py", line 47, in main vals = pool.map(cal_sim, gen_pair()) File "yobichi/python/2.7.10_2/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "yobichi/python/2.7.10_2/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value TypeError: unsupported operand type(s) for +: 'set' and 'set' </code></pre> <p>Could you please tell me what is the reason and how can I deal with it appropriately? </p>
1
2016-10-04T17:23:26Z
39,860,909
<p>You have an infinite recursion here:</p> <pre><code>def cal_sim(u_pair): u1, u2 = u_pair sim = cal_sim(df[u1], df[u2]) return sim </code></pre> <p>Because <code>cal_sim</code> calls <code>cal_sim</code> without any end condition.</p> <p>There is also a problem with the parameters, because <code>cal_sim</code> has 1 parameter and you call it with 2 arguments.</p>
0
2016-10-04T20:07:45Z
[ "python", "python-2.7", "multiprocessing" ]
Narcissistic number
39,858,316
<p>Today I saw an interesting task. To make a program which outputs all "narcissistic numbers" (all digits are raised to the power of 3). My program has this code</p> <pre><code>for number in range(1, 408): result = 0 for digit in str(number): result += int(digit) ** 3 if result == number: print(number) </code></pre> <p>The output is</p> <pre><code>1 153 370 370 371 407 </code></pre> <p>Why does 370 appear twice?</p>
0
2016-10-04T17:25:19Z
39,858,359
<p>You're checking whether <code>result==number</code> after each digit in the number. You probably want this check in the outer <code>for</code> loop. As it is, it sees that 370 = 3**3 + 7**3, but it is also 3**3 + 7**3 + 0**3, so it's printed on both of those iterations.</p>
0
2016-10-04T17:28:07Z
[ "python", "python-3.x" ]
Narcissistic number
39,858,316
<p>Today I saw an interesting task. To make a program which outputs all "narcissistic numbers" (all digits are raised to the power of 3). My program has this code</p> <pre><code>for number in range(1, 408): result = 0 for digit in str(number): result += int(digit) ** 3 if result == number: print(number) </code></pre> <p>The output is</p> <pre><code>1 153 370 370 371 407 </code></pre> <p>Why does 370 appear twice?</p>
0
2016-10-04T17:25:19Z
39,858,420
<p>You should unindent the last <code>if</code> statement, which runs after each digit:</p> <pre><code>for number in range(1, 408): result = 0 for digit in str(number): result += int(digit) ** 3 if result == number: print(number) </code></pre> <p>As another answer notes, this can give you false duplicates if there is match in a number with trailing 0's. There is an added danger, though, of <em>false positives</em> if there is a number whose left X digits equal it, but whose total digits do not.</p>
0
2016-10-04T17:31:12Z
[ "python", "python-3.x" ]
Test variables INSIDE a view function - no return
39,858,344
<p>I'm new to Django + Python so I'm not sure how much of this question will make sense.</p> <p>Basically, I'm working on a project (not created by me) that has a function within a views.py file. The purpose of this view function is not to give a HTTP response but to send an email. </p> <p>It accepts a request as a parameter (which contains data that will be looped through - some of it being inserted into the email.</p> <p>The end of the function does a call to an email_extrals.utils function send_mail_template(various different variables passed in).</p> <p>My issue is that I want to write a test for this function which essentially returns nothing (that I can see - it just sends an email). This view function is actually called elsewhere in an API. </p> <p>The purpose of this test is to ensure that if certain variables are present in the request data, then they should be present in a variable which gets passed to the send_email_template() call. So I'm kind of testing for variables inside the function - not what gets returned. </p> <p>I need a way of somehow accessing the internal variables of the function to test them.</p> <p>I can't think of a way to test this and at this point I'm banging my head against a wall. Any test info I can find online for views is mainly just testing responses or various model related issues. </p> <p>Any push in the right direction would be a huge help. A link to docs or a basic example of something similar. </p> <p>Thanks, Dean </p>
0
2016-10-04T17:26:55Z
39,858,583
<p>One way to approach this would be to make your own fake version of <code>send_email_template()</code> that does nothing except verify that it was called with the desired argument values, and raises an exception if they are wrong.</p> <p>Then, in your test setup, you would <em>replace</em> the real <code>send_email_template()</code> with your fake one. This is called <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow">Mocking</a>.</p> <p>And just to be safe you would also want to assert that your fake function was <em>actually called</em>.</p>
1
2016-10-04T17:41:22Z
[ "python", "django", "testing" ]
Stored salted token and token comparison
39,858,364
<p>I'm generating an url composed of a single use token, and sending it to a user by e-mail. The user should click this link and be redirected to a page which will validate the token and do some actions. </p> <p>On the database side, I'm storing this token (hashed and salted, for security reasons). The problem is I'm having some difficulties to validate the the token because, the way I'm storing it, I cannot generate the same salt for the same token. And, therefore, I cannot compare this salt with the ones I have stored.</p> <pre><code># Retrieving or creating object usertokens usr, created = UserToken.objects.get_or_create(email=email) # Adding a new token token = uuid.uuid4().hex usr.token = make_password(token) # Stores in the local database the salted and hashed token usr.save() </code></pre> <p>This make_password method I'm using is defined in <code>django.contrib.auth.hashers</code>.</p> <p>By using this method, I cannot generate two times the same salt from the same token.</p> <pre><code>&gt;&gt;&gt; token = 'test' &gt;&gt;&gt; enc_token1 = make_password(token) &gt;&gt;&gt; enc_token2 = make_password(token) &gt;&gt;&gt; enc_token1 == enc_token2 False </code></pre> <p>This, however, does not help me to retrieve from my database the entry corresponding to the token and I cannot validate it.</p>
2
2016-10-04T17:28:12Z
39,859,024
<p>Using a simple string equality check of two hashed and salted tokens will not work. The <a href="https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#django.contrib.auth.hashers.check_password" rel="nofollow">Django docs for password management</a> offer a very simple method in the <code>django.contrib.auth.hashers</code> namespace that handles all of this for you:</p> <pre><code>&gt;&gt;&gt; token = 'test' &gt;&gt;&gt; enc_token1 = make_password(token) &gt;&gt;&gt; check_password('test', enc_token1) True </code></pre> <p>The <code>check_password</code> method does a few things behind the hood, like check if the hashing algorithm has changed. It returns the result of the <code>verify</code> method of an algorithm that implements the <code>BasePasswordHasher</code> baseclass. Here's an example of an implementation from the <a href="https://docs.djangoproject.com/en/1.10/_modules/django/contrib/auth/hashers/#check_password" rel="nofollow">source of the <code>PBKDF2PasswordHasher</code></a>:</p> <pre><code>def verify(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt, int(iterations)) return constant_time_compare(encoded, encoded_2) </code></pre> <p>Note how the salt is found by splitting the encoded_string on '$', since the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#how-django-stores-passwords" rel="nofollow">Django docs note</a> that</p> <blockquote> <p>The password attribute of a User object is a string in this format:</p> <pre><code>&lt;algorithm&gt;$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt; </code></pre> </blockquote>
1
2016-10-04T18:08:30Z
[ "python", "django" ]
Python data display with graph
39,858,501
<p>I am just dipping my toes into Python and have had help on here to get a live updating Matplotlib graph to work for me. This program uses animation to pull data from a dynamically growing CSV file with data that looks like the following:</p> <pre><code>TimeStamp, ReadCount, Antenna, Protocol, RSSI, EPC, Sensor 09/28/2016 17:34:28.967, 5686, 2, GEN2, -25, E036115348A908CB, 23.16,0.00,0.00, (Infinity%), 09/28/2016 17:34:29.716, 5687, 2, GEN2, -32, E036115348A908CB, (Infinity%), 09/28/2016 17:34:31.155, 5689, 2, GEN2, -27, E036115348A908CB, 22.74,3.38, (Infinity%), 09/28/2016 17:34:32.351, 5692, 2, GEN2, -25, E036115348A908CB, 22.95,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:32.895, 5695, 2, GEN2, -23, E036115348A908CB, 22.95,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:33.397, 5698, 2, GEN2, -21, E036115348A908CB, 23.78,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:33.946, 5699, 2, GEN2, -23, E036115348A908CB, 23.57,0.00,3.38, (Infinity%), 09/28/2016 17:34:34.912, 5702, 2, GEN2, -27, E036115348A908CB, 23.36,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:35.394, 5705, 2, GEN2, -25, E036115348A908CB, 23.36,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:35.988, 5707, 2, GEN2, -23, E036115348A908CB, 23.78,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:36.489, 5710, 2, GEN2, -21, E036115348A908CB, 23.99,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:37.269, 5712, 2, GEN2, -23, E036115348A908CB, 23.78,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:37.796, 5715, 2, GEN2, -18, E036115348A908CB, 23.78,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:38.296, 5718, 2, GEN2, -7, E036115348A908CB, 22.32,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:38.826, 5721, 2, GEN2, -7, E036115348A908CB, 23.57,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:39.320, 5724, 2, GEN2, -30, E036115348A908CB, 23.36,0.00,0.00,3.38, (Infinity%), 09/28/2016 17:34:39.870, 5727, 2, GEN2, -9, E036115348A908CB, 23.36,0.00,0.00,3.38, (Infinity%), </code></pre> <p>This data is coming in from a sensor, and I'd like to be able to pull/display some other values which this data contains on a display along with this graph. The code for the plot looks like the following:</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation from datetime import datetime, timedelta import collections import csv offset = 16 slope = -.2081 def plot(ax, data, colour, width): if data: last_dt = data[0][0] gap = timedelta(seconds=10) x = [] y = [] # Plot groups of data not more than 60 seconds apart for dt, ten in data: if dt &lt;= last_dt + gap: x.append(dt) y.append(ten) else: ax.plot(matplotlib.dates.date2num(x), y, colour, linewidth=width) x = [dt] y = [ten] last_dt = dt ax.plot(matplotlib.dates.date2num(x), y, colour, linewidth=width) def animate(i, fig, ax): # Read in the CSV file data = collections.defaultdict(list) fields = ["TimeStamp", "ReadCount", "Antenna", "Protocol", "RSSI", "EPC", "Temp", "Ten", "Powr", "Unpowr", "Inf"] with open('SensorLogFile.csv') as f_input: csv_input = csv.DictReader(f_input, skipinitialspace=True, fieldnames=fields) header = next(csv_input) # Separate the rows based on the Antenna field for row in csv_input: try: data[row['Antenna']].append( [datetime.strptime(row['TimeStamp'], '%m/%d/%Y %H:%M:%S.%f'), int(float(row['Ten']) * float(slope) + float(offset))]) except: pass # Drop any data points more than 1.5 mins older than the last entry latest_dt = data[row['Antenna']][-1][0] # Last entry not_before = latest_dt - timedelta(minutes=.25) for antenna, entries in data.items(): data[antenna] = [[dt, count] for dt, count in entries if dt &gt;= not_before] # Redraw existing axis ax.clear() ax.spines['bottom'].set_color("#5998ff") ax.spines['top'].set_color("#5998ff") ax.spines['left'].set_color("#5998ff") ax.spines['right'].set_color("#5998ff") hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p') ax.xaxis.set_major_formatter(hfmt) fig.autofmt_xdate() plot(ax, data['1'], 'c', 6) # Antenna 1 plot(ax, data['2'], 'r', 6) # Antenna 2 plot(ax, data['3'], 'y', 6) # Antenna 3 ax.grid(True, color='w') plt.ylabel('Tension (lb)', color='w', fontsize=20) plt.title('Spiral 1 Tension', color='w', fontsize=26) ax.tick_params(axis='y', colors='w') ax.tick_params(axis='x', colors='w') # ax.set_ylim([21,28]) fig = plt.figure(facecolor='#07000d') ax = fig.add_subplot(111, axisbg='#07000d') ani = animation.FuncAnimation(fig, animate, fargs=(fig, ax), interval=250) plt.show() </code></pre> <p>I'd like to be able to have the graph on top and an open area below the graph (the full width of the graph) where I could put the following (probably have a box for each of these pieces of data):</p> <ul> <li>"Temp" (7th csv on each line, just need to convert to deg F)</li> <li>"Time" (current time)</li> <li>"Overdrive" (not showing anything with this data but just a placeholder for it in the future)</li> <li>"Cycles" (would be the number of times that Antenna 1 is first read after a minute gap)</li> <li>box with an image on the bottom right - for the example lets say this image <a href="http://i.stack.imgur.com/mmbRy.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/mmbRy.jpg" alt="this image here"></a></li> </ul> <p>I have looked into using Tkinter and tried to follow sentdex's <a href="https://www.youtube.com/watch?v=Zw6M-BnAPP0" rel="nofollow">video here</a></p> <p>But have not been able to get it to work.</p> <p>I am on a time crunch and can't struggle solo on this anymore - need some help from the pros here. Can anyone give me some direction/guidance on how to make a display like what I'm looking for?</p>
1
2016-10-04T17:36:30Z
39,859,405
<p>To get you started, there are probably some questions to be answered first.</p> <ol> <li>How live is live? Should it update in real time? In this case the use of <code>FuncAnimation</code> is probably a bad idea. <em>Answer: yes, real time</em></li> <li>How fast does it have to be, that is, how many updates per second? <em>Answer: Update 4 times per second</em></li> <li>Is there a trigger for the updates? Do you know when new data arrives? <em>Answer: No real trigger, but see 2.</em></li> <li>How much interactivity do you need? Is it just the plot that should open up and then run for itself or do you need interactive buttons/sliders that allow you to select part of the data? Even with some basic interactivity I would suggest to stay in matplotlib with an interactive backend and not fiddle around with tkinter too much - given that you seem to know nothing about it and are limited in time. <em>Answer: No interactivity needed</em></li> <li><p>When it comes to your data, I see a problem. Looking at those lines<br> <code>E036115348A908CB, 22.74,3.38, (Infinity%),</code><br> <code>E036115348A908CB, 22.95,0.00,0.00,3.38, (Infinity%),</code><br> there seem to be cases where the data is not complete?! Is this avoidable? </p></li> <li><p>What about the time axis for the plot? First, you <code>#Drop any data points more than 1.5 mins older than the last entry</code> and then you <code>#Plot groups of data not more than 60 seconds apart</code> , and then you discard any data which is older then <code>gap = timedelta(seconds=10)</code>. Can you tell us what "groups of data" means and how long the time axis should be?</p></li> <li><p>How would you calculate the <code>number of cycles</code>? </p></li> </ol> <p><hr> <strong>Result</strong> (so far): Here we go, this is what you can easily get with matplotlib. </p> <p><a href="http://i.stack.imgur.com/dw7qo.png" rel="nofollow"><img src="http://i.stack.imgur.com/dw7qo.png" alt="enter image description here"></a></p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.image as mpimg from datetime import datetime, timedelta import collections import csv class Anim(): """ This class provides a "live" plot of the contents of a log file in csv format. The class structure makes it easy to separate the plot generation from the frequent updating of the plot. The code is based on a question at stackoverflow http://stackoverflow.com/questions/39858501/python-data-display-with-graph """ def __init__(self): self.offset = 16. self.slope = -.2081 self.i = 0 self.axisbg = '#07000d' self.fig = plt.figure(figsize=(15,8), facecolor=self.axisbg) self.ax = self.fig.add_subplot(111, axisbg=self.axisbg) [self.ax.spines[wh].set_color("#5998ff") for wh in ['bottom', 'top', 'left', 'right']] self.hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p') self.ax.xaxis.set_major_formatter(self.hfmt) self.fig.autofmt_xdate() #self.framenumber = plt.figtext(0.9, .9, "0", color='w') self.ax.grid(True, color='w') plt.ylabel('Tension (lb)', color='w', fontsize=20) plt.title('Spiral 1 Tension', color='w', fontsize=26) self.ax.tick_params(axis='y', colors='w') self.ax.tick_params(axis='x', colors='w') initialx = [self.stime("09/28/2016 17:34:28.967"),self.stime("09/28/2016 17:34:29.716") ] initialy = [0,0 ] self.line1, = self.ax.plot(matplotlib.dates.date2num(initialx), initialy, color="c", linewidth=6) self.line2, = self.ax.plot(matplotlib.dates.date2num(initialx), initialy, color="r", linewidth=6) self.line3, = self.ax.plot(matplotlib.dates.date2num(initialx), initialy, color="y", linewidth=6) plt.subplots_adjust(left=0.1, bottom=0.28, right=0.9, top=0.9, wspace=0, hspace=0) self.ax_temp = plt.axes([0.1, 0.08, 0.2, 0.06], axisbg=self.axisbg) self.ax_time = plt.axes([0.2, 0.08, 0.2, 0.06], axisbg=self.axisbg) self.ax_overdrive = plt.axes([0.4, 0.08, 0.2, 0.06], axisbg=self.axisbg) self.ax_cycles = plt.axes([0.5, 0.08, 0.2, 0.06], axisbg=self.axisbg) self.ax_image = plt.axes([0.75, 0.03, 0.3, 0.2], axisbg=self.axisbg) self.tx_temp = self.ax_temp.text(0,0, "Temp", color="w", transform=self.ax_temp.transAxes, bbox={"pad" : 10, "ec" : "w", "fc" : self.axisbg}) self.tx_time = self.ax_time.text(0,0, "Time", color="w", transform=self.ax_time.transAxes, bbox={"pad" : 10, "ec" : "w", "fc" : self.axisbg}) self.tx_overdrive = self.ax_overdrive.text(0,0, "Overdrive", color="w", transform=self.ax_overdrive.transAxes, bbox={"pad" : 10, "ec" : "w", "fc" : self.axisbg}) self.tx_cycles = self.ax_cycles.text(0,0, "Cyles", color="w", transform=self.ax_cycles.transAxes, bbox={"pad" : 10, "ec" : "w", "fc" : self.axisbg}) self.ax_image.imshow(mpimg.imread('mmbRy.jpg')) self.ax_image.tick_params(axis='x',which='both',bottom='off', top='off',labelbottom='off') self.ax_image.tick_params(axis='y',which='both',left='off', right='off',labelleft='off') [self.ax_image.spines[wh].set_color("#5998ff") for wh in ['bottom', 'top', 'left', 'right']] self.timer = self.fig.canvas.new_timer(interval=250, callbacks=[(self.animate, [], {})]) self.timer.start() plt.show() def plot(self, data, line): if data: last_dt = data[0][0] gap = timedelta(seconds=10) x = [] y = [] # Plot groups of data not more than 60 seconds apart for dt, ten in data: if dt &lt;= last_dt + gap: x.append(dt) y.append(ten) else: line.set_data(matplotlib.dates.date2num(x), y) #ax.plot(, colour, linewidth=width) x = [dt] y = [ten] last_dt = dt line.set_data(matplotlib.dates.date2num(x), y) def animate(self): self.i +=1 #counting the number of frames # Read in the CSV file data = collections.defaultdict(list) fields = ["TimeStamp", "ReadCount", "Antenna", "Protocol", "RSSI", "EPC", "Temp", "Ten", "Powr", "Unpowr", "Inf"] temp = "" # the complete file is read in, which might be a problem once the file gets very large with open('SensorLogFile.csv') as f_input: csv_input = csv.DictReader(f_input, skipinitialspace=True, fieldnames=fields) header = next(csv_input) # Separate the rows based on the Antenna field for row in csv_input: try: data[row['Antenna']].append([self.stime(row['TimeStamp']), self.rten(row['Ten']) ]) temp= row['Temp'] except: pass # Drop any data points more than 1.5 mins older than the last entry latest_dt = data[row['Antenna']][-1][0] # Last entry not_before = latest_dt - timedelta(minutes=.25) for antenna, entries in data.items(): data[antenna] = [[dt, count] for dt, count in entries if dt &gt;= not_before] self.plot(data['1'], self.line1) # Antenna 1 self.plot(data['2'], self.line2) # Antenna 2 self.plot(data['3'], self.line3) # Antenna 3 #Filling the text boxes self.tx_temp.set_text(u"Temperature\n{temp:.2f} °F".format(temp=self.deg2F(temp))) self.tx_time.set_text("Time\n{time}".format(time=datetime.now().time()) ) self.tx_overdrive.set_text("Overdrive\nfill later") #Todo: how do you calculate this? self.tx_cycles.set_text("Cyles\n{cyles}".format(cyles=self.i)) #Todo: setting the limits correctly, depending on the user's need self.ax.set_ylim([0,16]) self.ax.set_xlim([matplotlib.dates.date2num(not_before), matplotlib.dates.date2num(latest_dt)]) #Update the canvas self.fig.canvas.draw() def deg2F(self,deg): return float(deg) * 9./5. + 32. def stime(self, timestamp): return datetime.strptime(timestamp, '%m/%d/%Y %H:%M:%S.%f') def rten(self, ten): return int(float(ten) * self.slope + self.offset) if __name__ == "__main__": Anim() </code></pre>
2
2016-10-04T18:33:55Z
[ "python", "matplotlib" ]
How to handle NA values when tokenizing the contents of a data frame?
39,858,543
<p>I have a pandas dataframe and I am trying to tokenize the contents of each row. </p> <pre><code>import pandas as pd import nltk as nk from nltk import word_tokenize TextData = pd.read_csv('TextData.csv') TextData['tokenized_summary'] = TextData.apply(lambda row: nk.word_tokenize(row['Summary']), axis=1) </code></pre> <p>When I run it, I get an error at line 67, </p> <pre><code>TypeError: ('expected string or buffer', u'occurred at index 67') </code></pre> <p>Which I think I am getting because the value for 'Summary' at iloc[67] is an NA value. </p> <pre><code>TextData.Summary.iloc[67] Out[45]: nan </code></pre> <p>Assuming it is the na value which is causing this, is there a way to tell word_tokenize or pandas to ignore the NA values whenever it comes across them? </p> <p>Else, what else might be causing this? </p>
0
2016-10-04T17:39:10Z
39,858,706
<p>You can use <code>fillna()</code> to replace NaN with a specified value:</p> <pre><code>import pandas as pd import nltk as nk from nltk import word_tokenize TextData = pd.read_csv('TextData.csv') TextData.fillna('some value') # or just: TextData['Summary'].fillna('some value') TextData['tokenized_summary'] = TextData.apply(lambda row: nk.word_tokenize(row['Summary']), axis=1) </code></pre> <hr> <h3>Previous Answer</h3> <p>You can simply "eliminate" the records where that value is null:</p> <pre><code>TextData = TextData[TextData['tokenized_summary'].notnull()] </code></pre> <p>Making the final product look like:</p> <pre><code>import pandas as pd import nltk as nk from nltk import word_tokenize TextData = pd.read_csv('TextData.csv') TextData = TextData[TextData['tokenized_summary'].notnull()] TextData['tokenized_summary'] = TextData.apply(lambda row: nk.word_tokenize(row['Summary']), axis=1) </code></pre>
1
2016-10-04T17:48:44Z
[ "python", "pandas", "nltk" ]
convert a text data to csv python
39,858,622
<p>I have a long text file where i was able to extract these lines by grabing just the ones that contain the word "Average":</p> <pre><code>Average time per layer: Average Forward pass: 4013.65 ms. Average Backward pass: 7425.13 ms. Average Forward-Backward: 11480.2 ms. </code></pre> <p>Here is what I need in a csv file so I can easily make a graph:</p> <pre><code>Average Forward pass 4013.65 Average Backward pass 7425.13 Average Forward-Backward 11480.2 </code></pre> <p>Here is the output I'm getting:</p> <pre><code> : 7425.13 ms. : 11480.2 ms. : : 4013.65 ms. </code></pre> <p>Here is what i have but it doesn't give me the right results:</p> <pre><code>def parse_output(outputName): "This reads the parsed file and formated it to a map" with open(outputName,'r') as parsedFile: entry = {} for line in parsedFile: key, value = map(line.strip, line.split(':',1)) entry[key] = value yield entry def print_csv(outputName, csvFile): "This reads the map and print it to csv" remove_file_exist(csvFile) for foo in parse_output(outputName): with open(csvFile, 'a') as csvFile: for entry in foo: csvFile.write(str(entry)) print(entry) print(foo); </code></pre> <p>I've tried to convert the original text to json, but didn't get it to work. any input will be appreciate it. I'm very very new to python. This is my first script in this language. </p>
0
2016-10-04T17:43:39Z
39,858,711
<p>You can use a <a href="https://www.regex101.com/r/O4njRs/1" rel="nofollow">regex</a> on data like this:</p> <pre><code>txt='''\ Average time per layer: Average Forward pass: 4013.65 ms. Average Backward pass: 7425.13 ms. Average Forward-Backward: 11480.2 ms.''' import re for k,v in re.findall(r'^([^:]+):\s*(\d+\.\d+)', txt, re.M): print k, v </code></pre>
0
2016-10-04T17:49:01Z
[ "python", "csv" ]
convert a text data to csv python
39,858,622
<p>I have a long text file where i was able to extract these lines by grabing just the ones that contain the word "Average":</p> <pre><code>Average time per layer: Average Forward pass: 4013.65 ms. Average Backward pass: 7425.13 ms. Average Forward-Backward: 11480.2 ms. </code></pre> <p>Here is what I need in a csv file so I can easily make a graph:</p> <pre><code>Average Forward pass 4013.65 Average Backward pass 7425.13 Average Forward-Backward 11480.2 </code></pre> <p>Here is the output I'm getting:</p> <pre><code> : 7425.13 ms. : 11480.2 ms. : : 4013.65 ms. </code></pre> <p>Here is what i have but it doesn't give me the right results:</p> <pre><code>def parse_output(outputName): "This reads the parsed file and formated it to a map" with open(outputName,'r') as parsedFile: entry = {} for line in parsedFile: key, value = map(line.strip, line.split(':',1)) entry[key] = value yield entry def print_csv(outputName, csvFile): "This reads the map and print it to csv" remove_file_exist(csvFile) for foo in parse_output(outputName): with open(csvFile, 'a') as csvFile: for entry in foo: csvFile.write(str(entry)) print(entry) print(foo); </code></pre> <p>I've tried to convert the original text to json, but didn't get it to work. any input will be appreciate it. I'm very very new to python. This is my first script in this language. </p>
0
2016-10-04T17:43:39Z
39,858,880
<p>It would help to show us what output you are getting versus what you expect. However it looks to me like you are writing <code>str(entry)</code> to a file, where <code>entry</code> is a dict, and expecting it to render as a csv line. I suspect it will look a little more similar to one JSON object per line.</p> <p>Whenever you want to write or read csv's in Python, the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow" title="csv">csv</a> module is usually a good first stop. You might do better with something like this:</p> <pre><code>import csv def parse_output(outputname): with open(outputname, 'r') as output: for row in output: yield [field.strip() for field in row.split(':', 1)] def print_csv(outputname, csvname): with open(csvname, 'wb') as csvfile: csvfile = csv.writer(csvfile) for parsedline in parse_output(outputname): csvfile.write(parsedline) </code></pre>
0
2016-10-04T17:59:47Z
[ "python", "csv" ]
What tool or algorithm should I use to generate words from a keyword which is at a given Damerau–Levenshtein distance?
39,858,659
<p>Damerau-Levenshtein distance is like:</p> <pre><code>"abcd", "aacd" =&gt; 1 DL distance "abcd", "aadc" =&gt; 2 DL distance </code></pre> <ul> <li>More about editdistance: <a href="https://pypi.python.org/pypi/editdistance" rel="nofollow">https://pypi.python.org/pypi/editdistance</a></li> <li>More about Damerau-Levenshtein distance: <a href="https://pypi.python.org/pypi/pyxDamerauLevenshtein" rel="nofollow">https://pypi.python.org/pypi/pyxDamerauLevenshtein</a></li> </ul> <p>I can use pyxDamerauLevenshtein modul in python to determine the DL distance of 2 words. I would like to make a generator method which can produce every words of a given keyword parameter in a given DL distance. I deal with 1 or 2 DL distances only.</p> <p>Are any tool in python which can I use to generate words of a word in a given DL distance?</p>
0
2016-10-04T17:45:49Z
39,858,843
<p>Look at this Norvig's article: <a href="http://norvig.com/spell-correct.html" rel="nofollow">How to Write a Spelling Corrector</a>.</p> <p>It contains the exact code that you need:</p> <pre><code>def edits1(word): "All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)&gt;1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) def edits2(word): "All edits that are two edits away from `word`." return (e2 for e1 in edits1(word) for e2 in edits1(e1)) </code></pre>
2
2016-10-04T17:58:04Z
[ "python", "edit-distance" ]
Python 3.5.1 - Much needed advice with a year old piece of code
39,858,707
<p>I've been trying to create a turn-based RPG using what meager knowledge of Python I have scince early 2015, but I abandoned the project because of a problem with this piece of code:</p> <pre><code>pattack="" pnote="" pdmg=0 ppriority=0 selectmove=int(input("Select move number 1-4")) if selectmove==1: pattack="Fire Ball" pdmg=pdmg+150 ppriority=ppriority+60 pnote="A firey ball is shot at the enemy" elif selectmove==2: pattack="Thunder Bolt" pdmg=pdmg+100 ppriority=ppriority+80 pnote="A bolt of electricity is shot at the enemy" elif selectmove==3: pattack="Leaf Wirlwind" pdmg=pdmg+175 ppriority=ppriority+50 pnote="A Wirlwind of razor sharp leaves is sent to the enemy" elif selectmove==4: pattack="Icicle Shot" pdmg=pdmg+75 ppriority=ppriority+100 pnote="A sharp icicle is shot at the enemy" pdmg=int(pdmg) ppriority=int(ppriority) print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" "))` </code></pre> <p>All I ever get is this error message:</p> <pre><code>`Traceback (most recent call last): File "C:\Users\Alberto\Desktop\My Test RPG\Battle System Idea\An Idea I have.py", line 30, in &lt;module&gt; print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" ")) ValueError: invalid literal for int() with base 10: 'Used the move Fire Ball\nDealt 150 Damage\nHas a priority of 60\nMove description: *NOT FINAL*\nA firey ball is shot at the enemy " </code></pre>
-2
2016-10-04T17:48:44Z
39,858,772
<pre><code>print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" ")) </code></pre> <p>That line should be:</p> <pre><code>print("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" ") </code></pre> <p>You don't want to convert the entire string to <code>int</code>.</p>
1
2016-10-04T17:52:20Z
[ "python", "python-3.x" ]
Python 3.5.1 - Much needed advice with a year old piece of code
39,858,707
<p>I've been trying to create a turn-based RPG using what meager knowledge of Python I have scince early 2015, but I abandoned the project because of a problem with this piece of code:</p> <pre><code>pattack="" pnote="" pdmg=0 ppriority=0 selectmove=int(input("Select move number 1-4")) if selectmove==1: pattack="Fire Ball" pdmg=pdmg+150 ppriority=ppriority+60 pnote="A firey ball is shot at the enemy" elif selectmove==2: pattack="Thunder Bolt" pdmg=pdmg+100 ppriority=ppriority+80 pnote="A bolt of electricity is shot at the enemy" elif selectmove==3: pattack="Leaf Wirlwind" pdmg=pdmg+175 ppriority=ppriority+50 pnote="A Wirlwind of razor sharp leaves is sent to the enemy" elif selectmove==4: pattack="Icicle Shot" pdmg=pdmg+75 ppriority=ppriority+100 pnote="A sharp icicle is shot at the enemy" pdmg=int(pdmg) ppriority=int(ppriority) print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" "))` </code></pre> <p>All I ever get is this error message:</p> <pre><code>`Traceback (most recent call last): File "C:\Users\Alberto\Desktop\My Test RPG\Battle System Idea\An Idea I have.py", line 30, in &lt;module&gt; print(int("Used the move "+pattack+"\nDealt "+str(pdmg)+" Damage\nHas a priority of "+str(ppriority)+"\nMove description: *NOT FINAL*\n"+pnote+" ")) ValueError: invalid literal for int() with base 10: 'Used the move Fire Ball\nDealt 150 Damage\nHas a priority of 60\nMove description: *NOT FINAL*\nA firey ball is shot at the enemy " </code></pre>
-2
2016-10-04T17:48:44Z
39,858,883
<p>In your last <code>print</code> line, you don't need the <code>int()</code> call: it's only used to convert a value into an integer, which that string is not.</p>
0
2016-10-04T18:00:04Z
[ "python", "python-3.x" ]
incorrect http protocol shown by chrome developer tools?
39,858,729
<p>I am checking the http protcol in use for this site <a href="http://www.dlf.in/" rel="nofollow">http://www.dlf.in/</a> Chrome developer tools shows it to be http/1.1 as in the image below.</p> <p>However the command line tool <a href="https://www.npmjs.com/package/is-http2-cli" rel="nofollow">is-http2</a> or alpn in python as seems to indicate the http/1.1 is not available. And only http1 is available. What's going on here?</p> <p>I am doing the ALPN negotiation in python as follows (openssl version : OpenSSL 1.0.2h and python version 3.5.1)</p> <pre><code>import ssl import socket port = 443 domain = 'www.dlf.in' ctx = ssl.create_default_context() ctx.set_alpn_protocols(['h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1']) conn = ctx.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), server_hostname=domain) conn.connect((domain, port)) print(conn.selected_alpn_protocol()) </code></pre> <p><a href="http://i.stack.imgur.com/OQbyi.png" rel="nofollow"><img src="http://i.stack.imgur.com/OQbyi.png" alt="network tab of chrome develper tools for dlf.in"></a></p>
0
2016-10-04T17:50:05Z
39,859,241
<p>That site doesn't have HTTPS on it. Browsers only support HTTP/2 over HTTPS despite the spec allowing it over HTTP in theory.</p>
0
2016-10-04T18:22:41Z
[ "python", "google-chrome", "http2", "http-1.1", "alpn" ]
incorrect http protocol shown by chrome developer tools?
39,858,729
<p>I am checking the http protcol in use for this site <a href="http://www.dlf.in/" rel="nofollow">http://www.dlf.in/</a> Chrome developer tools shows it to be http/1.1 as in the image below.</p> <p>However the command line tool <a href="https://www.npmjs.com/package/is-http2-cli" rel="nofollow">is-http2</a> or alpn in python as seems to indicate the http/1.1 is not available. And only http1 is available. What's going on here?</p> <p>I am doing the ALPN negotiation in python as follows (openssl version : OpenSSL 1.0.2h and python version 3.5.1)</p> <pre><code>import ssl import socket port = 443 domain = 'www.dlf.in' ctx = ssl.create_default_context() ctx.set_alpn_protocols(['h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1']) conn = ctx.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), server_hostname=domain) conn.connect((domain, port)) print(conn.selected_alpn_protocol()) </code></pre> <p><a href="http://i.stack.imgur.com/OQbyi.png" rel="nofollow"><img src="http://i.stack.imgur.com/OQbyi.png" alt="network tab of chrome develper tools for dlf.in"></a></p>
0
2016-10-04T17:50:05Z
39,859,372
<p>Using <code>telnet</code> and <code>HTTPie</code> to send HTTP requests (both 1.0 and 1.1), the web server responds with:</p> <blockquote> <p>HTTP/1.1 200 OK</p> </blockquote> <p>I tried it with 2.0 and got:</p> <blockquote> <p>HTTP/1.1 505 HTTP Version Not Supported</p> </blockquote>
0
2016-10-04T18:31:26Z
[ "python", "google-chrome", "http2", "http-1.1", "alpn" ]
Stopwatch implementing python
39,858,802
<p>I got this code for an assignment:</p> <pre><code>from stop_watch import StopWatch size = 1000000 stopWatch = StopWatch() sum = 0 for i in range(1, size + 1): sum += i stopWatch.stop() print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds") </code></pre> <p>I have to create a class which generates a stopwatch and this is my code:</p> <pre><code>import time class StopWatch: def __init__(self): pass def start(self): self.start = time.time() return self.start def stop(self): self.stop = time.time() return self.stop def get_elapsed_time(self): print(str(self.stop-self.start)) </code></pre> <p>I get this error:</p> <pre><code>File "week33.py", line 10, in &lt;module&gt; print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds") File "/Users/Marinkton/Desktop/stop_watch.py", line 16, in get_elapsed_time print(str(self.stop-self.start)) TypeError: unsupported operand type(s) for -: 'float' and 'method' </code></pre> <hr> <p>What am I doing wrong? I could not discover a mistake. </p>
0
2016-10-04T17:54:39Z
39,858,851
<p>You can't name your functions and your properties the same thing. When you do <code>self.stop = time.time()</code>, you overwrite the function <code>stop</code>.</p> <p>You need to change the name of the internal fields.</p> <pre><code>import time class StopWatch: def __init__(self): self.start_time = 0 self.stop_time = 0 def start(self): self.start_time = time.time() return self.start_time def stop(self): self.stop_time = time.time() return self.stop_time def get_elapsed_time(self): print(str(self.stop_time - self.start_time)) </code></pre> <p>PS: You're never calling start in your code.</p>
5
2016-10-04T17:58:24Z
[ "python", "python-3.x" ]
scipy.io.loadmat returns MemoryError for big matlab structures
39,858,857
<p>I want to open and process some big .mat files in python. The scipy.io.loadmat function is perfect for that purpose. However, the function returns MemoryError when the .mat files are big. The problem might be due to the python version I use (Python 2.7.10 32 bits, interfaced with spyder). This problem has already been raised but I can't find any decent solution. Ideally, I would be able to open these files without changing my python. Is there a way to make the scipy.io.loadmat function load just some variables contained in the .mat file? </p>
0
2016-10-04T17:58:32Z
39,858,926
<p>See the documentation here: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html</a></p> <p>You can pass a list of variable names to read from the file:</p> <pre><code>scipy.io.loadmat("myfile.mat", variable_names=["myvar1", "myvar2"]) </code></pre>
2
2016-10-04T18:02:38Z
[ "python", "matlab", "scipy", "32-bit" ]
Run build for C++ code (make) in Python script
39,858,958
<p>I keep running into an error when I want to compile code written in C++ using Python script to run "make" in x directory. Compiling the code takes about few seconds so I am using time module to have the script sleep for 60 seconds to finish compiling the code.</p> <p><strong>Here is the code:</strong></p> <pre><code>from subprocess import call from time import sleep def make_ut_adsmain(): os.system("make ../../ads/main/unittest") # call(["ls", "-l"]) sleep(60) make_ut_adsmain() # Run other functions when compiled... </code></pre> <p><strong>Error</strong> </p> <pre><code>make: *** No rule to make target `../../ads/main/unittest'. Stop. </code></pre> <p>The code never really compiles because the rest of the code depends on the log file which never gets created. Please guide me.</p>
0
2016-10-04T18:04:45Z
39,859,223
<p>I actually figured it out and able to run the build process by using the following code:</p> <pre><code>import subprocess from time import sleep def make_ut_adsmain(): subprocess.Popen(["make"], stdout=subprocess.PIPE, cwd="../../ads/main/unitest") sleep(60) make_ut_adsmain() </code></pre> <p>Note, the previous solution works only if you need to bypass errors. The correct way to do is the following. Check @tdelaney comment and read more on python docs <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">https://docs.python.org/2/library/subprocess.html</a></p> <pre><code>import subprocess from time import sleep def make_ut_adsmain(): subprocess.check_all(["make"], cwd="../../ads/main/unitest") make_ut_adsmain() </code></pre>
1
2016-10-04T18:21:03Z
[ "python", "c++", "shell", "scripting" ]
create panda dataframe and append values in for loop
39,858,961
<p>I have a list from which I would like to iterate over and create tuples in a pandas dataframe in order to imitate sliding window of size 4. What I am trying to do is:</p> <pre><code>tuples = pd.DataFrame() for index, row in expertsDF.iterrows(): newlst = row['name'] counter = 0 for x in newlst: if counter &lt; len(newlst) - 3: tuples['A'] = x tuples['B'] =newlst(counter+1) tuples['C'] =newlst(counter+2) tuples['D'] =newlst(counter+3) counter = counter + 1 </code></pre> <p>the newlst looks like this:</p> <pre><code>list (var1, var2, var3....) </code></pre> <p>and my DataFrame should be like this:</p> <pre><code> A B C D 1 var1 var2 var3 var4 2 var2 var3 var4 var5 3 var3 var4 var5 var6 </code></pre> <p>Is there a way to do that in python?</p>
1
2016-10-04T18:05:03Z
39,860,977
<p>Is this close?</p> <pre><code>import pandas as pd tuples = pd.DataFrame(columns=['A', 'B', 'C', 'D']) newlst = "abcdefg" i = 0 for x in newlst: if i &lt; len(newlst) - 3: t = pd.DataFrame([[x, newlst[i + 1], newlst[i + 2], newlst[i + 3]]], columns=['A', 'B', 'C', 'D']) tuples = tuples.append(t, ignore_index=True) i += 1 print tuples </code></pre> <p>This prints:</p> <pre><code> A B C D 0 a b c d 1 b c d e 2 c d e f 3 d e f g </code></pre>
1
2016-10-04T20:13:38Z
[ "python", "list", "dataframe", "append" ]
create panda dataframe and append values in for loop
39,858,961
<p>I have a list from which I would like to iterate over and create tuples in a pandas dataframe in order to imitate sliding window of size 4. What I am trying to do is:</p> <pre><code>tuples = pd.DataFrame() for index, row in expertsDF.iterrows(): newlst = row['name'] counter = 0 for x in newlst: if counter &lt; len(newlst) - 3: tuples['A'] = x tuples['B'] =newlst(counter+1) tuples['C'] =newlst(counter+2) tuples['D'] =newlst(counter+3) counter = counter + 1 </code></pre> <p>the newlst looks like this:</p> <pre><code>list (var1, var2, var3....) </code></pre> <p>and my DataFrame should be like this:</p> <pre><code> A B C D 1 var1 var2 var3 var4 2 var2 var3 var4 var5 3 var3 var4 var5 var6 </code></pre> <p>Is there a way to do that in python?</p>
1
2016-10-04T18:05:03Z
39,861,302
<p>How about creating the DataFrame from Series objects?</p> <pre><code>import pandas as pd data_list = list(map(lambda x: 'var{}'.format(x),range(0,100))) df = pd.Series(data_list[0:97]).to_frame(name='A') df['B'] = pd.Series(data_list[1:98]) df['C'] = pd.Series(data_list[2:99]) df['D'] = pd.Series(data_list[3:100]) df.head() # output # A B C D # 0 var0 var1 var2 var3 # 1 var1 var2 var3 var4 # 2 var2 var3 var4 var5 # 3 var3 var4 var5 var6 # 4 var4 var5 var6 var7 </code></pre>
1
2016-10-04T20:36:02Z
[ "python", "list", "dataframe", "append" ]
Time Comparison Multithreading
39,859,010
<p>I have a program that reads some input text files and write all of them into one separate file. I used two threads so it runs faster! I tried the following python code with both one thread and two threads! Why when I run with one thread it runs faster than when I run it with two threads?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>processedFiles=[] # Define a function for the threads def print_time( threadName, delay): for file in glob.glob("*.txt"): #check if file has been read by another thread already if file not in processedFiles: processedFiles.append(file) f = open(file,"r") lines = f.readlines() f.close() time.sleep(delay) f = open('myfile','a') f.write("%s \n" %lines) # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructor will call it print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: f = open('myfile', 'r+') f.truncate() start = timeit.default_timer() t1 = Thread(target=print_time, args=("Thread-1", 0,)) t2 = Thread(target=print_time, args=("Thread-2", 0,)) t1.start() t2.start() stop = timeit.default_timer() print stop - start except: print "Error: unable to start thread"</code></pre> </div> </div> </p>
0
2016-10-04T18:07:19Z
39,859,832
<p>You have several problems I'll get to in a moment, but generally your program is disk-bound (it can't go faster than your hard drive) so even a properly threaded program isn't any faster. It can be hard to measure disk performance because of the file system cache: You run this once with threads and you go at hard drive speed, you run it again without threads and the files are in the system so go fast. It makes it hard to figure out how the code will perform later when the data no longer in the system cache.</p> <p>So now for the problems.</p> <p><code>if file not in processedFiles:</code> isn't thread safe. Both threads could look at an empty list and decide to copy the same file. At a minimum you need a lock. Or you could do the <code>glob</code> once and pass the files to a queue that are read by the thread.</p> <p>Reading the file line-by-line then joining with <code>\n</code> is a crazy slow way to write a file. Use <code>shutil.copyfileobj</code> instead - its built to copy files efficiently.</p> <p><code>f = open('myfile','a')</code> now you have multiple file descriptors to a single file and each will advance their file pointers independently.... so one overwrites the other.</p> <p><code>f.write("%s \n" %lines)</code> is also not thread safe. You could end up with bits of the files interleaving each other in the output file.</p> <p><code>stop = timeit.default_timer()</code> - you didn't wait for the threads to complete their work so you didn't really measure anything useful. Code code severely under-reports execution time.</p> <p>You are much better off with a simple single-threaded script.</p>
0
2016-10-04T18:59:55Z
[ "python", "multithreading" ]
Matrix in python with a set column
39,859,062
<p>So I'm trying to make a 2x3 matrix with the output </p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[[1., 1980], [1., 1981], [1.,1982]] </code></pre> <p>However the output I'm getting is:</p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[1.0, [1980, 1981, 1982]] </code></pre> <p>my code is:</p> <pre><code>def l(x): for i in range(len(x)): xl = [1., x] return xl </code></pre> <p>I know I have to reiterate it multiple times using a for loop, but I'm not entirely sure how to do it.</p>
0
2016-10-04T18:11:16Z
39,859,106
<p>Here's a nice way to do it with a list comprehension:</p> <pre><code>def l(x): return [[1., e] for e in x] </code></pre>
4
2016-10-04T18:13:59Z
[ "python", "list", "matrix" ]
Matrix in python with a set column
39,859,062
<p>So I'm trying to make a 2x3 matrix with the output </p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[[1., 1980], [1., 1981], [1.,1982]] </code></pre> <p>However the output I'm getting is:</p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[1.0, [1980, 1981, 1982]] </code></pre> <p>my code is:</p> <pre><code>def l(x): for i in range(len(x)): xl = [1., x] return xl </code></pre> <p>I know I have to reiterate it multiple times using a for loop, but I'm not entirely sure how to do it.</p>
0
2016-10-04T18:11:16Z
39,859,107
<p>What you want is </p> <pre><code>def l(x): xl = [] for i in range(len(x)): xl.append([1., x[i]]) return xl </code></pre> <p>Or, since there is no need to use the index <code>i</code> for anything other than indexing the elements of <code>x</code>, you can use:</p> <pre><code>def l(x): xl = [] for e in x: xl.append([1., e]) return xl </code></pre> <p>Or you can simply compress all of this into a list concatenation as in Tim's answer:</p> <pre><code>def l(x): return [[1., e] for e in x] </code></pre>
1
2016-10-04T18:14:07Z
[ "python", "list", "matrix" ]
Matrix in python with a set column
39,859,062
<p>So I'm trying to make a 2x3 matrix with the output </p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[[1., 1980], [1., 1981], [1.,1982]] </code></pre> <p>However the output I'm getting is:</p> <pre><code> &gt;&gt;&gt;l([1980, 1981, 1982]) &gt;&gt;&gt;[1.0, [1980, 1981, 1982]] </code></pre> <p>my code is:</p> <pre><code>def l(x): for i in range(len(x)): xl = [1., x] return xl </code></pre> <p>I know I have to reiterate it multiple times using a for loop, but I'm not entirely sure how to do it.</p>
0
2016-10-04T18:11:16Z
39,859,184
<p>You can use <code>map</code> also:</p> <pre><code>&gt;&gt;&gt; li=[1980, 1981, 1982] &gt;&gt;&gt; map(lambda e: [1.0]+[e], li) [[1.0, 1980], [1.0, 1981], [1.0, 1982]] </code></pre> <p>Or, if you don't mind a list of tuples:</p> <pre><code>&gt;&gt;&gt; zip((1.0,)*len(li),li) [(1.0, 1980), (1.0, 1981), (1.0, 1982)] </code></pre> <p>Or, if you want to fix yours:</p> <pre><code>&gt;&gt;&gt; li2=[] &gt;&gt;&gt; for e in li: ... li2.append([1.0,e]) ... &gt;&gt;&gt; li2 [[1.0, 1980], [1.0, 1981], [1.0, 1982]] </code></pre>
0
2016-10-04T18:19:08Z
[ "python", "list", "matrix" ]
Directories - Why is this erroring out?
39,859,092
<p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p> <pre><code>secretpassageunearthed = 'No' pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' = '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'instructions': '0', 'letter': '0', 'key3': '0', 'oar': '0', 'boat': '0', 'red button': '0', 'eaglenest': '0', 'faberge egg': '0', 'trophy case': '0', 'facial': '0', 'gun': '0', 'safe': '0', 'diamond ring': '0', 'junk': '0', 'combination': '0', 'egg': '0', 'flashlight': '0', 'cork': '0', 'bottle': '0', 'oil': '0', 'crown': '0', 'shovel': '0', 'knob': '0', 'twinkies': '0', 'scanner': '0', 'toychest': '0'} #has the player been in the room? beenin = {'frontdoor': '0', 'forest': '0', 'forest2': '0', 'forest3': '0', 'forest4': '0', 'lakeshore': '0', 'garden': '0', 'shed': '0', 'lake': '0', 'farshore': '0', 'cliff1': '0', 'cliff2': '0', 'cliff3': '0', 'cliff4': '0', 'clifftop': '0', 'frontsteps': '0', 'frontlawn': '0', 'gate': '0', 'sittingroom': '0', 'livingroom': '0', 'pantry': '0', 'foyer': '0', 'trophyroom': '0', 'hall1': '0', 'diningroom': '0', 'kitchen': '0', 'elevatorup': '0', 'hall3': '0', 'hall2': '0', 'masterbed': '0', 'closet': '0', 'nursery': '0', 'bath': '0', 'guestroom': '0', 'study': '0', 'secretroom': '0', 'servantdining': '0', 'servantbath': '0', 'servantroom': '0', 'boilerroom': '0', 'mechanicalroom': '0', 'winecellar': '0', 'deadend': '0', 'torturechamber': '0', 'morgue': '0'} maxweight = 50 weights = {'broom': 5, 'rope': 8, 'torch': 5, 'coffin': 40, 'skeleton': 9, 'key1': 2, 'key2': 1, 'rock': 4, 'instructions': 0, 'mailbox': 60, 'letter': 1, 'gargoyle': 60, 'key3': 1, 'blockade': 60, 'oar': 5, 'boat': 30, 'button': 1, 'eagle nest': 60, 'faberge egg': 10, 'trophy case': 60, 'book': 3, 'facial': 1, 'gun': 3, 'safe': 60, 'diamondring': 5, 'junk': 1, 'combo': 1, 'egg': 1, 'flashlight': 3, 'oil': 4, 'bottle': 3, 'cork': 1, 'chandelier': 60, 'crown': 5, 'shovel': 5, 'knob': 3, 'twinkies': 2, 'pot of gold': 30, 'painting': 20, 'scanner': 60, 'toychest': 55} </code></pre> <p>Any help on why they are erroring out would be appreciated.</p>
0
2016-10-04T18:13:14Z
39,859,146
<p>You can't use <code>=</code> to assign in a dictionary</p> <p>Change <code>=</code> to <code>:</code> and this should work:</p> <pre><code>secretpassageunearthed = 'No' pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' : '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'instructions': '0', 'letter': '0', 'key3': '0', 'oar': '0', 'boat': '0', 'red button': '0', 'eaglenest': '0', 'faberge egg': '0', 'trophy case': '0', 'facial': '0', 'gun': '0', 'safe': '0', 'diamond ring': '0', 'junk': '0', 'combination': '0', 'egg': '0', 'flashlight': '0', 'cork': '0', 'bottle': '0', 'oil': '0', 'crown': '0', 'shovel': '0', 'knob': '0', 'twinkies': '0', 'scanner': '0', 'toychest': '0'} #has the player been in the room? beenin = {'frontdoor': '0', 'forest': '0', 'forest2': '0', 'forest3': '0', 'forest4': '0', 'lakeshore': '0', 'garden': '0', 'shed': '0', 'lake': '0', 'farshore': '0', 'cliff1': '0', 'cliff2': '0', 'cliff3': '0', 'cliff4': '0', 'clifftop': '0', 'frontsteps': '0', 'frontlawn': '0', 'gate': '0', 'sittingroom': '0', 'livingroom': '0', 'pantry': '0', 'foyer': '0', 'trophyroom': '0', 'hall1': '0', 'diningroom': '0', 'kitchen': '0', 'elevatorup': '0', 'hall3': '0', 'hall2': '0', 'masterbed': '0', 'closet': '0', 'nursery': '0', 'bath': '0', 'guestroom': '0', 'study': '0', 'secretroom': '0', 'servantdining': '0', 'servantbath': '0', 'servantroom': '0', 'boilerroom': '0', 'mechanicalroom': '0', 'winecellar': '0', 'deadend': '0', 'torturechamber': '0', 'morgue': '0'} maxweight = 50 weights = {'broom': 5, 'rope': 8, 'torch': 5, 'coffin': 40, 'skeleton': 9, 'key1': 2, 'key2': 1, 'rock': 4, 'instructions': 0, 'mailbox': 60, 'letter': 1, 'gargoyle': 60, 'key3': 1, 'blockade': 60, 'oar': 5, 'boat': 30, 'button': 1, 'eagle nest': 60, 'faberge egg': 10, 'trophy case': 60, 'book': 3, 'facial': 1, 'gun': 3, 'safe': 60, 'diamondring': 5, 'junk': 1, 'combo': 1, 'egg': 1, 'flashlight': 3, 'oil': 4, 'bottle': 3, 'cork': 1, 'chandelier': 60, 'crown': 5, 'shovel': 5, 'knob': 3, 'twinkies': 2, 'pot of gold': 30, 'painting': 20, 'scanner': 60, 'toychest': 55} </code></pre>
0
2016-10-04T18:16:52Z
[ "python", "directory", "adventure" ]
Directories - Why is this erroring out?
39,859,092
<p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p> <pre><code>secretpassageunearthed = 'No' pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' = '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'instructions': '0', 'letter': '0', 'key3': '0', 'oar': '0', 'boat': '0', 'red button': '0', 'eaglenest': '0', 'faberge egg': '0', 'trophy case': '0', 'facial': '0', 'gun': '0', 'safe': '0', 'diamond ring': '0', 'junk': '0', 'combination': '0', 'egg': '0', 'flashlight': '0', 'cork': '0', 'bottle': '0', 'oil': '0', 'crown': '0', 'shovel': '0', 'knob': '0', 'twinkies': '0', 'scanner': '0', 'toychest': '0'} #has the player been in the room? beenin = {'frontdoor': '0', 'forest': '0', 'forest2': '0', 'forest3': '0', 'forest4': '0', 'lakeshore': '0', 'garden': '0', 'shed': '0', 'lake': '0', 'farshore': '0', 'cliff1': '0', 'cliff2': '0', 'cliff3': '0', 'cliff4': '0', 'clifftop': '0', 'frontsteps': '0', 'frontlawn': '0', 'gate': '0', 'sittingroom': '0', 'livingroom': '0', 'pantry': '0', 'foyer': '0', 'trophyroom': '0', 'hall1': '0', 'diningroom': '0', 'kitchen': '0', 'elevatorup': '0', 'hall3': '0', 'hall2': '0', 'masterbed': '0', 'closet': '0', 'nursery': '0', 'bath': '0', 'guestroom': '0', 'study': '0', 'secretroom': '0', 'servantdining': '0', 'servantbath': '0', 'servantroom': '0', 'boilerroom': '0', 'mechanicalroom': '0', 'winecellar': '0', 'deadend': '0', 'torturechamber': '0', 'morgue': '0'} maxweight = 50 weights = {'broom': 5, 'rope': 8, 'torch': 5, 'coffin': 40, 'skeleton': 9, 'key1': 2, 'key2': 1, 'rock': 4, 'instructions': 0, 'mailbox': 60, 'letter': 1, 'gargoyle': 60, 'key3': 1, 'blockade': 60, 'oar': 5, 'boat': 30, 'button': 1, 'eagle nest': 60, 'faberge egg': 10, 'trophy case': 60, 'book': 3, 'facial': 1, 'gun': 3, 'safe': 60, 'diamondring': 5, 'junk': 1, 'combo': 1, 'egg': 1, 'flashlight': 3, 'oil': 4, 'bottle': 3, 'cork': 1, 'chandelier': 60, 'crown': 5, 'shovel': 5, 'knob': 3, 'twinkies': 2, 'pot of gold': 30, 'painting': 20, 'scanner': 60, 'toychest': 55} </code></pre> <p>Any help on why they are erroring out would be appreciated.</p>
0
2016-10-04T18:13:14Z
39,859,238
<p>As others have said, the problem is that you used <code>=</code> instead of <code>:</code> to assign a dictionary item.</p> <p>When you saw the error message, you may not have noticed that Python was trying to tell you exactly where the error was:</p> <pre><code> File "adventure.py", line 1 pickedup = {'coffin': '0', 'skeleton' = '0', 'rock': '0'} ^ SyntaxError: invalid syntax </code></pre> <p>See how the <code>^</code> is pointing right at the equals sign?</p>
0
2016-10-04T18:22:24Z
[ "python", "directory", "adventure" ]
Directories - Why is this erroring out?
39,859,092
<p>I am building a few directories for a program I am working on, but they keep erroring out when used within the game and without of it. Each line throws out the same error (<code>Syntax Error: invalid syntax</code>) and I am wondering why. The lines are:</p> <pre><code>secretpassageunearthed = 'No' pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' = '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'instructions': '0', 'letter': '0', 'key3': '0', 'oar': '0', 'boat': '0', 'red button': '0', 'eaglenest': '0', 'faberge egg': '0', 'trophy case': '0', 'facial': '0', 'gun': '0', 'safe': '0', 'diamond ring': '0', 'junk': '0', 'combination': '0', 'egg': '0', 'flashlight': '0', 'cork': '0', 'bottle': '0', 'oil': '0', 'crown': '0', 'shovel': '0', 'knob': '0', 'twinkies': '0', 'scanner': '0', 'toychest': '0'} #has the player been in the room? beenin = {'frontdoor': '0', 'forest': '0', 'forest2': '0', 'forest3': '0', 'forest4': '0', 'lakeshore': '0', 'garden': '0', 'shed': '0', 'lake': '0', 'farshore': '0', 'cliff1': '0', 'cliff2': '0', 'cliff3': '0', 'cliff4': '0', 'clifftop': '0', 'frontsteps': '0', 'frontlawn': '0', 'gate': '0', 'sittingroom': '0', 'livingroom': '0', 'pantry': '0', 'foyer': '0', 'trophyroom': '0', 'hall1': '0', 'diningroom': '0', 'kitchen': '0', 'elevatorup': '0', 'hall3': '0', 'hall2': '0', 'masterbed': '0', 'closet': '0', 'nursery': '0', 'bath': '0', 'guestroom': '0', 'study': '0', 'secretroom': '0', 'servantdining': '0', 'servantbath': '0', 'servantroom': '0', 'boilerroom': '0', 'mechanicalroom': '0', 'winecellar': '0', 'deadend': '0', 'torturechamber': '0', 'morgue': '0'} maxweight = 50 weights = {'broom': 5, 'rope': 8, 'torch': 5, 'coffin': 40, 'skeleton': 9, 'key1': 2, 'key2': 1, 'rock': 4, 'instructions': 0, 'mailbox': 60, 'letter': 1, 'gargoyle': 60, 'key3': 1, 'blockade': 60, 'oar': 5, 'boat': 30, 'button': 1, 'eagle nest': 60, 'faberge egg': 10, 'trophy case': 60, 'book': 3, 'facial': 1, 'gun': 3, 'safe': 60, 'diamondring': 5, 'junk': 1, 'combo': 1, 'egg': 1, 'flashlight': 3, 'oil': 4, 'bottle': 3, 'cork': 1, 'chandelier': 60, 'crown': 5, 'shovel': 5, 'knob': 3, 'twinkies': 2, 'pot of gold': 30, 'painting': 20, 'scanner': 60, 'toychest': 55} </code></pre> <p>Any help on why they are erroring out would be appreciated.</p>
0
2016-10-04T18:13:14Z
39,859,265
<p>The <a href="https://www.python.org/dev/peps/pep-0008/#id19" rel="nofollow">python style guide</a> recommends keeping lines &lt; 72 characters. Personally, I aim for 78. If you do that, your code is easier to read and as a bonus, its easier to spot problems. So for example, if you file was </p> <pre><code>secretpassageunearthed = 'No' pickedup = {'broom': '0', 'rope': '0', 'torch': '0', 'coffin': '0', 'skeleton' = '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', 'instructions': '0', 'letter': '0', 'key3': '0', 'oar': '0', 'boat': '0', 'red button': '0', 'eaglenest': '0', 'faberge egg': '0', 'trophy case': '0', 'facial': '0', 'gun': '0', 'safe': '0', 'diamond ring': '0', 'junk': '0', 'combination': '0', 'egg': '0', 'flashlight': '0', 'cork': '0', 'bottle': '0', 'oil': '0', 'crown': '0', 'shovel': '0', 'knob': '0', 'twinkies': '0', 'scanner': '0', 'toychest': '0'} </code></pre> <p>You'd see that python points exactly at the problem</p> <pre><code>td@mintyfresh ~/tmp $ python3 test.py File "test.py", line 3 'skeleton' = '0', 'key2': '0', 'rock': '0', 'key1': '0', 'mailbox': '0', ^ SyntaxError: invalid syntax </code></pre> <p>You basically said "I wrote code that is hard to read and can't find the error".</p>
0
2016-10-04T18:24:54Z
[ "python", "directory", "adventure" ]
Lower the brightness of all RGB pixels by 20% in Python?
39,859,109
<p>I have been trying to teach myself more advanced methods in Python but can't seem to find anything similar to this problem to base my code off of. </p> <p>First question: Is this only way to display an image in the terminal to install Pillow? I would prefer not to, as I'm trying to then teach what I learn to a very beginner student. My image.show() function doesn't do anything. </p> <p>Second question: What is the best way to go about lowering the brightness of all RGB pixels in an image by 20%? What I have below doesn't do anything to the alter the brightness, but it also can compile completely. I would prefer the most simple way to go about this as far as importing minimal libraries. </p> <p>Third Question: How do I made a new picture instead of changing the original? (IE- lower brightness 20%, "image-decreasedBrightness.jpg" is created from "image.jpg") </p> <p>here is my code - sorry it isn't formatted correctly. Every time i tried to indent it would tab down to the tags bar. </p> <pre><code>import Image import ImageEnhance fileToBeOpened = raw_input("What is the file name? Include file type.") image = Image.open(fileToBeOpened) def decreaseBrightness(image): image.show() image = image.convert('L') brightness = ImageEnhance.Brightness(image) image = brightness.enhance(20) image.show() return image decreaseBrightness(image) </code></pre>
0
2016-10-04T18:14:17Z
39,859,171
<p>To save the image as a file, there's an example on the documentation:</p> <pre><code>from PIL import ImageFile fp = open("lena.pgm", "rb") p = ImageFile.Parser() while 1: s = fp.read(1024) if not s: break p.feed(s) im = p.close() im.save("copy.jpg") </code></pre> <p>The key function is <code>im.save</code>.</p> <p>For a more in-depth solution, get a nice beverage, find a comfortable place to sit and enjoy your read: <a href="https://pillow.readthedocs.io/en/3.4.x/" rel="nofollow">Pillow 3.4.x Documentation</a>.</p>
0
2016-10-04T18:18:29Z
[ "python", "image" ]
What pandas function does change the column type in an "inline" manner?
39,859,118
<p>I know that the following commands could help change the column type:</p> <pre><code>df['date'] = str(df['date']) df['A'] = pd.to_datetime(df['A']) df['A'] = df.A.astype(np.datetime64) </code></pre> <p>But do you know a better way to change the column type in an inline manner to make it in one line following with other aggregating commands such as groupby, dropna, etc. For example:</p> <pre><code>df\ #.function to cast df.A to np.datetime64 \ .groupby('C') \ .apply(lambda x: x.set_index('A').resample('1M').sum()) </code></pre>
1
2016-10-04T18:14:59Z
39,859,167
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">assign</a>:</p> <pre><code>df.assign(A=pd.to_datetime(df['A'])) </code></pre> <hr> <pre><code>df = pd.DataFrame({'A': ['20150101', '20140702'], 'B': [1, 2]}) df Out: A B 0 20150101 1 1 20140702 2 df.assign(A=pd.to_datetime(df['A'])) Out: A B 0 2015-01-01 1 1 2014-07-02 2 </code></pre>
2
2016-10-04T18:18:14Z
[ "python", "pandas" ]
How to set axis values in matplotlib
39,859,178
<p>This is my first attempt to use <code>matplotlib</code> and failing... I have lists of data as:</p> <p><code>years = [1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]</code> </p> <p><code>temps = [14.11, 7.54, 5.22, 3.81, 2.9, 2.7, 2.4, 1.82, 1.66, 1.52, 1.34, 1.19, 1.12, 1.17, 1.04, 0.87, 0.87, 0.89, 0.76, 0.75, 0.73, 0.72, 0.69, 0.64, 0.62, 0.62, 0.6, 0.64, 0.53, 0.49]</code></p> <p><code>years</code> should be the x-axis and the <code>temps</code> should be the y-axis. Can't figure it how.</p> <pre><code>`plt.hist([temps, years], bins=10) plt.title('Temp_histogram') plt.xlabel('year') plt.ylabel('temp') plt.grid(True) plt.show()` </code></pre> <p><a href="http://i.stack.imgur.com/sCWGx.png" rel="nofollow"><img src="http://i.stack.imgur.com/sCWGx.png" alt="enter image description here"></a></p>
0
2016-10-04T18:18:46Z
39,859,695
<p>Are you sure that you want a histogram and not a simple bar chart? Something like this:</p> <pre><code>plt.bar(years,temps, 1, color='r') plt.title('Temp_histogram') plt.xlabel('year') plt.ylabel('temp') plt.grid(True) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/kJmvp.png" rel="nofollow"><img src="http://i.stack.imgur.com/kJmvp.png" alt="enter image description here"></a></p> <p>If you really want a histogram then think about (or tell us) by what quantity (a quantitiy is a physical entity, like "year" or "temp" in this case) you want to group the data.</p>
1
2016-10-04T18:52:34Z
[ "python", "matplotlib" ]
Python access to default parameters at init time
39,859,208
<p>The first part of my question is how can i access to the pre-set default parameters of a class to use their value as other arguments? What i want to do is something like this:</p> <pre><code>class C: def __init__(self, size_hint = (0, 0), **kwargs): self.size_hint = size_hint </code></pre> <p>and then making an instance:</p> <pre><code>&gt;&gt;&gt; c=C(x = self.size_hint) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'self' is not defined </code></pre> <p>but at initialization time <code>self</code> and <code>C</code> are also not known.</p> <p>The second question is in the class definition above how can i set the key, values in the <code>kwargs</code> dictionary as instance attributes? I know this doesn't work, but what i mean is something like:</p> <pre><code>for k, v in kwargs.items(): self.k = v </code></pre>
-1
2016-10-04T18:20:03Z
39,859,254
<p>Here's the answer to your first question (use <a href="https://docs.python.org/3/library/inspect.html#inspect.signature" rel="nofollow"><code>inspect.signature</code></a>):</p> <pre><code>import inspect class C: def __init__(self, size_hint = (0, 0), **kwargs): self.size_hint = size_hint assert inspect.signature(C.__init__).parameters['size_hint'].default == (0, 0) </code></pre> <p>There's an easier way to get default parameter values, but it doesn't allow you to get them by parameter name if you don't use keyword-only parameters:</p> <pre><code>assert C.__init__.__defaults__ == ((0, 0),) </code></pre> <p>And the answer to the second question:</p> <pre><code>for k, v in kwargs.items(): setattr(self, k, v) </code></pre>
0
2016-10-04T18:23:38Z
[ "python", "class", "python-3.x", "kwargs" ]
How to use HTML5 color picker in Django admin
39,859,224
<p>I'm trying to implement the HTML5 colorpicker in Django's admin page.</p> <p>Here is my model:</p> <pre><code>#model.py ... class Category(models.Model): ... color = models.CharField(max_length=7) </code></pre> <p>Here is the form:</p> <pre><code>#form.py from django.forms import ModelForm from django.forms.widgets import TextInput from .models import Category class CategoryForm(ModelForm): class Meta: model = Category fields = '__all__' widgets = { 'color': TextInput(attrs={'type': 'color'}), } class CategoryAdminForm(ModelForm): form = CategoryForm </code></pre> <p>And finally the admin:</p> <pre><code>#admin.py ... from .forms import CategoryAdminForm ... class CategoryAdmin(admin.ModelAdmin): form_class = CategoryAdminForm filter_horizontal = ('questions',) fieldsets = ( (None, { 'fields': (('name', 'letter'), 'questions', 'color') }), ) </code></pre> <p>However, the type for the field is still text. How do I change the type for the input field to color in the admin page?</p>
1
2016-10-04T18:21:26Z
39,864,918
<p>I found the answer in the documentation:</p> <p>The extra class in forms.py was not necessary</p> <pre><code>#form.py from django.forms import ModelForm from django.forms.widgets import TextInput from .models import Category class CategoryForm(ModelForm): class Meta: model = Category fields = '__all__' widgets = { 'color': TextInput(attrs={'type': 'color'}), } </code></pre> <p>And in the admin:</p> <pre><code>#admin.py ... from .forms import CategoryForm ... class CategoryAdmin(admin.ModelAdmin): form = CategoryForm filter_horizontal = ('questions',) fieldsets = ( (None, { 'fields': (('name', 'letter'), 'questions', 'color') }), ) </code></pre>
1
2016-10-05T03:22:06Z
[ "python", "django", "html5" ]
KeyError : APP_SETTINGS
39,859,234
<p>I'm getting a <code>KeyError</code>, this is the <code>apache2/error.log</code>:</p> <pre><code>tail /var/log/apache2/error.log [Tue Oct 04 18:07:13.305780 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] mod_wsgi (pid=15459): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://localhost/login/ [Tue Oct 04 18:07:13.305918 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] mod_wsgi (pid=15459): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://localhost/login/ [Tue Oct 04 18:07:13.306787 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] Traceback (most recent call last):, referer: http://45.55.236.208/login/ [Tue Oct 04 18:07:13.306833 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] File "/var/www/FlaskApp/flaskapp.wsgi", line 7, in &lt;module&gt;, referer: http://localhost/login/ [Tue Oct 04 18:07:13.306842 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] from FlaskApp import app as application, referer: http://localhost/login/ [Tue Oct 04 18:07:13.306855 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] File "/var/www/FlaskApp/FlaskApp/__init__.py", line 14, in &lt;module&gt;, referer: http://localhost/login/ [Tue Oct 04 18:07:13.306861 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] app.config.from_object(os.environ['APP_SETTINGS']), referer: http://localhost/login/ [Tue Oct 04 18:07:13.306872 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] File "/usr/lib/python3.5/os.py", line 725, in __getitem__, referer: http://localhost/login/ [Tue Oct 04 18:07:13.306892 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] raise KeyError(key) from None, referer: http://localhost/login/ [Tue Oct 04 18:07:13.306925 2016] [wsgi:error] [pid 15459:tid 140052675933952] [client 174.58.31.189:56852] KeyError: 'APP_SETTINGS', referer: http://localhost/login/ </code></pre> <p>In my main application I have:</p> <pre><code>import os app.config.from_object(os.environ['APP_SETTINGS']) </code></pre> <p>and, this is my <code>config.py</code>:</p> <pre><code># default config import os class BaseConfig(object): DEBUG = False SECRET_KEY = 'jjjjjjj' SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): DEBUG = False </code></pre> <p>What I did: </p> <pre><code>export APP_SETTINGS="config.DevelopmentConfig" export DATABASE_URL="postgresql://user:mypassword@localhost/database" </code></pre> <p>It doesn't tell me what key is missing or what is wrong, I'm running this app from digitalocean ubuntu, if that helps.</p>
0
2016-10-04T18:22:06Z
39,860,850
<p>There isn't a way to readily set environment variables in the startup environment for Apache. You would normally set them from the WSGI script file explicitly, or indirectly by having them in some separate file and have the WSGI script file read that and set them for you based on what was set in that separate file. The use of a separate file is where you don't want information in your code repo. That separate file could be under <code>/etc/</code> or elsewhere and only exists on the system you are deploying to.</p>
0
2016-10-04T20:04:22Z
[ "python", "python-3.x", "flask", "apache2", "flask-sqlalchemy" ]
Receive a shell command as an OptionParser string argument
39,859,287
<p>I am using OptionParser(), and define the following:</p> <pre><code>parser.add_option("--cmd", dest="command", help="command to run") </code></pre> <p>However, if i provide a complex shell command, such as :</p> <pre><code>python shell.py --cmd "for i in `seq 1 10`; do xxx; done" </code></pre> <p>And internally print <code>options.command</code>, i get something unexpected to me:</p> <pre><code>for i in 1 2 3 4 5 6 7 8 9 10; do </code></pre> <p>Is there a good way to pass an OptionParser option which is a shell command?</p>
0
2016-10-04T18:25:56Z
39,859,517
<p>When invoking:</p> <pre><code>python shell.py --cmd "for i in `seq 1 10`; do xxx; done" </code></pre> <p>The shell first substitute the command enclosed in ` with its output. Thus, the command you actually invoke is:</p> <pre><code>python shell.py --cmd "for i in 1 2 3 4 5 6 7 8 9 10; do ..." </code></pre> <hr> <p>To avoid this:</p> <p>Escape the ` character when invoking the command:</p> <pre><code>python shell.py --cmd "for i in \`seq 1 10\`; do xxx; done" </code></pre> <p>Use strong quoting (string enclosed in ')</p> <pre><code>python shell.py --cmd 'for i in `seq 1 10`; do xxx; done' </code></pre>
1
2016-10-04T18:41:16Z
[ "python", "shell", "optionparser" ]
setup.py "nice to have" dependency modules
39,859,289
<p>I'm looking at a setup.py file that looks a bit like this one:</p> <pre><code>#!/usr/bin/env python from setuptools import setup, find_packages import sys if sys.argv[1] == 'test': import multiprocessing, logging from billiard import util with open('requirements.txt') as f: required = f.read().splitlines() if sys.version_info &lt; (2, 7, 0): required.append('importlib') setup( version='0.1', name='...', description='...', author='...', author_email='...', packages=find_packages(), package_data={}, install_requires=required, include_package_data=True, tests_require=[ 'billiard', 'nose==1.3' ], test_suite='nose.collector' ) </code></pre> <p>I am trying to install the module on windows. It would appear that the module has been developed on another OS as it fails to compile one of the modules (<code>leveldb</code>) in <code>requirements.txt</code>.</p> <p>Looking at the code, it looks like it might work without <code>leveldb</code> (though perhaps with poorer performance). <strong>Is there any easy way to change the status of the <code>leveldb</code> library so its failure to install doesn't stop the main module from installing?</strong></p> <p>Clearly I could remove the dependency from requirements.txt, but I'm considering how the libary might be edited to accomodate windows.</p>
0
2016-10-04T18:26:06Z
39,859,335
<p>You can declare optional dependencies as <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies" rel="nofollow">extras in your setup.py</a></p>
2
2016-10-04T18:29:22Z
[ "python", "python-2.7", "setuptools", "distutils", "leveldb" ]
correct way to obtain the rest of the parameters of URL in Django rest framework
39,859,308
<p>Hi everyone I am using Django rest framework to create an API</p> <p>In my URLs.py file I have this</p> <pre><code> url(r'^cpuProjects/$', cpuProjectsViewSet.as_view({'get': 'list'})), url(r'^cpuProjects/(?P&lt;project_name&gt;[a-zA-Z0-9]+)$', cpuProjectsViewSet.as_view({'get': 'retrieve'})), </code></pre> <p>This work perfectly, and I have this to url</p> <pre><code>http://127.0.0.1:8000/cpuProjects/ http://127.0.0.1:8000/cpuProjects/ad </code></pre> <p>in my retrieve function, I have this to get the parameter</p> <pre><code> def retrieve(self, request, project_name=None): try: opc = self.kwargs.get(self.lookup_url_kwarg) print(opc) ... </code></pre> <p>Now, I add this to my URLs.py files</p> <pre><code>url(r'^cpuProjects/(?P&lt;project_name&gt;[a-zA-Z0-9]+/[a-zA-Z0-9]+)$', cpuProjectsViewSet.as_view({'get': 'retrieve'})), http://127.0.0.1:8000/cpuProjects/name_project/whatever_string_here </code></pre> <p>My <code>print(opc)</code> in this last case return this <code>ad/pending</code>.</p> <p>Is this the correct way to obtain the rest of the parameters of URL in Django rest framework?</p>
0
2016-10-04T18:27:16Z
39,859,564
<p>You have that entire path of the url wrapped in this same regex named group. You can instead separate the trailing part by putting it in a different group:</p> <pre><code>url(r'^cpuProjects/(?P&lt;project_name&gt;[a-zA-Z0-9]+)/(?P&lt;status&gt;[a-zA-Z0-9]+)$', ...), </code></pre> <p>And in your view:</p> <pre><code>def retrieve(self, request): try: opc = self.kwargs.get(self.lookup_url_kwarg) status = self.kwargs.get('status') ... </code></pre>
1
2016-10-04T18:44:00Z
[ "python", "django", "django-rest-framework", "django-cms" ]
Same Python code , different performance
39,859,331
<p>I wrote this code in Python and there's something driving me crazy. The same code when I put in function, give me different results!! How that can be? This is the code in the main and the same code in a function</p> <pre><code>def iterateTesting(k): Accuracy = [] for t in range(0,10): train_data,test_data = shuffleAndSplit(data) acurracy = test(train_data,test_data,k) Accuracy.append(acurracy) print ('{0:.2f}% , {1:.2f}').format(np.mean(Accuracy),np.std(Accuracy)) data = getData("d.data") train_data,test_data = shuffleAndSplit(data) Accuracy = [] for t in range(0,10): train_data,test_data = shuffleAndSplit(data) acurracy = test(train_data,test_data,1) Accuracy.append(acurracy) print ('{0:.2f}% , {1:.2f}').format(np.mean(Accuracy),np.std(Accuracy)) iterateTesting(1) </code></pre> <p>I get around 55% from the function and 65% from the main everytime I run the code. I'm calling the same functions and using the same data. I will really appreciate if someone clarify. Thanks</p>
-1
2016-10-04T18:28:59Z
39,875,052
<p>Problem solved by defining training and testing data as global variables in my function</p>
0
2016-10-05T13:17:06Z
[ "python", "python-2.7", "numpy", "scikit-learn", "kdtree" ]
Need help finding average in this file (Python)
39,859,346
<p>I was given this file that opens up in excel which looks something like this:</p> <pre><code>year interest inflation 1900 4.2 7.5 </code></pre> <p>This goes on a lot further, all the way to 2008 if i remember right. We are suppose to write a function that accepts a single filename as a parameter and returns a list with 5 items. The first item is the average inflation rate. I just want to try and figure out this first one, and then maybe I'll better understand the other ones. I'm really new to programming so this is quite confusing. I'll show you what I wrote myself.</p> <pre><code> def inflAvgMaxMin(file): file = open('thefilename', 'r') for line in file: print(line) </code></pre> <p>The 'thefilename' is not really what i put, but you know what i mean. So essentially all I was able to get done was being able to print the file in the interpreter. I just don't know where to start and how to write something to find the average inflation. Any suggestions?</p>
-3
2016-10-04T18:30:00Z
39,859,544
<p>Can you try this code?</p> <pre><code>def inflAvgMaxMin(file): with open('thefilename', 'r') as f: inflation = [] header = 1 for line in f: if header != 1: infl = line.split(",")[2] inflation.append(float(infl)) header += 1 avgInflation = sum(inflation)/len(inflation) return avgInflation </code></pre> <p>It reads file line by line and get the inflation scores in each line and put it in a list and finally it calculates the average by dividing the sum by the number of elements in the list.</p> <p><em>Detailed explanation:</em> <code>with open(...) as f</code> means you open the file and name it as <code>f</code> which is a file handle object which can be used to read the lines and manipulate the file. <code>with</code> syntax automatically close the file and you don't have to do it explicitly.</p> <p><code>line.split(",")</code> - split the line by comma; this will return a list; <code>line.split(",")[2]</code> means take the 3rd element in this list, which is the inflation score here. And finally you append it to a list; You do this for each line.</p> <p>Once the for loop ends, you just calculate the average. And this function finally returns this value. </p> <p><strong><em>Example:</em></strong></p> <pre><code>In [12]: inflation = [1.1, 2.2, 3.2, 4.4, 5.5] In [13]: avgInflation = sum(inflation)/len(inflation) In [14]: avgInflation Out[14]: 3.28 </code></pre>
-1
2016-10-04T18:42:47Z
[ "python", "python-3.x", "average" ]
Don't install dependencies when performing `setup.py test`
39,859,348
<p>I want to do an offline installation of a python package. As part of the installation, I run the package's tests with <code>python3 setup.py test</code>. When I run the test command, setuptools fetches all of the unsatisfied dependencies from <code>pypi.python.org</code>. However I'm providing all of the package's dependencies and if a dependency isn't satisfied, I want that to be an error -- I don't want setuptools to download dependencies for me. I'm not sure how to disable this behavior, or even how to tell it to use a different server. How can I stop this?</p>
1
2016-10-04T18:30:10Z
39,860,943
<p>OK, so here's one way to do it. It's possibly not the most elegant and it has some downsides, but it seems to work.</p> <p>Create (or modify an existing) <code>setup.cfg</code> file with the following lines:</p> <pre><code>[easy_install] find_links = file:///dev/null index_url = file:///dev/null </code></pre> <p>This will inform <code>easy_install</code> (which is what is operating under the hood) to not use any external pypi server.</p>
0
2016-10-04T20:10:31Z
[ "python", "setuptools" ]