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
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However...
6
2016-07-29T15:59:48Z
38,669,732
<p>I appreciate all of the you have provided! I did some asking around as well and found a clever way to accomplish what I was searching for. Here is what we came up with:</p> <pre><code>sharedStarsW = list() sharedStarsA = list() for s in Astars: distance = [((s["RA"] - star["RA"])**2 + (s["DEC"] - star["DEC"])**...
0
2016-07-30T02:11:29Z
[ "python", "numpy" ]
How to rotate image with Matplottlib without border?
38,663,110
<p>I have an image with a white background that I would like to rotate. The rotation, however, creates an unwanted border around the image (not the axes, but the grey outline around the pencil below). How can I remove this border?</p> <pre><code>fig,ax = plt.subplots(figsize=(8,6)) pencil = mpimg.imread('Pencil.jpg...
1
2016-07-29T16:03:32Z
38,663,306
<p><a href="http://stackoverflow.com/questions/9295026/matplotlib-plots-removing-axis-legends-and-white-spaces">Matplotlib plots: removing axis, legends and white spaces</a></p> <p>Use <code>mpimg.axis('off')</code></p> <p>See also the matplotlib documentation:</p> <p><a href="http://matplotlib.org/api/axis_api.html...
3
2016-07-29T16:16:06Z
[ "python", "matplotlib" ]
Python-Twiter: Can't covert 'bytes' object to string
38,663,142
<p>I am trying to encode tweets from unicode to utf-8 but I get the following error gets logged on CLI when I execute the file:</p> <pre><code>File "PI.py", line 21, in analyze text += s.text.encode('utf-8') TypeError: Can't convert 'bytes' object to str implicitly </code></pre> <p>Here is my code:</p> <pre><code>te...
0
2016-07-29T16:05:48Z
38,663,175
<p>You should initialize your <code>text</code> as bytes by appending a leading <code>b</code>:</p> <pre><code>text = b"" </code></pre> <p>This will allow the new bytes object to be concatenated without errors to the existing bytes object <code>text</code></p>
1
2016-07-29T16:07:49Z
[ "python", "encoding", "utf-8", "python-twitter" ]
Pivot table error:1 ndim Categorical are not supported at this time
38,663,150
<p>My goal is to box-plot the 'score' by 'label', I don't care about "date" and "Cusip". I want to use 'pivot' to reshape the data, so that each Label is in one column and I can boxplot it.</p> <pre><code> date Cusip Label Score 663182 2015-07-31 00846UAG AAA 138.15 663183 2015-07-31 00846UAH ...
0
2016-07-29T16:06:17Z
38,675,092
<p>You really should be using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> as you have got duplicate entries in your <code>date</code> column.</p> <pre><code>pd.pivot_table(df, values='Score', index=['date', 'Cusip'], columns=['Labe...
1
2016-07-30T14:37:40Z
[ "python", "pandas", "pivot" ]
How to select a specific tag within this html?
38,663,186
<p>How would I select all of the titles in this page</p> <pre><code>http://bulletin.columbia.edu/columbia-college/departments-instruction/african-american-studies/#coursestext </code></pre> <p>for example: I'm trying to get all the lines similar to this:</p> <pre><code>AFAS C1001 Introduction to African-American Stu...
1
2016-07-29T16:08:39Z
38,663,230
<p>Iterate over elements with <code>courseblock</code> class, then, for every course, get the element with <code>courseblocktitle</code> class. Working example using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow"><code>select()</code> and <code>select_one()</code> methods<...
3
2016-07-29T16:11:51Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Strange results from timedelta with pandas
38,663,296
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'date_sent': ['06/11/2015', '', 'Not required', '06/11/2015'], 'date_published': ['06/11/2015', '', '', '23/01/2016']}) </code></pre> <p>I want to calculate the difference between the two dates in each row, so first I co...
0
2016-07-29T16:15:42Z
38,663,462
<p>It is exactly 226 days between those dates.</p>
0
2016-07-29T16:25:04Z
[ "python", "pandas" ]
Strange results from timedelta with pandas
38,663,296
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'date_sent': ['06/11/2015', '', 'Not required', '06/11/2015'], 'date_published': ['06/11/2015', '', '', '23/01/2016']}) </code></pre> <p>I want to calculate the difference between the two dates in each row, so first I co...
0
2016-07-29T16:15:42Z
38,665,477
<p>See if this helps.</p> <pre><code> print pd.to_datetime('06/11/2016', dayfirst =True, format='%d/%m/%Y', errors = 'ignore') print pd.to_datetime('06/11/2016', format='%m/%d/%Y', errors = 'ignore') 2016-11-06 00:00:00 2016-06-11 00:00:00 </code></pre>
0
2016-07-29T18:35:56Z
[ "python", "pandas" ]
How to setup path and env so correct Python used
38,663,318
<p>System A has both Python 2.7 and Python 3.4 installed. System B has both Python 2.7 and Python 3.5 installed.</p> <p>I have at top of Python script:</p> <pre><code>#!/usr/bin/env python3.5 </code></pre> <p>The reason being that python3 compiler must be used. I want to move it between machines but this will fail n...
0
2016-07-29T16:16:39Z
38,663,371
<p>for me just</p> <pre><code>#!/usr/bin/env python3 </code></pre> <p>works fine</p>
1
2016-07-29T16:19:55Z
[ "python", "bash", "unix", "environment-variables" ]
How to setup path and env so correct Python used
38,663,318
<p>System A has both Python 2.7 and Python 3.4 installed. System B has both Python 2.7 and Python 3.5 installed.</p> <p>I have at top of Python script:</p> <pre><code>#!/usr/bin/env python3.5 </code></pre> <p>The reason being that python3 compiler must be used. I want to move it between machines but this will fail n...
0
2016-07-29T16:16:39Z
38,663,443
<p>Use Virtualenv to setup your python environment.</p>
0
2016-07-29T16:24:10Z
[ "python", "bash", "unix", "environment-variables" ]
How to setup path and env so correct Python used
38,663,318
<p>System A has both Python 2.7 and Python 3.4 installed. System B has both Python 2.7 and Python 3.5 installed.</p> <p>I have at top of Python script:</p> <pre><code>#!/usr/bin/env python3.5 </code></pre> <p>The reason being that python3 compiler must be used. I want to move it between machines but this will fail n...
0
2016-07-29T16:16:39Z
38,663,718
<p>If your are set on using <code>#!/usr/bin/env python3.5</code>, you could create a symbolic link to the python3.4 version (called python3.5) and then reference that in your script. So both environments could use the directive <code>#!/usr/bin/env python3.5</code>. Of course, please add a comment somewhere that th...
0
2016-07-29T16:42:17Z
[ "python", "bash", "unix", "environment-variables" ]
How can I turn the results from this joined query into dict based on one of the key values?
38,663,333
<p>Sorry i'm a bit new to all this.</p> <p>I'm using psycopg2, python, and postgres.</p> <p>I have two tables - Users and Events. I've set up a many-to-many relationship because an event can have many users and users can join many events. There's an intermediate table called UsersEvents matching User id to Event id. ...
1
2016-07-29T16:17:29Z
38,664,575
<p>You want to build a data structure for each event by name. Create a dict that will map names to event data. For each row, either create or update the data for the event. Finally, the values from the dict is the list of event data.</p> <pre><code>for id, event, user in results: event = events.setdefault(id, {...
0
2016-07-29T17:39:09Z
[ "python", "psycopg2" ]
How can I force NumPy to append a list as an object?
38,663,380
<p>I have an empty <s>list</s> array declared, as such:</p> <p><code>r = np.array([])</code></p> <p>And I have an operation that adds an array of values to <code>r</code> on every loop. Say the first loop adds <code>[1,2,3]</code> and the next adds <code>[4,5,6,7]</code>. How can I append to the array <code>r</code> ...
1
2016-07-29T16:20:23Z
38,663,521
<p>You can use a list comprehension when creating the array:</p> <pre><code>&gt;&gt;&gt; np.array([row for row in [1, 2, 3], [4, 5, 6, 6]]) array([[1, 2, 3], [4, 5, 6, 6]], dtype=object) </code></pre>
2
2016-07-29T16:29:06Z
[ "python", "arrays", "numpy" ]
Python encryption and rotation
38,663,417
<p>Could you please help with the following code. I am trying to write a function def encrypt(text, rot), which will receive input as a string and integer. My function should result of rotating each letter in the text by no of rotations to the right. For example my output should be like this:`The final outcome is like<...
-1
2016-07-29T16:22:48Z
38,663,862
<p>You don't have to check if the index is less than 26. Because the <code>%</code> operator returns the dividend when the dividend is less than the divisor (26) and the remainder when the dividend is greater than or equal to the divisor.</p> <pre><code>def rotate(s, n): from string import ascii_letters as letters...
0
2016-07-29T16:52:26Z
[ "python", "python-2.7", "python-3.x" ]
Repeat numbers according to pattern numpy
38,663,470
<p>I have an array, say <code>p = [2,3,2,4]</code> and a number, say <code>n = 4</code>. I need to generate an array of ones and zeros according to the pattern p, n-p. That is for each element, u in p, there are u ones followed by n-u zeros. It's very easy to do this using the np.insert operation. But theano doesn't ha...
2
2016-07-29T16:25:20Z
38,663,777
<pre><code>p = numpy.array([2, 3, 2, 4]) n = 4 result = (p[:, None] &gt; numpy.arange(n)).ravel().astype(int) </code></pre> <p>We compare</p> <pre><code>[[2] [3] [2] [4]] </code></pre> <p>to <code>[0 1 2 3]</code> to get an array of booleans, then flatten it and convert it to integers to get the output you want.<...
3
2016-07-29T16:46:15Z
[ "python", "numpy" ]
Python: subprocess.Popen().communicate() prints output of an SSH command to stdout instead of returning the output
38,663,473
<p>Here's a copy of my python terminal:</p> <pre><code>&gt;&gt; import subprocess &gt;&gt; import shlex &gt;&gt; host = 'myhost' &gt;&gt; subprocess.Popen(shlex.split('ssh -o LogLevel=error -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes %s "hostname --short"' ...
0
2016-07-29T16:25:32Z
38,663,586
<p>You need to give the <code>subprocess.Popen</code> call a <code>stdout</code> argument. For example:</p> <pre><code>&gt;&gt;&gt; subprocess.Popen("ls", stdout=subprocess.PIPE).communicate() (b'Vagrantfile\n', None) &gt;&gt;&gt; </code></pre> <p>The output of the command then appears where you expect it.</p>
2
2016-07-29T16:33:06Z
[ "python", "python-2.7", "subprocess", "shlex" ]
Setting values for a numpy ndarray using mask
38,663,530
<p>I want to calculate business days between two times, both of which contain null values, following <a href="http://stackoverflow.com/questions/37576552/dealing-with-none-values-when-using-pandas-groupby-and-apply-with-a-function">this question</a> related to calculating business days. I've identified that the way I'...
3
2016-07-29T16:29:37Z
38,669,888
<p>Your problem is that with your version of numpy, you can't use a boolean array as an index to an array. Just use <code>np.where(mask==True)</code> instead of mask and <code>np.where(mask==False)</code> instead of ~mask, and it will work as desired.</p>
1
2016-07-30T02:44:03Z
[ "python", "numpy", "pandas" ]
reshape dataframe in pandas to layout data horizontally
38,663,573
<p>I have the following DataFrame:</p> <pre><code>data = [['label1', 1234], ['label1', 12345], ['label2', 2345], ['label2', 4567], ['label3', 123], ['label2', 4589]] pd.DataFrame(data, columns=['label', 'id']) </code></pre> <p>outputs:</p> <pre><code> label id 0 label1 1234 1 label1 12345 2 label2 2345...
0
2016-07-29T16:32:07Z
38,663,683
<p>Assign a new column to enumerate the ids, then use pivot:</p> <pre><code>(df.assign(ids='id' + (df.groupby('label').cumcount()+1).astype(str)) .pivot(index='label', columns='ids', values='id')) Out: ids id1 id2 id3 label label1 1234.0 12345.0 NaN label2 2345.0 4...
2
2016-07-29T16:40:15Z
[ "python", "pandas", "reshape" ]
How can I serve a HTTP page and a websocket on the same url in tornado
38,663,666
<p>I have an API and, depending on the request protocol, I want to either serve the client an HTTP response, or I want to connect a websocket and send the response followed by incremental updates. However in Tornado I can only specify a single handler for any URL.</p>
0
2016-07-29T16:38:51Z
38,663,667
<p>The difference between a request for an HTTP page and a websocket is the presence of a header. Unfortunately afaik there is no way to tell the tornado router to choose one or the other handler based on a header (other than host).</p> <p>I can however make a handler that inherits from both my already quite elaborate...
0
2016-07-29T16:38:51Z
[ "python", "websocket", "tornado" ]
Python Pandas - Combining Multiple Columns into one Staggered Column
38,663,711
<p>How do you combine multiple columns into one staggered column? For example, if I have data:</p> <pre><code> Column 1 Column 2 0 A E 1 B F 2 C G 3 D H </code></pre> <p>And I want it in the form:</p> <pre><code> Column 1 0 A 1 E ...
2
2016-07-29T16:41:45Z
38,663,768
<p>First stack the columns and then drop the multiindex:</p> <pre><code>df.stack().reset_index(drop=True) Out: 0 A 1 E 2 B 3 F 4 C 5 G 6 D 7 H dtype: object </code></pre>
5
2016-07-29T16:45:14Z
[ "python", "pandas" ]
Python Pandas - Combining Multiple Columns into one Staggered Column
38,663,711
<p>How do you combine multiple columns into one staggered column? For example, if I have data:</p> <pre><code> Column 1 Column 2 0 A E 1 B F 2 C G 3 D H </code></pre> <p>And I want it in the form:</p> <pre><code> Column 1 0 A 1 E ...
2
2016-07-29T16:41:45Z
38,663,788
<p>To get a dataframe:</p> <pre><code> pd.DataFrame(df.values.reshape(-1, 1), columns=['Column 1']) </code></pre> <p><a href="http://i.stack.imgur.com/axhTD.png" rel="nofollow"><img src="http://i.stack.imgur.com/axhTD.png" alt="enter image description here"></a></p> <p>For a series answering OP question:</p> <pre><...
4
2016-07-29T16:46:52Z
[ "python", "pandas" ]
Submitting form using mechanize in python
38,663,745
<p>I am trying to submit a form to <a href="http://apps.fas.usda.gov/esrquery/esrq.aspx" rel="nofollow">http://apps.fas.usda.gov/esrquery/esrq.aspx</a> in python, using the following code:</p> <pre><code>import urllib from bs4 import BeautifulSoup import mechanize import datetime today = datetime.date.today().strfti...
0
2016-07-29T16:44:06Z
38,665,747
<p>You're close, but there's more you need to do after submitting. In this case, just add:</p> <pre><code>doc = response.read() ofile = '&lt;your path&gt;' with open(ofile, 'w') as f: f.write(doc) </code></pre> <p>I couldn't actually test this on your website at the moment, so I'm just assuming all your settings...
0
2016-07-29T18:53:27Z
[ "python", "forms", "submit", "mechanize", "submission" ]
Given multiple two columns sets of a min/max how to return index if a number falls between min/max
38,663,764
<p>My input CSV looks like this </p> <pre><code>Tier | A | | B | | C | | Min | Max | Min | Max | Min | Max 1 | 0 | .5 | 0 | .25 | 0 | .92 2 |.51 | 1.0 | .26 | .50 | .93 | 1.5 </code></pre> <p>Given an input dictionary <code>{A: .56, B: .22, C: .99}</code> I want to r...
1
2016-07-29T16:44:58Z
38,664,879
<p>Skip the first couple rows. You can use the kwarg <code>header=[0,1]</code> to read the first two rows as a <code>MultiIndex</code> but the missing values in level 0 cause placeholder names to be used (in the columns that don't have an 'A', 'B', or 'C'.</p> <p>See the <code>read_csv</code> <a href="http://pandas.py...
2
2016-07-29T17:58:50Z
[ "python", "pandas" ]
Given multiple two columns sets of a min/max how to return index if a number falls between min/max
38,663,764
<p>My input CSV looks like this </p> <pre><code>Tier | A | | B | | C | | Min | Max | Min | Max | Min | Max 1 | 0 | .5 | 0 | .25 | 0 | .92 2 |.51 | 1.0 | .26 | .50 | .93 | 1.5 </code></pre> <p>Given an input dictionary <code>{A: .56, B: .22, C: .99}</code> I want to r...
1
2016-07-29T16:44:58Z
38,668,405
<p>With this setup: </p> <pre><code>arrays = [[0, .5, 0, .25, 0, .92,],[.51,1, .26, .5, .93, 1.5, ]] col = pd.MultiIndex.from_product([('A', 'B', 'C'), ('Min', 'Max')]) df = pd.DataFrame(arrays, columns=col ) A B C Min Max Min Max Min Max 0 0.00 0.5 0.00 0.25 0.0...
0
2016-07-29T22:33:25Z
[ "python", "pandas" ]
Why is this inter-process communication working?
38,663,898
<p>In Python, exchanging objects between processes is well documented: queues, pipes or pools should be used (see <a href="https://docs.python.org/3/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">doc</a>). So why is this super simple code working without any of these communication too...
0
2016-07-29T16:54:25Z
38,664,067
<p>Because it is only relying on shared memory between the threads. But if you want to send blocking messages and have both good response time and low cpu consumption you have to share pipes or whatever.</p> <p>In your example you use random sleep calls so it is not representative.</p>
0
2016-07-29T17:05:26Z
[ "python", "process", "multiprocessing" ]
Why is this inter-process communication working?
38,663,898
<p>In Python, exchanging objects between processes is well documented: queues, pipes or pools should be used (see <a href="https://docs.python.org/3/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">doc</a>). So why is this super simple code working without any of these communication too...
0
2016-07-29T16:54:25Z
38,664,146
<p>That's because <strong>no</strong> interprocess communication is happening.</p> <p>Modify the code to print the value of <code>_memory</code> in the child process:</p> <pre><code>def run(self): while True: print('Memory is', self._memory) sleep(random()) </code></pre> <p>And you'll see that th...
0
2016-07-29T17:11:04Z
[ "python", "process", "multiprocessing" ]
Executing script requiring root access via CGI
38,663,991
<p>I have a script <strong>script.py</strong> which I'm able to execute via CGI by navigating to <em>mydomain.com/runscript</em>.</p> <p>The script however makes a subprocess call to <strong>echo "mysqldump ..." | sudo -i</strong> and <strong>sudo python</strong> using <strong>os.system(COMMAND)</strong>. When I attem...
0
2016-07-29T17:00:26Z
38,981,305
<p>You can pass the password into sudo command by piping it:</p> <p><code>echo &lt;your password&gt; | sudo -S &lt;your command&gt;</code> </p>
0
2016-08-16T17:45:10Z
[ "python", "apache", "cgi", "root", "sudoers" ]
split string list into sublist in python
38,663,995
<p>Looking for a way to split the following string list into sublist and print using a for loop.</p> <pre><code>[[[u'Book1', None, u'Thriller', u'John C', u'07/12/2012'], [u'Book2', u'1', u'Action', u'Tom B', u'07/12/2012'], [u'Book3', None, u'Romance', u'Angie P', u'07/12/2012'], [u'Book4', None, u'Comedy', u'Tracy N...
0
2016-07-29T17:00:39Z
38,664,137
<p>Your question is a bit vague! If I understood your question correctly, you can do it like this:</p> <pre><code>a = [[[u'Book1', None, u'Thriller', u'John C', u'07/12/2012'], [u'Book2', u'1', u'Action', u'Tom B', u'07/12/2012'], [u'Book3', None, u'Romance', u'Angie P', u'07/12/2012'], [u'Book4', None, u'Comedy', u'T...
1
2016-07-29T17:10:28Z
[ "python", "string", "list", "loops", "split" ]
split string list into sublist in python
38,663,995
<p>Looking for a way to split the following string list into sublist and print using a for loop.</p> <pre><code>[[[u'Book1', None, u'Thriller', u'John C', u'07/12/2012'], [u'Book2', u'1', u'Action', u'Tom B', u'07/12/2012'], [u'Book3', None, u'Romance', u'Angie P', u'07/12/2012'], [u'Book4', None, u'Comedy', u'Tracy N...
0
2016-07-29T17:00:39Z
38,664,142
<p>Are you looking for this?</p> <pre><code>def testString(): input = [[ [u'Book1', None, u'Thriller', u'John C', u'07/12/2012'], [u'Book2', u'1', u'Action', u'Tom B', u'07/12/2012'], [u'Book3', None, u'Romance', u'Angie P', u'07/12/2012'], [u'Book4', None, u'Comedy', u'Tracy N', u'07/12/2012'], ...
2
2016-07-29T17:10:47Z
[ "python", "string", "list", "loops", "split" ]
How do I Put 2 Conditions in an "if" Statement?
38,664,017
<p>I am trying to set up a function in a way so that it will only execute if two conditions are met: if the variable is greater than some value and smaller than a another value.</p> <p>I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by ...
-3
2016-07-29T17:02:04Z
38,664,094
<p>The error is from the fact you are comparing an array (a.k.a. <code>juld</code>) to a number. In short, you need to specify either a specific element for the if statement to check, or use the <code>any()</code> or <code>all()</code> methods as detailed in the error message. You can find the definition of these metho...
1
2016-07-29T17:07:22Z
[ "python", "function", "loops", "if-statement", "python-3.5" ]
How do I Put 2 Conditions in an "if" Statement?
38,664,017
<p>I am trying to set up a function in a way so that it will only execute if two conditions are met: if the variable is greater than some value and smaller than a another value.</p> <p>I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by ...
-3
2016-07-29T17:02:04Z
38,664,167
<p>I don't really understand what you want to do here, but there are three options. If you only want to go into the block if all values in the array satisfy it, use a.all(condition). If you want to go in if any values satisfy the condition, use a.any(condition). If you want to go in to the block for each value of the a...
0
2016-07-29T17:12:23Z
[ "python", "function", "loops", "if-statement", "python-3.5" ]
How do I Put 2 Conditions in an "if" Statement?
38,664,017
<p>I am trying to set up a function in a way so that it will only execute if two conditions are met: if the variable is greater than some value and smaller than a another value.</p> <p>I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by ...
-3
2016-07-29T17:02:04Z
38,664,402
<p>The problem is because you are comparing an array i.e. <code>juld</code> to two dates/numbers, <code>start_date</code> and <code>end_date</code>. So you need to be able to change the array to a date/number. I can't see the what is in <code>juld</code> but I suspect if you just change your code to: </p> <pre><code>i...
0
2016-07-29T17:29:18Z
[ "python", "function", "loops", "if-statement", "python-3.5" ]
How do I Put 2 Conditions in an "if" Statement?
38,664,017
<p>I am trying to set up a function in a way so that it will only execute if two conditions are met: if the variable is greater than some value and smaller than a another value.</p> <p>I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by ...
-3
2016-07-29T17:02:04Z
38,959,290
<p>First of all, I think you'd wanna look at the min/max value of <code>juld</code>, as it is an array. Try something like:</p> <pre><code>if max(juld) &lt; start_date or min(juld) &gt; end_date: </code></pre> <p>I think that should work!</p>
1
2016-08-15T16:45:33Z
[ "python", "function", "loops", "if-statement", "python-3.5" ]
How do I get PHP to kill www-data processes?
38,664,033
<p>I have a Debian server running apache2/PHP. From this website I can execute many python scripts over time. I want to be able to kill these scripts after a certain amount of time so that they don't pile up. The python scripts are owned by www-data.</p> <p>I have tried killing the python scripts by storing the PID an...
0
2016-07-29T17:03:40Z
38,664,116
<pre><code>exec("sudo -u &lt;YOURUSER&gt; -S kill $PID"); </code></pre>
0
2016-07-29T17:08:58Z
[ "php", "python", "linux", "bash" ]
Scrape heading of a video using selenium python3
38,664,035
<p>I want to scrape video name of this <a href="https://www.youtube.com/watch?v=POk-uOQSJVk" rel="nofollow">link</a> as it is " Insane Woman Goes Crazy On Guy Who Just Wants A Refund". </p> <p>The code on the web is:</p> <pre><code>&lt;span id="eow-title" class="watch-title" dir="ltr" title="Insane Woman Goes Crazy ...
0
2016-07-29T17:03:42Z
38,664,087
<p>First of all, <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_class_name" rel="nofollow"><code>find_elements_by_class_name()</code> method</a> <em>returns a list of <code>WebElement</code>s, while you need a single one</em>. Also, you need to <a ...
0
2016-07-29T17:06:49Z
[ "python", "python-3.x", "selenium", "web-crawler" ]
Difference of type() function in Python 2 and Python 3
38,664,068
<p>When trying the following script in Python 2, </p> <pre><code>a = 200 print type(a) </code></pre> <p>its output is </p> <pre><code>&lt;type 'int'&gt; </code></pre> <p>and in Python 3, the script </p> <pre><code>a = 200 print (type(a)) </code></pre> <p>its output is, </p> <pre><code>&lt;class 'int'&gt...
3
2016-07-29T17:05:29Z
38,664,124
<p><code>type</code> isn't behaving any differently. They just changed things so all classes show up as <code>&lt;class ...&gt;</code> instead of <code>&lt;type ...&gt;</code>, regardless of whether the class is a built-in type like <code>int</code> or a class created with the <code>class</code> statement. It's one of ...
2
2016-07-29T17:09:16Z
[ "python", "python-2.7", "python-3.x" ]
Difference of type() function in Python 2 and Python 3
38,664,068
<p>When trying the following script in Python 2, </p> <pre><code>a = 200 print type(a) </code></pre> <p>its output is </p> <pre><code>&lt;type 'int'&gt; </code></pre> <p>and in Python 3, the script </p> <pre><code>a = 200 print (type(a)) </code></pre> <p>its output is, </p> <pre><code>&lt;class 'int'&gt...
3
2016-07-29T17:05:29Z
38,664,249
<p>In the days of yore, built-in types such as <code>int</code> and <code>dict</code> and <code>list</code> were very different from types built with <code>class</code>. You could not subclass built-in types for example.</p> <p>Gradually, in successive Python 2.x releases, the differences between <code>class</code> ty...
6
2016-07-29T17:18:02Z
[ "python", "python-2.7", "python-3.x" ]
Python jsonrpclib not working after upgrade to Python 3.5.2
38,664,102
<p>I previously had Python 2.7 installed and was making calls like this:</p> <pre><code>api = jsonrpclib.Server('my host') api.someFunctionCall() </code></pre> <p>I then upgraded to Python 3.5.2 and now when I run the code above, I'm receiving this message:</p> <pre><code>Traceback (most recent call last): File "C...
0
2016-07-29T17:08:02Z
38,780,308
<p>Python 3.x has relocated the xmlrpclib module. Per the <a href="https://docs.python.org/2.7/library/xmlrpclib.html" rel="nofollow">Python 2.7 xmlrpclib documentation</a>:</p> <p>"The xmlrpclib module has been renamed to xmlrpc.client in Python 3. The 2to3 tool will automatically adapt imports when converting your s...
0
2016-08-05T02:45:13Z
[ "python", "python-3.x", "xml-rpc", "json-rpc" ]
return inverse string selection in python
38,664,190
<p>I have a python snippet that returns the contents within two strings using regex.</p> <pre><code>res = re.search(r'Presets = {(.*)Version = 1,', data, re.DOTALL) </code></pre> <p>What I now want to do is return the two strings surrounding this inner part. Keep in mind this is a multiline string. How can I get the ...
0
2016-07-29T17:13:42Z
38,664,291
<p>Regex is really not a good tool for parsing these strings, but you can use <code>re.split</code> to achieve what you wanted. It can even combine the 2 tasks into one:</p> <pre><code>begin, middle, end = re.split(r'presets = \{(.*)version = 1,', data, flags=re.DOTALL) </code></pre> <p><code>re.split</code> spli...
1
2016-07-29T17:21:27Z
[ "python" ]
UnicodeDecodeError while loading file in python
38,664,228
<p>I'm running this:</p> <pre><code>news_train = load_mlcomp('20news-18828', 'train') vectorizer = TfidfVectorizer(encoding='latin1') X_train = vectorizer.fit_transform((open(f, errors='ignore').read() for f in news_train.filenames)) </code></pre> <p>but it got UnicodeDecodeError: 'utf...
0
2016-07-29T17:16:24Z
38,666,703
<p>Well I found the solution. Using </p> <pre><code>open(f, encoding = "latin1") </code></pre> <p>I'm not sure why it only happens on my mac though. Wish to know it.</p>
0
2016-07-29T20:07:23Z
[ "python", "character-encoding", "environment" ]
UnicodeDecodeError while loading file in python
38,664,228
<p>I'm running this:</p> <pre><code>news_train = load_mlcomp('20news-18828', 'train') vectorizer = TfidfVectorizer(encoding='latin1') X_train = vectorizer.fit_transform((open(f, errors='ignore').read() for f in news_train.filenames)) </code></pre> <p>but it got UnicodeDecodeError: 'utf...
0
2016-07-29T17:16:24Z
38,668,240
<p>Actually in Python 3+, the <code>open</code> function opens and reads file in default mode <code>'r'</code> which will decode the file content (on most platform, in UTF-8). Since your files are encoded in latin1, decode them using UTF-8 could cause <code>UnicodeDecodeError</code>. The solution is either opening the ...
0
2016-07-29T22:16:24Z
[ "python", "character-encoding", "environment" ]
Nosetests and Coverage not excluding lines
38,664,407
<p>Running into a small problem with some code coverage using nosetests and coverage with a Django web application. I have created a .coveragerc file to exclude a huge amount of code (things like class declarations) but I'm still getting some weird results.</p> <p>Here is my .coveragerc file:</p> <pre><code>[run] om...
1
2016-07-29T17:29:43Z
38,666,754
<p>Your <code>.coveragerc</code> file should list things to exclude starting from the root of your directory.</p> <p>For example:</p> <p><code> proj |-- app1 | -- models.py -- migrations.py |-- app2 </code></p> <p>Then your <code>coverage.rc</code> file should look like:</p> <p><code> [run] omit = app1/mig...
0
2016-07-29T20:10:37Z
[ "python", "django", "coverage.py" ]
Nosetests and Coverage not excluding lines
38,664,407
<p>Running into a small problem with some code coverage using nosetests and coverage with a Django web application. I have created a .coveragerc file to exclude a huge amount of code (things like class declarations) but I'm still getting some weird results.</p> <p>Here is my .coveragerc file:</p> <pre><code>[run] om...
1
2016-07-29T17:29:43Z
39,024,710
<p>Found the solution to my problem. It turns out I don't need to use nosetests at all. I can simply run the coverage.py with manage.py test and pass in the test modules. The code coverage worked great and I'm up to 96% coverage :-)</p>
0
2016-08-18T17:59:32Z
[ "python", "django", "coverage.py" ]
Setting Django WSGI workers with long external API response
38,664,410
<p>I'm writing an e-commerce plug-in app in Python/Django that integrates with Shopify stores. Whenever a customer for a store reaches checkout, Shopify sends a request to my app with shopping cart and destination address data, and my app is required to respond with shipping price information. The problem is that I nee...
1
2016-07-29T17:29:57Z
38,667,337
<p>There are a couple of things you can do to improve the performance of gunicorn here. Given your design, it's almost certain that your workers are IO-bound. So for a start you could configure them to use multiple threads per worker; the docs suggest 2-4.</p> <p>However, again because of the IO-bound nature of your s...
0
2016-07-29T20:55:23Z
[ "python", "django", "django-views", "wsgi", "web-worker" ]
Creating a tree/deeply nested dict with lists from an indented text file
38,664,465
<p>I want to iterate through a file and put the contents of each line into a deeply nested dict, the structure of which is defined by leading whitespace. This desire is very much like that documented <a href="http://stackoverflow.com/questions/17858404/creating-a-tree-deeply-nested-dict-from-an-indented-text-file-in-py...
1
2016-07-29T17:32:56Z
38,778,867
<p>This approach is (logically) a lot more straightforward (though longer):</p> <ol> <li>Track the <code>level</code> and <code>key</code>-<code>value</code> pair of each line in your multi-line string</li> <li>Store this data in a <code>level</code> keyed dict of lists: {<code>level1</code>:[<code>dict1</code>,<code>...
0
2016-08-04T23:23:02Z
[ "python", "json", "parsing", "data-structures", "nested" ]
heroku hosting apython flask application error
38,664,520
<p>i have recently deployed my python flask app to heroku but the following error occurs:</p> <pre><code>2016-07-29T17:32:00.145010+00:00 heroku[web.1]: State changed from crashed to starting 2016-07-29T17:32:11.162187+00:00 heroku[web.1]: Starting process with command `gunicorn myapp:app --log-file=-` 2016-07-29T17:3...
0
2016-07-29T17:35:57Z
38,665,275
<p>Well, the answer is in the traceback. Error code <code>H10</code> means the app crashed when Gunicorn tried to load it onto the dyno. There's an error at line 71 of your <code>myapp.py file</code>, the <code>data[i]={**a[i],**b,**c,**d,**e}</code> line. You may need to show the rest of your file to debug that. <...
1
2016-07-29T18:24:06Z
[ "python", "heroku", "flask", "hosting" ]
Parsing / Scraping a table using Python, Urllib from an FTP site
38,664,529
<p>I'm trying to parse / scrape some data from an FTP site. Specifically: <a href="ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA_000513335.1_PCAMFM013_20131106" rel="nofollow">ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA_000513335.1_PCAMFM013_20131106</a> </p> <p>Eventually I would like to be able to have a Python script ...
0
2016-07-29T17:36:38Z
38,664,808
<p>The HTML table is not sent by the FTP server. Only the browser will generate the HTML based on the directory listing returned by the FTP server. This means you can not use BeautifulSoup to parse it. Instead look into <a href="https://docs.python.org/3/library/ftplib.html" rel="nofollow">ftplib</a> for interacting w...
2
2016-07-29T17:54:40Z
[ "python", "parsing", "ftp", "web-scraping", "beautifulsoup" ]
Python- What colormap scheme should I use for exponential-ish data?
38,664,560
<p><strong>The issue</strong></p> <p>I have a plot I'm trying to make for trends of precipitation rates around the world using gridded data. I can make the plot itself fine, but the color range is giving me issues. I can't figure out how to make the colormap better fit my data, which seems exponential. <strong>I tried...
5
2016-07-29T17:38:24Z
39,135,115
<h1>A hack</h1> <p>You could try applying a maximum value, i.e. for any value above 2 simply replace it with 2.</p> <p>Then you would have a single color (the maximum) representing 2+ and the rest of the colors would be spread across your data more evenly.</p>
0
2016-08-25T00:56:10Z
[ "python", "matplotlib", "exponential", "colormap" ]
How to initialize OpenGL context with PyGame instead of GLUT
38,664,572
<p>I'm trying to start with OpenGL, using Python and PyGame.</p> <p>I'm going to use PyGame instead of GLUT to do all the initializing, windows opening, input handling, etc.</p> <p>However, my shaders are failing to compile, unless I specify exactly the version of OpenGL and profile. </p> <p>They <em>do</em> compile...
2
2016-07-29T17:38:59Z
38,675,169
<p>I think this: </p> <blockquote> <p><a href="https://gist.github.com/MorganBorman/4243336" rel="nofollow">https://gist.github.com/MorganBorman/4243336</a></p> </blockquote> <p>might be what your looking for. It shows how to use vertex shaders and fragment shaders in pygame and PyOpenGL. If your not using PyOpenGL...
0
2016-07-30T14:46:54Z
[ "python", "opengl", "pygame", "glut", "pyopengl" ]
Any way to access methods from individual stages in PySpark PipelineModel?
38,664,620
<p>I've created a PipelineModel for doing LDA in Spark 2.0 (via PySpark API):</p> <pre><code>def create_lda_pipeline(minTokenLength=1, minDF=1, minTF=1, numTopics=10, seed=42, pattern='[\W]+'): """ Create a pipeline for running an LDA model on a corpus. This function does not need data and will not actually do...
1
2016-07-29T17:42:06Z
38,664,792
<p>All transformers in the pipeline are stored in <code>stages</code> property. Extract <code>stages</code>, take the last one, and you're ready to go:</p> <pre><code>model.stages[-1].logPerplexity(testing) </code></pre>
3
2016-07-29T17:54:06Z
[ "python", "apache-spark", "pyspark", "apache-spark-mllib" ]
str object is not callable - calling a function with a function/string as an argument
38,664,642
<p>when I execute this code:</p> <pre><code>clffunc = sys.argv[1] def fun(clffunc): error_vector = clffunc() print error_vector loss_total = sum(error_vector) loss_mean = np.mean(error_vector) print "The mean error is %.2f" % loss_mean def svm_clf(): #The clasificator object ...
0
2016-07-29T17:43:50Z
38,664,775
<p><code>svm_clf</code> is a string, not a function object. The <em>contents</em> of that string may match the name of a function, but that doesn't make it that function.</p> <p>You could use the a dictionary to map valid names to function:</p> <pre><code>functions = {'svm_clf': svm_clf} if __name__ == "__main__": ...
1
2016-07-29T17:52:54Z
[ "python", "python-2.7" ]
str object is not callable - calling a function with a function/string as an argument
38,664,642
<p>when I execute this code:</p> <pre><code>clffunc = sys.argv[1] def fun(clffunc): error_vector = clffunc() print error_vector loss_total = sum(error_vector) loss_mean = np.mean(error_vector) print "The mean error is %.2f" % loss_mean def svm_clf(): #The clasificator object ...
0
2016-07-29T17:43:50Z
38,665,307
<p>You could directly access the <code>globals</code> and index by the function's name.</p> <pre><code>def some_func(): print 'called some_func!' def some_other_func(): print 'called some_other_func!' globals()['some_func']() globals()['some_other_func']() globals()[sys.argv[1]]() </code></pre> <p>Also, yo...
0
2016-07-29T18:25:46Z
[ "python", "python-2.7" ]
str object is not callable - calling a function with a function/string as an argument
38,664,642
<p>when I execute this code:</p> <pre><code>clffunc = sys.argv[1] def fun(clffunc): error_vector = clffunc() print error_vector loss_total = sum(error_vector) loss_mean = np.mean(error_vector) print "The mean error is %.2f" % loss_mean def svm_clf(): #The clasificator object ...
0
2016-07-29T17:43:50Z
38,665,370
<pre><code>import sys def foo(): sys.stdout.write("foo called\n") def foo1(): sys.stdout.write("foo1 called\n") if __name__ == "__main__": if len(sys.argv) &lt; 2: # prevent IndexError sys.stdout.write("Use commandline argument: foo or foo1\n") sys.exit() # Print --hel...
0
2016-07-29T18:29:37Z
[ "python", "python-2.7" ]
str object is not callable - calling a function with a function/string as an argument
38,664,642
<p>when I execute this code:</p> <pre><code>clffunc = sys.argv[1] def fun(clffunc): error_vector = clffunc() print error_vector loss_total = sum(error_vector) loss_mean = np.mean(error_vector) print "The mean error is %.2f" % loss_mean def svm_clf(): #The clasificator object ...
0
2016-07-29T17:43:50Z
38,665,525
<p>The problem is that you don't properly understand what you are trying to accomplish. </p> <pre><code>clffunc = sys.argv[1] def fun(clffunc): error_vector = clffunc() </code></pre> <p>You are trying to call a string. <code>sys.argv[1]</code> returns second argument as string. You are doing this : <code>"...
0
2016-07-29T18:39:30Z
[ "python", "python-2.7" ]
Different solution in Matematica and Python
38,664,651
<p>This is another "my-results-doesn't-match-wolfram-website question".</p> <p>I recently decided to give a try to python (I'm not sure why, to be honest, I'm spending too much time of my research in learn something which I don't know if I will use... Curiosity I suppose). I'm a really novel beginner in Python, so for...
2
2016-07-29T17:44:05Z
38,665,565
<p>Not sure if you realize, but your equation has infinitely many solutions, which, except for zero, are very close to the zeros of <code>Cos</code> or approximately <code>(n+1/2) Pi</code> for large <code>n</code>. </p> <p>The wolfram alpha page is a bit misleading in not telling you that.</p> <p>Here are the first...
0
2016-07-29T18:41:29Z
[ "python", "python-3.x", "wolfram-mathematica", "solver", "equation-solving" ]
using dict to connect items
38,664,781
<p>I have taken data from a text file, and currently have a list that contains numerous urls, some of which repeat, and unix timestamps (tab delimited). I want to create an output that has each unique url, the number of times the url occurs, and the time of the earliest occurrence. This is what the data look like:</p> ...
-1
2016-07-29T17:53:30Z
38,664,859
<p>Make your url as a key to dictionary as it will always be unique and you can maintain dictionary something like</p> <pre><code>Dict = {url1 : [mintime, count]} #to track minimum and count </code></pre> <p>or</p> <pre><code>Dict = {url1 : [time1, time2, time3]} #to track all timestamps, # I would prefer this one ...
0
2016-07-29T17:57:56Z
[ "python", "csv", "dictionary", "count" ]
using dict to connect items
38,664,781
<p>I have taken data from a text file, and currently have a list that contains numerous urls, some of which repeat, and unix timestamps (tab delimited). I want to create an output that has each unique url, the number of times the url occurs, and the time of the earliest occurrence. This is what the data look like:</p> ...
-1
2016-07-29T17:53:30Z
38,664,964
<p>This is an instance where a Counter object might also be useful: <a href="https://docs.python.org/2/library/collections.html" rel="nofollow">https://docs.python.org/2/library/collections.html</a></p> <p>Here's an implementation (please don't downvote, this works):</p> <pre><code>from collections import Counter # ...
-2
2016-07-29T18:04:14Z
[ "python", "csv", "dictionary", "count" ]
using dict to connect items
38,664,781
<p>I have taken data from a text file, and currently have a list that contains numerous urls, some of which repeat, and unix timestamps (tab delimited). I want to create an output that has each unique url, the number of times the url occurs, and the time of the earliest occurrence. This is what the data look like:</p> ...
-1
2016-07-29T17:53:30Z
38,665,428
<p>Here's a solution using <code>pandas</code>.</p> <pre><code>import pandas as pd df = pd.read_csv('input.txt', names=['url', 'timestamp'], header=None, delim_whitespace=True) output = df.groupby('url')['timestamp'].agg({'count': 'size', 'time': 'min'}) output.to_csv('output.csv') </code></pre>
-1
2016-07-29T18:32:58Z
[ "python", "csv", "dictionary", "count" ]
using dict to connect items
38,664,781
<p>I have taken data from a text file, and currently have a list that contains numerous urls, some of which repeat, and unix timestamps (tab delimited). I want to create an output that has each unique url, the number of times the url occurs, and the time of the earliest occurrence. This is what the data look like:</p> ...
-1
2016-07-29T17:53:30Z
38,665,753
<p>Here's a solution using only Python standard libraries.</p> <pre><code>import csv from collections import defaultdict d = defaultdict(list) with open('input.txt', 'r') as f: for line in f.readlines(): url, timestamp = line.split() d[url].append(int(timestamp)) with open('output.csv', 'w') as f...
0
2016-07-29T18:53:53Z
[ "python", "csv", "dictionary", "count" ]
What's the advantage of making your appengine app thread safe?
38,664,788
<p>I have an appserver that is getting painfully complicated in that it has to buffer data from incoming requests then push those buffers out, via pubsub, after enough has been received. The buffering isn't the problem, but efficient locking is... hairy, and I'm concerned that it's slowing down my service. I'm consider...
1
2016-07-29T17:54:01Z
38,665,116
<p>Multithreading is not related to billing in any way - you still pay for one instance even if 10 threads are running in parallel on that instance.</p>
0
2016-07-29T18:13:51Z
[ "python", "multithreading", "google-app-engine" ]
Smartsheet Error Objects - Attribute Error
38,664,805
<p>I'm trying to grab all of the cell history of a given sheet and spit it out to a csv. The code works on one sheet but not on another. When I get to the revision section of the code, I get a bunch of attribute errors. The following code is in the guts of a function cycling through the cells of a sheet. </p> <p>Erro...
0
2016-07-29T17:54:35Z
38,776,623
<p>This is likely because the cell has no history. You'll need to do a safety check to verify that the attribute exists before accessing it.</p> <pre><code>if not hasattr(action, 'data'): print('no history found') </code></pre> <p>You may be polling the API too rapidly, which is why sometimes values aren't return...
0
2016-08-04T20:12:07Z
[ "python", "smartsheet-api" ]
is while loop infinite
38,664,876
<p>I'm trying to build a list of inputs from several files. I need the list to consist only of the first file with a given basename. So if I a &amp; b were folders, and there were "C:\a\file1.ext", "C:\b\file1" and "C:\c\file1" and I had a list of names file1, file2 and so on, I would want the script to find file1 in C...
-1
2016-07-29T17:58:42Z
38,664,992
<p>Your while loop will be infinite because it only achieves the exit condition if <code>os.path.basename(file) == name+".dbf"</code> returns <code>True</code>. If it isn't true, then count will never be updated, and the loop will perform the same conditional check over and over again. </p> <p><code>os.path.basename(f...
1
2016-07-29T18:05:49Z
[ "python", "while-loop" ]
is while loop infinite
38,664,876
<p>I'm trying to build a list of inputs from several files. I need the list to consist only of the first file with a given basename. So if I a &amp; b were folders, and there were "C:\a\file1.ext", "C:\b\file1" and "C:\c\file1" and I had a list of names file1, file2 and so on, I would want the script to find file1 in C...
-1
2016-07-29T17:58:42Z
38,665,222
<p>I know it has been mentioned in comments, but I figured I would demonstrate it. Your loop keeps going until x is no longer less than 1. This only happens when a file is found with ".dbf" in it, because that leads to x += 1. If a file with ".dbf" is not found, the loop will keep running.</p> <p>For example...</p> ...
0
2016-07-29T18:20:27Z
[ "python", "while-loop" ]
TensorFlow placement algorithm
38,664,942
<p>I would like to know when the placement algorithm of TensorFlow (as described in the white paper) gets actually employed. All examples for distributing TensorFlow that I have seen so far seem to specify manually where the nodes should be executed on, using "tf.device()".</p>
1
2016-07-29T18:02:34Z
38,666,008
<p>The dynamic placement algorithm described in Section 3.2.1 of the <a href="http://download.tensorflow.org/paper/whitepaper2015.pdf" rel="nofollow">TensorFlow whitepaper</a> was not included in the open-source release. Instead, the "simple placer" (whose implementation can be found in <a href="https://github.com/tens...
3
2016-07-29T19:12:04Z
[ "python", "algorithm", "tensorflow", "distributed", "placement" ]
Python/Django database username and password?
38,664,958
<p>I'm learning python and I want to understand the database section and when setting up for postgresql database.</p> <p><a href="https://docs.djangoproject.com/en/1.9/ref/settings/#databases" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#databases</a></p> <p>Are all the values necessary? </p> <...
0
2016-07-29T18:03:43Z
38,665,182
<blockquote> <p><strong>Yes!</strong> <strong><em>all of those information are necessary</em></strong> , there is no way you could connect to the database unless those values are specified.</p> </blockquote> <p><strong>Yes!</strong> <em><code>user</code></em> and <em><code>password</code></em> are the actual crede...
2
2016-07-29T18:17:40Z
[ "python", "django", "postgresql" ]
Python/Django database username and password?
38,664,958
<p>I'm learning python and I want to understand the database section and when setting up for postgresql database.</p> <p><a href="https://docs.djangoproject.com/en/1.9/ref/settings/#databases" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#databases</a></p> <p>Are all the values necessary? </p> <...
0
2016-07-29T18:03:43Z
38,665,944
<blockquote> <p>Specifically USER, PASSWORD, HOST, PORT? Is USER and PASSWORD values that we can create in django settings.py? Or is this the actual USER/PASSWORD of the database? Also, HOST is currently 127.0.0.1 for localhost, but when deploying to production, do I change this to the domain name (<a href="h...
1
2016-07-29T19:07:43Z
[ "python", "django", "postgresql" ]
Python 3(.5.2) Tkinter
38,665,059
<p>I need help. I was developing an interface with tkinter. at one point, when I insert a button in the window, it does not work as it should ... in fact, does not work. I give me this error when i press the button:</p> <pre><code> File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__in...
0
2016-07-29T18:09:58Z
38,665,155
<p>You have a definition problem there: your callback defintion is never reached,as Tkinter's <code>mainloop</code> is called before. What happens when the Button is pressed, it tries to call the button object itself, not the <code>encode</code> function defined bellow.</p> <p>To get it working as is, simply move your...
1
2016-07-29T18:16:06Z
[ "python", "python-3.x", "button", "tkinter", "messagebox" ]
Calling python script from a Bash script
38,665,093
<p>I'm trying to call a python script from a bash script. I get import errors only if I try to run the .py from the bash script. If I run with python myscript.py everything is fine. This is my bash script: </p> <pre><code>while true; do python script.py echo "Restarting..."; sleep 3; done </code></pre> <p>The ...
1
2016-07-29T18:11:55Z
38,665,366
<p>Your problem is in the script itself, your bash code is OK!. If you don't have problem running <code>python scrip.py</code> from bash directly, you should test if you use the same interpreter for both calls. You can check the shebang line in the python script, it is the first line in the file for example <code>#!/us...
1
2016-07-29T18:29:31Z
[ "python", "bash", "import" ]
Calling python script from a Bash script
38,665,093
<p>I'm trying to call a python script from a bash script. I get import errors only if I try to run the .py from the bash script. If I run with python myscript.py everything is fine. This is my bash script: </p> <pre><code>while true; do python script.py echo "Restarting..."; sleep 3; done </code></pre> <p>The ...
1
2016-07-29T18:11:55Z
38,665,779
<p>There is more to this story that isn't in your question. Your PYTHONPATH variable is getting confused somewhere along the way.<br> Insert a couple quick test lines:</p> <p>in bash:</p> <pre><code>echo $PYTHONPATH </code></pre> <p>in your python:</p> <pre><code>import os print os.environ["PYTHONPATH"] </code></pr...
3
2016-07-29T18:55:53Z
[ "python", "bash", "import" ]
Python py2exe Not Including `os` Module
38,665,237
<p>I have a python program which imports <code>os</code> so that I can retrieve the application's path (i.e. <code>os.path.dirname(os.path.realpath(__file__))</code>). I have been using py2exe to make this python file into an exe, and I have had no issues until I started to use <code>os</code>. Here is the command wind...
0
2016-07-29T18:21:16Z
38,666,635
<p>Use cx-Freeze for create a .exe on windows instead of py2exe.</p>
0
2016-07-29T20:01:58Z
[ "python", "py2exe" ]
Python subprocess called from Matlab fails
38,665,247
<p>I've hit a problem in trying to join some code from different sources in Matlab and I don't really know how to approach it. Essentially, I have some Python code for a compression algorithm called from the command line, which itself uses subprocess to run and communicate with C++ code compiled to a binary.</p> <p>Th...
1
2016-07-29T18:21:58Z
38,671,699
<pre><code>repeats = self.__extractRepeats(repeatClass) for r in repeats: #Extracting maximum repeat repeatStats = r.split() idx = map(int,repeatStats[2][1:-1].split(','))[0] </code></pre> <p>Assuming your repeatStats[2] is xersiox,10</p> <p>Then repeatStats[2][1:-1] becomes ersiox,1</p> <p>Then repeatStats[...
0
2016-07-30T07:56:28Z
[ "python", "matlab", "ubuntu", "subprocess" ]
django : LookupError: App ' doesn't have a 'models' model
38,665,252
<p><a href="http://i.stack.imgur.com/PejnM.png" rel="nofollow"><img src="http://i.stack.imgur.com/PejnM.png" alt="enter image description here"></a></p> <p>I'm working through <a href="https://bixly.com/blog/awesome-forms-django-crispy-forms/" rel="nofollow">https://bixly.com/blog/awesome-forms-django-crispy-forms/</a...
0
2016-07-29T18:22:26Z
38,665,300
<p>The <code>AUTH_USER_MODEL</code> settings should be of the form <code>&lt;app name&gt;.&lt;model&gt;</code>. Your model name is <code>User</code>, not <code>model</code>, so your setting should be:</p> <pre><code>AUTH_USER_MODEL = 'app1.User' </code></pre> <p>You should also remove the following <code>User</code> ...
5
2016-07-29T18:25:29Z
[ "python", "django" ]
Python win32api get "stack" of windows
38,665,380
<p>I'm looking for a way to find out what order windows are open on my desktop in order to tell what parts of what windows are visible to the user. </p> <p>Say, in order, I open up a maximized chrome window, a maximized notepad++ window, and then a command prompt that only covers a small portion of the screen. Is ther...
0
2016-07-29T18:30:09Z
38,867,461
<p>This does not yet have any logic deciding if windows are overlaid but it does return a dictionary of existing windows with info of their title, visibility, minimization, size and the next window handle.</p> <pre><code>import win32gui import win32con def enum_handler(hwnd, results): results[hwnd] = { "...
0
2016-08-10T08:00:10Z
[ "python", "pywin32" ]
typeerror exception not working
38,665,383
<p>I'm trying to complete an exercise asking me to use the TypeError exception in Python to account for strings when integers are required. The example is simple, I ask the user for two numbers and then add them. I want to use a try block to handle when the user accidentally puts in a string instead of an int. What I...
0
2016-07-29T18:30:17Z
38,665,488
<p>It's great you already have a <code>try/except</code> block, but the problem is the <em>construct</em> is not being correctly used. If a letter is entered instead of a number, that will be a <code>ValueError</code> not a <code>TypeError</code>. That's why you have a <code>ValueError</code> being raised by your code ...
0
2016-07-29T18:36:28Z
[ "python", "exception", "typeerror" ]
How to read in an edge list to make a scipy sparse matrix
38,665,388
<p>I have a large file where each line has a pair of 8 character strings. Something like:</p> <pre><code>ab1234gh iu9240gh </code></pre> <p>on each line.</p> <p>This file really represents a graph and each string is a node id. I would like to read in the file and directly make a scipy sparse adjacency matrix. I wi...
2
2016-07-29T18:30:31Z
38,667,644
<p>I think this is a regular task in <code>sklearn</code>, so there must be some tool in the package that does this, or an answer in other SO questions. We need to add the correct tag.</p> <p>But just working from my knowledge of <code>numpy</code> and <code>sparse</code>, where what I'd do:</p> <p>Make a sample 2d ...
2
2016-07-29T21:18:35Z
[ "python", "numpy", "scipy", "scikit-learn", "igraph" ]
How can I associate a dict key to an attribute of an object within a list?
38,665,404
<pre><code>class SpreadsheetRow(object): def __init__(self,Account1): self.Account1=Account1 self.Account2=0 </code></pre> <p>I have a while loop that fills a list of objects ,and another loop that fills a dictionary associating Var1:Account2. But, I need to get that dictionary's value into each object, if the...
1
2016-07-29T18:31:28Z
38,665,489
<p>You can use a generator expression within <code>any()</code> to check if any <code>account1</code> attribute of those objects is equal with <code>k</code>:</p> <pre><code>if any(k == item.account1 for item in listOfSpreadsheetRows): </code></pre>
0
2016-07-29T18:36:30Z
[ "python", "object", "dictionary" ]
How can I associate a dict key to an attribute of an object within a list?
38,665,404
<pre><code>class SpreadsheetRow(object): def __init__(self,Account1): self.Account1=Account1 self.Account2=0 </code></pre> <p>I have a while loop that fills a list of objects ,and another loop that fills a dictionary associating Var1:Account2. But, I need to get that dictionary's value into each object, if the...
1
2016-07-29T18:31:28Z
38,665,634
<p>You can try to use the <a href="https://docs.python.org/3/library/functions.html#next" rel="nofollow"><code>next</code></a> function like this:</p> <pre><code>next(i for i in listOfSpreadsheetRows if k == i.account1) </code></pre>
0
2016-07-29T18:45:45Z
[ "python", "object", "dictionary" ]
How can I associate a dict key to an attribute of an object within a list?
38,665,404
<pre><code>class SpreadsheetRow(object): def __init__(self,Account1): self.Account1=Account1 self.Account2=0 </code></pre> <p>I have a while loop that fills a list of objects ,and another loop that fills a dictionary associating Var1:Account2. But, I need to get that dictionary's value into each object, if the...
1
2016-07-29T18:31:28Z
38,666,382
<p>If you have a dictionary <code>d</code> and want to get the value associated to the key <code>x</code> then you look up that value like this:</p> <pre><code>v = d[x] </code></pre> <p>So if your dictionary is called <code>dict_of_account1_to_account2</code> and the key is <code>self.Account1</code> and you want to ...
0
2016-07-29T19:41:24Z
[ "python", "object", "dictionary" ]
Creating a superclass SunPlanet for Sun and Planets using inheritance.
38,665,407
<p>My Class Program:</p> <pre><code>import turtle import math class SunPlanet: def __init__(self,iname,irad,im): self.name = iname self.radius = irad self.mass = im def getMass(self): return self.mass class Sun(SunPlanet): def __init__(sel...
0
2016-07-29T18:31:42Z
38,665,539
<p>Addressing only the error, <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow"><code>super()</code></a> isn't being called correctly. Change it to:</p> <pre><code>super(Sun, self).__init__(iname, irad, im) </code></pre> <p>And later:</p> <pre><code>super(Planet, self).__init__(iname, ...
0
2016-07-29T18:40:08Z
[ "python", "inheritance" ]
Comparing a string to a list of characters
38,665,427
<p>Say I have a list of characters <code>['h','e','l','l','o']</code> and I wanted to see if the list of characters match a string <code>'hello'</code>, how would I do this? The list needs to match the characters exactly. I thought about using something like:</p> <pre><code>hList = ['h','e','l','l','o'] hStr = "Hello"...
1
2016-07-29T18:32:47Z
38,665,451
<p>You want <code>''.join(hList) == hStr</code>.</p> <p>That turns the list into a string, so it can be easily compared to the other string.</p> <p>In your case you don't seem to care about case, so you can use a case insensitive compare. See <a href="http://stackoverflow.com/questions/319426/how-do-i-do-a-case-insen...
5
2016-07-29T18:34:07Z
[ "python", "string", "list", "python-3.x" ]
Comparing a string to a list of characters
38,665,427
<p>Say I have a list of characters <code>['h','e','l','l','o']</code> and I wanted to see if the list of characters match a string <code>'hello'</code>, how would I do this? The list needs to match the characters exactly. I thought about using something like:</p> <pre><code>hList = ['h','e','l','l','o'] hStr = "Hello"...
1
2016-07-29T18:32:47Z
38,665,485
<p>Or, another way is the reverse of what the other answer suggests, create a list out of <code>hStr</code> and compare that:</p> <pre><code>list(hStr) == hList </code></pre> <p>Which simply compares the lists: </p> <pre><code>list('Hello') == hList False list('hello') == hList True </code></pre>
1
2016-07-29T18:36:23Z
[ "python", "string", "list", "python-3.x" ]
Comparing a string to a list of characters
38,665,427
<p>Say I have a list of characters <code>['h','e','l','l','o']</code> and I wanted to see if the list of characters match a string <code>'hello'</code>, how would I do this? The list needs to match the characters exactly. I thought about using something like:</p> <pre><code>hList = ['h','e','l','l','o'] hStr = "Hello"...
1
2016-07-29T18:32:47Z
38,665,512
<p>Alternative solution is to split the string into array:</p> <pre><code>list(hStr) == hList &gt;&gt;&gt; list("hello") ['h', 'e', 'l', 'l', 'o'] </code></pre>
0
2016-07-29T18:37:57Z
[ "python", "string", "list", "python-3.x" ]
Custom logger with time stamp in python
38,665,440
<p>I have lots of code on a project with print statements and wanted to make a quick a dirty logger of these print statements and decided to go the custom route. I managed to put together a logger that prints both to the terminal and to a file (with the help of this site), but now I want to add a simple time stamp to ...
0
2016-07-29T18:33:31Z
38,665,535
<p>It calls the <code>.write()</code> method of your stream twice because in cpython <code>print</code> calls the stream <code>.write()</code> method twice. The first time is with the object, and the second time it writes a newline character. For example look at <a href="https://hg.python.org/cpython/file/v3.5.2/Lib/pp...
1
2016-07-29T18:39:59Z
[ "python", "python-2.7" ]
Custom logger with time stamp in python
38,665,440
<p>I have lots of code on a project with print statements and wanted to make a quick a dirty logger of these print statements and decided to go the custom route. I managed to put together a logger that prints both to the terminal and to a file (with the help of this site), but now I want to add a simple time stamp to ...
0
2016-07-29T18:33:31Z
38,665,792
<p>You probably need to use newline character.</p> <pre><code>class Logger(object): def __init__(self, stream): self.terminal = stream self.log = open("test.log", 'a') def write(self, message): self.terminal.flush() self.terminal.write(self.stamp() + message + "\n") sel...
0
2016-07-29T18:57:05Z
[ "python", "python-2.7" ]
Number path: using recursion in a maze-like situation
38,665,518
<p>I'm struggling with an assignment for my CS class. Here are some of the instructions: </p> <hr> <p>In this assignment, you will write a program that finds a path through a grid of numbers using a technique called depth-first search.</p> <p>As input, you will be given a grid of numbers, a start point, an end point...
-2
2016-07-29T18:38:33Z
38,665,696
<p>What algorithms have you used? I recommend that you research basic graph traversal algorithms. <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="nofollow">Dijkstra's algorithm</a> is a good starting point, and is readily available in <a href="http://code.activestate.com/recipes/119466-dijkstras-a...
0
2016-07-29T18:50:06Z
[ "python", "recursion", "path", "grid", "maze" ]
Matching words and vectors in gensim Word2Vec model
38,665,556
<p>I have had the <a href="https://radimrehurek.com/gensim/" rel="nofollow">gensim</a> <a href="https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec" rel="nofollow">Word2Vec</a> implementation compute some word embeddings for me. Everything went quite fantastically as far as I can tell; ...
2
2016-07-29T18:40:54Z
38,669,212
<p>If all you want to do is map a <em>word</em> to a <em>vector</em>, you can simply use the <code>[]</code> operator, e.g. <code>model["hello"]</code> will give you the vector corresponding to hello.</p> <p>If you need to recover a word from a vector you could loop through your list of vectors and check for a match, ...
1
2016-07-30T00:25:56Z
[ "python", "vector", "machine-learning", "gensim", "word2vec" ]
Matching words and vectors in gensim Word2Vec model
38,665,556
<p>I have had the <a href="https://radimrehurek.com/gensim/" rel="nofollow">gensim</a> <a href="https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec" rel="nofollow">Word2Vec</a> implementation compute some word embeddings for me. Everything went quite fantastically as far as I can tell; ...
2
2016-07-29T18:40:54Z
38,695,747
<p>As @bpachev mentioned, gensim does have an option of searching by vector, namely <code>similar_by_vector</code>.</p> <p>It however implements a brute force linear search, i.e. computes cosine similarity between given vector and vectors of all words in vocabulary, and gives off the top neighbours. An alternate optio...
0
2016-08-01T09:47:50Z
[ "python", "vector", "machine-learning", "gensim", "word2vec" ]
pip install pubnub throws 'gcc' failed error
38,665,704
<p>I am trying to install pubnub libraries and I get the error when I do pip install pubnub </p> <pre><code>Compiling support for Intel AES instructions building 'Crypto.Hash._MD2' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wa...
0
2016-07-29T18:50:25Z
38,665,726
<p>You need to install Python's header files. How you do that will depend on your operating system.</p> <p>On Debian or Ubuntu, for example, something like</p> <pre><code>sudo apt-get install python-dev </code></pre> <p>should do it.</p> <p>On Fedora / CentOS / Red Hat, try</p> <pre><code>sudo yum install python-d...
2
2016-07-29T18:51:48Z
[ "python", "python-2.7", "python-3.x", "pip", "pubnub" ]
pip install pubnub throws 'gcc' failed error
38,665,704
<p>I am trying to install pubnub libraries and I get the error when I do pip install pubnub </p> <pre><code>Compiling support for Intel AES instructions building 'Crypto.Hash._MD2' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wa...
0
2016-07-29T18:50:25Z
38,668,288
<p>The solution for this, I had to follow these steps</p> <pre><code>ld -lpython2.7 --verbose attempt to open /usr/x86_64-amazon-linux/lib64/libpython2.7.so failed attempt to open /usr/x86_64-amazon-linux/lib64/libpython2.7.a failed attempt to open /usr/local/lib64/libpython2.7.so failed attempt to open /usr/local/li...
1
2016-07-29T22:22:04Z
[ "python", "python-2.7", "python-3.x", "pip", "pubnub" ]
Python tkinter password strength checker gui
38,665,732
<p>I'm trying to create a password strength checker gui that checks a password for length(over 8 characters) lowercase and uppercase letters, numbers and special characters and then tells you what level it is, weak, strong etc.... It then creates an md5 hash and displays this, then you can store this hash in a text fil...
1
2016-07-29T18:52:19Z
38,665,916
<p>You have the results of the checkPassword function,where the passwords are either less than 4 or 1 characters, being returned as return statements. You have no variable assigned to the result of checkPassword, so in those two cases can not receive data from function. I'd Suggest something more like:</p> <pre><code>...
1
2016-07-29T19:05:03Z
[ "python", "user-interface", "tkinter" ]
automatically send an email when a file gets generated
38,665,759
<p>I am trying to write a python script that automatically sends an email when a specific file is generated. I think i have the code for sending the email, but im not sure how to monitor a directory looking for a specific file. </p> <p>a high level example is:</p> <p>from within directory foo/ when file baz is popula...
1
2016-07-29T18:54:17Z
38,665,786
<pre><code>import os.path if os.path.exists(file_path) and os.path.isfile(fname): send_email() </code></pre>
0
2016-07-29T18:56:25Z
[ "python", "bash", "scripting" ]
Neural Network classifier in python
38,665,776
<p>Here I developed a neural network classifier to solve the titanic problem.</p> <pre><code>from sknn.mlp import Classifier, Layer nn = Classifier( layers=[ Layer("Maxout", units=100, pieces=2), Layer("Softmax")], learning_rate=0.001, n_iter=25) nn.fit(X_train, y_train) </code></pre> <...
-2
2016-07-29T18:55:36Z
38,665,810
<p>The signature of <a href="http://scikit-neuralnetwork.readthedocs.io/en/latest/module_mlp.html#layer-specifications" rel="nofollow"><code>Layer</code></a> does not define any argument called <code>pieces</code>. To create two layers with same parameters, you'll have to define the <code>Layer</code> object twice:</p>...
0
2016-07-29T18:58:33Z
[ "python", "csv", "numpy" ]
Extracting information from json input in python on the basis of other field's value
38,665,823
<pre><code>{ "Steps": [ { "Status": { "State": "PENDING", "StateChangeReason": {} }, "ActionOnFailure": "CANCEL_AND_WAIT", "Name": "ABCD" }, { "Status": { "State": "COMPLETED", ...
-3
2016-07-29T18:59:35Z
38,665,976
<p>You can type this:</p> <pre><code>[step['Status']['State'] for step in data['Steps'] if step['Name']=='KLMN'] </code></pre> <p>Where <em>data</em> is your data structure. You will get :</p> <pre><code>['COMPLETED'] </code></pre> <p>Which is list with one element.</p>
1
2016-07-29T19:10:21Z
[ "python", "json" ]
Extracting information from json input in python on the basis of other field's value
38,665,823
<pre><code>{ "Steps": [ { "Status": { "State": "PENDING", "StateChangeReason": {} }, "ActionOnFailure": "CANCEL_AND_WAIT", "Name": "ABCD" }, { "Status": { "State": "COMPLETED", ...
-3
2016-07-29T18:59:35Z
38,666,048
<pre><code>steps = { "Steps": [ { "Status": { "State": "PENDING", "StateChangeReason": {} }, "ActionOnFailure": "CANCEL_AND_WAIT", "Name": "ABCD" }, { "Status": { "State": "COMPLETED",...
1
2016-07-29T19:15:32Z
[ "python", "json" ]
Kivy tutorial - pong.py no listeners error - .kv doesn't close properly
38,665,903
<p>I am new to GUIs in Python and wanted to try Kivy. But already in the Pong tutorial I get stuck: I run the original scripts and get the following errors:</p> <pre><code>[WARNING ] [Lang ] The file C:\Users\Canopy\Skripts\Pong\pong.kv is loaded multiples times, you might have unwanted behaviors. [IN...
0
2016-07-29T19:04:14Z
38,666,200
<p>Ok, the basic IT solution actually worked: After restating the PC the error didn't occur anymore. <strong>EDIT</strong>: After running the application again, I ran into the same problem. Still solution needed!</p>
0
2016-07-29T19:28:06Z
[ "python", "user-interface", "kivy" ]
Convert PIL Image into pygame surface image
38,665,920
<p>I'm trying to load .png images into a program using PIL.Image, so that I can manipulate them, ready for use as pygame surfaces in sprites. The following code shows how I've tried to convert those Pil Images into pygame images :</p> <pre><code>bytes = someImagefile.tobytes() new_image = pygame.image.fromstring(bytes...
0
2016-07-29T19:05:08Z
38,667,537
<p>The following code works for me. Python2.7+PIL 2.5+Pygame1.9.2</p> <pre><code>import Image import pygame image = Image.open("SomeImage.png") mode = image.mode size = image.size data = image.tobytes() py_image = pygame.image.fromstring(data, size, mode) </code></pre>
0
2016-07-29T21:10:15Z
[ "python", "image", "pygame", "python-imaging-library" ]
Using python 2.7 - regex to find all CR character at end of lines
38,665,931
<p>I have a folder with about 50,000 text files in it, and I need to see if any of them have lines that end in the CR character only (not CR/LF, or LF) - hex 0x0D.</p> <p>The following code doesn't return any results, and takes a LONG time to process.</p> <pre><code>import re import os rootDir = 'Z:\Archive\\2016070...
0
2016-07-29T19:06:45Z
38,666,716
<p>This line is wrong:</p> <pre><code>for filename in rootDir: # rootDir is 'Z:\Archive\\20160701' </code></pre> <p>Should be:</p> <pre><code>for filename in files: </code></pre> <p>If all the files are in one folder, as you said, it is easier to use <code>os.listdir</code> You don't need all the power of <code>...
1
2016-07-29T20:08:09Z
[ "python", "regex" ]
python __new__ - must return an instance of cls
38,665,942
<p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">According to the docs,</a></p> <blockquote> <p>Typical implementations create a new instance of the class by invoking the superclass’s <code>__new__()</code> method using <code>super(currentclass, cls).__new__(cls[, ....
-3
2016-07-29T19:07:39Z
38,666,185
<p>Few things, first of all you need to write explicit inheritance from <code>object</code> like this:</p> <pre><code>class MyClass(object): </code></pre> <p>You should read about <a href="http://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python">old classes an...
0
2016-07-29T19:26:53Z
[ "python", "super", "python-internals" ]
python __new__ - must return an instance of cls
38,665,942
<p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">According to the docs,</a></p> <blockquote> <p>Typical implementations create a new instance of the class by invoking the superclass’s <code>__new__()</code> method using <code>super(currentclass, cls).__new__(cls[, ....
-3
2016-07-29T19:07:39Z
38,666,378
<p><code>super(MyClass, cls).__new__(cls)</code> first searches the MRO (method resolution order) of the <code>cls</code> object (skipping past <code>MyClass</code> in that sequence), until it finds an object with a <code>__new__</code> attribute.</p> <p>In your case, that is <code>object.__new__</code>:</p> <pre><co...
1
2016-07-29T19:41:12Z
[ "python", "super", "python-internals" ]
Matplotlib Basemap example code fails due to MemoryError
38,665,977
<p>I'm trying to use the Basemap toolkit from matplotlib to plot data on a map. When I try to run the following code</p> <pre><code>from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. # set resolution=None to skip processing of boundary datasets. m = Basemap(widt...
1
2016-07-29T19:10:26Z
38,667,615
<p>Solved the issue by upgrading to 64-bit python. It seems that even though Basemap publishes a version for 32-bit python not all the map functions work in 32-bit, even the standard examples.</p>
0
2016-07-29T21:16:33Z
[ "python", "matplotlib", "matplotlib-basemap" ]
Deleting files using wildcards with python glob module
38,665,986
<p>Was looking for a method to delete files using a wildcard. Came across <a href="http://stackoverflow.com/questions/5532498/delete-files-with-python-through-os-shell?answertab=oldest#tab-top">this question</a> which helped me out. I thought the accepted answer was easier to understand and that's the method I would pr...
0
2016-07-29T19:10:58Z
38,666,266
<blockquote> <p>There should be one-- and preferably only one --obvious way to do it.</p> </blockquote> <p>The one obvious way to find all path names that match a pattern is the glob module, since that is <a href="https://docs.python.org/3/library/glob.html" rel="nofollow">what it is documented to do</a>.</p> <p>Th...
0
2016-07-29T19:32:59Z
[ "python", "glob" ]