title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Find next lower value in list of (float) numbers?
39,662,977
<p>How should I write the <code>find_nearest_lower</code> function?</p> <pre><code>&gt;&gt;&gt; values = [10.1, 10.11, 10.20] &gt;&gt;&gt; my_value = 10.12 &gt;&gt;&gt; nearest_lower = find_nearest_lower(values, my_value) &gt;&gt;&gt; nearest_lower 10.11 </code></pre> <p>This needs to work in Python 2.6 without acces...
-2
2016-09-23T14:14:14Z
39,663,064
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhile" rel="nofollow"><code>itertools.dropwhile</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import dropwhile &gt;&gt;&gt; values = [10.1, 10.11, 10.20] &gt;&gt;&gt; my_value = 10.12 &gt;&gt;&gt; next(dropwhile(lambda x: x...
1
2016-09-23T14:17:56Z
[ "python", "python-2.6" ]
Restructuring Array of Tuples
39,663,071
<p>I have an array of tuples of tuples where the second level should not be a tuple and I want to convert it all to something like a 2-d array. Is there a quick way to restructure from this messy 1-d to a nice clean 2-d or structured array?</p> <p>Note: These tuples <strong>do</strong> contain various types. I would ...
0
2016-09-23T14:18:14Z
39,663,599
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html" rel="nofollow">np.squeeze</a></p> <p><code>np.squeeze(&lt;your array&gt;)</code></p>
0
2016-09-23T14:44:28Z
[ "python", "arrays", "numpy", "dimensions" ]
Restructuring Array of Tuples
39,663,071
<p>I have an array of tuples of tuples where the second level should not be a tuple and I want to convert it all to something like a 2-d array. Is there a quick way to restructure from this messy 1-d to a nice clean 2-d or structured array?</p> <p>Note: These tuples <strong>do</strong> contain various types. I would ...
0
2016-09-23T14:18:14Z
39,664,883
<p>The <code>dtype</code> is important here. The closest I can come to your display is with a nested dtype</p> <pre><code>In [182]: dt1=np.dtype('i,i,f') In [183]: dt=np.dtype([('a',dt1,),('b',dt1,),('c',dt1,)]) In [184]: x=np.ones(1,dtype=dt) In [185]: print(x) [((1, 1, 1.0), (1, 1, 1.0), (1, 1, 1.0))] </code></pr...
0
2016-09-23T15:50:53Z
[ "python", "arrays", "numpy", "dimensions" ]
How can I add a python script to the windows system path?
39,663,091
<p>I'm using windows cmd to run my python script. I want to run my python script withouth to give the cd command and the directory path. I would like to type only the name of the python script and run it.</p> <p>I'm using python 2.7</p>
0
2016-09-23T14:18:59Z
39,663,773
<p>1.Go to <strong>Environmental Variables</strong> > <strong>system variable</strong> > <strong>Path</strong> > <strong>Edit</strong></p> <p>2.It look like this</p> <p><strong><em>Path C:\Program Files\Java\jdk1.8.0\bin;%SystemRoot%\system32;C:\Program Files\nodejs\;</em></strong></p> <p>3.You can add semicolon ...
-1
2016-09-23T14:53:18Z
[ "python", "python-2.7", "cmd" ]
pandas elementwise difference between two DatetimeIndex
39,663,117
<p>Is there a pandas idiomatic way to find the difference in days between two pandas DatetimeIndex?</p> <pre><code>&gt;&gt;&gt; d1 = pd.to_datetime(['2000-01-01', '2000-01-02']) &gt;&gt;&gt; d2 = pd.to_datetime(['2001-01-01', '2001-01-02']) </code></pre> <p><code>-</code> operator is set difference, ie dates in d1 bu...
1
2016-09-23T14:20:21Z
39,663,228
<p>You use <code>np.subtract</code> directly:</p> <pre><code>np.subtract(d2, d1) </code></pre> <p>Which'll give you a TimedeltaIndex as a result:</p> <pre><code>TimedeltaIndex(['366 days', '366 days'], dtype='timedelta64[ns]', freq=None) </code></pre> <p>Then if wanted use <code>.days</code> on that.</p> <p>Anothe...
1
2016-09-23T14:25:53Z
[ "python", "pandas" ]
pandas elementwise difference between two DatetimeIndex
39,663,117
<p>Is there a pandas idiomatic way to find the difference in days between two pandas DatetimeIndex?</p> <pre><code>&gt;&gt;&gt; d1 = pd.to_datetime(['2000-01-01', '2000-01-02']) &gt;&gt;&gt; d2 = pd.to_datetime(['2001-01-01', '2001-01-02']) </code></pre> <p><code>-</code> operator is set difference, ie dates in d1 bu...
1
2016-09-23T14:20:21Z
39,663,248
<p>This is because the <code>dtype</code> is <code>datetimeIndex</code> so arithmetic operations are set-wise by design, if you construct a <code>Series</code> from them then you can perform the element-wise subtraction as desired:</p> <pre><code>In [349]: d1 = pd.to_datetime(['2000-01-01', '2000-01-02']) d2 = pd.to_d...
1
2016-09-23T14:26:43Z
[ "python", "pandas" ]
Python share global variable only for functions inside of function
39,663,207
<p>I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.</p> <p>Something like that:</p> <pre><code>def testglobal(): x = 0 def incx(): global x x += 2 incx() return x testglobal() # should return 2 </code></pre> <p>H...
1
2016-09-23T14:24:43Z
39,663,266
<p>You want to use the <code>nonlocal</code> statement to access <code>x</code>, which is not global but local to <code>testglobal</code>.</p> <pre><code>def testglobal(): x = 0 def incx(): nonlocal x x += 2 incx() return x assert 2 == testglobal() </code></pre> <p>The closest you can come to doing t...
1
2016-09-23T14:27:26Z
[ "python", "scope", "global-variables", "python-3.5" ]
Python share global variable only for functions inside of function
39,663,207
<p>I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.</p> <p>Something like that:</p> <pre><code>def testglobal(): x = 0 def incx(): global x x += 2 incx() return x testglobal() # should return 2 </code></pre> <p>H...
1
2016-09-23T14:24:43Z
39,663,269
<p>This will work unless you are still using Python 2.x:</p> <pre><code>def testglobal(): x = 0 def incx(): nonlocal x x += 2 incx() return x testglobal() # should return 2 </code></pre> <p>Possible a cleaner solution though would be to define a class to store your state between method calls.</p>
3
2016-09-23T14:27:34Z
[ "python", "scope", "global-variables", "python-3.5" ]
Python share global variable only for functions inside of function
39,663,207
<p>I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.</p> <p>Something like that:</p> <pre><code>def testglobal(): x = 0 def incx(): global x x += 2 incx() return x testglobal() # should return 2 </code></pre> <p>H...
1
2016-09-23T14:24:43Z
39,663,287
<p>Use the <a href="https://docs.python.org/3/reference/simple_stmts.html#nonlocal" rel="nofollow"><code>nonlocal</code></a> statement, so <code>incx</code> will use the <code>x</code> variable from <code>testglobal</code>:</p> <pre><code>def testglobal(): x = 0 def incx(): nonlocal x x += 2 ...
2
2016-09-23T14:28:28Z
[ "python", "scope", "global-variables", "python-3.5" ]
Sorting and arranging a list using pandas
39,663,214
<p>I have an input file as shown below which needs to be arranged in such an order that the key values need to be in ascending order, while the keys which are not present need to be printed in the last. I am getting the data arranged in the required format but the order is missing.</p> <p>I have tried using sort() me...
0
2016-09-23T14:25:06Z
39,663,524
<p>Here:</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv('inputfile', index_col=None, names=['text']) s = df.text.str.split('|') ds = [dict(w.split('=', 1) for w in x) for x in s] p1 = pd.DataFrame.from_records(ds).fillna('n/a') st = p1.stack(level=0,dropna=False) for k, v in st.groupby(level=0...
0
2016-09-23T14:40:43Z
[ "python", "sorting", "pandas", "split" ]
Sorting and arranging a list using pandas
39,663,214
<p>I have an input file as shown below which needs to be arranged in such an order that the key values need to be in ascending order, while the keys which are not present need to be printed in the last. I am getting the data arranged in the required format but the order is missing.</p> <p>I have tried using sort() me...
0
2016-09-23T14:25:06Z
39,663,724
<p>Replace your ds line with</p> <pre><code>ds = [{int(pair[0]): pair[1] for pair in [w.split('=', 1) for w in x]} for x in s] </code></pre> <p>To convert the index to an integer so it will be sorted numerically</p> <p>To output the n/a values at the end, you could use the pandas selection to output the nonnull valu...
0
2016-09-23T14:50:16Z
[ "python", "sorting", "pandas", "split" ]
Manipulating list of lists and dictionary
39,663,232
<p>I have a list of lists representing the keys in a dictionary. I wish to pickup the smaller key for each list in lists. For instance,</p> <pre><code>L1 = [['1_A','2_A'],['1_B','2_B']] D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373} for li in L1: for ll in li: if ll in D1.keys(): ...
1
2016-09-23T14:25:58Z
39,663,364
<p>You're not comparing the values anywhere.</p> <pre><code>L1 = [['1_A','2_A'],['1_B','2_B']] D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373} template = "Value for {} is {}" for i,j in L1: if D1[i] &lt; D1[j]: print template.format(i,D1[i]) else: print template.format(j,...
2
2016-09-23T14:32:13Z
[ "python", "python-2.7", "dictionary" ]
Manipulating list of lists and dictionary
39,663,232
<p>I have a list of lists representing the keys in a dictionary. I wish to pickup the smaller key for each list in lists. For instance,</p> <pre><code>L1 = [['1_A','2_A'],['1_B','2_B']] D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373} for li in L1: for ll in li: if ll in D1.keys(): ...
1
2016-09-23T14:25:58Z
39,746,525
<p>I found another simple answer !</p> <pre><code>L1 = [['1_A','2_A'],['1_B','2_B']] D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373} for i in L1: val = (sorted(i, key=D1.get))[0] newlist.append(val) "newlist = ['2_A', '2_B']" </code></pre> <p>A list comprehension version:</p> <pre><cod...
0
2016-09-28T11:44:59Z
[ "python", "python-2.7", "dictionary" ]
Writing a table with values for several years as a dictionary?
39,663,310
<p>I have a table I want to write as a Python code, but I'm stuck and can't figure out how to do it.</p> <p>I have a table with data for two years (1991 and 1992), and different values for each year (men: 35 (1991) and 42 (1992), women: 38 (1991), 39 (1992) and children: 15 (1991), 10 (1992).</p> <p>What I want is to...
-1
2016-09-23T14:29:38Z
39,663,527
<p>You want a nested dict:</p> <pre><code>people = { "men": { 1991: 35, 1992: 42 }, "women": { 1991: 38, 1992: 39 }, "children": { 1991: 15, 1992: 10 } } </code></pre> <p>Now you can do <code>people['men'][1991]</code> to get the result 35.</p>
1
2016-09-23T14:40:57Z
[ "python", "dictionary", "tuples" ]
Writing a table with values for several years as a dictionary?
39,663,310
<p>I have a table I want to write as a Python code, but I'm stuck and can't figure out how to do it.</p> <p>I have a table with data for two years (1991 and 1992), and different values for each year (men: 35 (1991) and 42 (1992), women: 38 (1991), 39 (1992) and children: 15 (1991), 10 (1992).</p> <p>What I want is to...
-1
2016-09-23T14:29:38Z
39,663,546
<p>I would suggest something like the following:</p> <pre><code>people = {'1991':{'men':35, 'women':38, 'children':15}, '1992':{'men':42, 'women':39, 'children':10}} </code></pre> <p>Then you can access specific example data using:</p> <pre><code>print(people['1991']['men']) </code></pre> <p><strong>EDIT<...
3
2016-09-23T14:41:52Z
[ "python", "dictionary", "tuples" ]
Writing a table with values for several years as a dictionary?
39,663,310
<p>I have a table I want to write as a Python code, but I'm stuck and can't figure out how to do it.</p> <p>I have a table with data for two years (1991 and 1992), and different values for each year (men: 35 (1991) and 42 (1992), women: 38 (1991), 39 (1992) and children: 15 (1991), 10 (1992).</p> <p>What I want is to...
-1
2016-09-23T14:29:38Z
39,664,253
<p>I suggest you put the dictionary in a custom class. This will give you a lot of flexibility regardless of how the data is laid-out in the dictionary itself because you can create methods to add, change, and delete entries in the table that will hide the details of the data structure. </p> <p>For example, let's say ...
0
2016-09-23T15:17:50Z
[ "python", "dictionary", "tuples" ]
Plotting line with marker as head
39,663,311
<p>I have the following code that produces an animation of drawing a circle.</p> <pre><code>from math import cos, sin import matplotlib.pyplot as plt import matplotlib.animation as animation def update_plot(num, x, y, line): line.set_data(x[:num], y[:num]) line.axes.axis([-1.5, 1.5, -1.5, 1.5]) return lin...
0
2016-09-23T14:29:42Z
39,664,135
<p>You need to return <code>scat</code> in <code>update_plot()</code>. </p> <p>Here is another method, draw the line with <code>markevery</code> argument:</p> <pre><code>line, = ax.plot(x, y, "-o", color="k", markevery=100000) </code></pre> <p>reverse the points order:</p> <pre><code>line.set_data(x[:num][::-1], y[...
1
2016-09-23T15:12:08Z
[ "python", "matplotlib", "plot" ]
Plotting line with marker as head
39,663,311
<p>I have the following code that produces an animation of drawing a circle.</p> <pre><code>from math import cos, sin import matplotlib.pyplot as plt import matplotlib.animation as animation def update_plot(num, x, y, line): line.set_data(x[:num], y[:num]) line.axes.axis([-1.5, 1.5, -1.5, 1.5]) return lin...
0
2016-09-23T14:29:42Z
39,696,945
<p>I ended up finding a way to add the scatter plot to the same animation. The key was to use <code>scat.set_offsets</code> to set the data. The changes that are needed is as follows:</p> <pre><code>def update_plot(num, x, y, line, scat): # ... scat.set_offsets([x[num - 1], y[num - 1]]) return line, scat ...
0
2016-09-26T07:24:21Z
[ "python", "matplotlib", "plot" ]
ckan datapusher /api/3/action/resource_show (Caused by <class 'socket.error'>: [Errno 111] Connection refused) error
39,663,415
<p>I'm trying install ckan 2.2.1 + pgsql 9.1 + solr 3.6 + rhel 6.6.</p> <p>I set file store, and datastore plugin. I tried to use 'upload to datastore' menu in ckan web. then I got this error.</p> <pre><code>2016-09-23 23:16:54,655 INFO [ckan.lib.base] /dataset/datastore/resource_data/7a82b5c2-d68c-4bed-b5c6-fcc460...
2
2016-09-23T14:34:45Z
39,742,223
<p>As you noticed in your comment, the problem is that <strong>the datapusher is trying to connect to the wrong port</strong>:</p> <blockquote> <p>ConnectionError: HTTPConnectionPool(host='default.ckan.com', <strong>port=80</strong>): Max retries exceeded with url: /api/3/action/resource_show (Caused by : [Errno 111...
1
2016-09-28T08:41:24Z
[ "python", "datastore", "ckan" ]
HTTP500 result from SOAP request in python
39,663,479
<p>this question might be fairly specific for one service but I don't understand why I am getting a HTTP500 response from the SOAP service. I am seeing the service I want to access and I see which parameters are required. Still I am getting HTTP500. Is there something wrong with the service or my code?</p> <pre><code>...
0
2016-09-23T14:37:33Z
39,664,288
<p>Generally a 500 result means the server encountered an unexpected error while processing your request.</p> <p>This could be a temporary situation which will get resolved in a day or two: perhaps the server has a bad RAM chip, or its disk is full.</p> <p>Or it could be completely intentional: perhaps one of the val...
0
2016-09-23T15:19:18Z
[ "python", "soap", "bioinformatics" ]
HTTP500 result from SOAP request in python
39,663,479
<p>this question might be fairly specific for one service but I don't understand why I am getting a HTTP500 response from the SOAP service. I am seeing the service I want to access and I see which parameters are required. Still I am getting HTTP500. Is there something wrong with the service or my code?</p> <pre><code>...
0
2016-09-23T14:37:33Z
39,666,255
<p>Your code looks fine and I just tried to access the server via <code>suds</code> and it works.</p> <pre><code>from suds.client import Client client = Client('http://bioinf.cs.ucl.ac.uk/psipred_api/wsdl') print('PsipredSubmit' in client.wsdl.services[0].ports[0].methods) &gt;&gt;&gt; True </code></pre> <p>Are you u...
1
2016-09-23T17:15:59Z
[ "python", "soap", "bioinformatics" ]
reindex some DataFrame columns to multi index
39,663,486
<p>At some point in my workflow I end up with a regular pandas DataFrame with some columns and some rows. I want to export this DataFrame into a latex table,using <code>df.to_latex()</code>. This worked great, however, I know want to use multicolumn where some columns are part of a multi table. For instance a DataFrame...
1
2016-09-23T14:38:20Z
39,664,088
<p>You can assign the multiIndex to the columns attribute of the data frame directly:</p> <pre><code>df.columns = multi_index df </code></pre> <p><a href="http://i.stack.imgur.com/WpwiH.png" rel="nofollow"><img src="http://i.stack.imgur.com/WpwiH.png" alt="enter image description here"></a></p>
1
2016-09-23T15:09:51Z
[ "python", "pandas", "dataframe", "multi-index", "reindex" ]
reindex some DataFrame columns to multi index
39,663,486
<p>At some point in my workflow I end up with a regular pandas DataFrame with some columns and some rows. I want to export this DataFrame into a latex table,using <code>df.to_latex()</code>. This worked great, however, I know want to use multicolumn where some columns are part of a multi table. For instance a DataFrame...
1
2016-09-23T14:38:20Z
39,664,125
<pre><code>pd.concat([df.set_index('a')[['b', 'c']], df.set_index('a')[['d', 'e']]], axis=1, keys=['bc', 'de']).reset_index(col_level=1) </code></pre> <p><a href="http://i.stack.imgur.com/oOFSv.png" rel="nofollow"><img src="http://i.stack.imgur.com/oOFSv.png" alt="enter image description here"></a...
1
2016-09-23T15:11:43Z
[ "python", "pandas", "dataframe", "multi-index", "reindex" ]
What should be my python packages path?
39,663,498
<p>I'm on Mac OS X and I've heard that to avoid global installation of packages (using sudo) that might cause problems with the python files that OS X uses, the path to install python packages must be different than that of OS X. </p> <p>Currently python executables are installed in : </p> <pre><code>/usr/local/bin/ ...
1
2016-09-23T14:39:09Z
39,663,639
<p>You shouldn't be mucking about with Python package paths, and you shouldn't be installing Python packages globally at all. Use a virtualenv for each project, and let pip install the libraries locally inside the virtualenv.</p>
0
2016-09-23T14:46:10Z
[ "python", "osx", "pip" ]
What should be my python packages path?
39,663,498
<p>I'm on Mac OS X and I've heard that to avoid global installation of packages (using sudo) that might cause problems with the python files that OS X uses, the path to install python packages must be different than that of OS X. </p> <p>Currently python executables are installed in : </p> <pre><code>/usr/local/bin/ ...
1
2016-09-23T14:39:09Z
39,663,690
<p>I suggest you to make use of virtual environments, you can learn more about them here: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></p> <p>to sum up </p> <ol> <li>Create a virtual environment (venv): <code>$ virtualenv ...
0
2016-09-23T14:48:06Z
[ "python", "osx", "pip" ]
What should be my python packages path?
39,663,498
<p>I'm on Mac OS X and I've heard that to avoid global installation of packages (using sudo) that might cause problems with the python files that OS X uses, the path to install python packages must be different than that of OS X. </p> <p>Currently python executables are installed in : </p> <pre><code>/usr/local/bin/ ...
1
2016-09-23T14:39:09Z
39,664,129
<p>There are a number of options you can take, the easiest (as others have suggested) is <code>virtualenv</code>. Hopefully that's already installed if not, this is one of the few modules you should install globally. If you have Python 3.4+, you "should" have <code>venv</code> module (which is similar to virtualenv, bu...
0
2016-09-23T15:11:57Z
[ "python", "osx", "pip" ]
What should be my python packages path?
39,663,498
<p>I'm on Mac OS X and I've heard that to avoid global installation of packages (using sudo) that might cause problems with the python files that OS X uses, the path to install python packages must be different than that of OS X. </p> <p>Currently python executables are installed in : </p> <pre><code>/usr/local/bin/ ...
1
2016-09-23T14:39:09Z
39,665,806
<p>If you are on OS X, you should also have Python in <code>/usr/bin</code>:</p> <pre><code>$ which -a python /usr/local/bin/python /usr/bin/python </code></pre> <p>If you are using <code>brew</code>, the first <code>python</code> should be a symlink:</p> <pre><code>$ ls -hl $(which python) lrwxr-xr-x 1 user admin...
0
2016-09-23T16:47:24Z
[ "python", "osx", "pip" ]
How can I match the current date in a <td></td> based on datetime.date.today()?
39,663,526
<p>everyone! I'm having some trouble in matching two strings.</p> <p>So, I've got this HTML code from a page I'm testing:</p> <pre><code>&lt;td class="fixedColumn ng-binding" ng-style="{'padding':'5px','line-height':'10px'}" style="padding: 5px; line-height: 10px;"&gt; (today's date: 2016-09-23) &lt;/td&gt; </code...
1
2016-09-23T14:40:49Z
39,663,824
<pre><code>todayDate = driver.find_element_by_xpath("//td[contains(text(), 'currentDate']") </code></pre> <p>The quotes around currentDate are making the XPath refer to something that contains the actual text 'currentDate', not the text that the currentDate variable refers to, you need to change it to this:</p> <pre>...
1
2016-09-23T14:56:04Z
[ "python", "string", "selenium", "selenium-webdriver" ]
How can I match the current date in a <td></td> based on datetime.date.today()?
39,663,526
<p>everyone! I'm having some trouble in matching two strings.</p> <p>So, I've got this HTML code from a page I'm testing:</p> <pre><code>&lt;td class="fixedColumn ng-binding" ng-style="{'padding':'5px','line-height':'10px'}" style="padding: 5px; line-height: 10px;"&gt; (today's date: 2016-09-23) &lt;/td&gt; </code...
1
2016-09-23T14:40:49Z
39,696,512
<p>Ok, so it's been about 10 minutes since I've added a comment, but I've made it work. Code before:</p> <pre><code>todayDate = driver.find_element_by_xpath("//td[contains(text(), " + str(currentDate) + ")]") </code></pre> <p>Code after:</p> <pre><code>todayDate = driver.find_element_by_xpath("//td[contains(text(),...
0
2016-09-26T06:58:30Z
[ "python", "string", "selenium", "selenium-webdriver" ]
spark Dataframe/RDD equivalent to pandas command given in description?
39,663,596
<p>How to perform same functionality as this pandas command via Pyspark dataframe or RDD ?</p> <pre><code>df.drop(df.std()[(df.std() == 0)].index, axis=1) </code></pre> <p>For details on what this command does, refer: <a href="http://stackoverflow.com/questions/39658574/how-to-drop-columns-which-have-same-values-in-a...
0
2016-09-23T14:44:20Z
39,664,296
<p>In general you can use <code>countDistinct</code>:</p> <pre><code>from pyspark.sql.functions import countDistinct cnts = (df .select([countDistinct(c).alias(c) for c in df.columns]) .first() .asDict()) df.select(*[k for (k, v) in cnts.items() if v &gt; 1]) ## +---+-----+-----+-----+ ## | id|index| n...
0
2016-09-23T15:19:45Z
[ "python", "pandas", "pyspark", "rdd", "spark-dataframe" ]
Generating pandas column values based upon filename
39,663,649
<p>I wish to populate three columns (day, week, year) in a pandas data frame.</p> <p>The data is to be extracted from a filename which are in this format:</p> <pre><code>AAAA_DDWWYYYY.txt </code></pre> <p>where:</p> <ul> <li>AAAA = alpha characters</li> <li>DD = Day</li> <li>WW = Month</li> <li>YYYY = Year</li> </u...
-1
2016-09-23T14:46:30Z
39,664,077
<p>Assuming <code>df</code> is your dataframe::</p> <pre><code>df.ix[df.filename == 'NDVI_01012016.txt', 'Day'] = 1 df.ix[df.filename == 'NDVI_01012016.txt', 'Week'] = '01' df.ix[df.filename == 'NDVI_01012016.txt', 'Year'] = '2016' </code></pre>
0
2016-09-23T15:09:12Z
[ "python", "pandas" ]
Problems when using py2app to freeze a python script which uses pdfkit
39,663,767
<p>I recently created an application using pdfkit that takes a keyword entered by the user and makes various internet searches using that keyword. It then uses pdfkit to generate pdf files of each of the separate searches and saves them to a user-defined directory.</p> <p>Everything works dandy when I run the code fro...
0
2016-09-23T14:53:05Z
39,666,097
<p>Ok found an answer so anyone who is having the same problem can use it.</p> <p>Basically the problem lies in the fact that pdfkit is just a wrapper for the module WKHTMLTOPDF. </p> <p>So basically all that happens when you call on PDFKIT is that it just asks WKHTMLTOPDF to do the work for it, however on my system ...
0
2016-09-23T17:06:05Z
[ "python", "py2app", "python-pdfkit" ]
Manipulating dictionaries within lists
39,663,866
<p>I have a list with dictionaries in it as below:</p> <pre><code>wordsList = [ {'Definition': 'Allows you to store data with ease' , 'Word': 'Database'}, {'Definition': 'This can either be static or dynamic' , 'Word': 'IP'}, ] </code></pre> <p>Essentially, what I want to do is:</p> <ul> <li>Be able to print...
-1
2016-09-23T14:58:16Z
39,663,887
<pre><code>for word_def in wordsList: print word_def.get("Word") print word_def.get("Definition") print </code></pre> <p>output</p> <pre><code>Database Allows you to store data with ease IP This can either be static or dynamic </code></pre>
1
2016-09-23T14:59:40Z
[ "python", "list", "dictionary" ]
Manipulating dictionaries within lists
39,663,866
<p>I have a list with dictionaries in it as below:</p> <pre><code>wordsList = [ {'Definition': 'Allows you to store data with ease' , 'Word': 'Database'}, {'Definition': 'This can either be static or dynamic' , 'Word': 'IP'}, ] </code></pre> <p>Essentially, what I want to do is:</p> <ul> <li>Be able to print...
-1
2016-09-23T14:58:16Z
39,663,972
<p>Essentially, these are "regular" lists/dictionaries.</p> <p>You must understand, that a list in Python can contain any object, also dicts. Thus, neither the list nor the contained dicts become anyhow "irregular".</p> <p>You can access anything inside your list/dict like that:</p> <pre><code>word_def[index][name] ...
1
2016-09-23T15:03:34Z
[ "python", "list", "dictionary" ]
Write to file bytes and strings
39,663,909
<p>I have to create files which have some chars and hex value in little-endian encoding. To do encoding, I use:</p> <pre><code>pack("I", 0x01ddf23a) </code></pre> <p>and this give me:</p> <pre><code>b':\xf2\xdd\x01' </code></pre> <p>First problem is that, this give me bytes string which I cannot write to file. Seco...
0
2016-09-23T15:00:31Z
39,664,488
<p>You are producing bytes, which can be written to files opened in <em>binary mode</em> without issue. Add <code>b</code> to the file mode when opening and either use <code>bytes</code> string literals or encode your strings to bytes if you need to write other data too:</p> <pre><code>with open("file", "wb") as fs: ...
1
2016-09-23T15:28:49Z
[ "python", "python-3.x", "file-io", "byte" ]
xlwings:How to acrire the value of the cell and to indicate message box
39,663,923
<p>I'm using xlwings on a Windows. I acquire the value of the cell and want to indicate message box.</p> <pre><code>import xlwings as xw import win32ui def msg_box(): wb = xw.Book.caller() win32ui.MessageBox(xw.sheets[0].range(4, 1).value,"MesseageBox") </code></pre> <p>However, Python stops.Could you tell m...
0
2016-09-23T15:01:26Z
39,670,133
<p>On Windows, something like this should work as a workaround:</p> <pre><code>import xlwings as xw import win32api def msg_box(): wb = xw.Book.caller() win32api.MessageBox(wb.app.hwnd, "YourMessage") </code></pre>
0
2016-09-23T21:58:42Z
[ "python", "winapi", "messagebox", "xlwings" ]
Splitting up a list with all values sitting in the same index in Python
39,664,024
<p>Im pretty new to Python. I have a list which looks like the following:</p> <pre><code>list = [('foo,bar,bash',)] </code></pre> <p>I grabbed it from and sql table (someone created the most rubbish sql table!), and I cant adjust it. This is literally the only format I can pull it in. I need to chop it up. I can't sp...
0
2016-09-23T15:06:26Z
39,664,051
<p><code>list = [('foo,bar,bash',)]</code> is a list which contains a tuple with 1 element. You should also use a different variable name instead of <code>list</code> because <code>list</code> is a python built in.</p> <p>You can split that one element using <code>split</code>:</p> <pre><code>lst = [('foo,bar,bash',)...
1
2016-09-23T15:07:53Z
[ "python", "sql", "list" ]
selenium Action error
39,664,031
<p>I am trying to automate a mouse movement to an element, and I see that the method for doing so is something like: </p> <pre><code>Actions action = new Actions(driver) action.moveToElement(hoverElement) </code></pre> <p>However when I run this code I get a syntax error, and Pycharm is telling me Actions is an unres...
0
2016-09-23T15:06:48Z
39,664,399
<p>In Python, it is not <code>Actions</code>, it is <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="nofollow"><code>ActionChains</code></a> - imported this way:</p> <pre><code>from selenium.webdriver.common.action_chains import ActionChains </code></pre> <p...
2
2016-09-23T15:24:50Z
[ "python", "selenium" ]
Is there any equivalent to the Perl regexes' \K backslash sequence in Python?
39,664,058
<p>Perl's regular expressions have the <a href="http://perldoc.perl.org/perlrebackslash.html#Misc" rel="nofollow"><code>\K</code></a> backslash sequence:</p> <blockquote> <p><strong>\K</strong><br> This appeared in perl 5.10.0. Anything matched left of <code>\K</code> is not included in <code>$&amp;</code>, and ...
4
2016-09-23T15:08:19Z
39,664,218
<p>The proposed replacement to the Python <code>re</code> module, <a href="https://pypi.python.org/pypi/regex" rel="nofollow">available from <code>pypi</code> under the name <code>regex</code></a>, has this feature. Its canonical source repository and bug tracker are <a href="https://bitbucket.org/mrabarnett/mrab-regex...
4
2016-09-23T15:16:24Z
[ "python", "regex", "perl" ]
cython: run prange sequentially (profiling/debugging)
39,664,080
<p>I have a meanwhile pretty large code base written mostly in Cython. Meanwhile, I've started parallelizing it by replacing "range"s by "prange"s. (So far more or less at random, as I still have to develop a gut feeling as to where I really profit from this and where not so much.)</p> <p>One big question to which I h...
0
2016-09-23T15:09:36Z
39,673,882
<p>There's at least three very easy ways:</p> <ol> <li><p><code>prange</code> takes a <code>num_threads</code> argument. Set that equal to 1. This gives you local control.</p></li> <li><p>If you compile without OpenMP it'll still still run, but not in parallel. Remove <code>extra_compile_args=['-fopenmp']</code> and <...
2
2016-09-24T07:45:02Z
[ "python", "python-3.x", "debugging", "parallel-processing", "cython" ]
getting weighted average then grouping in pandas
39,664,195
<p>I have the following dataframe. </p> <pre><code> weight x value 0 5 -8.7 2 1 9 -8.7 3 2 12 -21.4 10 3 32 -21.4 15 </code></pre> <p>I need to get weighted average of the value and grouped on x. Result will be:</p> <p>-8.7: (5/...
0
2016-09-23T15:15:19Z
39,664,322
<p><code>numpy.average</code> admits a <code>weights</code> argument:</p> <pre><code>import io import numpy as np import pandas as pd data = io.StringIO('''\ weight x value 0 5 -8.7 2 1 9 -8.7 3 2 12 -21.4 10 3 32 -21.4 15 ''') ...
1
2016-09-23T15:21:09Z
[ "python", "pandas", "numpy" ]
getting weighted average then grouping in pandas
39,664,195
<p>I have the following dataframe. </p> <pre><code> weight x value 0 5 -8.7 2 1 9 -8.7 3 2 12 -21.4 10 3 32 -21.4 15 </code></pre> <p>I need to get weighted average of the value and grouped on x. Result will be:</p> <p>-8.7: (5/...
0
2016-09-23T15:15:19Z
39,664,553
<p>Here's a vectorized approach using NumPy tools -</p> <pre><code># Get weighted averages and corresponding unique x's unq,ids = np.unique(df.x,return_inverse=True) weight_avg = np.bincount(ids,df.weight*df.value)/np.bincount(ids,df.weight) # Store into a dataframe df_out = pd.DataFrame(np.column_stack((unq,weight_a...
0
2016-09-23T15:31:59Z
[ "python", "pandas", "numpy" ]
Regex Search in Python: Exclude port 22 lines with ' line 22 '
39,664,230
<p>My current regex search in python looks for lines with <code>' 22 '</code>, but I would like to exclude lines that have <code>' line 22 '</code>. How could I express this in <code>Regex</code>? Would I be <code>'.*(^line) 22 .*$'</code></p> <pre><code>import re sshRegexString='.* 22 .*$' sshRegexExpression=re.comp...
1
2016-09-23T15:16:53Z
39,670,306
<p>You current requirement to find a line that <em>contains</em> <code> 22 </code> but does not contain <code>line 22 </code> can be implemented without the help of a regex. </p> <p>Just check if these texts are <code>in</code> or are <code>not in</code> the string inside list comprehension. Here is a <a href="http:/...
0
2016-09-23T22:16:48Z
[ "python", "regex" ]
run a while loop untill a css selector is present on web page
39,664,323
<p>I need to run this loop until ".loadMore" css selector is present on webpage:</p> <pre><code>while ec.presence_of_element_located('.loadMore'): element_number = 25 * i wait = WebDriverWait(driver, time1); sub_button = (by, hook + str(element_number)) wait.until(ec.presence_of_element...
0
2016-09-23T15:21:15Z
39,665,004
<p>Write your def to check for element presence</p> <pre><code>from selenium.common.exceptions import NoSuchElementException def check_element_presence(selector): try: webdriver.find_element_by_css_selector(selector) except NoSuchElementException: return False return True </code></p...
-1
2016-09-23T15:57:33Z
[ "python", "python-2.7", "selenium", "chrome-web-driver" ]
Tensorflow CIFAR10 code analysis
39,664,345
<p>I'm trying to figure out, a Tensorflow CIFAR10 tutorial and currently I can't understand <a href="https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/image/cifar10/cifar10.py#L245" rel="nofollow">line #245</a>, namely why is the shape for weight [dim, 384]? Is 384 a hyperparameter or is it somehow ...
-1
2016-09-23T15:21:58Z
39,669,418
<p>Basically it was an arbitrary choice that worked out with their batch size and knowledge about the dataset.</p> <p>So cifar images are 32 * 32 * 3 and by the convolution now they have 32 * 32 * 64 features and just before that they had 64 filters but they just max pooled it so now it's half the size so now its 16 *...
1
2016-09-23T20:55:30Z
[ "python", "image-processing", "tensorflow", "conv-neural-network" ]
Indexing an array with a logical array of the same shape in Python
39,664,432
<p>I would like to be able to do:</p> <pre><code>a = [1,2,3] a[[True, True, False]] &gt;&gt; array([1,2]) </code></pre> <p>I just can't find the simple way how... Thanks!</p>
1
2016-09-23T15:26:19Z
39,664,474
<p>There's <a href="https://docs.python.org/3.1/library/itertools.html#itertools.compress" rel="nofollow"><code>itertools.compress</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import compress &gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; mask = [True, True, False] &gt;&gt;&gt; list(compress(a, mask)) [1, 2] </code><...
2
2016-09-23T15:28:08Z
[ "python" ]
Indexing an array with a logical array of the same shape in Python
39,664,432
<p>I would like to be able to do:</p> <pre><code>a = [1,2,3] a[[True, True, False]] &gt;&gt; array([1,2]) </code></pre> <p>I just can't find the simple way how... Thanks!</p>
1
2016-09-23T15:26:19Z
39,664,548
<p>You can use <code>zip</code> and list comprehension.</p> <pre><code>a = [1,2,3] b = [True, True, False] c = [i for i,j in zip(a,b) if j] </code></pre>
0
2016-09-23T15:31:41Z
[ "python" ]
Indexing an array with a logical array of the same shape in Python
39,664,432
<p>I would like to be able to do:</p> <pre><code>a = [1,2,3] a[[True, True, False]] &gt;&gt; array([1,2]) </code></pre> <p>I just can't find the simple way how... Thanks!</p>
1
2016-09-23T15:26:19Z
39,664,560
<p>You can play with built-in <code>filter</code> and <code>map</code></p> <pre><code>k = [True, True, False, True] l = [1,2,3,4] print map(lambda j: j[1], filter(lambda i: i[0], zip(k,l))) </code></pre>
0
2016-09-23T15:32:24Z
[ "python" ]
Indexing an array with a logical array of the same shape in Python
39,664,432
<p>I would like to be able to do:</p> <pre><code>a = [1,2,3] a[[True, True, False]] &gt;&gt; array([1,2]) </code></pre> <p>I just can't find the simple way how... Thanks!</p>
1
2016-09-23T15:26:19Z
39,664,612
<p>If <code>a</code> and the mask are truly Python arrays, then you can do a simple list comprehension:</p> <pre><code>arr = [1,2,3] mask = [True, True, False] [a for a, m in zip(arr, mask) if m] </code></pre> <p>If you are OK with additional imports, you can use @moses-koledoye's suggestion of using <code>itertools....
2
2016-09-23T15:34:49Z
[ "python" ]
using django celery beat locally I get error 'PeriodicTask' object has no attribute '_default_manager'
39,664,493
<p>using django celery beat locally I get error 'PeriodicTask' object has no attribute '_default_manager'. I am using Django 1.10. When i schedule a task it works. But then a few moments later a red error traceback like the following occurs</p> <pre><code>[2016-09-23 11:08:34,962: INFO/Beat] Writing entries... [2016-0...
0
2016-09-23T15:29:04Z
39,665,447
<p>I figured it out. At line 98 in schedulers.py it was</p> <pre><code>obj = self.model._default_manager.get(pk=self.model.pk) </code></pre> <p>so a line above it I added</p> <pre><code>Model = type(self.model) </code></pre> <p>and changed </p> <pre><code>obj = self.model._default_manager.get(pk=self.model.pk) </c...
0
2016-09-23T16:24:17Z
[ "python", "django", "heroku", "redis", "scheduled-tasks" ]
How can I add to the initial definition of a python class inheriting from another class?
39,664,509
<p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p> <pre><code>class Object(): def __init__(self): self.data="1234" class New_Object(Object): # Code changing self.data here </code></pre> <p>But I ran into an issue.</p> <pre><code>class Object(): def __init__...
2
2016-09-23T15:29:43Z
39,664,564
<p>You use <code>super</code> to call the original implementation.</p> <pre><code>class New_Object(Object): def __init__(self): super(NewObject, self).__init__() self.info = 'whatever' </code></pre>
3
2016-09-23T15:32:33Z
[ "python", "class", "inheritance", "instance" ]
How can I add to the initial definition of a python class inheriting from another class?
39,664,509
<p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p> <pre><code>class Object(): def __init__(self): self.data="1234" class New_Object(Object): # Code changing self.data here </code></pre> <p>But I ran into an issue.</p> <pre><code>class Object(): def __init__...
2
2016-09-23T15:29:43Z
39,664,566
<p>That's what <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow"><code>super</code></a> is for:</p> <pre><code>class NewObject(Object): def __init__(self): super(NewObject, self).__init__() # self.data exists now, and you can modify it if necessary </code></pre>
2
2016-09-23T15:32:36Z
[ "python", "class", "inheritance", "instance" ]
How can I add to the initial definition of a python class inheriting from another class?
39,664,509
<p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p> <pre><code>class Object(): def __init__(self): self.data="1234" class New_Object(Object): # Code changing self.data here </code></pre> <p>But I ran into an issue.</p> <pre><code>class Object(): def __init__...
2
2016-09-23T15:29:43Z
39,664,645
<p>You can use <code>super().__init__()</code> to call <code>Object.__init__()</code> from <code>New_Object.__init__()</code>.</p> <p>What you would do:</p> <pre><code>class Object: def __init__(self): print("Object init") self.data = "1234" class New_Object(Object): def __init__(self): ...
1
2016-09-23T15:36:40Z
[ "python", "class", "inheritance", "instance" ]
How can I add to the initial definition of a python class inheriting from another class?
39,664,509
<p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p> <pre><code>class Object(): def __init__(self): self.data="1234" class New_Object(Object): # Code changing self.data here </code></pre> <p>But I ran into an issue.</p> <pre><code>class Object(): def __init__...
2
2016-09-23T15:29:43Z
39,664,748
<p>The answer is that you call the superclass's <code>__init__</code> explicitly during the subclass's <code>__init__</code>. This can be done either of two ways:</p> <pre><code>Object.__init__(self) # requires you to name the superclass explicitly </code></pre> <p>or</p> <pre><code>super(NewObject, self).__init...
1
2016-09-23T15:42:25Z
[ "python", "class", "inheritance", "instance" ]
Group DataFrame by period of time with aggregation
39,664,657
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/delaC.png" rel="nofollow"><img src="http://i.stack.imgur.com/delaC.png" alt="enter image description here"></a></p> <p>I grouped many datetimes by minute and I did an aggregation in order to have the sum...
0
2016-09-23T15:37:06Z
39,664,924
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling" rel="nofollow">resample</a>. </p> <p><code> df.resample('5Min').sum() </code></p> <p>This assumes your index is properly set as a DateTimeIndex. </p> <p>you can also use the TimeGrouper, as resampling is really just a groupby ope...
1
2016-09-23T15:53:18Z
[ "python", "pandas", "group-by", "aggregate", "aggregation" ]
pandas pivot table aggfunc troubleshooting
39,664,739
<p>This <code>DataFrame</code> has two columns, both are object type.</p> <pre><code> Dependents Married 0 0 No 1 1 Yes 2 0 Yes 3 0 Yes 4 0 No </code></pre> <p>I want to aggregate 'Dependents' based on 'Married'.</p> <pre><code>table = df.pivot_tabl...
0
2016-09-23T15:41:53Z
39,670,029
<p>Both examples of code provided in your question work. However, they are not the idiomatic way to achieve what you want to do -- particularly the first one.</p> <p>I think this is the proper way to obtain the expected behavior.</p> <pre><code># Test data df = DataFrame({'Dependents': ['0', '1', '0', '0', '0'], ...
0
2016-09-23T21:48:00Z
[ "python", "pandas", "pivot-table" ]
scatter update with animation
39,664,741
<p>I am trying to do a real time scatter-kind plot using matplotlib's animation module but I'm quite a newbie with it. My objective is to update the plot whenever I receive the data I want to plot, so that any time data is received, previous points disappear and the new ones are plotted. </p> <p>My program can be writ...
0
2016-09-23T15:42:00Z
39,669,252
<p>I think you do not need an animation. You need a simple endless loop (<code>while</code> for example) with plot update in a thread. I can propose something like this:</p> <pre><code>import threading,time import matplotlib.pyplot as plt import numpy as np fig = plt.figure() data = np.random.uniform(0, 1, (5, 3)) pl...
0
2016-09-23T20:44:16Z
[ "python", "animation", "matplotlib", "scatter-plot" ]
How to show the actual value of a signature using the RSA library in Python?
39,665,045
<p>I'm using the <a href="https://stuvel.eu/python-rsa-doc/index.html" rel="nofollow">RSA library</a> to check a digital signature using the Public Key as follows:</p> <pre><code>rsa.verify(message, sig, key) </code></pre> <p>The function works as expected however, for incorrect cases the library prints out </p> <p...
0
2016-09-23T15:59:59Z
39,667,265
<p>Using the <code>verify()</code> method as a template: </p> <pre><code>from rsa import common, core, transform keylength = common.byte_size(base) decrypted = core.decrypt_int(sig, exp, base) clearsig = transform.int2bytes(decrypted, keylength) </code></pre> <p>This is with the assumption that your signature is gi...
1
2016-09-23T18:22:11Z
[ "python", "rsa", "digital-signature" ]
String index out of range while sending email
39,665,065
<p>I'm running into this error: <a href="http://pastebin.com/hH1ZbeWZ" rel="nofollow">link</a>, while trying to send mail with Django EmailMultiAlternatives. I tried searching for this error but no luck, also I tried removing or changing every variable for email, but with no luck.</p> <p>This is the code:</p> <pre><c...
0
2016-09-23T16:01:13Z
39,665,394
<p>The problem was with redundant wrapping list of emails in another list.</p> <p>So basically variable <code>to = ["[email protected]"]</code>, then when line run</p> <pre><code>msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) </code></pre> <p>it wrapped <code>to</code> one more time with <code>[ ...
0
2016-09-23T16:21:29Z
[ "python", "django", "email" ]
pandas - add a column of the mean of the last 3 elements in groupby
39,665,074
<p>I have a dataframe of several columns, which I sorted, grouped by index and calculated the difference between each row and the next one in the group. Next I want to add a column of the means of the last 3 differences. For example:</p> <pre><code>index A B A_diff B_diff A_diff_last3mean B_diff_last3mean ...
0
2016-09-23T16:01:41Z
39,665,907
<pre><code>import io import pandas as pd data = io.StringIO('''\ group A B 1111 1 2 1111 1 2 1111 2 4 1111 4 6 2222 5 7 2222 2 8 ''') df = pd.read_csv(data, delim_whitespace=True) diff = (df.groupby('group') .diff() .fillna(0) .add_suffix('_diff')) df = df.join(diff) ...
1
2016-09-23T16:53:02Z
[ "python", "pandas" ]
TemplateDoesNotExist but it exist
39,665,105
<p>Python 2.7 &amp; Django 1.10 my template exist but i do somesing wrong! </p> <pre><code>TemplateDoesNotExist at /basicview/2/ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;TEST&lt;/title&gt; &lt;/head&gt; &lt;body&gt; This is template_two view! &lt;/body&gt; &lt;/...
0
2016-09-23T16:03:14Z
39,665,150
<p>In your <em>settings.py</em> you have <code>'DIRS': ['templates'],</code></p> <p>And path to your template is <code>mainapp/templetes/myview.html</code></p> <p>You have typo <code>templetes != templates</code>. Rename folder with templates to <code>templates</code>.</p>
1
2016-09-23T16:05:51Z
[ "python", "django", "python-2.7", "django-templates" ]
TemplateDoesNotExist but it exist
39,665,105
<p>Python 2.7 &amp; Django 1.10 my template exist but i do somesing wrong! </p> <pre><code>TemplateDoesNotExist at /basicview/2/ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;TEST&lt;/title&gt; &lt;/head&gt; &lt;body&gt; This is template_two view! &lt;/body&gt; &lt;/...
0
2016-09-23T16:03:14Z
39,665,895
<p>I would suggest that you put your temlates in your app.</p> <p>Your file will then be here: </p> <pre><code>mainapp/mainapp/templates/myview.html </code></pre> <p>Please make sure you add <code>mainapp</code> to your <code>INSTALLED_APPS</code> like this:</p> <pre><code>INSTALLED_APPS = [ ... 'mainapp', ] ...
0
2016-09-23T16:52:24Z
[ "python", "django", "python-2.7", "django-templates" ]
TemplateDoesNotExist but it exist
39,665,105
<p>Python 2.7 &amp; Django 1.10 my template exist but i do somesing wrong! </p> <pre><code>TemplateDoesNotExist at /basicview/2/ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;TEST&lt;/title&gt; &lt;/head&gt; &lt;body&gt; This is template_two view! &lt;/body&gt; &lt;/...
0
2016-09-23T16:03:14Z
39,666,505
<p>The problem is that you are manually rendering your template and using the <code>render</code> shortcut at the same time. Your <code>get_template</code> is working, but when you call <code>render(request, html, {})</code>, Django is treating <code>html</code> as the filename, and looking for a template file named <c...
0
2016-09-23T17:32:37Z
[ "python", "django", "python-2.7", "django-templates" ]
Unwanted Rainbow icon on pygame
39,665,152
<p>I'm currently working on a pygame script, which is basically displaying an user interface over a webcam stream. This app is running on raspberry pi, on dual screen via fbcp.</p> <p>I noticed that a strange rainbow square icon did recently appeared in the upper right corner of the screen. </p> <p>Looking like this,...
-1
2016-09-23T16:05:58Z
39,667,920
<p>I found the answer by myself :</p> <p>This icon is shown by the raspberry itself to inform about under-voltage issue. To prevent it from showing, solve the power issue, or remove rpi warnings (not a safe approach), by adding to /boot/config.txt :</p> <pre><code>avoid_warnings=2 </code></pre>
1
2016-09-23T19:06:55Z
[ "python", "raspberry-pi", "pygame", "webcam", "raspberry-pi2" ]
youtube-dl python script postprocessing error: FFMPEG codecs aren't being recognized
39,665,160
<p>My python script is trying to download youtube videos with youtube-dl.py. Works fine unless postprocessing is required. The code:</p> <pre><code>import youtube_dl options = { 'format':'bestaudio/best', 'extractaudio':True, 'audioformat':'mp3', 'outtmpl':'%(id)s', #name the file the ID of the vi...
0
2016-09-23T16:06:26Z
39,669,975
<p>This is a bug in the interplay between youtube-dl and ffmpeg, caused by the lack of extension in the filename. youtube-dl calls ffmpeg. Since the filename does not contain any extension, youtube-dl asks ffmpeg to generate a temporary file <code>mp3</code>. However, ffmpeg detects the output container type automatica...
1
2016-09-23T21:43:47Z
[ "python", "youtube", "ffmpeg", "youtube-dl" ]
Define a variable in sympy to be a CONSTANT
39,665,207
<pre><code>from sympy import * from sympy.stats import * mu, Y = symbols('mu Y', real = True, constant = True) sigma = symbols('sigma', real = True, positive=True) X = Normal('X', mu, sigma) </code></pre> <p>When asking for:</p> <pre><code>E(X, evaluate=False) </code></pre> <p>I get:</p> <pre><code>∞ ...
3
2016-09-23T16:09:18Z
39,668,837
<p>Your problem appears to be a limitation in the current inequality solver: the algorithm that transforms a system of inequalities to a union of sets apparently needs to sort the boundary points determined by those inequalities (even if there's only one such point). Reduction of inequalities with symbolic limits has n...
3
2016-09-23T20:12:26Z
[ "python", "symbols", "sympy" ]
Is there a difference between str function and percent operator in Python
39,665,286
<p>When converting an object to a string in python, I saw two different idioms:</p> <p>A: <code>mystring = str(obj)</code></p> <p>B: <code>mystring = "%s" % obj</code></p> <p>Is there a difference between those two? (Reading the Python docs, I would suspect no, because the latter case would implicitly call <code>str...
9
2016-09-23T16:14:31Z
39,665,338
<p>The second version does more work.</p> <p>The <code>%s</code> operator calls <code>str()</code> on the value it interpolates, but it also has to parse the template string first to find the placeholder in the first place.</p> <p>Unless your template string contains <em>more text</em>, there is no point in asking Py...
16
2016-09-23T16:17:33Z
[ "python", "python-2.7" ]
How to make a group id using pandas
39,665,374
<p>R's <code>data.table</code> package has a really convenient <code>.GRP</code> method for generating group index values.</p> <pre><code>library(data.table) dt &lt;- data.table( Grp=c("a", "z", "a", "f", "f"), Val=c(3, 2, 1, 2, 2) ) dt[, GrpIdx := .GRP, by=Grp] Grp Val GrpIdx 1: a 3 1 2: z 2 ...
1
2016-09-23T16:20:28Z
39,666,130
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.rank.html" rel="nofollow"><code>rank</code></a> to identify unique groups with the <code>method</code> arg set to <code>dense</code> which accepts <code>string</code> values:</p> <pre><code>df['GrpIdx'] = df['Grp'].ra...
2
2016-09-23T17:08:32Z
[ "python", "pandas", "dataframe" ]
I want to make it either print true or false from using variables and lists
39,665,375
<pre><code> x = 1 y = ['1','2'] if x/y[1] == 2: print ('true') else: print ('false') </code></pre> <p>But the variable can not be divided by a list and it gives out</p> <pre><code> TypeError: unsupported operand type(s) for /: 'int' and 'str' </code></pre> <p>Please help. </p>
-3
2016-09-23T16:20:31Z
39,665,419
<p>That's because you're trying to divide a string. Changing your code to convert <code>y</code> into an <code>int</code> will fix your problem.</p> <pre><code>x = 1 y = ['1','2'] if x/int(y[1]) == 2: print ('true') else: print ('false') </code></pre>
1
2016-09-23T16:22:47Z
[ "python" ]
Failed to extends User form in django
39,665,404
<p>The error I get is: extend user to a custom form, the "user_id" field is my custom form is the "property", which is linked to the table "auth_user" is not saved, and I need both tables relate to make use my custom form attributes and shape of the User of django.</p> <p>my models.py</p> <pre><code>from __future__ i...
0
2016-09-23T16:22:01Z
39,665,460
<p>You are not setting <code>user</code> to that instance of <code>Profile</code>:</p> <pre><code>profile = Profile() profile.user = user # Notice the case of Profile </code></pre>
1
2016-09-23T16:24:51Z
[ "python", "django", "user" ]
Failed to extends User form in django
39,665,404
<p>The error I get is: extend user to a custom form, the "user_id" field is my custom form is the "property", which is linked to the table "auth_user" is not saved, and I need both tables relate to make use my custom form attributes and shape of the User of django.</p> <p>my models.py</p> <pre><code>from __future__ i...
0
2016-09-23T16:22:01Z
39,665,498
<p>You should be careful with your capitalisation. You've assigned the user value to the class, not the instance. It should be:</p> <pre><code>profile = Profile() profile.user = user </code></pre> <p>Or better:</p> <pre><code>profile = Profile(user=user) </code></pre>
1
2016-09-23T16:27:43Z
[ "python", "django", "user" ]
Python BeautifulSoup does not print()
39,665,413
<p>Following beautifulsoup script shows no output. Did i miss anything? It was intended to hit some of the prints.</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url1 = "https://www.youtube.com/watch?v=APmUWC8S1_M" def getTitle(url): ...
-2
2016-09-23T16:22:30Z
39,665,869
<p>For BeautifulSoup4, I would reccommend using the requests module (obtained via pip), for getting the website data.</p> <p>To get the html of the desired site, use</p> <pre><code>content = requests.get(url).content </code></pre> <p>That will save the entire html doc to the variable "content".</p> <p>From that, yo...
1
2016-09-23T16:51:00Z
[ "python", "printing", "error-handling", "beautifulsoup" ]
Python BeautifulSoup does not print()
39,665,413
<p>Following beautifulsoup script shows no output. Did i miss anything? It was intended to hit some of the prints.</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url1 = "https://www.youtube.com/watch?v=APmUWC8S1_M" def getTitle(url): ...
-2
2016-09-23T16:22:30Z
39,666,174
<h3>EDIT:</h3> <p>You problem is finally... identation.</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url1 = "https://www.youtube.com/watch?v=APmUWC8S1_M" def getTitle(url): try: html = urlopen(url) except HTTPError as...
0
2016-09-23T17:11:11Z
[ "python", "printing", "error-handling", "beautifulsoup" ]
Python BeautifulSoup does not print()
39,665,413
<p>Following beautifulsoup script shows no output. Did i miss anything? It was intended to hit some of the prints.</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url1 = "https://www.youtube.com/watch?v=APmUWC8S1_M" def getTitle(url): ...
-2
2016-09-23T16:22:30Z
39,667,169
<p>This worked for me:</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys def getContent(url): try: html = urlopen(url) except HTTPError as e: print(e) return None try: bsObj = BeautifulSoup(html.re...
0
2016-09-23T18:16:02Z
[ "python", "printing", "error-handling", "beautifulsoup" ]
Is there a better way to handle writing csv in text mode and reading in binary mode?
39,665,461
<p>I have code that looks something like this:</p> <pre><code>import csv import os import tempfile from azure.storage import CloudStorageAccount account = CloudStorageAccount( account_name=os.environ['AZURE_ACCOUNT'], account_key=os.environ['AZURE_ACCOUNT_KEY'], ) service = account.create_block_blob_service...
1
2016-09-23T16:24:51Z
39,665,852
<p>Files opened in text mode have a <a href="https://docs.python.org/3/library/io.html#io.TextIOBase.buffer" rel="nofollow"><code>buffer</code></a> attribute. This object is the same one you would get by opening the file in binary mode, the text mode is just a wrapper on top of it.</p> <p>Open your file in text mode,...
2
2016-09-23T16:50:09Z
[ "python", "python-3.x", "csv", "azure", "windows-azure-storage" ]
grouping list elements in python
39,665,472
<pre><code>list = [('a5', 1), 1, ('a1', 1), 0, 0] </code></pre> <p>I want to group the elements of the list into 3, if the second or third element is missing in the list 'None' has to appended in the corresponding location.</p> <pre><code>exepected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]] </code></pre> <p>Is...
1
2016-09-23T16:25:49Z
39,665,682
<p>As far as I am aware, the only way to get the result you want is to loop through your list and detect when you encounter tuples. </p> <p>Example which should work:</p> <pre><code>temp = None result = [] for item in this_list: if type(item) == tuple: if temp is not None: while len(temp) &lt;...
0
2016-09-23T16:39:15Z
[ "python", "python-2.7" ]
grouping list elements in python
39,665,472
<pre><code>list = [('a5', 1), 1, ('a1', 1), 0, 0] </code></pre> <p>I want to group the elements of the list into 3, if the second or third element is missing in the list 'None' has to appended in the corresponding location.</p> <pre><code>exepected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]] </code></pre> <p>Is...
1
2016-09-23T16:25:49Z
39,666,046
<p>Here's a slightly different approach from the other answers, doing a comparison on the type of each element and then breaking the original list into chunks.</p> <pre><code>li = [('a5', 1), 1, ('a1', 1), 0, 0] for i in range(0, len(li), 3): if type(li[i]) is not tuple: li.insert(i, None) if type(li[...
1
2016-09-23T17:02:29Z
[ "python", "python-2.7" ]
Is it possible to create python virtual environment with ansible playbook?
39,665,553
<p>I have tried to create virtual environment in vagrant VM using ansible-local, but failed.</p> <p>This is my Vagrant file:</p> <pre><code>Vagrant.configure(2) do |config| config.vm.provider "virtualbox" do |v| v.memory = 4096 v.cpus = 2 end config.vm.define "shortener" do |shortener| shortener.vm...
1
2016-09-23T16:31:01Z
39,667,204
<p>I have found a solution. This is my "playbook.yml" file:</p> <pre><code>- name: Deploy shortener hosts: all remote_user: vagrant tasks: - name: Install packages become: true become_method: sudo apt: update_cache=yes name={{ item }} state=present with_items: - git ...
0
2016-09-23T18:18:09Z
[ "python", "vagrant", "ansible", "virtualenv", "ansible-local" ]
Calculate run time of a given function python
39,665,630
<p>I have created a function that takes in a another function as parameter and calculates the run time of that particular function. but when i run it, i can not seem to understand why this is not working . Does any one know why ? </p> <pre><code>import time import random import timeit import functools def ListGenerat...
-2
2016-09-23T16:35:45Z
39,666,397
<p>It looks like the code just executes incredibly fast. In <code>bubbleSort</code>, I added an additional <code>for</code> loop to execute the comparisons another <code>10000</code> times:</p> <pre><code>@timeit def bubbleSort(NumList): compCount,copyCount= 0,0 for i in range(10000): for currentRange...
0
2016-09-23T17:25:35Z
[ "python", "timeit" ]
REGEX extracting specific part non greedy
39,665,633
<p>I'm new to Python 2.7. Using regular expressions, I'm trying to extract from a text file just the emails from input lines. I am using the non-greedy method as the emails are repeated 2 times in the same line. Here is my code:</p> <pre><code>import re f_hand = open('mail.txt') for line in f_hand: line.rstrip(...
0
2016-09-23T16:35:50Z
39,665,834
<p>try this <code>re.findall('mailto:(\S+@\S+?\.\S+)\"',str))</code></p> <p>It should give you something like <code>['[email protected]']</code></p>
1
2016-09-23T16:48:48Z
[ "python", "regex", "python-2.7", "non-greedy" ]
REGEX extracting specific part non greedy
39,665,633
<p>I'm new to Python 2.7. Using regular expressions, I'm trying to extract from a text file just the emails from input lines. I am using the non-greedy method as the emails are repeated 2 times in the same line. Here is my code:</p> <pre><code>import re f_hand = open('mail.txt') for line in f_hand: line.rstrip(...
0
2016-09-23T16:35:50Z
39,665,875
<p><code>\S</code> means not a space. <code>"</code> and <code>&gt;</code> are not spaces.</p> <p>You should use <code>mailto:([^@]+@[^"]+)</code> as the regex (quoted form: <code>'mailto:([^@]+@[^"]+)'</code>). This will put the email address in the first capture group.</p>
1
2016-09-23T16:51:12Z
[ "python", "regex", "python-2.7", "non-greedy" ]
REGEX extracting specific part non greedy
39,665,633
<p>I'm new to Python 2.7. Using regular expressions, I'm trying to extract from a text file just the emails from input lines. I am using the non-greedy method as the emails are repeated 2 times in the same line. Here is my code:</p> <pre><code>import re f_hand = open('mail.txt') for line in f_hand: line.rstrip(...
0
2016-09-23T16:35:50Z
39,665,913
<p>If you parse a simple file with anchors for email addresses and always the same syntax (like double quotes to enclose attributes), you can use:</p> <pre><code>for line in f_hand: print re.findall(r'href="mailto:([^"@]+@[^"]+)"&gt;\1&lt;/a&gt;', line) </code></pre> <p><em>(<code>re.findall</code> returns only ...
1
2016-09-23T16:53:28Z
[ "python", "regex", "python-2.7", "non-greedy" ]
REGEX extracting specific part non greedy
39,665,633
<p>I'm new to Python 2.7. Using regular expressions, I'm trying to extract from a text file just the emails from input lines. I am using the non-greedy method as the emails are repeated 2 times in the same line. Here is my code:</p> <pre><code>import re f_hand = open('mail.txt') for line in f_hand: line.rstrip(...
0
2016-09-23T16:35:50Z
39,665,931
<p>\S accepts many characters that aren't valid in an e-mail address. Try a regular expression of</p> <pre><code>[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+\\.[a-zA-Z0-9-_.]+ </code></pre> <p>(presuming you are not trying to support Unicode -- it seems that you aren't since your input is a "text file").</p> <p>This will requir...
1
2016-09-23T16:54:49Z
[ "python", "regex", "python-2.7", "non-greedy" ]
REGEX extracting specific part non greedy
39,665,633
<p>I'm new to Python 2.7. Using regular expressions, I'm trying to extract from a text file just the emails from input lines. I am using the non-greedy method as the emails are repeated 2 times in the same line. Here is my code:</p> <pre><code>import re f_hand = open('mail.txt') for line in f_hand: line.rstrip(...
0
2016-09-23T16:35:50Z
39,667,321
<p>This is the format of an email address - <a href="https://tools.ietf.org/html/rfc5322#section-3.4.1" rel="nofollow">https://tools.ietf.org/html/rfc5322#section-3.4.1</a>.</p> <p>Keeping that in mind the regex that you need is - <code>r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"</code>. <em>(This works withou...
0
2016-09-23T18:25:24Z
[ "python", "regex", "python-2.7", "non-greedy" ]
Split large JSON file into batches of 100 at a time to run through an API
39,665,699
<p>I am so close to being done with this tool I am developing, but as a junior developer with NO senior programmer to work with I am stuck. I have a script in python that takes data from our data base converts it to JSON to be run through an Address validation API, I have it all working, but the fact is that the API on...
1
2016-09-23T16:40:52Z
39,665,784
<p>So assuming the rest of your code works, this will give the api a break every 100 rows for 10 secs. You will need to import the time module.</p> <pre><code> for i, object in enumerate(dict_ready): r = requests.post(url, data=dict_ready, headers=headers) if i%100==0: time.sleep(10) </c...
0
2016-09-23T16:46:15Z
[ "python", "json" ]
Split large JSON file into batches of 100 at a time to run through an API
39,665,699
<p>I am so close to being done with this tool I am developing, but as a junior developer with NO senior programmer to work with I am stuck. I have a script in python that takes data from our data base converts it to JSON to be run through an Address validation API, I have it all working, but the fact is that the API on...
1
2016-09-23T16:40:52Z
39,665,824
<p>As I read it, you have a range of objects, and you want to break it up into subsets, each of which is no more than 100 items.</p> <p>Assuming that <code>dict_ready</code> is a list of objects (if it's not, modify your code to make it so):</p> <pre><code>count = 100 subsets = (dict_ready[x:x + count] for x in range...
2
2016-09-23T16:48:15Z
[ "python", "json" ]
Split large JSON file into batches of 100 at a time to run through an API
39,665,699
<p>I am so close to being done with this tool I am developing, but as a junior developer with NO senior programmer to work with I am stuck. I have a script in python that takes data from our data base converts it to JSON to be run through an Address validation API, I have it all working, but the fact is that the API on...
1
2016-09-23T16:40:52Z
39,665,844
<p>try this as your second chunk of code</p> <pre><code>with open('.json', 'r') as run: dict_run = json.loads(run) ss_output=[] for i in range(0,len(dict_ready),100): # do something with object to only run 100 at a time dict_ready=json.dumps(dict_run[i:i+100]) r = requests.post(url, data=dict_ready, h...
1
2016-09-23T16:49:42Z
[ "python", "json" ]
Tensorflow: value error with variable_scope
39,665,702
<p>This is my code below:</p> <pre><code>''' Tensorflow LSTM classification of 16x30 images. ''' from __future__ import print_function import tensorflow as tf from tensorflow.python.ops import rnn, rnn_cell import numpy as np from numpy import genfromtxt from sklearn.cross_validation import train_test_split import p...
2
2016-09-23T16:41:11Z
39,704,568
<p>You are not iterating over the same variable in line 92 and 97, since those will always be in the same namespace, at least in the current setting, since you are calling one namespace from within another (since one is embedded in the RNN function). So your effective variable scope will be something like <code>'backwa...
1
2016-09-26T13:44:10Z
[ "python", "numpy", "machine-learning", "tensorflow" ]
matplotlib place axes within figure box
39,665,712
<p>This is my code (I am running it in a jupyter notebook on OS X )</p> <pre><code>% matplotlib inline import matplotlib.pyplot as plt fig = plt.figure() fig.set_facecolor('gray') ax = fig.add_axes([0.2, 0.2, 0.2, 0.2]) print fig.get_figwidth() </code></pre> <p>I was expecting to see a large gray figure box with a sm...
0
2016-09-23T16:41:44Z
39,667,989
<p>After some more experimentation and digging I found the answer in the <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-matplotlib" rel="nofollow">matplotlib magic</a> documentation referenced from <a href="http://stackoverflow.com/questions/37864735/matplotlib-and-ipython-notebook-displ...
0
2016-09-23T19:11:12Z
[ "python", "matplotlib" ]
matplotlib node alignment and custom line style
39,665,724
<p>I'm plotting netowrk graphs (Water distribution networks) using bokeh and or matplotlib. From the reference software the plots look like this:</p> <p><img src="http://i.stack.imgur.com/8myGf.jpg" alt="Overview from EPAnet"></p> <p>As you can see pumps and water towers have their own little symbols. I'm using matp...
0
2016-09-23T16:42:41Z
39,665,889
<p>Instead of rotating the triangle, you may consider <a href="http://matplotlib.org/examples/pylab_examples/arrow_simple_demo.html" rel="nofollow">arrows</a>. If you really want to rotate the triangle, I normally rotate the three points of the triangle around its center (by rotation matrix). </p> <p>About custom sym...
1
2016-09-23T16:52:09Z
[ "python", "matplotlib", "plot", "bokeh" ]
wxPython - code highlighting and pygment
39,665,775
<p>I am trying to utilize pygment for some code highlighting in a wxPython RichTextCtrl.</p> <p>I can't find much online (other than broken links) about achieving this.</p> <p>Here is some sample code. I've tried a few different formatters and they all fail. I believe editra using pygment and wxpython, but the source...
0
2016-09-23T16:45:48Z
39,705,793
<p>I ended up using StyledTextCtrl as suggested in the comments. It turns out there are 2 demos included with the wxPython source, the 2nd of which does exactly what I was trying. I would post the code but it is ~400 lines.</p>
0
2016-09-26T14:41:51Z
[ "python", "wxpython", "wxwidgets", "wx" ]
How to remove all the elements in the array without changing its size in python
39,665,960
<p>If i created an array </p> <pre><code>b = [[] for _ in xrange(10)] </code></pre> <p>and i store some numbers in it like this</p> <pre><code>b = [[], [1], [22, 132], [3, 123], [], [], [6], [], [], [89]] </code></pre> <p>Now i want to delete all the elements and it should look like this</p> <pre><code> b = [[], [...
-4
2016-09-23T16:56:59Z
39,666,197
<p>You need to loop over <code>b</code>, either setting each element to the empty list or deleting the contents of that element:</p> <pre><code>for i in xrange(len(b)): b[i] = [] </code></pre> <p>or</p> <pre><code>for i in xrange(len(b)): del b[i][:] </code></pre>
0
2016-09-23T17:12:21Z
[ "python" ]
Button position in kivy gridlayout
39,665,964
<p>I'm trying to move this button to top-right but no matters what I do I just can't move it. It is <strong>always</strong> in the bottom-left and never leaves this position.</p> <p>This is my .py:</p> <pre><code> #!/usr/bin/python # coding=UTF-8 import kivy from kivy.uix.gridlayout import GridLayout ...
0
2016-09-23T16:57:12Z
39,668,212
<p>I suggest using relative layout. for example </p> <pre><code>RelativeLayout: Button: text: 'botao1' on_press: root.bt1() pos_hint: {'center_x': 0.5, 'center_y': 0.5} </code></pre> <p>change <code>center_x</code> and <code>center_y</code> till they meet your needs.</p>
2
2016-09-23T19:26:24Z
[ "python", "python-2.7", "kivy", "kivy-language" ]
Parsing XML with throws unknown key error in function but works at command prompt
39,666,022
<p>I'm running Python 2.7.12 in Anaconda 4.1.1. I installed untangle to parse a pretty complex XML document.</p> <p>Here's my code:</p> <pre><code>import untangle obj = untangle.parse('ear.xml') for rd in obj.SaData.Session.Test.Data.RecordedData: tls = rd.Measured.TestLines tl = tls.Testline for line i...
0
2016-09-23T17:00:58Z
39,667,877
<p>It was a stupid typo. I wrote Testline when I should have written TestLine. Sorry to waste everyone's time.</p> <p>Dessie</p>
0
2016-09-23T19:04:22Z
[ "python", "xml" ]
how to compile cython code
39,666,048
<p>I want to compile my code. I want to write my own cpp file that calls functions from other libraries.</p> <p>my cpp code</p> <pre><code>//my_vl.h int my_vl_k(int normalized_feat_set, int k){} </code></pre> <p>my pxd file</p> <pre><code>#my_vl.pxd import libc.stdlib cdef extern from "my_vl.h": int my_vl_k(in...
-2
2016-09-23T17:02:36Z
39,666,191
<p>In my_v1.h you should use header guards:</p> <p>my_v1.h:</p> <pre><code>#ifndef MY_V1_H #define MY_V1_H // your function decl. #endif </code></pre>
0
2016-09-23T17:12:01Z
[ "python", "cython" ]
how to compile cython code
39,666,048
<p>I want to compile my code. I want to write my own cpp file that calls functions from other libraries.</p> <p>my cpp code</p> <pre><code>//my_vl.h int my_vl_k(int normalized_feat_set, int k){} </code></pre> <p>my pxd file</p> <pre><code>#my_vl.pxd import libc.stdlib cdef extern from "my_vl.h": int my_vl_k(in...
-2
2016-09-23T17:02:36Z
39,668,693
<p>You provide the definition of <code>my_vl_k</code> in your header file (<code>{}</code>). Instead write</p> <pre><code>int my_vl_k(int normalized_feat_set, int k); </code></pre> <p>(replace the curly brackets which provide a useless empty definition with a semi-colon which just says that the function exists).</p>
0
2016-09-23T20:02:22Z
[ "python", "cython" ]
how to use the `query` method to check if elements of a column contain a specific string
39,666,081
<p>I know how to check if a column contains a string. My preffered method is to use <code>.str.contains</code>. However, that returns a boolean array that I have to use as a mask on the original dataframe. The convenience of <code>query</code> is that it returns the already filtered dataframe.</p> <p>consider the <...
1
2016-09-23T17:04:51Z
39,666,369
<p>This is currently not supported, <code>query</code> only implements a subset of operations, basically none of the string functions.</p> <p>Just a sidenote to the comment, <code>query</code> does support a vectorized version of the <code>in</code> keyword.</p> <pre><code>df.query('X in ["aw", "dw"]') Out[9]: X...
4
2016-09-23T17:23:48Z
[ "python", "pandas" ]
How do go into a directory without being given its full path in python 2?
39,666,121
<p>I am currently trying to go into a folder and call a python 2 script, but I cannot get any answer to go into a folder without using its full path. As example in DOS I would normally type this:</p> <pre><code>C:\unknownpath\&gt; cd otherpath C:\unknownpath\otherpath\&gt; </code></pre> <p>Thanks for any help.</p>
0
2016-09-23T17:07:47Z
39,666,241
<p>Try this:</p> <pre><code>import os os.chdir('otherpath') </code></pre> <p>This at least matches your DOS example, and will change your working directory to <code>otherpath</code> relative to the directory the command is run from. For example if you are in <code>/home/myusername/</code>, then this will take you to ...
1
2016-09-23T17:15:02Z
[ "python" ]
How do go into a directory without being given its full path in python 2?
39,666,121
<p>I am currently trying to go into a folder and call a python 2 script, but I cannot get any answer to go into a folder without using its full path. As example in DOS I would normally type this:</p> <pre><code>C:\unknownpath\&gt; cd otherpath C:\unknownpath\otherpath\&gt; </code></pre> <p>Thanks for any help.</p>
0
2016-09-23T17:07:47Z
39,666,281
<p><code>os.chdir</code> works on relative path.</p> <pre><code>&gt;&gt;&gt; os.getcwd() 'C:\\Users\\sba001\\PycharmProjects' &gt;&gt;&gt; os.listdir('.') ['untitled', 'untitled1', 'untitled2', 'untitled3', 'untitled4', 'untitled5'] &gt;&gt;&gt; os.chdir('untitled') &gt;&gt;&gt; os.getcwd() 'C:\\Users\\sba001\\Pycharm...
0
2016-09-23T17:17:29Z
[ "python" ]
Logical operations with array of strings in Python
39,666,136
<p>I know the following logical operation works with numpy: </p> <pre><code>A = np.array([True, False, True]) B = np.array([1.0, 2.0, 3.0]) C = A*B = array([1.0, 0.0, 3.0]) </code></pre> <p>But the same isn't true if B is an array of strings. Is it possible to do the following: </p> <pre><code>A = np.array([True, ...
2
2016-09-23T17:08:51Z
39,666,157
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html"><code>np.where</code></a> for making such selection based on a mask -</p> <pre><code>np.where(A,B,'') </code></pre> <p>Sample run -</p> <pre><code>In [4]: A Out[4]: array([ True, False, True], dtype=bool) In [5]: B Out[5...
5
2016-09-23T17:10:07Z
[ "python", "string", "numpy", "logical-operators" ]