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
Boto3: create, execute shell command, terminate on ec2 instance
38,754,839
<p>I am newbie to <strong>EC2</strong> and <strong>boto</strong>. I have to create an EC2 running instance, where I can send a command with S3 file and execute a shell script. </p> <p>I searched a lot and found a way with <strong>boto</strong> and <strong>paramiko</strong>. I don't know, whether it is possible to run ...
0
2016-08-03T22:44:51Z
38,755,787
<p>The boto.manage.cmdshell module can be used to do this. To use it, you must have the paramiko package installed. A simple example of it's use:</p> <pre><code>import boto.ec2 from boto.manage.cmdshell import sshclient_from_instance # Connect to your region of choice conn = boto.ec2.connect_to_region('us-west-2') ...
0
2016-08-04T00:42:41Z
[ "python", "shell", "amazon-ec2", "boto3" ]
getting module import error while running PyInstaller generated binary
38,754,847
<p>I'm getting an error while trying to a simple hello.py using PyInstaller on RHEL X64.</p> <p>Python 2.7.12 is alt installed in /opt/python</p> <p>Compilation Output:</p> <pre><code>[root@myrig CommandManager]# pyinstaller Hello.py 21 INFO: PyInstaller: 3.2 21 INFO: Python: 2.7.12 22 INFO: Platform: Linux-3.10.0-3...
0
2016-08-03T22:45:42Z
38,781,390
<p>PyInstaller needs python to be compiled with <code>--enable-shared and LDFLAGS=-Wl,-rpath=&lt;path to python lib&gt;</code>.</p> <p>In my case:</p> <blockquote> <p>./configure --enable-shared --prefix=/opt/python LDFLAGS=-Wl,-rpath=/opt/python/lib</p> </blockquote> <p>Additional reference: <a href="https://bu...
0
2016-08-05T04:56:12Z
[ "python", "python-2.7", "pyinstaller" ]
Why am I getting "ValueError: setting an array element with a sequence." when using the brute function from Scipy.optimization?
38,754,937
<p>Working on a model to predict electrophysiological data given a set of parameters. This script is trying to find values for those parameters that give predictions closest to experimental data. I'm running Python 2.7, Scipy 0.17.0, and Numpy 1.10.4. The script is attached below. The line that is getting the error is ...
0
2016-08-03T22:56:36Z
38,764,129
<p>The <code>scipy.optimize</code> routines call the function with a vector of parameters to be optimized. Your function is thus called as <code>min_params(x, *params)</code>, where the <code>*params</code> are your custom arguments to the function that you supplied to the function using the keyword argument <code>args...
0
2016-08-04T09:55:42Z
[ "python", "numpy", "scipy", "scientific-computing" ]
get text after specific tag with beautiful soup
38,754,940
<p>I have a text like</p> <pre><code>page.content = &lt;body&gt;&lt;b&gt;Title:&lt;/b&gt; Test title&lt;/body&gt; </code></pre> <p>I can get the Title tag with </p> <pre><code>soup = BeautifulSoup(page.content) record_el = soup('body')[0] b_el = record_el.find('b',text='Title:') </code></pre> <p>but how can I get t...
1
2016-08-03T22:56:39Z
38,754,999
<p>Referring to <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#going-sideways" rel="nofollow">the docs</a> you might want to use the <code>next_sibling</code> of your <code>b_el</code>:</p> <pre><code>b_el.next_sibling # contains " Test title" </code></pre> <p>"Sibling" in this context is the next...
1
2016-08-03T23:02:28Z
[ "python", "html", "beautifulsoup" ]
How does one extract the alpha channel from an image using Pillow
38,754,957
<p>How does one export just an alpha mask from a PNG using Pillow?</p> <p>Ideally, the result would be a grayscale image that represents the alpha channel.</p>
0
2016-08-03T22:58:09Z
38,754,958
<pre><code># Open the image and convert it to RGBA, just in case it was indexed image = Image.open(image_path).convert('RGBA') # Extract just the alpha channel alpha = image.split()[-1] # Unfortunately the alpha channel is still treated as such and can't be dumped # as-is # Create a new image with an opaque black ba...
0
2016-08-03T22:58:09Z
[ "python", "pillow" ]
Why set is not in locals, globals or vars dictionaries
38,754,974
<p>When I try to check if a set is available in current local scope, or in global scope, I always get the below error.</p> <pre><code>&gt;&gt;my_set = set() &gt;&gt;my_set in locals() &gt;&gt;Traceback (most recent call last): File "&lt;ipython-input-22-47b6756e3345&gt;", line 1, in &lt;module&gt; my_set in lo...
0
2016-08-03T22:59:11Z
38,755,002
<p>You need to quote the name when checking.</p> <pre><code>&gt;&gt;&gt; my_set = set() &gt;&gt;&gt; locals &lt;built-in function locals&gt; &gt;&gt;&gt; locals() {'__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__name__': '__main__', 'my_set': set([]), '__doc__': None, '__package__': None} &gt;&gt;&gt; 'my_...
6
2016-08-03T23:02:43Z
[ "python" ]
How to randomly select a character everytime it's needed
38,754,990
<p>How do I randomly select a character from a string of characters every time I want it to be changed, for example:</p> <pre><code>import random def user_input(): chars = 'abcdefghijklmnopqrstuvwxyz' present = random.choice(chars) while True: print present to_eval = raw_input('Enter key: ...
0
2016-08-03T23:01:05Z
38,755,008
<pre><code>import random def user_input(): chars = 'abcdefghijklmnopqrstuvwxyz' present = random.choice(chars) while True: print present to_eval = raw_input('Enter key: ') if to_eval == present: print 'Correct!' present = random.choice(chars) user_input() </...
1
2016-08-03T23:03:33Z
[ "python", "random" ]
How to randomly select a character everytime it's needed
38,754,990
<p>How do I randomly select a character from a string of characters every time I want it to be changed, for example:</p> <pre><code>import random def user_input(): chars = 'abcdefghijklmnopqrstuvwxyz' present = random.choice(chars) while True: print present to_eval = raw_input('Enter key: ...
0
2016-08-03T23:01:05Z
38,755,011
<p>It think this is what you want:</p> <pre><code>import random def user_input(): while True: chars = 'abcdefghijklmnopqrstuvwxyz' present = random.choice(chars) print present to_eval = raw_input('Enter key: ') if to_eval == present: print 'Correct!' ...
0
2016-08-03T23:03:49Z
[ "python", "random" ]
How to randomly select a character everytime it's needed
38,754,990
<p>How do I randomly select a character from a string of characters every time I want it to be changed, for example:</p> <pre><code>import random def user_input(): chars = 'abcdefghijklmnopqrstuvwxyz' present = random.choice(chars) while True: print present to_eval = raw_input('Enter key: ...
0
2016-08-03T23:01:05Z
38,755,081
<p>you could play with <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">yield</a> to try simplify your code too:</p> <pre><code>import random def guesses(): chars = 'abcd..' while True: yield random.choice(chars) == raw_input('Enter Key: ').strip() def play...
0
2016-08-03T23:12:15Z
[ "python", "random" ]
Reading bluetooth low energy data from a custom app to a ble dongle(csr8510)
38,755,087
<p>I am having a problem connecting and sending Bluetooth low energy data from a custom built app I created in android studio to a BLE dongle. The app I created has 4 virtual push buttons and every time I press one these buttons its send a 4bit number letting the Bluetooth dongle( peripheral) know. The problem is that ...
0
2016-08-03T23:12:42Z
38,758,013
<p>I am also looking forward for something similar application where Android application sends some button command to Linux Application via Bluetooth and nearest similar example I get from github.</p> <p>Here is <a href="https://gist.github.com/dvas0004/8209b67ff556cb18651d#file-aquapi-py" rel="nofollow">Python applic...
0
2016-08-04T03:28:20Z
[ "python", "linux", "android-studio", "bluetooth", "bluetooth-lowenergy" ]
Dividing a large file into several smaller, stochastic writing to multiple files
38,755,111
<p>It's a bit embarrassing but I having a bit of a difficulty with a rather simple (at least it should be) task: </p> <p>I want to have a script that takes a large text file (several GBs) and divides into smaller pieces. This partitioning however is supposed to happen not on the order of lines but based on matching st...
0
2016-08-03T23:15:57Z
38,755,334
<p>Idea: define a class named, say, Pattern. In here are several member variables: one is the <code>"&lt;some pattern&gt;"</code> that you have already; another is the filename; a third is the mode to use for the next call to open() on that file. The mode would be "w" the first time (creating a new file) and then you...
0
2016-08-03T23:42:15Z
[ "python", "io" ]
How to add a number to an index range of a pandas array
38,755,143
<p>In pandas, how can I operate on a subset of rows in a column, selected by index?</p> <p>In particular, how can I add 1.0 to column y here, only where the date is greater than 2016-08-04?</p> <pre><code>&gt;&gt;&gt; pandas.DataFrame( ... index=[datetime.date.today(), datetime.date.today() + datetime.timedelta(1)], ...
2
2016-08-03T23:19:55Z
38,755,233
<p>If you convert the index to a DateTimeIndex it becomes easier:</p> <pre><code>df.index = pd.to_datetime(df.index) df.loc[df.index &gt; '2016-08-04', 'y'] += 1 df Out: x y 2016-08-04 1.2 234 2016-08-05 3.3 433 </code></pre>
3
2016-08-03T23:31:45Z
[ "python", "pandas" ]
How to add a number to an index range of a pandas array
38,755,143
<p>In pandas, how can I operate on a subset of rows in a column, selected by index?</p> <p>In particular, how can I add 1.0 to column y here, only where the date is greater than 2016-08-04?</p> <pre><code>&gt;&gt;&gt; pandas.DataFrame( ... index=[datetime.date.today(), datetime.date.today() + datetime.timedelta(1)], ...
2
2016-08-03T23:19:55Z
38,755,262
<p>You can use the <code>.where</code> method on the <code>y</code> column.</p> <pre><code>df.y = df.y.where(df.index &lt; datetime.date(2016, 8, 4), lambda k: k + 1) </code></pre>
0
2016-08-03T23:35:27Z
[ "python", "pandas" ]
How to add a number to an index range of a pandas array
38,755,143
<p>In pandas, how can I operate on a subset of rows in a column, selected by index?</p> <p>In particular, how can I add 1.0 to column y here, only where the date is greater than 2016-08-04?</p> <pre><code>&gt;&gt;&gt; pandas.DataFrame( ... index=[datetime.date.today(), datetime.date.today() + datetime.timedelta(1)], ...
2
2016-08-03T23:19:55Z
38,755,269
<p>As a non-inplace alternative, you can use <code>df.add</code>:</p> <pre><code>df.add(df.index &gt; pd.to_datetime('2016-08-04'), axis=0, level="y") </code></pre>
1
2016-08-03T23:36:12Z
[ "python", "pandas" ]
How to add a number to an index range of a pandas array
38,755,143
<p>In pandas, how can I operate on a subset of rows in a column, selected by index?</p> <p>In particular, how can I add 1.0 to column y here, only where the date is greater than 2016-08-04?</p> <pre><code>&gt;&gt;&gt; pandas.DataFrame( ... index=[datetime.date.today(), datetime.date.today() + datetime.timedelta(1)], ...
2
2016-08-03T23:19:55Z
38,755,614
<p>Checkout <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow">the docs</a> for <code>DatetimeIndex</code> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow">the docs</a> for the convenience function <code>date_r...
1
2016-08-04T00:15:31Z
[ "python", "pandas" ]
Develop Raspberry apps from windows
38,755,220
<p>Is it possible to open files from a Raspberry pi in windows for editing (using for example notepad++)?</p> <p>I am currently using the built in python IDE in Raspbian but i feel that it would speed up the development process if i could use a windows IDE for development. I have also tried using a git repo to share f...
0
2016-08-03T23:29:25Z
38,755,272
<p>Why not just set up a VM on your windows machine with rasbian running? Something like this will get you started: <a href="http://www.makeuseof.com/tag/emulate-raspberry-pi-pc/" rel="nofollow">http://www.makeuseof.com/tag/emulate-raspberry-pi-pc/</a></p> <p>Otherwise - set up a network share between the two, edit fi...
1
2016-08-03T23:36:33Z
[ "python", "windows", "git", "raspberry-pi" ]
Develop Raspberry apps from windows
38,755,220
<p>Is it possible to open files from a Raspberry pi in windows for editing (using for example notepad++)?</p> <p>I am currently using the built in python IDE in Raspbian but i feel that it would speed up the development process if i could use a windows IDE for development. I have also tried using a git repo to share f...
0
2016-08-03T23:29:25Z
38,759,185
<p>Sure. I go through many ways and I found one of the best way is using <a href="https://winscp.net/eng/download.php" rel="nofollow">WinSCP</a>. </p> <p>It's very easy for you to edit and update file with notepad++ right in the Windows.</p>
1
2016-08-04T05:35:37Z
[ "python", "windows", "git", "raspberry-pi" ]
Develop Raspberry apps from windows
38,755,220
<p>Is it possible to open files from a Raspberry pi in windows for editing (using for example notepad++)?</p> <p>I am currently using the built in python IDE in Raspbian but i feel that it would speed up the development process if i could use a windows IDE for development. I have also tried using a git repo to share f...
0
2016-08-03T23:29:25Z
38,760,276
<p>You can run a SAMBA server on your Raspberry Pi, set your python project folder as a network disk. Then you can use any windows IDE you like, just open the file which is on the network disk.</p> <p>Currently I am using VS2015 + Python Tools for Visual Studio for remote debugging purpose.</p>
1
2016-08-04T06:47:47Z
[ "python", "windows", "git", "raspberry-pi" ]
Access similar lines from a file and apply a function
38,755,263
<p>I am trying to access similar lines from a file and then apply a sum on their values.</p> <p>Here is my input file format:</p> <pre><code>K1 20 K2 23 K3 24 K3 14 K3 10 K2 5 </code></pre> <p>So, my goal is to create an output file that creates a sum of values per record:</p> <pre><code>K1 20 K2 28 K3 48 </code></...
0
2016-08-03T23:35:41Z
38,755,383
<p>The following should accomplish the desired functionality.</p> <pre><code>from collections import Counter output = Counter() with open("input.txt") as file: for line in file.read().split('\n'): if line: key, value = line.split() output[key] += int(value) with open("output.txt...
1
2016-08-03T23:48:59Z
[ "python" ]
Access similar lines from a file and apply a function
38,755,263
<p>I am trying to access similar lines from a file and then apply a sum on their values.</p> <p>Here is my input file format:</p> <pre><code>K1 20 K2 23 K3 24 K3 14 K3 10 K2 5 </code></pre> <p>So, my goal is to create an output file that creates a sum of values per record:</p> <pre><code>K1 20 K2 28 K3 48 </code></...
0
2016-08-03T23:35:41Z
38,755,433
<blockquote> <p>It is a big text file >20GB. So I cannot store the whole thing into memory at once.</p> </blockquote> <ol> <li>It does not matter how big the file is. What matters is how many unique records are there because you will be keeping only unique records.</li> <li>Python <code>Counter</code> would still be...
0
2016-08-03T23:54:10Z
[ "python" ]
Encoding csv files on opening with Python
38,755,277
<p>So i have this csv which has rows like these:</p> <pre><code>"41975","IT","Catania","2016-01-12T10:57:50+01:00",409.58 "538352","DE","Düsseldorf","2015-12-18T20:50:21+01:00",95.03 "V22211","GB","Nottingham","2015-12-31T11:17:59+00:00",872 </code></pre> <p>In the current example the first and the third word are wo...
1
2016-08-03T23:37:06Z
38,755,510
<p>The issue here is that when python writes to a stream, it attempts to write text in a fashion that is compatible with the encoding or character set of that stream.</p> <p>In this case, it appears you are running the command in a Windows console that is set to display Cyrillic text (CP866). The Cyrillic codepage do...
0
2016-08-04T00:02:48Z
[ "python", "python-3.x", "csv", "encoding", "utf-8" ]
Restricted set operations on python dictionary key views
38,755,358
<p>Lets see the code snippet below:</p> <pre><code>d = {1:1} keys = d.keys() print(keys &amp; {1,2,3})# {1} d[2] = 2 print(keys &amp; {1,2,3}) # {1,2} # keys() is a view/reference print({1,2}.issubset({1,2,3})) # True print(keys.issubset({1,2,3})) # 'dict_keys' object has no attribute 'issubset' </code></pre> <p>It ...
5
2016-08-03T23:45:14Z
38,755,413
<blockquote> <p>Why, for example, are not side-effect free operation like <code>issuperset</code> or <code>issubset</code> operation not permitted?</p> </blockquote> <p>They are; you just have to use the <code>&gt;=</code> and <code>&lt;=</code> operators:</p> <pre><code>print(keys &lt;= {1, 2, 3}) </code></pre> <...
6
2016-08-03T23:52:26Z
[ "python", "set" ]
Stripping punctuation from text file including 's and commas
38,755,412
<p>I am creating a list of most frequent words in a text file. But I keep getting words and their possessive versions. Like iphone and iphone's. I also need to strip the commas after words like iphone and iphone, in my results. I want to count those words together as one entity. Here is my entire code.</p> <pre><code...
1
2016-08-03T23:52:15Z
38,755,502
<p>You need to say <code>for i in words:</code> not <code>for i in d:</code> You are iterating through an empty dictionary during the replacement steps, so nothing is changing. Just remove that loop and move the replacement steps to the top of the <code>for w in words:</code> loop, so you only have to make one pass th...
0
2016-08-04T00:01:44Z
[ "python", "replace", "strip" ]
Python IndexError when Scanning Files
38,755,425
<p>I'm trying to scan/search files and it throws:</p> <blockquote> <p>IndexError: list index out of range on the line "list = self.scanFolder(path[t])"</p> </blockquote> <p>This is an Object and has some methods/functions that aren't shown here since they are not relevant to this code. </p> <pre><code>def scanFold...
0
2016-08-03T23:53:22Z
38,755,525
<p>You are trying to access an invalid position.</p> <pre><code>for t in range(len(paths)): print(paths) print(t) list = self.scanFolder(paths[t]) </code></pre> <p>The valid list indexes are 0..len(path)-1</p> <p>You should access the list elements in a more pythonic form:</p> <pre><code>for path in pat...
1
2016-08-04T00:04:15Z
[ "python", "list", "indexoutofboundsexception", "iterable" ]
Error with multiple numpy.delete uses on array?
38,755,506
<p>So, I was trying to understand the <code>numpy.delete</code> function, and I came up with something weird. Here's the program: </p> <pre><code>&gt;&gt;&gt;import numpy as np &gt;&gt;&gt;a = np.arange(10) &gt;&gt;&gt; a array([0, 1, 2, 3, 4, 6, 7, 9]) &gt;&gt;&gt; a[5] 5 &gt;&gt;&gt; a=np.delete(a,[a[5]...
0
2016-08-04T00:02:03Z
38,755,544
<p>The second argument should be the <strong>index</strong> of the element you want to delete, not the element itself.</p> <pre><code>a=np.delete(a,6) </code></pre> <p>In the first case, it only worked because a[5] happened to equal 5, so the index and the value were the same.</p> <p>When you have:</p> <pre><code>a...
1
2016-08-04T00:07:12Z
[ "python", "arrays", "python-2.7", "numpy" ]
Extract terms of an expression
38,755,517
<p>Is there a sympy function that extracts all terms of an equation of <code>Add</code> , <code>Mul</code> and <code>Div</code> expressions, as a list or set?</p> <p>For example:</p> <pre><code>(x**2 +(x-1)*ln(x)+(x+2)/(x-1)) </code></pre> <p>I want to get :</p> <pre><code>[x**2,(x+1)*ln(x),(x+2)/(x-1)] </code></pr...
2
2016-08-04T00:03:40Z
38,775,467
<p>For a sum or product, you can use <code>expr.args</code>:</p> <pre><code>In [1]: ((x**2 +(x-1)*ln(x)+(x+2)/(x-1))).args Out[1]: ⎛ 2 x + 2 ⎞ ⎜x , ─────, (x - 1)⋅log(x)⎟ ⎝ x - 1 ⎠ In [2]: ((x-1)*ln(x)).args Out[2]: (x - 1, log(x)) </code></pre> <p>For a divi...
1
2016-08-04T19:06:18Z
[ "python", "sympy" ]
Read a distributed Tab delimited CSV
38,755,522
<p>Inspired from this <a href="http://stackoverflow.com/questions/31898964/how-to-write-the-resulting-rdd-to-a-csv-file-in-spark-python">question</a>, I wrote some code to store an RDD (which was read from a Parquet file), with a Schema of (photo_id, data), in pairs, delimited by tabs, and just as a detail base 64 enco...
3
2016-08-04T00:03:57Z
38,775,296
<p>Let's try a simple example. For convenience I'll be using handy <a href="https://github.com/pytoolz/toolz" rel="nofollow"><code>toolz</code></a> library but it is not really required here.</p> <pre><code>import sys import base64 if sys.version_info &lt; (3, ): import cPickle as pickle else: import pickle ...
2
2016-08-04T18:56:16Z
[ "python", "hadoop", "apache-spark", "io", "distributed-computing" ]
Subprocess doesn't show data from tcpdump in realtime. It shows with a pause about 10-20 seconds
38,755,545
<p>So i wanna get all data from <code>tcpdump</code> and add some logic in the future. I haven't such problem yet with subprocess' pipes. I wrote code and ran <code>tcpdump</code> and <code>run.py</code> in parallel.</p> <p>run.py:</p> <pre><code>from subprocess import Popen, PIPE # process = Popen(['/usr/bin/sudo'...
1
2016-08-04T00:07:18Z
38,755,655
<p>Try: sudo stdbuf -oL tcpdump -i wlan0 </p> <p>It works for me </p> <pre><code>from subprocess import Popen, PIPE # process = Popen(['/usr/bin/sudo', '/usr/sbin/tcpdump', '-i', 'wlan0'], bufsize=1, stdout=PIPE, stderr=PIPE) process = Popen('sudo stdbuf -oL tcpdump -i wlan0', bufsize=1, universal_newlines=True, sh...
2
2016-08-04T00:22:22Z
[ "python", "pipe", "subprocess", "real-time" ]
Subprocess doesn't show data from tcpdump in realtime. It shows with a pause about 10-20 seconds
38,755,545
<p>So i wanna get all data from <code>tcpdump</code> and add some logic in the future. I haven't such problem yet with subprocess' pipes. I wrote code and ran <code>tcpdump</code> and <code>run.py</code> in parallel.</p> <p>run.py:</p> <pre><code>from subprocess import Popen, PIPE # process = Popen(['/usr/bin/sudo'...
1
2016-08-04T00:07:18Z
38,755,782
<p>It's stdio buffering in tcpdump process.<br> By default stdio sets the buffering mode to _IOFBF(full) on redirected streams.<br> Luckily tcpdump has <code>-l</code> option which switches the mode to line-buffered:</p> <pre><code>process = Popen('sudo tcpdump -l -i wlan0', bufsize=1, universal_newlines=True, ...
2
2016-08-04T00:41:42Z
[ "python", "pipe", "subprocess", "real-time" ]
Define an arbitrary Field on a django-rest-framework Serializer that doesn't exist on the Django Model
38,755,622
<p>I'd want to define an arbitrary <code>Field</code> on a <strong>django-rest-framework</strong> <code>Serializer</code> that doesn't exist on the Django <code>Model</code>.</p> <p>My code looks like so:</p> <pre><code>class Person(models.Model): pass class PersonSerializer(serializers.ModelSerializer): fo...
2
2016-08-04T00:16:42Z
38,755,647
<p>You could do it like this, using a <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow"><code>SerializerMethodField</code></a>:</p> <pre><code>class PersonSerializer(serializers.ModelSerializer): foo = serializers.SerializerMethodField() ... def get_fo...
1
2016-08-04T00:20:54Z
[ "python", "django", "rest", "django-rest-framework" ]
how can i use scrapy to extract two level text?
38,755,681
<p>My code is not working properly.</p> <p>The second for loop is not getting all text.</p> <p>How can I do that in scrapy?</p> <p>Thanks for any tips and let me know if I'm missing anything.</p> <pre><code>&lt;dl&gt; &lt;dt&gt;Release Date:&lt;/dt&gt; &lt;dd&gt;Aug. 01, 2016&lt;br&gt; &lt;/dd&gt; &lt;dt&gt;Runtim...
0
2016-08-04T00:26:19Z
38,757,218
<p>Replace your second loop with this:</p> <pre><code>actresses = sel.xpath("//*[@itemprop='actors']//*[@itemprop='name']/text()").extract() item['Actress'] = [x.strip() for x in actresses] yield item </code></pre> <p>It will give an item which has a list of actresses.</p> <p>BYW, please stop posting the same ques...
0
2016-08-04T01:46:40Z
[ "python", "scrapy" ]
Pythonic way to chain python generator function to form a pipeline
38,755,702
<p>I'm doing a pipeline code refactoring using python.</p> <p>Assuming we have a series of <strong>generator</strong> functions and we want to chain those to form a data processing pipeline. <br></p> <p>Example:</p> <pre><code>#!/usr/bin/python import itertools def foo1(g): for i in ...
3
2016-08-04T00:29:37Z
38,755,760
<p>I sometimes like to use a left fold (called <code>reduce</code> in Python) for this type of situation:</p> <pre><code>from functools import reduce def pipeline(*steps): return reduce(lambda x, y : y(x), list(steps)) res = pipeline(range(0,5), foo1, foo2, foo3) </code></pre> <p>Or even better:</p> <pre><code>...
6
2016-08-04T00:39:27Z
[ "python", "generator" ]
Pythonic way to chain python generator function to form a pipeline
38,755,702
<p>I'm doing a pipeline code refactoring using python.</p> <p>Assuming we have a series of <strong>generator</strong> functions and we want to chain those to form a data processing pipeline. <br></p> <p>Example:</p> <pre><code>#!/usr/bin/python import itertools def foo1(g): for i in ...
3
2016-08-04T00:29:37Z
38,755,838
<p>Following up on your runner.run approach, let's define this utility function:</p> <pre><code>def recur(ops): return ops[0](recur(ops[1:])) if len(ops)&gt;1 else ops[0] </code></pre> <p>As an example:</p> <pre><code>&gt;&gt;&gt; ops = foo3, foo2, foo1, range(0, 5) &gt;&gt;&gt; list( recur(ops) ) ['foo3:11', 'f...
1
2016-08-04T00:49:22Z
[ "python", "generator" ]
Pandas Pivot Table Keeps Returning False Instead of 0
38,755,711
<p>I am making a pivot table using pandas. If I set <code>aggfunc=sum</code> or <code>aggfunc=count</code> on a column of boolean values, it works fine provided there's at least one <code>True</code> in the column. E.g. <code>[True, False, True, True, False]</code> would return 3. However, if all the values are <code>F...
2
2016-08-04T00:30:09Z
38,755,781
<pre><code>df = pd.DataFrame({'count': [False] * 12, 'index': [0, 1] * 6, 'cols': ['a', 'b', 'c'] * 4}) print(df) </code></pre> <p>outputs</p> <pre><code> cols count index 0 a False 0 1 b False 1 2 c False 0 3 a False 1 4 b False 0 5 c False 1 6 a F...
3
2016-08-04T00:41:25Z
[ "python", "pandas", "boolean", "aggregate-functions", "pivot-table" ]
feed_dict in TensorFlow throwing unexpected error (summary operations)
38,755,719
<p>My training script, for training a TensorFlow model, very slightly modified from the tutorials online:</p> <pre><code>def train(data_set_dir, train_set_dir): data = data_input.read_data_sets(data_set_dir, train_set_dir) with tf.Graph().as_default(): global_step = tf.Variable(0, trainable=False) ...
0
2016-08-04T00:31:44Z
38,762,088
<p>Obvious error. I didn't specify a <code>feed_dict</code> for the session run on <code>summary_op</code>.</p> <pre><code>if step % 100 == 0: summary_str = sess.run(summary_op, feed_dict=feed_dict) summary_writer.add_summary(summary_str, step) </code></pre> <p>Explicitly mentioning the <code>feed_dict</code>...
0
2016-08-04T08:21:09Z
[ "python", "tensorflow" ]
Python logs between multiple modules only work in functions called by original file?
38,755,732
<p>I'm trying to add logging between a couple different modules. Why, when I place a log somewhere that isn't referenced in my original file, why does all logging break? I'm importing <code>logging</code> in both files. I import the <code>other_file</code> in <code>file1</code>.</p> <p>Here is an example of what I'm r...
1
2016-08-04T00:33:45Z
38,755,901
<h3>What's the problem?</h3> <p>The function <code>get_something</code> is called before logging be configured. Then, it don't will appear on your <code>logfile</code>. This occur when you import the module <code>other_file</code>. Python automatically execute the function <code>get_something</code> and assign the res...
1
2016-08-04T00:57:30Z
[ "python", "logging", "module" ]
Python logs between multiple modules only work in functions called by original file?
38,755,732
<p>I'm trying to add logging between a couple different modules. Why, when I place a log somewhere that isn't referenced in my original file, why does all logging break? I'm importing <code>logging</code> in both files. I import the <code>other_file</code> in <code>file1</code>.</p> <p>Here is an example of what I'm r...
1
2016-08-04T00:33:45Z
38,757,080
<p>Your problem is related to how module import works in python.</p> <p>Well, when importing the module other_file, Python automatically evaluates the line <code>bar = set_something()</code> by executing the function and store the result in <code>bar</code> and all of this is done before the logging starts. About putt...
1
2016-08-04T01:26:50Z
[ "python", "logging", "module" ]
Run a flask python app on apache server
38,755,885
<p>I am running an Amazon EC2 micro instance and I want to run a python app from it using Flask.</p> <p>Here is my <code>app.py</code> file where I'm doing a simple file upload (it works fine on <code>localhost:5000</code>):</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route('/') def hello_world...
0
2016-08-04T00:55:14Z
38,758,498
<p>Okay, so looking at the error logs helped me figure out my answer. </p> <p>Since my error was:</p> <pre><code>(13)Permission denied: mod_wsgi (pid=30315): Unable to connect to WSGI daemon process 'lumos' on '/etc/httpd/logs/wsgi.30311.0.1.sock' after multiple attempts. </code></pre> <p>I added this <code>WSGISock...
0
2016-08-04T04:28:48Z
[ "python", "apache", "amazon-web-services", "amazon-ec2", "flask" ]
Run a flask python app on apache server
38,755,885
<p>I am running an Amazon EC2 micro instance and I want to run a python app from it using Flask.</p> <p>Here is my <code>app.py</code> file where I'm doing a simple file upload (it works fine on <code>localhost:5000</code>):</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route('/') def hello_world...
0
2016-08-04T00:55:14Z
38,760,224
<blockquote> <p>Please make sure in advance that any app.run() calls you might have in your application file are inside an if <strong>name</strong> == '<strong>main</strong>': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if...
1
2016-08-04T06:44:10Z
[ "python", "apache", "amazon-web-services", "amazon-ec2", "flask" ]
Send a message multiple times all at once in Python
38,755,902
<p>In python 3.5 is it possible to send multiple messages with <code>sock.send(msg) * 10</code>. In this case will it send 10 times or just one time and have some sort of error in the background?</p>
0
2016-08-04T00:57:34Z
38,757,032
<p>If you want to call <code>sock.send(msg)</code> ten times, you can use a <code>for</code> loop as such:</p> <pre><code>for x in range(0,9): sock.send(msg) </code></pre> <p><em>Reference: <a href="https://wiki.python.org/moin/ForLoop" rel="nofollow">https://wiki.python.org/moin/ForLoop</a></em></p>
0
2016-08-04T01:18:35Z
[ "python", "sockets" ]
Send a message multiple times all at once in Python
38,755,902
<p>In python 3.5 is it possible to send multiple messages with <code>sock.send(msg) * 10</code>. In this case will it send 10 times or just one time and have some sort of error in the background?</p>
0
2016-08-04T00:57:34Z
38,757,223
<p>if list-creation side-effect is not a problem, then you can do it as a list comprehension as well:</p> <pre><code>[sock.send(msg) for _ in range(10)] </code></pre> <p><code>_</code> is a sort of "throwaway" variable, you can use any other identifier name there.</p>
0
2016-08-04T01:47:33Z
[ "python", "sockets" ]
Python increment loop to add filter parameters to dataframe
38,756,950
<p>I created a dictionary with a set of functions. Then, I created a while loop that attempts to use those functions. But part of the loop doesn't call the functions the way I want it to. Here's the code:</p> <pre><code>while bool(str(w).endswith(' 2')) != True: a = re.search('[0-9]{1,2}$', str(w)) w = w &amp;...
-1
2016-08-04T01:06:09Z
38,756,998
<p><code>34 &amp; 33</code> <em>is</em> <code>32</code>. <code>&amp;</code> is the bitwise and operator.</p> <p>Saying you want <code>"34 &amp; 33"</code> suggests that you want a <em>string</em> as a result, but that seems to conflict w/ the use of <code>str(w)</code> throughout your code. Or maybe you are just unc...
3
2016-08-04T01:13:10Z
[ "python", "loops", "dataframe", "while-loop" ]
Python increment loop to add filter parameters to dataframe
38,756,950
<p>I created a dictionary with a set of functions. Then, I created a while loop that attempts to use those functions. But part of the loop doesn't call the functions the way I want it to. Here's the code:</p> <pre><code>while bool(str(w).endswith(' 2')) != True: a = re.search('[0-9]{1,2}$', str(w)) w = w &amp;...
-1
2016-08-04T01:06:09Z
38,793,923
<p>Okay, I figured it out. I needed q = f[w] and then q = q &amp; f[w-n], where f[w] defines parameters to filter a dataframe (df) based on a column, and f[w-n] defines a different parameter for filtering based on the next adjacent column. So, the progression should be f[w], f[w] &amp; f[w-n], f[w] &amp; f[w-n] &amp; f...
0
2016-08-05T16:29:20Z
[ "python", "loops", "dataframe", "while-loop" ]
TwythonError: Twitter API returned a 404 for string 'usernames'
38,756,952
<p>I am refering to this <a href="http://social-metrics.org/twitter-user-data/" rel="nofollow">article</a>.The article used <code>twython</code> to download user profile information with reference to <code>UserID</code> (int) and I am trying to use <code>username</code>(str). </p> <p>The exact same code works when <co...
0
2016-08-04T01:06:33Z
38,773,813
<p>This works for me. Is this what you want?</p> <p>Please note, screen_name can be a list. e.g.: ["aaaa","bbb","ccc","ddd"]</p> <pre><code># Create a Twython instance with your application key and access token twitter = Twython(APP_KEY, APP_SECRET, oauth_version=1) output = twitter.lookup_user(screen_name="BarackOb...
1
2016-08-04T17:27:08Z
[ "python", "twitter", "twython" ]
What's the equivalent 'nth_element' function in Python?
38,757,089
<p>I want to implement Vantage Point Tree in the python, but it use the std::nth_element in the C++.</p> <p>So I want to find the equivalent 'nth_element' function in Python or in numpy.</p> <p>Notice, the nth_element would only partial order an array, and it's O(N).</p> <pre><code>int the_array[10] = {4,5,7,3,6,0,1...
1
2016-08-04T01:29:03Z
38,757,666
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html</a></p> <p>Just make sure that the numpy partition will create two new arrays, meaning that you will quickly make a lot of new arrays. They are m...
1
2016-08-04T02:40:13Z
[ "python", "c++", "nth-element" ]
How can I put two arguments in one string for a input function in python?
38,757,134
<p>I am pretty new to python and am trying to create a small game just to help develop my skills, but I ran in to one code line I just can't figure out.</p> <pre><code>r = str(input("Player 1 please enter a integer between 1 and 10: ")) </code></pre> <p>I have another line that goes earlier and asks the player for a ...
0
2016-08-04T01:35:03Z
38,757,160
<p>You can use string formatting for this.</p> <pre><code>r = str(input("%s please enter a integer between 1 and 10: " % name)) </code></pre>
1
2016-08-04T01:38:25Z
[ "python", "string" ]
How can I put two arguments in one string for a input function in python?
38,757,134
<p>I am pretty new to python and am trying to create a small game just to help develop my skills, but I ran in to one code line I just can't figure out.</p> <pre><code>r = str(input("Player 1 please enter a integer between 1 and 10: ")) </code></pre> <p>I have another line that goes earlier and asks the player for a ...
0
2016-08-04T01:35:03Z
38,757,161
<p>You can use the <a href="https://docs.python.org/3/tutorial/inputoutput.html#old-string-formatting" rel="nofollow">formated string</a>:</p> <pre><code>r = str(input("%s please enter a integer between 1 and 10: " % player_name)) </code></pre> <p><code>input</code> expects a string. So, first you construct a appropr...
1
2016-08-04T01:38:44Z
[ "python", "string" ]
How can I put two arguments in one string for a input function in python?
38,757,134
<p>I am pretty new to python and am trying to create a small game just to help develop my skills, but I ran in to one code line I just can't figure out.</p> <pre><code>r = str(input("Player 1 please enter a integer between 1 and 10: ")) </code></pre> <p>I have another line that goes earlier and asks the player for a ...
0
2016-08-04T01:35:03Z
38,757,234
<p>I strongly suggest that you use (according to <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow">PEP-3101</a>) :</p> <pre><code>r = str(input('{} please enter a integer between 1 and 10: '.format(name))) </code></pre> <p>Instead of using the modulo operator (%) like :</p> <pre><code>r = str(input...
1
2016-08-04T01:49:24Z
[ "python", "string" ]
How can I put two arguments in one string for a input function in python?
38,757,134
<p>I am pretty new to python and am trying to create a small game just to help develop my skills, but I ran in to one code line I just can't figure out.</p> <pre><code>r = str(input("Player 1 please enter a integer between 1 and 10: ")) </code></pre> <p>I have another line that goes earlier and asks the player for a ...
0
2016-08-04T01:35:03Z
38,757,404
<p>You can also do this since you are working with integers:</p> <p>However, this solution will only work in Python 2</p> <pre><code>player_name = raw_input("What is your name") r = int(input("%s Enter a number:" % player_name)) </code></pre>
1
2016-08-04T02:09:20Z
[ "python", "string" ]
Python: sqlite3: List index out of range
38,757,175
<p>Hi i am looking for some help with an "List index out of range" error i am getting while trying to insert data into my sqlite3 database.</p> <p>This is my first attempt at using a class helper to parse data to and from my database, so please don't laugh at my unwieldy coding. :))</p> <p>here is my main.py for test...
0
2016-08-04T01:40:39Z
38,757,450
<p>There is way too much string manipulation going on there. This <code>insertInto</code> is probably closer to what you want:</p> <pre><code>def insertInto(self, db_name, table_name, column_data, data): self.db_name = db_name self.table_name = table_name self.column_data = column_data self.data = data...
1
2016-08-04T02:15:08Z
[ "python", "sqlite3", "kivy" ]
Best practice for config variables in Python
38,757,351
<p>So recently my programs have become more complex, and are starting to require more configuration. I've been doing the following, however it feels wrong...</p> <pre><code>class config: delay = 1.3 files = "path/to/stuff" name = "test" dostuff(config.name) #etc... </code></pre> <p>I've never been a fan ...
1
2016-08-04T02:02:34Z
38,757,685
<p>I recommend use of <a href="https://github.com/henriquebastos/python-decouple" rel="nofollow">python-decouple</a>. This library allow separate code from configurations(data).</p> <p>UPDATE:</p> <h3>Brief explanation of usage of this library:</h3> <p>Simply create a <strong>.env</strong> text file on your reposito...
2
2016-08-04T02:42:25Z
[ "python" ]
How do I set a boundary in which my image can go through in Pygame?How do I keep an image from going behind another?
38,757,357
<p>This is the code for my pygame</p> <pre><code>import pygame import os img_path=os.path.join('C:/Desktop/Python Stuff','Angry Birds.jpg') class pic(object): def __init__(self): """ The constructor of the class """ self.image = pygame.image.load(img_path) # the bird's position self.x = 0 self...
0
2016-08-04T02:03:33Z
38,785,647
<h2>Border collision</h2> <p>An easy way to implement border collision is to just check if the current position is outside the screen, and if it is you move it back. It's easiest done by creating a Rect object from the <em>screen</em> which you could pass in an <strong>update</strong> method of your class <em>pic</em>...
0
2016-08-05T09:18:08Z
[ "python", "pygame" ]
How do I set a boundary in which my image can go through in Pygame?How do I keep an image from going behind another?
38,757,357
<p>This is the code for my pygame</p> <pre><code>import pygame import os img_path=os.path.join('C:/Desktop/Python Stuff','Angry Birds.jpg') class pic(object): def __init__(self): """ The constructor of the class """ self.image = pygame.image.load(img_path) # the bird's position self.x = 0 self...
0
2016-08-04T02:03:33Z
38,792,765
<h1>A) Keep rect on screen</h1> <p>The simplest way would be using <a href="http://www.pygame.org/docs/ref/rect.html#pygame.Rect.clamp_ip" rel="nofollow" title="Rect.clamp_ip&#40;rect&#41;"><code>Rect.clamp_ip(rect)</code></a> on a <a href="http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite" rel="nofollow...
0
2016-08-05T15:23:08Z
[ "python", "pygame" ]
String to time python in hours and minutes and calculate difference
38,757,367
<p>I am taking time as input from the user in the <code>HH:MM</code> format. Let's say 00:00 and now I want to keep adding a minute to the time and make it 00:01, 00:02 and so on.</p> <p>Also, I am taking two inputs form the user <code>start_time</code> and <code>end_time</code> as strings. How can I calculate the dif...
0
2016-08-04T02:04:56Z
38,757,716
<pre><code>import datetime time_diff = datetime.datetime.strptime(end_time, '%H:%M') - datetime.datetime.strptime(start_time, '%H:%M') minutes = int(time_diff.total_seconds()/60) print minutes </code></pre> <p><code>datetime</code> is a class of the <code>datetime</code> module that has a classmethod called <code>str...
0
2016-08-04T02:46:35Z
[ "python", "datetime", "time" ]
String to time python in hours and minutes and calculate difference
38,757,367
<p>I am taking time as input from the user in the <code>HH:MM</code> format. Let's say 00:00 and now I want to keep adding a minute to the time and make it 00:01, 00:02 and so on.</p> <p>Also, I am taking two inputs form the user <code>start_time</code> and <code>end_time</code> as strings. How can I calculate the dif...
0
2016-08-04T02:04:56Z
38,757,760
<p>First part of your question, you can use the <a href="https://docs.python.org/3.5/library/datetime.html" rel="nofollow">datetime module</a>:</p> <pre><code>from datetime import datetime as dt from datetime import timedelta as td UsrInput = '00:00' fmtString = '%H:%M' myTime = dt.strptime(UsrInput, fmtString) increm...
0
2016-08-04T02:52:09Z
[ "python", "datetime", "time" ]
Why boost python calls the copy constructor?
38,757,369
<p>Assume a wrapper class is provided</p> <pre><code>class Example { public: Example() { std::cout &lt;&lt; "hello\n"; } Example(const Example&amp; e) { std::cout &lt;&lt; "copy\n"; counter++; } ~Example() { std::cout &lt;&lt; "bye\n"; } Example&a...
1
2016-08-04T02:05:07Z
38,759,433
<p>The copy constructor is called because <code>return_value_policy&lt;copy_non_const_reference&gt;()</code> is being set and by <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/copy_non_const_reference.html" rel="nofollow">boost docs</a>:</p> <blockquote> <p>copy_non_const_reference is a model of Re...
2
2016-08-04T05:54:04Z
[ "python", "boost", "boost-python" ]
Error when installing 'pycryptodome'
38,757,403
<p>Whenever I install the package, I get this string out:-</p> <p>Command "/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;<strong>file</strong>='/private/var/folders/l8/nrwgdgr96v33vfcd95r2yl3m0000gp/T/pip-build-AJpKPV/pycryptodomex/setup...
0
2016-08-04T02:09:19Z
38,782,031
<p>Have you tried to upgrade <code>pip</code> first?</p> <pre><code>pip install --upgrade pip </code></pre> <p>And then install the <code>pycryptodome</code> package.</p>
0
2016-08-05T05:53:52Z
[ "python", "osx", "pip" ]
How do you submit a PHP form that doesn't return results immediately using Python?
38,757,415
<p>There is a PHP form which queries a massive database. The URL for the form is <a href="https://db.slickbox.net/venues.php" rel="nofollow">https://db.slickbox.net/venues.php</a>. It takes up to 10 minutes after the form is sent for results to be returned, and the results are returned inline on the same page. I've tri...
0
2016-08-04T02:10:28Z
38,757,548
<p>I usually rely on Curl to do these kind of thing. Instead of sending the form with the button to retrieve the source, call directly the response page (giving it your request). As i work under PHP, it's quite easy to do this. With python, you will need pycURL to manage the same thing.</p> <p>So the only thing to do ...
0
2016-08-04T02:26:07Z
[ "php", "python", "forms", "post" ]
How do you submit a PHP form that doesn't return results immediately using Python?
38,757,415
<p>There is a PHP form which queries a massive database. The URL for the form is <a href="https://db.slickbox.net/venues.php" rel="nofollow">https://db.slickbox.net/venues.php</a>. It takes up to 10 minutes after the form is sent for results to be returned, and the results are returned inline on the same page. I've tri...
0
2016-08-04T02:10:28Z
38,757,620
<p>How about <a href="https://github.com/jeanphix/Ghost.py" rel="nofollow">ghost</a>?</p> <pre><code>from ghost import Ghost ghost = Ghost() with ghost.start() as session: page, extra_resources = session.open("https://db.slickbox.net/venues.php", wait_onload_event=True) ghost.set_field_value("input[name=vname...
0
2016-08-04T02:35:38Z
[ "php", "python", "forms", "post" ]
'None' is being displayed in the output of quotient and remainder
38,757,462
<p>Writing a program to print quotient and remainder, but everywhere change the quotientProblem function into one called quotientString that merely returns the string rather than printing the string directly. Have the main function print the result of each call to the quotientString function.</p> <pre><code>def value(...
-2
2016-08-04T02:16:18Z
38,757,501
<p>You assigned the result of the <code>print</code> call to <code>z</code>. <code>print</code> has no specific return, which means it returns <code>None</code>. Your <code>division</code> function then prints that. Don't use the return value from <code>print</code>. I have no idea what you're expecting it to do, but i...
0
2016-08-04T02:20:50Z
[ "python", "python-3.x" ]
'None' is being displayed in the output of quotient and remainder
38,757,462
<p>Writing a program to print quotient and remainder, but everywhere change the quotientProblem function into one called quotientString that merely returns the string rather than printing the string directly. Have the main function print the result of each call to the quotientString function.</p> <pre><code>def value(...
-2
2016-08-04T02:16:18Z
38,757,505
<p>What do you expect to happen? <code>division</code> is a function that takes three arguments and returns the last. So <code>division(a, b, z)</code> returns <code>z</code>. What is <code>z</code>? It's the return value of <code>print</code>. The <code>print</code> function returns <code>None</code>. So <code>divisio...
0
2016-08-04T02:21:08Z
[ "python", "python-3.x" ]
creating an sql query using a DataFrame column
38,757,655
<p>Based on this qs from stackoverflow: <a href="http://stackoverflow.com/questions/29738859/sql-where-in-clause-using-column-in-pandas-dataframe">SQL where in clause using column in pandas dataframe</a></p> <p>I tried:</p> <pre><code>import pandas as pd df1 = pd.DataFrame() df1['col1'] = [1,2,3,4,5] str = ','.join...
0
2016-08-04T02:39:08Z
38,757,759
<p>Maybe something like:</p> <pre><code>df1['new'] = df1['col1'].apply(lambda x: f(x) if x in df1['col1'].unique().tolist() else 'n/a') </code></pre> <p>You'll need to define f(x) to take in the unique value, run the query, and return the results you want to append. You can also change 'n/a' to whatever you want if ...
0
2016-08-04T02:52:09Z
[ "python", "sql", "pandas" ]
Remove NaNs from numpy array that has string values and numerical values
38,757,657
<p>I have a <code>(M x N)</code> numpy array, which contains string values, numerical values and nans. I want to drop the rows which contain <code>NaN</code> values. I've tried:</p> <pre><code>arr[~np.isnan(arr)] </code></pre> <p>however i get the error: </p> <pre><code>TypeError: ufunc 'isnan' not supported for the...
0
2016-08-04T02:39:10Z
38,759,206
<p>I get your error if I make an object dtype array:</p> <pre><code>In [112]: arr=np.ones((3,2),object) In [113]: arr Out[113]: array([[1, 1], [1, 1], [1, 1]], dtype=object) In [114]: np.isnan(arr) ... TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced...
0
2016-08-04T05:37:39Z
[ "python", "arrays", "numpy" ]
Remove NaNs from numpy array that has string values and numerical values
38,757,657
<p>I have a <code>(M x N)</code> numpy array, which contains string values, numerical values and nans. I want to drop the rows which contain <code>NaN</code> values. I've tried:</p> <pre><code>arr[~np.isnan(arr)] </code></pre> <p>however i get the error: </p> <pre><code>TypeError: ufunc 'isnan' not supported for the...
0
2016-08-04T02:39:10Z
38,763,221
<p>One solution is you can use np.sum() to sum each row up. because nan + any float = nan, so that you can get which lines incluede nan value.</p> <pre><code>np.sum(arr,axis = 1) rowsWithoutNaN = [ not(np.isnan(i)) for i in b] result = np.array( [val for shouldKeep, val in zip(rowsWithoutNaN,arr) if shouldKeep]) </cod...
0
2016-08-04T09:15:06Z
[ "python", "arrays", "numpy" ]
Targets don't match node IDs in networkx json file
38,757,701
<p>I have a network I want to output to a json file. However, when I output it, node targets become converted to numbers and do not match the node ids which are strings.</p> <p>For example:</p> <pre><code>G = nx.DiGraph(data) G.edges() </code></pre> <p>results in:</p> <pre><code>[(22, 'str1'), (22, 'str2'), (22, '...
0
2016-08-04T02:44:21Z
38,765,461
<blockquote> <p>Why is this</p> </blockquote> <p>It's a feature. Not all graph libraries accept strings as identifiers, but all that I know of accept integers.</p> <blockquote> <p>how can I prevent it?</p> </blockquote> <p>Replace the ids by node names using the <code>nodes</code> map:</p> <pre><code>&gt;&gt;&g...
1
2016-08-04T10:57:52Z
[ "python", "networkx" ]
pandas.io.common.CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file
38,757,713
<p>I have large csv files with size more than 10 mb each and about 50+ such files. These inputs have more than 25 columns and more than 50K rows. </p> <p>All these have same headers and I am trying to merge them into one csv with headers to be mentioned only one time. </p> <p>Option: One Code: Working for small sized...
2
2016-08-04T02:46:09Z
38,758,363
<p>If I understand your problem, you have large csv files with the same structure that you want to merge into one big CSV file. </p> <p>My suggestion is to use <a href="http://dask.pydata.org/en/latest/examples/dataframe-csv.html" rel="nofollow"><code>dask</code></a> from Continuum Analytics to handle this job. You ...
3
2016-08-04T04:11:57Z
[ "python", "csv", "pandas", "concatenation" ]
AttributeError: 'tuple' object has no attribute 'decode' while trying to decode string
38,757,724
<p>I am running this code on Python 3. I encoded the data using <code>.encode('utf_8')</code> while accepting from the server. But now I want to <code>decode</code> it in order make it human readable.</p> <pre><code> All1 = soup.findAll('tag_name', class_='class_name') All2 = "".join([p.text for p in All1]) str = "1...
-2
2016-08-04T02:47:19Z
38,757,750
<p><code>str</code> (don't name your variables after built-in functions, by the way) is a <code>tuple</code>, not a string.</p> <pre><code>str = "1",All2.encode('utf_8') </code></pre> <p>This is equivalent to the more readable:</p> <pre><code>str = ("1", All2.encode('utf_8')) </code></pre> <p>I don't know what you ...
1
2016-08-04T02:51:18Z
[ "python", "string", "python-3.x", "encoding" ]
cannot locate a web element
38,757,830
<p>I just want to write a simple log in script for Apple website: <a href="https://secure2.store.apple.com/shop/sign_in?c=aHR0cDovL3d3dy5hcHBsZS5jb20vc2hvcC9iYWd8MWFvczVjNGU3ZWNjZjgwODVjNWY4NDk0OTA0ODJhMDc2Y2FkNmU3ODJkOTE&amp;o=O01LV0gy&amp;r=SXYD4UDAPXU7P7KXF&amp;s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9zaG9wL2NoZ...
0
2016-08-04T03:02:36Z
38,757,962
<p>I recommend you try the following:</p> <pre><code>driver.find_element_by_id("login-appleId") driver.find_element_by_id("login-password") </code></pre>
0
2016-08-04T03:21:13Z
[ "python", "selenium-webdriver" ]
cannot locate a web element
38,757,830
<p>I just want to write a simple log in script for Apple website: <a href="https://secure2.store.apple.com/shop/sign_in?c=aHR0cDovL3d3dy5hcHBsZS5jb20vc2hvcC9iYWd8MWFvczVjNGU3ZWNjZjgwODVjNWY4NDk0OTA0ODJhMDc2Y2FkNmU3ODJkOTE&amp;o=O01LV0gy&amp;r=SXYD4UDAPXU7P7KXF&amp;s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9zaG9wL2NoZ...
0
2016-08-04T03:02:36Z
38,762,379
<p>Sometimes in <code>WebDriver</code> there are scenarios where the <code>WebElement</code> isn't loaded properly on <code>DOM</code> and webdriver tries to find it. So to handle these kind of scenarios there are 2 types of wait provided by <code>WebDriver</code> library.</p> <p>You just need to implement one of thes...
0
2016-08-04T08:36:38Z
[ "python", "selenium-webdriver" ]
cannot locate a web element
38,757,830
<p>I just want to write a simple log in script for Apple website: <a href="https://secure2.store.apple.com/shop/sign_in?c=aHR0cDovL3d3dy5hcHBsZS5jb20vc2hvcC9iYWd8MWFvczVjNGU3ZWNjZjgwODVjNWY4NDk0OTA0ODJhMDc2Y2FkNmU3ODJkOTE&amp;o=O01LV0gy&amp;r=SXYD4UDAPXU7P7KXF&amp;s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9zaG9wL2NoZ...
0
2016-08-04T03:02:36Z
38,762,790
<p>You can Follow this code .. It works ..!!</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome('E:\chromedriver.exe') #location dri...
1
2016-08-04T08:55:01Z
[ "python", "selenium-webdriver" ]
Python threading - Run function at certain times
38,757,831
<p>I have a set of data like</p> <pre><code>schedule = [(2, 5), (4, 6), (10, 2)] </code></pre> <p>with the first element of each tuple being a time (in seconds) and the second element being a value.</p> <p>I would like to start a separate thread which tracks the time and at each scheduled tim...
0
2016-08-04T03:02:50Z
38,758,579
<p>If you need them to be in separate threads then a Timer object or as a commenter pointed out APScheduler. If you want to do the threading manually you could also use sched. They added support for threads in version 3.3. <a href="https://docs.python.org/3/library/sched.html" rel="nofollow">Docs</a></p>
1
2016-08-04T04:38:36Z
[ "python", "timer", "python-multithreading" ]
Python 3 non-blocking read with pySerial (Cannot get pySerial's "in_waiting" property to work)
38,757,906
<p>For the life of me, I cannot figure out how to do a non-blocking serial read in Python 3 using my Raspberry Pi.</p> <p>Here's my code: </p> <pre><code>import serial #for pySerial ser = serial.Serial('/dev/ttyUSB0', 9600) #open serial port print ('serial port = ' + ser.name) #print the port used while (True): ...
0
2016-08-04T03:12:51Z
38,758,047
<p>You have to run the open port function first then at the end close it using the close function.</p>
0
2016-08-04T03:31:35Z
[ "python", "raspberry-pi", "pyserial" ]
Python 3 non-blocking read with pySerial (Cannot get pySerial's "in_waiting" property to work)
38,757,906
<p>For the life of me, I cannot figure out how to do a non-blocking serial read in Python 3 using my Raspberry Pi.</p> <p>Here's my code: </p> <pre><code>import serial #for pySerial ser = serial.Serial('/dev/ttyUSB0', 9600) #open serial port print ('serial port = ' + ser.name) #print the port used while (True): ...
0
2016-08-04T03:12:51Z
38,758,474
<p>The documentation link you listed shows <code>in_waiting</code> as a property added in PySerial 3.0. Most likely you're using PySerial &lt; 3.0 so you'll have to call the <code>inWaiting()</code> function.</p> <p>You can check the version of PySerial as follows:</p> <pre class="lang-py prettyprint-override"><code>...
1
2016-08-04T04:26:00Z
[ "python", "raspberry-pi", "pyserial" ]
python appengine-gcs-client demo with local devserver hitting AccessTokenRefreshError(u'internal_failure',)
38,757,936
<p>I'm having trouble getting the python appengine-gcs-client demo working using the 1.9.40 (latest presently) SDK's <code>dev_appserver.py</code>.</p> <p>I followed the <a href="https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/setting-up-cloud-storage" rel="nofollow">Setting Up Google Cloud Sto...
1
2016-08-04T03:16:51Z
38,771,428
<p>Actually the reason was what IMHO is a quite silly bug - inability to read the credentials from a local file written by an earlier version of the SDK (or related package?) and failure to fallback to a more decent action which leads to a rather misleading traceback throwing off the investigation.</p> <p>Credit goes ...
0
2016-08-04T15:23:13Z
[ "python", "google-app-engine", "google-cloud-storage" ]
How to update and delete data using Luigi?
38,757,994
<p>what module can be use from luigi for update/delete data into database? i have use copy to table and sql alchemy for inserting data. for update and delete document is not clear how can it be achieved? please advise.</p>
0
2016-08-04T03:25:27Z
38,797,266
<p>If the database is Postgres, you may be able to use PostgresQuery. <a href="http://luigi.readthedocs.io/en/stable/api/luigi.postgres.html#luigi.postgres.PostgresQuery" rel="nofollow">http://luigi.readthedocs.io/en/stable/api/luigi.postgres.html#luigi.postgres.PostgresQuery</a></p>
0
2016-08-05T20:23:42Z
[ "python", "apache", "luigi" ]
How to use AIML with Python
38,758,029
<p>I would like to integrate <code>python</code> scripts into my <code>pandorabot</code> written in <code>aiml</code>. </p> <p>I know that you can tag <code>aiml</code> syntax with <code>javascript</code>, but I haven't found any documentation on <code>python</code>, except the following, which uses <code>&lt;oob&gt;<...
0
2016-08-04T03:30:00Z
39,268,101
<p>While I have no experience working with python in conjunction with pandorabots, but I did work with php, and this is what I came up with conceptually. The objective was similar, but in my case I needed to add information for the pandorabot response from an external api, and the following is what I did :</p> <p>I us...
2
2016-09-01T09:44:28Z
[ "python", "nltk", "aiml", "pandorabots" ]
change file name of uploaded file django
38,758,084
<p>this is what I am trying to do. I created a method that will upload a file however, I would like to change its file name. I was able to change the filename but I also lost the extension.</p> <p>this is how my codes look:</p> <pre><code>def upload_delivery_to_media(self,deliveryId, deliveryFile): with open('/a...
0
2016-08-04T03:36:39Z
38,760,576
<p>It's better to use <a href="https://docs.python.org/3/library/os.path.html#os.path.splitext" rel="nofollow">splitext</a> instead of method <code>split()</code>:</p> <pre><code>import os from django.conf import settings def upload_delivery_to_media(self, delivery_id, delivery_file): _, ext = os.path.splitext(de...
0
2016-08-04T07:04:37Z
[ "python", "django" ]
How to give 2 characters in "delimiter" using 'csv' module?
38,758,158
<p>I'm trying to generate the csv with delimiter '@|@' but, I couldn't achieve through below code.</p> <pre><code>import csv ifile = open('test.csv', "rb") reader = csv.reader(ifile) ofile = open('ttest.csv', "wb") writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: ...
1
2016-08-04T03:45:50Z
38,758,249
<p>In csv <a href="https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter" rel="nofollow">documentation</a> they say </p> <blockquote> <p>A one-character string used to separate fields. It defaults to ','.</p> </blockquote> <p>So you can do this as an alternative.</p> <pre><code>csv.reader((line.replace(...
0
2016-08-04T03:57:24Z
[ "python", "csv" ]
How to give 2 characters in "delimiter" using 'csv' module?
38,758,158
<p>I'm trying to generate the csv with delimiter '@|@' but, I couldn't achieve through below code.</p> <pre><code>import csv ifile = open('test.csv', "rb") reader = csv.reader(ifile) ofile = open('ttest.csv', "wb") writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: ...
1
2016-08-04T03:45:50Z
38,758,327
<p>Life is too short, just use <code>pandas</code></p> <pre><code>import pandas as pd df.to_csv('output.csv', sep='|') </code></pre> <p>By default, the delimiator is <code>','</code>, that is why it is called Commasv. But by changing the <code>sep</code> to <code>'|'</code>, you could simply achieve what you want.</p...
0
2016-08-04T04:07:18Z
[ "python", "csv" ]
How to give 2 characters in "delimiter" using 'csv' module?
38,758,158
<p>I'm trying to generate the csv with delimiter '@|@' but, I couldn't achieve through below code.</p> <pre><code>import csv ifile = open('test.csv', "rb") reader = csv.reader(ifile) ofile = open('ttest.csv', "wb") writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: ...
1
2016-08-04T03:45:50Z
38,758,467
<p>The <em>csvfile</em> argument to a the <code>csv.writer</code> constructor only has to be a "file-like object". This means you could supply an instance of your own class which changes a single character into one with two or more characters (but which otherwise acts like a open output file object).</p> <p>Here's wha...
0
2016-08-04T04:25:27Z
[ "python", "csv" ]
Can the repetition in this line be avoided?
38,758,187
<p><code>'=' not in access and name + '.' not in access</code></p> <p>I hope to avoid the multiplicity of <code>not in access</code>s in a line of Python code. I've used expression evaluation loops for cases of higher numbers of repetitions for convenience but it just seems odd at two.</p>
0
2016-08-04T03:49:14Z
38,758,232
<p>Here's another option:</p> <pre><code>all(s not in access for s in ('=', name + '.')) </code></pre> <p>It's up to you to decide if this is simpler than your code - but at least it avoids having to write <code>not in access</code> <em>twice</em>.</p>
0
2016-08-04T03:55:43Z
[ "python", "repetition", "non-repetitive" ]
Can't select textbox in selenium
38,758,221
<p>I am trying to access the comment textbox in a generic huffington post artical. When I right click inspect element I get the following HTML code:</p> <pre><code>&lt;div class="UFIInputContainer"&gt; &lt;div class="_1cb _5yk1"&gt; &lt;div class="_5yk2" tabindex="-2"&gt; &lt;div class="_5rp7"&gt; </code></pre> ...
0
2016-08-04T03:54:16Z
38,758,561
<p>You have to switch to the iframe containing the text box. Try the following approach, it should work: Clicking the load comments button might be required first if load comment button is displayed</p> <pre><code>load_comment = driver.find_element_by_css_selector('.comment-button.js-comment-button') load_comment.clic...
0
2016-08-04T04:36:17Z
[ "python", "selenium", "selenium-webdriver" ]
Is it possible to set a default intent in Wit.ai?
38,758,342
<p>I'm working on a chatbot project based on Facebook's Wit.ai and was wondering if it is possible to set a default intent? </p> <p>For example, my bot currently supports only a handful of questions, such as "Where are you located?" or "What is your phone number?", each of these questions has an intent and story assoc...
1
2016-08-04T04:09:13Z
38,828,177
<p>There is no any functionality available yet in wit.ai</p> <p>But you can get the required functionality by using the confidence value returned by the wit api. You can set a threshold value of the confidence and if the value falls below your threshold return a custom message. you can handle this functionality in you...
3
2016-08-08T11:33:46Z
[ "python", "facebook", "wit.ai" ]
Why Does This Usage of a Class Work in Python?
38,758,345
<p>I run the following very trivial Python code. I am very surprised that it actually run. Could someone explain to me why I can even assign values to "nd" and "hel" without defining them in the class definition? Is this because the attribute can be added in the instance level?</p> <pre><code>class tempClass(object): ...
0
2016-08-04T04:09:43Z
38,758,573
<p>Python has no notion of variable declaration, only assignments. The same applies to attributes: you simply assign an initial value to bring it into existence.</p> <p>There is nothing special about the <code>__init__</code> method in this regard. For example,</p> <pre><code>class TempClass(object): def __init__...
2
2016-08-04T04:37:46Z
[ "python", "class", "instance" ]
How to define an element belongs to other categories?
38,758,367
<p>I know the topic is really hard to understand but I don't know how to describe my problem in one sentence...T^T</p> <p>Here is what I'm trying to do.</p> <p>I have a set of 1-dimensional points in three categories.</p> <pre><code>A = [[0,1], [0,2], [0,3], [1,1], [2,1], [3,2], [3,3], [4,2], [4,3], [5,3], [6,3]] </...
1
2016-08-04T04:12:12Z
38,758,501
<p>You can use not in, like this: <code>X[i+1] not in group[j]</code></p> <p>Secondly, your algorithm seems overly complicated. What something like this?</p> <pre><code>A = [[0,1], [0,2], [0,3], [1,1], [2,1], [3,2], [3,3], [4,2], [4,3], [5,3], [6,3]] point, label = A[0] cuts = [] for npoint, nlabel in A[1:]: if not...
2
2016-08-04T04:28:57Z
[ "python", "list" ]
How to define an element belongs to other categories?
38,758,367
<p>I know the topic is really hard to understand but I don't know how to describe my problem in one sentence...T^T</p> <p>Here is what I'm trying to do.</p> <p>I have a set of 1-dimensional points in three categories.</p> <pre><code>A = [[0,1], [0,2], [0,3], [1,1], [2,1], [3,2], [3,3], [4,2], [4,3], [5,3], [6,3]] </...
1
2016-08-04T04:12:12Z
38,758,682
<p>This is sort of a weird problem you've got, but here's a functional way to do.</p> <pre><code>from itertools import groupby </code></pre> <p><code>groupby</code> will let us easily merge your X coordinates, assuming the array is pre-sorted by them.</p> <pre><code>l = [(i, [x[1] for x in g]) for i, g in groupby(A,...
2
2016-08-04T04:49:05Z
[ "python", "list" ]
How to convert a tuple list with duplicated keys and values into a fancy dicionary?
38,758,378
<p>I have a tuple list like the code below, an identifier has multiple values(both identifier and values maybe duplicated), I thought using <code>dict</code> with a <code>str</code> as a key and a <code>set</code> as it's value would be reasonable, but how?</p> <pre><code>tuple_list = [ ('id1', 123), ('id1', 1...
-2
2016-08-04T04:13:08Z
38,758,406
<p>You can use <code>setdefaultdict</code>:</p> <pre><code>map_data = {} for id, val in tuple_list: map_data.setdefault(id,set()).add(val) </code></pre>
1
2016-08-04T04:17:28Z
[ "python", "dictionary" ]
How to convert a tuple list with duplicated keys and values into a fancy dicionary?
38,758,378
<p>I have a tuple list like the code below, an identifier has multiple values(both identifier and values maybe duplicated), I thought using <code>dict</code> with a <code>str</code> as a key and a <code>set</code> as it's value would be reasonable, but how?</p> <pre><code>tuple_list = [ ('id1', 123), ('id1', 1...
-2
2016-08-04T04:13:08Z
38,758,552
<p>To use a <code>dict</code> containing a <code>set</code> do it like this.</p> <pre><code>from collections import defaultdict tuple_list = [ ('id1', 123), ('id1', 123), ('id2', 123), ('id1', 456), ('id2', 456), ('id1', 789), ('id2', 789) ] map_data = defaultdict(set) for id, val in tup...
1
2016-08-04T04:35:05Z
[ "python", "dictionary" ]
python flask bucketlist app
38,758,389
<p>I am attempting to build a python flask web app with a tutorial and I am having trouble implementing my signUp method. Tutorial: <a href="http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">http://code.tutsplus.com/tutorials/creating-a-web-app-fr...
1
2016-08-04T04:14:53Z
38,758,447
<p>I also encountered the same issue when I was implementing the same recently.</p> <p>Change your signUp code in app.py as follows including the import.</p> <pre><code>from flask import Flask, render_template, json, request def signUp(): _name = request.form['inputName'] _email = request.form['inputEmail'] ...
1
2016-08-04T04:23:22Z
[ "python", "ajax", "flask" ]
Installing Qutip in fedora 24
38,758,428
<p>I can't install Qutip in my fedora 24</p> <pre><code>pip install qutip </code></pre> <p>Whenever I type this , error message showing <a href="http://i.stack.imgur.com/r8g3z.png" rel="nofollow">It starts like this </a> But at the end <a href="http://i.stack.imgur.com/q54nr.png" rel="nofollow">this</a> happens , a...
0
2016-08-04T04:20:50Z
38,758,648
<p>The error is quite evident:</p> <pre><code>gcc: error: /usr/lib/rpm/redhat/redhat-hardened-001: No such file or directory </code></pre> <p>Somehow this file has vanished from your computer. Find out which package provides this file.</p> <pre><code>sudo dnf provides /usr/lib/rpm/redhat/redhat-hardened-cc1 Last met...
1
2016-08-04T04:46:40Z
[ "python", "fedora", "qutip" ]
running Scrapy on terminal server
38,758,532
<p>i wanna crawling on server side but my python it isnt so good...</p> <p>my source is works so well, if i running it on mylaptop terminal, but it was going wrong when running it on server terminal</p> <p>here my source code </p> <pre><code>from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathS...
0
2016-08-04T04:32:34Z
38,761,763
<p>Seems like your scrapy version is out of date. <code>scrapy.Selector</code> method <code>.extract_first()</code> was only added in scrapy 1.1, so you want to upgrade the scrapy package on your server.</p>
0
2016-08-04T08:04:46Z
[ "python", "server", "scrapy", "web-crawler", "client" ]
Why wont my {% extends %} command work in my django app
38,758,580
<p>I am making a web app with django, and in one portion I am trying to make use of the {% extends %} command to put some html from one template on to another. Here is the code:</p> <p>home.html - </p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; {% block content %} {% endbl...
-2
2016-08-04T04:38:42Z
38,772,740
<p>What you want to happen is to direct people to your search <code>view</code> so that view has to know about <code>search.html</code></p> <pre><code>def index(request): all_games = GameCard.objects.all() template = loader.get_template('search.html') &lt;!-- or whichever file --&gt; context = { 'a...
1
2016-08-04T16:26:17Z
[ "python", "django" ]
Haystack index objects using their reverse relation
38,758,617
<p>I have a two models: </p> <pre><code>class Question(models.Model): question_text = models.TextField() class Response(models.Model): response_text = models.TextField() question = models.ForeignKey(Question, related_name='responses', on_delete=models.CASCADE) </code></pre> <p>I have one haystack search ...
1
2016-08-04T04:43:19Z
38,758,666
<p>You can supply a <a href="http://django-haystack.readthedocs.io/en/v2.4.1/searchindex_api.html#prepare-foo-self-object" rel="nofollow"><code>prepare_</code> method</a> for that field to specify what data is indexed:</p> <pre><code>class QuestionIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharF...
1
2016-08-04T04:47:58Z
[ "python", "django", "search", "tastypie", "django-haystack" ]
Grouping Functions by Using Classes in Python
38,758,668
<p>I have been a Python Scientific Programmer for a few years now, and I find myself coming to a sort specific problem as my programs get larger and larger. I am self taught so I have never had any formal training and spent any time really on 'conventions' of coding in Python "properly".</p> <p>Anyways, to the point, ...
0
2016-08-04T04:48:03Z
38,758,786
<p>I think doing so is perfectly pythonic. This is exactly the purpose of <code>staticmethod</code> constructor.</p> <p>For python conventions, see <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>.</p>
0
2016-08-04T05:00:34Z
[ "python", "class", "conventions" ]
Grouping Functions by Using Classes in Python
38,758,668
<p>I have been a Python Scientific Programmer for a few years now, and I find myself coming to a sort specific problem as my programs get larger and larger. I am self taught so I have never had any formal training and spent any time really on 'conventions' of coding in Python "properly".</p> <p>Anyways, to the point, ...
0
2016-08-04T04:48:03Z
38,758,993
<p>I wouldn't use a <code>class</code> for this, I'd use a <code>module</code>. A class consisting of only staticmethods strikes me as a code smell too. Here's how to do it with modules: any time you stick code in a separate file and import it into another file, Python sticks that code in a module with the same name as...
0
2016-08-04T05:18:02Z
[ "python", "class", "conventions" ]
Grouping Functions by Using Classes in Python
38,758,668
<p>I have been a Python Scientific Programmer for a few years now, and I find myself coming to a sort specific problem as my programs get larger and larger. I am self taught so I have never had any formal training and spent any time really on 'conventions' of coding in Python "properly".</p> <p>Anyways, to the point, ...
0
2016-08-04T04:48:03Z
38,759,051
<p>Another approach is to make a <code>util</code> <em>package</em> and split up your functions into different modules within that package. The basics of packages: make a directory (whose name will be the package name) and put a special file in it, the <code>__init__.py</code> file. This <em>can</em> contain code, but ...
1
2016-08-04T05:24:12Z
[ "python", "class", "conventions" ]
incrementally rank pandas dataframe subject to other boolean dataframe in panel
38,758,691
<p>I have two pandas dataframes in a panel and would like to create a third df that ranks the first df (by row) but only include those where the corresponding element of the second df is True. Some sample data to illustrate:</p> <pre><code>p['x'] A B C D ...
1
2016-08-04T04:49:59Z
38,759,134
<pre><code>pd.DataFrame(np.where(p['y'] == True, p['x'], np.nan), p.major_axis, p.minor_axis).rank(1, ascending=False) </code></pre> <p><a href="http://i.stack.imgur.com/8VDxF.png" rel="nofollow"><img src="http://i.stack.imgur.com/8VDxF.png" alt="enter image description here"></a></p>
2
2016-08-04T05:31:54Z
[ "python", "pandas", null, "rank" ]
Repeat each elements based on a list of values
38,758,708
<p>Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example <code>A</code> in list <code>x</code> position 0 is repeated 2 times because of the value <code>2</code> at position 0 in the list <code>y</code>.</p> <pre><code>&gt;&gt;&gt; x = ['A', 'B', 'C...
2
2016-08-04T04:52:24Z
38,758,755
<p>Try this</p> <pre><code>x = ['A', 'B', 'C'] y = [2, 1, 3] newarray = [] for i in range(0,len(x)): newarray.extend(x[i] * y[i]) print newarray </code></pre>
0
2016-08-04T04:57:28Z
[ "python", "list" ]
Repeat each elements based on a list of values
38,758,708
<p>Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example <code>A</code> in list <code>x</code> position 0 is repeated 2 times because of the value <code>2</code> at position 0 in the list <code>y</code>.</p> <pre><code>&gt;&gt;&gt; x = ['A', 'B', 'C...
2
2016-08-04T04:52:24Z
38,758,764
<p>One way would be the following</p> <pre><code>x = ['A', 'B', 'C'] y = [2, 1, 3] s = [] for a, b in zip(x, y): s.extend([a] * b) print(s) </code></pre> <p>result</p> <pre><code>['A', 'A', 'B', 'C', 'C', 'C'] </code></pre>
2
2016-08-04T04:58:10Z
[ "python", "list" ]
Repeat each elements based on a list of values
38,758,708
<p>Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example <code>A</code> in list <code>x</code> position 0 is repeated 2 times because of the value <code>2</code> at position 0 in the list <code>y</code>.</p> <pre><code>&gt;&gt;&gt; x = ['A', 'B', 'C...
2
2016-08-04T04:52:24Z
38,758,772
<pre><code>from itertools import chain list(chain(*[[a] * b for a, b in zip(x, y)])) ['A', 'A', 'B', 'C', 'C', 'C'] </code></pre> <p>There is <code>itertools.repeat</code> as well, but that ends up being uglier for this particular case.</p>
2
2016-08-04T04:58:41Z
[ "python", "list" ]