title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Find the second highest value out of various lists of numbers
38,665,990
<p>I made a simple code to find the highest value out of various lists of numbers</p> <pre><code>lists = [[1,-3,5,2,6,11,78,5,-345,-3,6,98,-5,0],[1,2,3,4,5,6,7,6,5,4,4],[-435,-64,-4,-6,-45,-8,-98,-7,-8],[32,45,56,554,12,33]] for w in lists: lst = w a = float ("-inf") for x in range (0, len (lst)): ...
0
2016-07-29T19:11:07Z
38,666,039
<pre><code>&gt;&gt;&gt; lst = [1,-3,5,2,6,11,78,5,-345,-3,6,98,-5,0] &gt;&gt;&gt; sorted(lst) [-345, -5, -3, -3, 0, 1, 2, 5, 5, 6, 6, 11, 78, 98] &gt;&gt;&gt; &gt;&gt;&gt; second_most = sorted(lst)[-2] &gt;&gt;&gt; second_most 78 &gt;&gt;&gt; &gt;&gt;&gt; lst.index(78) 6 &gt;&gt;&gt; </code></pre> <p>You can sort ...
1
2016-07-29T19:14:50Z
[ "python", "find", "value" ]
Find the second highest value out of various lists of numbers
38,665,990
<p>I made a simple code to find the highest value out of various lists of numbers</p> <pre><code>lists = [[1,-3,5,2,6,11,78,5,-345,-3,6,98,-5,0],[1,2,3,4,5,6,7,6,5,4,4],[-435,-64,-4,-6,-45,-8,-98,-7,-8],[32,45,56,554,12,33]] for w in lists: lst = w a = float ("-inf") for x in range (0, len (lst)): ...
0
2016-07-29T19:11:07Z
38,666,370
<p>You can use numpy to do this. The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>np.argsort</code></a> method returns a numpy array of the indices which would sort the list.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; list = [1,-3,5,2,6,11,78,5...
0
2016-07-29T19:40:24Z
[ "python", "find", "value" ]
Find the second highest value out of various lists of numbers
38,665,990
<p>I made a simple code to find the highest value out of various lists of numbers</p> <pre><code>lists = [[1,-3,5,2,6,11,78,5,-345,-3,6,98,-5,0],[1,2,3,4,5,6,7,6,5,4,4],[-435,-64,-4,-6,-45,-8,-98,-7,-8],[32,45,56,554,12,33]] for w in lists: lst = w a = float ("-inf") for x in range (0, len (lst)): ...
0
2016-07-29T19:11:07Z
38,668,309
<p>Try this approach, that maps all the positions and rankings in a dictionary:</p> <pre><code>from operator import itemgetter lists = [[1,-3,5,2,6,11,78,5,-345,-3,6,98,-5,0], [1,2,3,4,5,6,7,6,5,4,4], [-435,-64,-4,-6,-45,-8,-98,-7,-8], [32,45,56,554,12,33]] rank = 0 mapping = {(rank, lst_n...
0
2016-07-29T22:24:19Z
[ "python", "find", "value" ]
TensorFlow: AttributeError: 'Tensor' object has no attribute 'shape'
38,666,040
<p>I have the following code which uses TensorFlow. After I reshape a list, it says </p> <blockquote> <p>AttributeError: 'Tensor' object has no attribute 'shape'</p> </blockquote> <p>when I try to print its shape.</p> <pre><code># Get the shape of the training data. print "train_data.shape: " + str(train_data.shap...
0
2016-07-29T19:14:55Z
38,666,116
<p>Indeed, <code>tf.Tensor</code> doesn't have a <code>.shape</code> property. You should use the <code>Tensor.get_shape()</code> method instead:</p> <pre><code>train_data = tf.reshape(train_data, [400, 1]) print "train_data.shape: " + str(train_data.get_shape()) </code></pre> <p>Note that in general you might not be...
2
2016-07-29T19:21:18Z
[ "python", "neural-network", "tensorflow" ]
Fast Queue of read only numpy arrays
38,666,078
<p>I have a multiprocessing job where I'm queuing read only numpy arrays, as part of a producer consumer pipeline.</p> <p>Currently they're being pickled, because this is the default behaviour of <code>multiprocessing.Queue</code> which slows down performance.</p> <p>Is there any pythonic way to pass references to sh...
10
2016-07-29T19:18:18Z
38,774,630
<p>Your example does not seem to run on my computer, although that may have to do with the fact that I'm running windows (issues pickling anything not in <code>__main__</code> namespace (anything decorated))... would something like this help? (you would have to be put pack and unpack inside each of f(), g(), and h()) <...
0
2016-08-04T18:16:59Z
[ "python", "numpy", "parallel-processing", "multiprocessing" ]
Fast Queue of read only numpy arrays
38,666,078
<p>I have a multiprocessing job where I'm queuing read only numpy arrays, as part of a producer consumer pipeline.</p> <p>Currently they're being pickled, because this is the default behaviour of <code>multiprocessing.Queue</code> which slows down performance.</p> <p>Is there any pythonic way to pass references to sh...
10
2016-07-29T19:18:18Z
38,775,513
<h2>Sharing memory between threads or processes</h2> <h3>Use threading instead of multiprocessing</h3> <p>Since you're using numpy, you can take advantage of the fact that <a href="http://scipy-cookbook.readthedocs.io/items/ParallelProgramming.html" rel="nofollow">the global interpreter lock is released during numpy ...
6
2016-08-04T19:10:25Z
[ "python", "numpy", "parallel-processing", "multiprocessing" ]
Fast Queue of read only numpy arrays
38,666,078
<p>I have a multiprocessing job where I'm queuing read only numpy arrays, as part of a producer consumer pipeline.</p> <p>Currently they're being pickled, because this is the default behaviour of <code>multiprocessing.Queue</code> which slows down performance.</p> <p>Is there any pythonic way to pass references to sh...
10
2016-07-29T19:18:18Z
38,799,008
<p>Check out the <a href="https://github.com/uqfoundation/pathos/blob/master/pathos/multiprocessing.py" rel="nofollow">Pathos-multiprocessing project</a>, which avoids the standard <code>multiprocessing</code> reliance on pickling. This should allow you to get around both the inefficiencies of pickling, and give you ac...
0
2016-08-05T23:22:44Z
[ "python", "numpy", "parallel-processing", "multiprocessing" ]
Why does a column from pandas DataFrame not work in this loop?
38,666,111
<p>I have a DataFrame that I took from basketball-reference with player names. The code below is how I built the DataFrame. It has 5 columns of player names, but each name also has the player's position.</p> <pre><code>url = "http://www.basketball-reference.com/awards/all_league.html" dframe_list = pd.io.html.read_htm...
1
2016-07-29T19:20:52Z
38,666,726
<p>If the position labels are always only one character, the simple solution is this:</p> <pre><code>&gt;&gt;&gt; df.apply(lambda c: c.str[:-2]) name1 name2 0 Marc Gasol Lebron James 1 Pau Gasol Kevin Durant 2 Dwight Howard Kyrie Irving </code></pre> <p>The <code>str</code> attribute o...
2
2016-07-29T20:08:35Z
[ "python", "pandas", "for-loop", "dataframe" ]
Getting an instance's actual used (allocated) disk space in vmware with pyvmomi
38,666,195
<p>I've recently started using pyvmomi to get a detailed inventory of vmware servers prior to migrating instances into AWS.</p> <p>In the vcenter web interface, or vsphere client, I can inspect an instance and see its disks, and it'll tell me the disk size (provisioned), and how much of it is in use (used storage).</p...
3
2016-07-29T19:27:35Z
38,868,247
<p>For getting the <strong><em>freespace</em></strong> from the VM via <strong>PyVMomi</strong> first you have to check if the <em>VMware tools</em> for VM's is installed on your system or not. For checking if its installed, check from your <em>VM's guest information from its summary page (via MOB)</em> if it shows:</p...
1
2016-08-10T08:39:39Z
[ "python", "vmware", "pyvmomi" ]
How to install python if it doesn't exist from setuptools msi
38,666,274
<p>I wanted to package up my python installer so it would be easier to integrate into our WIX installer or other forms of product distribution. I was able to successfully build an exe (<code>python setup.py bdist_wininst</code>) and the msi (<code>python setup.py bdist_msi</code>) using setuptools, but what about the c...
0
2016-07-29T19:33:24Z
38,666,614
<p>The user of your <code>.exe</code> does not need to have python installed; that's beauty of creating binaries. All of the instructions that the client's computer needs to run the program are already in the <code>.exe</code></p>
0
2016-07-29T20:00:31Z
[ "python", "setuptools" ]
Is it possible to assign a default value when unpacking?
38,666,283
<p>I have the following:</p> <pre><code>&gt;&gt;&gt; myString = "has spaces" &gt;&gt;&gt; first, second = myString.split() &gt;&gt;&gt; myString = "doesNotHaveSpaces" &gt;&gt;&gt; first, second = myString.split() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: need more...
2
2016-07-29T19:33:54Z
38,666,361
<p>May I suggest you to consider using a different method, i.e. <code>partition</code> instead of <code>split</code>: </p> <pre><code>&gt;&gt;&gt; myString = "has spaces" &gt;&gt;&gt; left, separator, right = myString.partition(' ') &gt;&gt;&gt; left 'has' &gt;&gt;&gt; myString = "doesNotHaveSpaces" &gt;&gt;&gt; left,...
5
2016-07-29T19:39:37Z
[ "python", "iterable-unpacking" ]
Is it possible to assign a default value when unpacking?
38,666,283
<p>I have the following:</p> <pre><code>&gt;&gt;&gt; myString = "has spaces" &gt;&gt;&gt; first, second = myString.split() &gt;&gt;&gt; myString = "doesNotHaveSpaces" &gt;&gt;&gt; first, second = myString.split() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: need more...
2
2016-07-29T19:33:54Z
38,666,737
<p>A general solution would be to <a href="https://docs.python.org/3.5/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> your iterable with a <a href="https://docs.python.org/3.5/library/itertools.html#itertools.repeat" rel="nofollow"><code>repeat</code></a> of <code>None</code> values and t...
1
2016-07-29T20:09:16Z
[ "python", "iterable-unpacking" ]
Treeview Tkinter widget - clickable links
38,666,326
<p>I have ten links in my treeview widget (<a href="http://www.example.com" rel="nofollow">http://www.example.com</a>, <a href="http://www.example1.com" rel="nofollow">http://www.example1.com</a> and so on). It is plain text inserted into treeview. Is it possible to make it clickable? How can I convert text into links?...
0
2016-07-29T19:36:40Z
38,676,455
<p>For each widget, you can <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">bind</a> Python functions and methods to events.<code>Bind</code> a function to your <code>treeview</code>.You need to bind your tree,add this in <code>__init__</code> function:</p> <pre><code>self.tree....
1
2016-07-30T17:06:57Z
[ "python", "tkinter", "treeview" ]
Jupyter notebook wrong path
38,666,329
<p>I need to test a few functions from a code I am building which I import into a jupyter notebook.</p> <p>issue is, <em>simTools_path</em> is different in the functions and the jupyter notebook. More, when I call these functions from my main python script, it works fine.</p> <p><strong>MWE</strong></p> <p><em>simTo...
0
2016-07-29T19:36:55Z
38,748,048
<p>You have confused the variable <code>simTools_path</code> and the literal string <code>"simTools_path"</code>. To correct the problem, simply change the line as follows:</p> <pre><code>os.environ["SIMTOOLS_PATH"] = simTools_path </code></pre>
1
2016-08-03T15:37:42Z
[ "python", "path", "jupyter-notebook", "sys.path" ]
Calling a python script from another script and passing variables to it
38,666,348
<p>I have a python script that contains a large function that filters a list and exports the contents to excel. I want to be able to make different python scripts where I can specify different filters for different cases and pass them to my python scripts with the function that applies the filter.</p> <p>For example</...
0
2016-07-29T19:38:28Z
38,666,456
<p>execfile(filename[, globals[, locals]])</p>
-1
2016-07-29T19:47:05Z
[ "python" ]
Calling a python script from another script and passing variables to it
38,666,348
<p>I have a python script that contains a large function that filters a list and exports the contents to excel. I want to be able to make different python scripts where I can specify different filters for different cases and pass them to my python scripts with the function that applies the filter.</p> <p>For example</...
0
2016-07-29T19:38:28Z
38,666,539
<p>Let's assume that file with large function is in one directory with all others :</p> <pre><code>some folder |-functions_file.py |-main.py </code></pre> <p>So your functions file will contain your functions for example :</p> <pre><code>def add(num1, num2): return num1+num2 def subtract(num1, num2): return...
0
2016-07-29T19:53:23Z
[ "python" ]
Matplotlib: RGB colors appear black with Python 2
38,666,357
<p>I have a code snippet that works fine with Python 3 but doesn't with Python 2. I'm trying to use RGB codes to define a color palette: I get the right colors with Python 3, but Python 2 show them all black... </p> <p>Below is a very simple code snippet that shows this weird behavior:</p> <pre><code>%matplotlib inli...
0
2016-07-29T19:39:18Z
38,666,419
<p>Problem occurs in this line:</p> <pre><code>i/255 for i in colors[col] </code></pre> <p>It's because integer division is different in python 2 and python 3. </p> <p>Python 2</p> <pre><code>&gt;&gt;&gt; 2/3 &gt;&gt;&gt; 0 </code></pre> <p>Python 3</p> <pre><code>&gt;&gt;&gt; 2/3 &gt;&gt;&gt; 0.66... </code></pr...
1
2016-07-29T19:44:47Z
[ "python", "python-2.7", "matplotlib" ]
Matplotlib: RGB colors appear black with Python 2
38,666,357
<p>I have a code snippet that works fine with Python 3 but doesn't with Python 2. I'm trying to use RGB codes to define a color palette: I get the right colors with Python 3, but Python 2 show them all black... </p> <p>Below is a very simple code snippet that shows this weird behavior:</p> <pre><code>%matplotlib inli...
0
2016-07-29T19:39:18Z
38,666,448
<p>It looks like you never heard of different behavior of division in python 2 and python 3. Shortly - add this to the top of your python code - <code>from __future__ import division</code>. Python 2 will correct it's unobvious behavior, and python 3 will just ignore this statement - it's already fixed.</p>
1
2016-07-29T19:46:46Z
[ "python", "python-2.7", "matplotlib" ]
Calculating time between text field interactions
38,666,464
<p>I have a dataset of text field interactions across several dozen users of my application across the span of several months. I'm trying to calculate the average time between keystrokes in pandas. The data look something like this:</p> <pre><code>timestamp before_text after_text 1453481138188 ...
4
2016-07-29T19:47:26Z
38,667,035
<p>Your problem essentially is to identify when a given interaction stops and when another begins. Perhaps compute the difference between <code>timestamp</code>s, and if greater than a threshold, set a flag on which you can group.</p> <pre><code>thresh = 1e5 ts = (df['timestamp'] - df['timestamp'].shift()) &gt; thresh...
0
2016-07-29T20:31:23Z
[ "python", "pandas", "time-series" ]
Calculating time between text field interactions
38,666,464
<p>I have a dataset of text field interactions across several dozen users of my application across the span of several months. I'm trying to calculate the average time between keystrokes in pandas. The data look something like this:</p> <pre><code>timestamp before_text after_text 1453481138188 ...
4
2016-07-29T19:47:26Z
38,667,058
<p>I'd do it by calculating the text difference between 'before' and 'after'. If the difference is greater than some threshold, then that is a new session.</p> <p>It requires <code>from Levenshtein import distance as ld</code>. I installed it via <code>pip</code> like so:</p> <pre><code>pip install python-levenshte...
3
2016-07-29T20:33:21Z
[ "python", "pandas", "time-series" ]
What is the necessity of plt.figure() in matplotlib for scatter plots?
38,666,527
<pre><code>plt.figure(figsize=(10,8)) plt.scatter(df['attacker_size'][df['year'] == 298], # attacker size in year 298 as the y axis df['defender_size'][df['year'] == 298], # the marker as marker='x', # the color color='b', # the alpha alpha=0.7, #...
2
2016-07-29T19:52:34Z
38,666,557
<p>It is not always necessary because a <code>figure</code> is implicitly created when you create a <code>scatter</code> plot; however, in the case you have shown, the figure is being created explicitly using <code>plt.figure</code> so that the figure will be a specific size rather than the default size.</p> <p>The ot...
1
2016-07-29T19:54:35Z
[ "python", "matplotlib" ]
List of duplicate values in a dictionary python
38,666,639
<p>I have a dictionary that has has filename like 1.xml and then the DeviceIDs like 3 and 12.</p> <pre><code>{'1.xml': ['3', '12'], '2.xml': ['23', '17''], '3.xml': ['1', '12']} </code></pre> <p>And I have a code that compares the DeviceIDs and displays when there are duplicates. Right now it only works when all of t...
2
2016-07-29T20:02:53Z
38,666,804
<p>The <code>set</code> intersection drops all the previous duplicates when a new value in the dictionary does not contain them. So instead of the <code>set</code>, you can use a <em>multiset</em> - <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter...
3
2016-07-29T20:14:21Z
[ "python", "dictionary" ]
List of duplicate values in a dictionary python
38,666,639
<p>I have a dictionary that has has filename like 1.xml and then the DeviceIDs like 3 and 12.</p> <pre><code>{'1.xml': ['3', '12'], '2.xml': ['23', '17''], '3.xml': ['1', '12']} </code></pre> <p>And I have a code that compares the DeviceIDs and displays when there are duplicates. Right now it only works when all of t...
2
2016-07-29T20:02:53Z
38,667,156
<p>The answer posted by Moses is fewer lines of code, but this addresses your question more directly and might perform better, depending on the dataset:</p> <p>The reason your code doesn't work is because rather than <code>&amp;</code>-ing the intersections together, you actually want to take the union of all intersec...
1
2016-07-29T20:42:03Z
[ "python", "dictionary" ]
Running Fabric command in Seperate Process Group Hanging
38,666,727
<p>I'm having trouble understanding exactly why this is hanging. I have stripped down this example to the core components. I have a file, let's call it <code>do_ls.py</code></p> <pre><code>import fabric.api import time host = "myhost.mydomain" username = "username" password = "password" def main(): with fabric.a...
2
2016-07-29T20:08:37Z
38,790,749
<p>Since the following lines work:</p> <pre><code>cmd = ["ssh", "-q", "username@hostname", "ls"] p = sp.Popen(cmd, preexec_fn=os.setpgrp) </code></pre> <p>but <code>main.py</code> continuously hangs, I assume that </p> <pre><code>while p.poll() is None: </code></pre> <p>never evaluates to <code>False</code>. So <co...
1
2016-08-05T13:40:18Z
[ "python", "subprocess", "multiprocessing", "fabric" ]
Where is a Python built-in object's __enter__() and __exit__() defined?
38,666,733
<p>I've read that the object's __ enter__() and __ exit__() methods are called every time 'with' is used. I understand that for user-defined objects, you can define those methods yourself, but I don't understand how this works for built-in objects/functions like 'open' or even the testcases.</p> <p>This code works as ...
2
2016-07-29T20:09:03Z
38,666,817
<p>You're checking whether the <code>open</code> function itself or the <code>assertRaises</code> method itself has <code>__enter__</code> and <code>__exit__</code> methods, when you should be looking at what methods the return value has.</p>
2
2016-07-29T20:15:14Z
[ "python", "with-statement", "contextmanager", "code-inspection" ]
Where is a Python built-in object's __enter__() and __exit__() defined?
38,666,733
<p>I've read that the object's __ enter__() and __ exit__() methods are called every time 'with' is used. I understand that for user-defined objects, you can define those methods yourself, but I don't understand how this works for built-in objects/functions like 'open' or even the testcases.</p> <p>This code works as ...
2
2016-07-29T20:09:03Z
38,666,820
<p><code>open</code> is a function that returns a file object with the context methods, and <code>self.assertRaises</code> is a method that returns an object with the context methods, try checking the <code>dir</code> of their return value:</p> <pre><code>&gt;&gt;&gt; x = open(__file__, "r") &gt;&gt;&gt; x &lt;_io.Tex...
5
2016-07-29T20:15:30Z
[ "python", "with-statement", "contextmanager", "code-inspection" ]
Where is a Python built-in object's __enter__() and __exit__() defined?
38,666,733
<p>I've read that the object's __ enter__() and __ exit__() methods are called every time 'with' is used. I understand that for user-defined objects, you can define those methods yourself, but I don't understand how this works for built-in objects/functions like 'open' or even the testcases.</p> <p>This code works as ...
2
2016-07-29T20:09:03Z
38,666,836
<p><code>open()</code> is a function. It <em>returns</em> something that has an <code>__enter__</code> and <code>__exit__</code> method. Look at something like this:</p> <pre><code>&gt;&gt;&gt; class f: ... def __init__(self): ... print 'init' ... def __enter__(self): ... print 'enter' ... ...
7
2016-07-29T20:16:49Z
[ "python", "with-statement", "contextmanager", "code-inspection" ]
The most regex-y way to understand commutative operations?
38,666,744
<p>I want to parse both 1.05*f and f*1.05 to be equivalent things where f is a fixed letter, the number is any positive float and the * is always between the 'f' and the float (i.e. multiplication). If there is no multiplication, then that is ok too and 'f' as the entire string is ok - so the '1.05*' is optional. Not...
1
2016-07-29T20:10:02Z
38,667,299
<p>Negative look(ahead|behind)s to the rescue:</p> <pre><code>pattern=r'((?!.*f\*)[\d.]+\*)?f((?&lt;!\*f)\*[\d.]+)?' s="""1.05*f*1.05 1.05*f f*1.05 f""" for line in s.split("\n"): if re.match(pattern, line): print("yay") else: print("nay") </code></pre> <p>prints:</p> <pre><code>nay yay yay...
-1
2016-07-29T20:52:33Z
[ "python", "regex" ]
The most regex-y way to understand commutative operations?
38,666,744
<p>I want to parse both 1.05*f and f*1.05 to be equivalent things where f is a fixed letter, the number is any positive float and the * is always between the 'f' and the float (i.e. multiplication). If there is no multiplication, then that is ok too and 'f' as the entire string is ok - so the '1.05*' is optional. Not...
1
2016-07-29T20:10:02Z
38,667,353
<p>With multi-line modifier on:</p> <pre><code>^(?:f\*\d*\.\d+|\d*\.\d+\*f|f)$ </code></pre> <p><a href="https://regex101.com/r/uU8uM0/2" rel="nofollow">Live demo</a></p>
1
2016-07-29T20:56:29Z
[ "python", "regex" ]
Using a boolean in returned tuple for "if" statement?
38,666,852
<p>Current situation:</p> <pre><code>def isTooLarge(intValue): if intValue &gt; 100: print "too large"; return True return False if isTooLarge(101): break </code></pre> <p>Now I like to make the function more "library-friendly" by returning the errormessagetext instead of printing it:</p> <pre><code>def isTooLa...
0
2016-07-29T20:17:52Z
38,667,074
<pre><code>def isTooLarge(intValue): return "too large" if intValue &gt; 100 else False x = isTooLarge(101); x and print(x) </code></pre> <p>However. Please don't do this. Exceptions exist for a reason. Putting things in one line simply for the sake of it makes your code hard to read.</p>
0
2016-07-29T20:34:28Z
[ "python", "python-2.7" ]
Using a boolean in returned tuple for "if" statement?
38,666,852
<p>Current situation:</p> <pre><code>def isTooLarge(intValue): if intValue &gt; 100: print "too large"; return True return False if isTooLarge(101): break </code></pre> <p>Now I like to make the function more "library-friendly" by returning the errormessagetext instead of printing it:</p> <pre><code>def isTooLa...
0
2016-07-29T20:17:52Z
38,667,134
<p>You can be much more "library friendly" by using errors like they are meant for, as errors:</p> <pre><code>def CheckNotTooLarge(intValue): if intValue &gt; 100: raise ValueError("too large") #or AssertionError return #or maybe do something else? </code></pre> <p>then a user could use the error mess...
2
2016-07-29T20:40:06Z
[ "python", "python-2.7" ]
python: how to run a program with a command line call (that takes a user's keystroke as input) from within another program?
38,666,864
<p>I can run one program by typing: <code>python enable_robot.py -e</code> in the command line, but I want to run it from within another program.</p> <p>In the other program, I imported subprocess and had <code>subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])</code>, but I get an error m...
1
2016-07-29T20:18:39Z
38,666,985
<p>If <code>enable_robot.py</code> requires user input, probably it wasn't meant to run from another python script. you might want to import it as a module: <code>import enable_robot</code> and run the functions you want to use from there.</p> <p>If you want to stick to the subprocess, you can pass input with <code>co...
0
2016-07-29T20:27:43Z
[ "python", "ros" ]
python: how to run a program with a command line call (that takes a user's keystroke as input) from within another program?
38,666,864
<p>I can run one program by typing: <code>python enable_robot.py -e</code> in the command line, but I want to run it from within another program.</p> <p>In the other program, I imported subprocess and had <code>subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])</code>, but I get an error m...
1
2016-07-29T20:18:39Z
38,667,617
<p>Your program <code>enable_robot.py</code> should meet the following requirements:</p> <ul> <li>The first line is a path indicating what program is used to interpret the script. In this case, it is the python path.</li> <li>Your script should be executable</li> </ul> <h2>A very simple example. We have two python sc...
0
2016-07-29T21:16:35Z
[ "python", "ros" ]
What is the inverse of the numpy cumsum function?
38,666,924
<p>If I have <code>z = cumsum( [ 0, 1, 2, 6, 9 ] )</code>, which gives me <code>z = [ 0, 1, 3, 9, 18 ]</code>, how can I get back to the original array <code>[ 0, 1, 2, 6, 9 ]</code> ?</p>
10
2016-07-29T20:23:38Z
38,666,925
<p>Here is code that does that. Order will apply the function that many times. If the order is negative, it returns cumsum that many times.</p> <pre><code>import numpy as np def inverse_cumsum(z, order=1): # main part temp=[] for ind in xrange( len(z) ): try: temp.append( z[::-1][i...
2
2016-07-29T20:23:38Z
[ "python", "numpy", "cumsum" ]
What is the inverse of the numpy cumsum function?
38,666,924
<p>If I have <code>z = cumsum( [ 0, 1, 2, 6, 9 ] )</code>, which gives me <code>z = [ 0, 1, 3, 9, 18 ]</code>, how can I get back to the original array <code>[ 0, 1, 2, 6, 9 ]</code> ?</p>
10
2016-07-29T20:23:38Z
38,666,977
<pre><code>z[1:] -= z[:-1].copy() </code></pre> <p>Short and sweet, with no slow Python loops. We take views of all but the first element (<code>z[1:]</code>) and all but the last (<code>z[:-1]</code>), and subtract elementwise. The copy makes sure we subtract the original element values instead of the values we're co...
10
2016-07-29T20:27:10Z
[ "python", "numpy", "cumsum" ]
What is the inverse of the numpy cumsum function?
38,666,924
<p>If I have <code>z = cumsum( [ 0, 1, 2, 6, 9 ] )</code>, which gives me <code>z = [ 0, 1, 3, 9, 18 ]</code>, how can I get back to the original array <code>[ 0, 1, 2, 6, 9 ]</code> ?</p>
10
2016-07-29T20:23:38Z
38,666,999
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="nofollow"><code>np.diff</code></a> to compute elements <code>1...N</code> which will take the difference between any two elements. This is the opposite of <code>cumsum</code>. The only difference is that <code>diff</code> ...
5
2016-07-29T20:28:31Z
[ "python", "numpy", "cumsum" ]
What is the inverse of the numpy cumsum function?
38,666,924
<p>If I have <code>z = cumsum( [ 0, 1, 2, 6, 9 ] )</code>, which gives me <code>z = [ 0, 1, 3, 9, 18 ]</code>, how can I get back to the original array <code>[ 0, 1, 2, 6, 9 ]</code> ?</p>
10
2016-07-29T20:23:38Z
40,024,880
<p>My favorite:</p> <pre><code>orig = np.r_[z[0], np.diff(z)] </code></pre>
0
2016-10-13T15:16:05Z
[ "python", "numpy", "cumsum" ]
Pandas NLTK tokenizing "unhashable type: 'list'"
38,666,973
<p>Following this example: <a href="https://www.linkedin.com/pulse/twitter-data-mining-python-gephi-case-synthetic-biology-mikko-dufva" rel="nofollow">Twitter data mining with Python and Gephi: Case synthetic biology</a></p> <p><code>CSV to: df['Country', 'Responses']</code></p> <pre><code>'Country' Italy Italy Franc...
1
2016-07-29T20:26:57Z
38,667,176
<p>The <code>FreqDist</code> function takes in an iterable of hashable objects (made to be strings, but it probably works with whatever). The error you're getting is because you pass in an iterable of lists. As you suggested, this is because of the change you made:</p> <pre><code>df['tokenized_sents'] = df['Response...
1
2016-07-29T20:43:31Z
[ "python", "pandas", "nltk" ]
restarted computer and got: ImportError: No module named django.core.management
38,667,260
<p>I have been having some issues with gulp serving my files so I restarted my computer, upon going back to my project and starting the server I suddenly got the error: <code>ImportError: No module named django.core.management</code>. </p> <p>I am working locally and in my files I can see the django folder - it's path...
1
2016-07-29T20:49:56Z
38,667,411
<p>You're missing python packages which means you're <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">VirtualEnv</a> isn't activated.</p> <p><a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">VirtualEnv</a> creates a folder named <code>env</code> by default (though the name can be changed) wh...
2
2016-07-29T21:00:11Z
[ "python", "mysql", "django" ]
Understanding Python Tuples and Reassignments
38,667,266
<p>Ok, I do not think this question has been answered here before.</p> <p>I am wondering exactly how Python is executing this for loop. FYI this is a part of lesson 2 from 6.00SC MIT OCW:</p> <pre><code>def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. ...
-1
2016-07-29T20:50:20Z
38,667,626
<p>i is assigned to those numbers in the loop: 0,1,2,3,4 because xrange creates a range from 0 till the parameter minus 1. Parameter is len(poly) that returns 5 (the size of the array. Therefore i is assigned from 0 till 4(=5-1)</p> <p>First iteration i equals 0:</p> <p>poly[0] actually equals to the first element of...
1
2016-07-29T21:17:19Z
[ "python", "tuples", "variable-assignment" ]
Getting List object is not callable error on python 2.7, matplotlib
38,667,276
<p>Here is my code:</p> <pre><code>import numpy, math, time from matplotlib import pyplot def parse_FFT_hex(string): invert_arrays = True num_bits = 12 numpy.array = [] overflow = False ch_0_re = []; ch_0_im = []; ch_1_re = []; ch_1_im = [] for i in range(0,len(string), 32): # if any ...
-1
2016-07-29T20:51:02Z
38,667,482
<p>Your problem:</p> <pre><code>numpy.array = [] </code></pre> <p>Don't do that. You're turning <code>numpy.array</code> into a list. Remove that line and your code will work just fine, presumably.</p>
1
2016-07-29T21:05:49Z
[ "python", "python-2.7", "numpy", "matplotlib" ]
Using Concurrent.Futures.ProcessPoolExecutor to run simultaneous & independents ABAQUS models
38,667,290
<p>I wish to run a total of <strong><em>nAnalysis=25</em></strong> Abaqus models, each using X number of Cores, and I can run concurrently <strong><em>nParallelLoops=5</em></strong> of these models. If one of the current 5 analysis finishes, then another analysis should start until all <strong><em>nAnalysis</em></stron...
1
2016-07-29T20:51:57Z
38,668,070
<p>It looks OK to me, but I can't run your code as-is. How about trying something vastly simpler, then <em>add</em> things to it until "a problem" appears? For example, does the following show the kind of behavior you want? It does on my machine, but I'm running Python 3.5.2. You say you're running 2.7, but <code>c...
0
2016-07-29T21:59:02Z
[ "python", "multiprocessing", "python-multiprocessing", "concurrent.futures", "abaqus" ]
Using Concurrent.Futures.ProcessPoolExecutor to run simultaneous & independents ABAQUS models
38,667,290
<p>I wish to run a total of <strong><em>nAnalysis=25</em></strong> Abaqus models, each using X number of Cores, and I can run concurrently <strong><em>nParallelLoops=5</em></strong> of these models. If one of the current 5 analysis finishes, then another analysis should start until all <strong><em>nAnalysis</em></stron...
1
2016-07-29T20:51:57Z
38,677,673
<p>I introduced a loop in the <code>safeABQrun</code> and that managed the 5 different "queues". The loop is necessary to avoid the case of an analysis trying to run in a node while another one is still running. The analysis are pre-configured to run in one of the requested nodes before starting any actual analysis.</p...
0
2016-07-30T19:19:16Z
[ "python", "multiprocessing", "python-multiprocessing", "concurrent.futures", "abaqus" ]
function to return copy of np.array with some elements replaced
38,667,350
<p>I have a Numpy array and a list of indices, as well as an array with the values which need to go into these indices.</p> <p>The quickest way I know how to achieve this is:</p> <pre><code>In [1]: a1 = np.array([1,2,3,4,5,6,7]) In [2]: x = np.array([10,11,12]) In [3]: ind = np.array([2,4,5]) In [4]: a2 = np.copy(...
4
2016-07-29T20:56:22Z
38,667,778
<p>Well you asked for a one-liner, here's one using sparse matrices with <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow"><code>Scipy's csr_matrix</code></a> -</p> <pre><code>In [280]: a1 = np.array([1,2,3,4,5,6,7]) ...: x = np.array([10,11,12]) ...: i...
2
2016-07-29T21:31:54Z
[ "python", "python-2.7", "numpy" ]
Django rest framework GET all data but POST pk
38,667,368
<p>I am creating an API and trying to figure out how to return all data from my <code>Shipping</code> model into the GET method, but still sending the pk through the POST method.</p> <p>I already read some solutions <a href="http://stackoverflow.com/questions/34278408/django-rest-framework-dynamic-serializer-relation-...
0
2016-07-29T20:57:25Z
38,668,750
<p>If <code>get</code> and <code>post</code> are being handled by the same rest api view, I think you are using something like a <code>ViewSet</code> (or an appropriately mixed GenericAPIView). Your <code>ViewSet</code> will use a different serializer for getting and for posting.</p> <p>For getting/listing you will us...
1
2016-07-29T23:17:13Z
[ "python", "django", "django-rest-framework" ]
Pytest plugin: Overriding pytest_runtest_call and friends
38,667,429
<p>I'm developing a test suite using pytest for a project of mine. Because of the nature of the project, I need to create a Pytest plugin that controls how the tests are being run; they are not run locally, but sent to a different process to run. (I know about <code>xdist</code> but I think it doesn't solve my problem....
7
2016-07-29T21:01:09Z
38,823,263
<p><a href="http://doc.pytest.org/en/latest/writing_plugins.html#_pytest.hookspec.pytest_runtest_protocol" rel="nofollow">Generic “runtest” hooks</a></p> <p>All runtest related hooks receive a pytest.Item object.</p> <p>pytest_runtest_protocol(item, nextitem)[source]</p> <pre><code>implements the runtest_setup/c...
0
2016-08-08T07:14:55Z
[ "python", "plugins", "py.test" ]
Python use regex to match characters for number, letter, space and brackets
38,667,454
<p>I know that to match only numbers letters and space, I can use:</p> <pre><code>re.match(r'[A-Za-z0-9 ]+$', word) </code></pre> <p>but I would like to also match brackets such as <code>()</code>, <code>{}</code>, <code>[]</code>. I extended the above regex to :</p> <pre><code>re.match(r'[A-Z][a-z][0-9][ ][(][)][{]...
-2
2016-07-29T21:02:59Z
38,667,470
<p>The <code>r'[A-Z][a-z][0-9][ ][(][)][{][}][[][]]]+$'</code> matches a <em>sequence</em> of patterns defined:</p> <ul> <li><code>[A-Z]</code> - uppercase ASCII letters</li> <li><code>[a-z]</code> - lowercase ASCII letters</li> <li><code>[0-9]</code> - ASCII digits</li> <li><code>[ ]</code> - a space</li> <li><code>[...
4
2016-07-29T21:04:20Z
[ "python", "regex" ]
Python use regex to match characters for number, letter, space and brackets
38,667,454
<p>I know that to match only numbers letters and space, I can use:</p> <pre><code>re.match(r'[A-Za-z0-9 ]+$', word) </code></pre> <p>but I would like to also match brackets such as <code>()</code>, <code>{}</code>, <code>[]</code>. I extended the above regex to :</p> <pre><code>re.match(r'[A-Z][a-z][0-9][ ][(][)][{]...
-2
2016-07-29T21:02:59Z
38,669,326
<p>In non-Java character classes, the only special characters are the escape <code>\</code>,<br> the dash <code>-</code>, the caret <code>^</code>, and the closing bracket <code>]</code>. </p> <p>Of those - </p> <ul> <li><p>If the caret is not at the beginning, it's a literal,<br> at the beginning, its a negation.<...
0
2016-07-30T00:48:27Z
[ "python", "regex" ]
Pixely Rendering of latex using matplotlib
38,667,565
<p>In various cases whenever I use latex in matplotlib, I am getting a very pixely appearance when rendering the figure to an image. When I view the figure in interactive mode it looks fine. For example, I'm setting the yaxis label with:</p> <p>'Emissions Flux '+r'($\mathregular{(\mu g/m^2 s)}$'</p> <p>I'm also set...
1
2016-07-29T21:12:37Z
38,687,504
<p>I as far I understand the problem your images are too pixelated. Often this is the result of saving an image using a bitmap format. To receive better images one should export them to vector-graphs, like for example <code>pdf</code>.</p> <p>To export images as vector-graphs your save statement should be something li...
1
2016-07-31T19:09:03Z
[ "python", "matplotlib", "latex" ]
Python and R: how do you show a plot with Pyper in a Jupyter notebook?
38,667,572
<p>I am creating a report using Jupyter. Most of my code is in Python, but I need to use some R functionalities. </p> <p>I use a package called Pyper to call R in Python. It works well, but I could not figure out how to display a plot made in R (via Pyper) in the Jupiter notebook. Everything seems to work well, but Ju...
2
2016-07-29T21:13:14Z
38,667,975
<p>I have found a workaround if anyone is using Pyper and wants to add a plot to Jupyter:</p> <pre><code>from pyper import * r = R() r("library(TSA)") r("data(star)") # Save the figure r("png('rplot.png');periodogram(star);dev.off()") # Upload the figure to Jupyter from IPython.display import Image Image("rplot.pn...
1
2016-07-29T21:50:22Z
[ "python", "jupyter", "rpy2", "pyper" ]
wxPython dynamically add pages to wizard
38,667,611
<p>I have been working on developing a wxPython based wizard which I would like to be capable of dynamically increasing in size based on input provided within the wizard itself. This wizard progresses through a series of pages and then prompts the user to enter a number. The goal is to get the wizard to then increase...
0
2016-07-29T21:16:22Z
38,689,077
<p>You could just pass the Dynawiz instance to AddPage's constructor. Then AddPage can modify pageList. See below:</p> <pre><code>import wx import wx.wizard as wiz ######################################################################## #---------------------------------------------------------------------- # Wiz...
0
2016-07-31T22:59:57Z
[ "python", "wxpython", "wizard", "dynamically-generated" ]
Runtime error in Scikit-learn during import
38,667,659
<p>I am new to Python. So, sorry in advance if this sounds silly but I couldn't find an understandable solution in the forum. I am trying to run my programs in Pycharm and recently changed it from Python 3.5 to Python 2.7.12. After doing so I have started getting the below error while importing from Scikit-learn:</p> ...
0
2016-07-29T21:20:04Z
38,667,753
<p>It looks like you're still running out of <code>lib/python2.7/site-packages/</code>, per your error message. You need to configure your interpreter to use Anaconda for Python 3. If you've installed Anaconda correctly, you should be able to go to Settings -> NameOfYourProject -> Project Interpreter. Change the Interp...
1
2016-07-29T21:29:14Z
[ "python", "python-2.7", "python-3.x", "scikit-learn", "pycharm" ]
Django authentication LDAP unable to find user
38,667,685
<p>I'm working on a django project and I'm trying to authenticate my APP against LDAP server. settings.py:</p> <pre><code>AUTH_LDAP_SERVER_URI = "ldap://domain.local" AUTH_LDAP_BIND_DN = "domain\django" AUTH_LDAP_BIND_PASSWORD = "&lt;Password&gt;" AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=Users,dc=domain,dc=local", ...
0
2016-07-29T21:22:19Z
38,667,777
<p>Ok, I found the answer, my AD doesn't use UID but CN so instead of</p> <pre><code>AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=Users,dc=domain,dc=local", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") </code></pre> <p>I used</p> <pre><code>AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=Users,dc=domain,dc=local", ldap.SCOPE_SUBTREE, "(c...
0
2016-07-29T21:31:24Z
[ "python", "django", "ldap" ]
Python tkinter password checker gui - hashing issue
38,667,724
<p>I've almost finished my gui. Which is supposed to check an entered password for strength i.e how long it is, upper and lowercase, special characters etc... Hash that password into an md5 hash, store it in a text file. Then the user would re enter password, re-hashing would take place, then the text file checked to s...
0
2016-07-29T21:25:53Z
38,676,467
<p>In my previous example nothing was passed through the hexidigest to produce the Hash. I have amended the last part of the code and the gui now works as planned.</p> <p>The new code:</p> <pre><code>def verifyHash(): hash_obj2 = hashlib.md5() pwmd52 = vHash.get().encode('utf-8') hash_obj2.update(pwmd52)...
0
2016-07-30T17:07:43Z
[ "python", "user-interface", "hash", "tkinter", "md5" ]
Matplotlib Histogram scale y-axis by a constant factor
38,667,728
<p>Im plotting some values in a histogram and want to scale the y-axis but I only find ways to either normalize the y-axis values or to scale them logarithmically. My values are in 100ps timesteps and I want to multiply every y-axis value by 0.1 to get to a nice and easier to understand ns step size.</p> <p>How can I...
1
2016-07-29T21:26:10Z
38,669,541
<p>The way I would solve is very simple: just multiply your arrays values1 and values2 by 0.1 before plotting it. </p> <p>The reason why log-scaling exists in matplotlib is that log-transformations are very common. For simple multiplicative scaling, it is very easy to just multiply the array(s) that you are plotting.<...
0
2016-07-30T01:31:55Z
[ "python", "matplotlib" ]
return value in a dictionary that's within a list, the whole thing in a dictionary
38,667,733
<p>I have an empty table in SQL management studio that I’d like to populate with values for each sentence. The table has 3 columns – SentId, Word, Count.</p> <p>My sentence has this structure:</p> <pre><code>sentence = {‘features’: [{}, {}, {}…] , ‘id’: 1234} </code></pre> <p>-->To fill out SentId valu...
-3
2016-07-29T21:26:46Z
38,667,881
<p>As you can maybe see for yourself, sentence['features'] returns a list. Not a dictionary. In order to get an element from a list in Python, you need to index it.</p> <pre><code>a=[1,2,3] print(a[0]) #would print 1 </code></pre> <p>So in your case, that would lead to the following code:</p> <pre><code>print(senten...
0
2016-07-29T21:41:14Z
[ "python" ]
Recursive method to build a vector
38,667,745
<p>I have a simple recursive function:</p> <pre><code>def subTree(z,sublevels): if(z &lt; sublevels): print "from z = ", z, " to z = ", z+1 subTree(z+1,sublevels) else: print "z = ", z, " !" </code></pre> <p>this simply goes from z to sublevels, ex:</p> <pre><code>subTree(2, 6) from ...
-4
2016-07-29T21:28:12Z
38,667,858
<p>This code changes "a" list to [2,3,4,5,6]</p> <pre><code>def subTree(z,sublevels,a): a.append(z) if(z &lt; sublevels): subTree(z+1,sublevels,a) a=[] subTree(2,6,a) </code></pre>
0
2016-07-29T21:38:44Z
[ "python", "recursion" ]
Recursive method to build a vector
38,667,745
<p>I have a simple recursive function:</p> <pre><code>def subTree(z,sublevels): if(z &lt; sublevels): print "from z = ", z, " to z = ", z+1 subTree(z+1,sublevels) else: print "z = ", z, " !" </code></pre> <p>this simply goes from z to sublevels, ex:</p> <pre><code>subTree(2, 6) from ...
-4
2016-07-29T21:28:12Z
38,685,866
<p>I share keiv.fly's bias for a recursive function that returns a result:</p> <pre><code>def subTree(z, sublevels): result = [z] if z &lt; sublevels: result += subTree(z + 1, sublevels) return result a = subTree(2, 6) </code></pre> <p>It can be reduced to the slightly less efficient one-liner:...
1
2016-07-31T16:04:11Z
[ "python", "recursion" ]
python - factory function as static member of class to instantiate
38,667,756
<p>I have a class whose existence - or not - depends on the correctness of some input parameters.</p> <p><strong>QUESTION:</strong><br/> Would it be ok to create that factory function as a static member of the class I want an instance of? Is that the best way? </p> <p>I initially tried to do it inside the <code>__new...
0
2016-07-29T21:29:25Z
38,667,933
<p>An alternative to using @classmethod would be to put the factory function in the same file as the class.</p> <p>myclasses.py</p> <pre><code>def GetAMy(arg): if arg == 5: return None else: return MyClass(arg) class MyClass(object): ... </code></pre> <p>You then import the module from y...
0
2016-07-29T21:45:45Z
[ "python" ]
how to pass multiple lists of distributions to sklearn randomizedSearchCV
38,667,784
<p>I have a customized estimator object in Python (<code>mkl_regressor</code>). One of the learning parameters of such an object is a <code>numpy.array</code> of floats. Usually sklearn estimator objects are tuned by single parameters, like the <code>C</code> of a SVM. Thus the <code>randomizedSearchCV</code> search ob...
2
2016-07-29T21:32:30Z
38,669,597
<p>RandomizedSearchCV can take either a <strong>list of parameter values to try</strong> or a <strong>distribution object with an rvs method for sampling</strong>. If you pass it a list, it will assume you passed a discrete set of parameter values to sample from. It does not support a list of distributions for a single...
1
2016-07-30T01:44:02Z
[ "python", "scipy", "scikit-learn", "shogun" ]
how to pass multiple lists of distributions to sklearn randomizedSearchCV
38,667,784
<p>I have a customized estimator object in Python (<code>mkl_regressor</code>). One of the learning parameters of such an object is a <code>numpy.array</code> of floats. Usually sklearn estimator objects are tuned by single parameters, like the <code>C</code> of a SVM. Thus the <code>randomizedSearchCV</code> search ob...
2
2016-07-29T21:32:30Z
38,676,863
<p>The solution @bpachev suggested worked for me. The distribution class:</p> <pre><code>class expon_vector(stats.rv_continuous): def __init__(self, loc = 1.0, scale = 50.0, min_size=2, max_size = 10): self.loc = loc self.scale = scale self.min_size = min_size self.max_size = max_s...
0
2016-07-30T17:53:34Z
[ "python", "scipy", "scikit-learn", "shogun" ]
Comparing complicated lists
38,667,785
<p>So I've got a function in python that has a list containing lists and I'm trying to compare the contents of the list to see if I have a duplicate within it, and then return True if there are duplicates. Essentially something like this;</p> <pre><code>def dupCheck(): aList = ([3.3,3.2], [1,1], [3.3,3.2], [7,7])...
0
2016-07-29T21:32:35Z
38,667,885
<p>Normally when checking whether a list has duplicates, you would just create a <code>set</code> from the list, thus removing the duplicates, and then compare the size of that set to the size of the original list. In this case this is not possible, as the nested lists are not hashable and can thus not be added to a se...
2
2016-07-29T21:41:40Z
[ "python", "list", "duplicates" ]
Comparing complicated lists
38,667,785
<p>So I've got a function in python that has a list containing lists and I'm trying to compare the contents of the list to see if I have a duplicate within it, and then return True if there are duplicates. Essentially something like this;</p> <pre><code>def dupCheck(): aList = ([3.3,3.2], [1,1], [3.3,3.2], [7,7])...
0
2016-07-29T21:32:35Z
38,668,041
<p>You can do it lazily, returning True on the first duplicate in place of creating a whole set first:</p> <pre><code>def dup_check(lst): seen = set() for tup in map(tuple, lst): if tup in seen: return True seen.add(tup) return False </code></pre> <p>To keep lazy evaluation you...
4
2016-07-29T21:55:51Z
[ "python", "list", "duplicates" ]
Comparing complicated lists
38,667,785
<p>So I've got a function in python that has a list containing lists and I'm trying to compare the contents of the list to see if I have a duplicate within it, and then return True if there are duplicates. Essentially something like this;</p> <pre><code>def dupCheck(): aList = ([3.3,3.2], [1,1], [3.3,3.2], [7,7])...
0
2016-07-29T21:32:35Z
38,674,175
<p>A solution to the list of list problem:</p> <pre><code>def remove_doubles(a): """Removes list doubles in list where list(set(a)) will raise a TypeError.""" clean_list = [] for b in a: if b not in clean_list: clean_list += [b] return clean_list </code></pre>
1
2016-07-30T12:52:06Z
[ "python", "list", "duplicates" ]
matplotlib aggregate multiple points of a series within a pixel
38,667,838
<p>I have a pandas series ts with index in datetime and its resolution is 1s; this time series spans 23 hours. I am trying to plot this on multiple charts with a config parameter chart_sec (how many secs showing up in one chart) with a fixed dpi=20; the resolution may not be enough to plot every single point of ts in t...
1
2016-07-29T21:37:10Z
38,763,416
<p>One idea if you need to distinguish the points is to save the figure at large size and high dpi. I'm guessing a bit what your data looks like from your example.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt ts = pd.DataFrame(50*pd.np.random.rand(7200)+pd.np.array(range(7200)), ...
0
2016-08-04T09:23:35Z
[ "python", "matplotlib" ]
Comparing data from one fetch request with another
38,667,931
<p>I have three postgres tables: users, files, and likes.</p> <p>The users table has a one to many relationship with the files table.<br> The files table has a one to many relationship with the likes table. </p> <p>My application has a feed with two sections: "community" and "likes". The "community" section consist...
0
2016-07-29T21:45:36Z
38,668,643
<p>Check for liked in the first query:</p> <pre><code>cur.execute(''' select f.*, u.username, l.user_id is not null as liked from files f inner join users u on u.id = f.user_id left join likes l on l.user_id = u.id and f.share = true where u.id = %s order by f.id...
0
2016-07-29T23:02:08Z
[ "python", "postgresql" ]
Extract text files into multiple columns in python
38,667,951
<p>I have different text files and I want to extract the values from there into a csv file. Each file has the following format</p> <pre><code>main cost: 30 additional cost: 5 </code></pre> <p>I managed to do that but the problem that I want it to insert the values of each file into a different columns I also want the...
0
2016-07-29T21:47:53Z
38,668,038
<p>You could use a dictionary to do this where the key will be the "header" you want to use and the value be a list.</p> <p>So it would look like <code>someDict = {'main cost': [30,40], 'additional cost': [5,10]}</code></p> <p>edit2: Went ahead and cleaned up this answer so it makes a little more sense.</p> <p>You c...
2
2016-07-29T21:55:48Z
[ "python", "csv", "extract", "multiple-columns" ]
Extract text files into multiple columns in python
38,667,951
<p>I have different text files and I want to extract the values from there into a csv file. Each file has the following format</p> <pre><code>main cost: 30 additional cost: 5 </code></pre> <p>I managed to do that but the problem that I want it to insert the values of each file into a different columns I also want the...
0
2016-07-29T21:47:53Z
38,668,799
<p>This is how I might do it. Assumes the fields are the same in all the files. Make a list of names, and a dictionary using those field names as keys, and the list of values as the entries. Instead of running on <code>file1.text</code>, <code>file2.text</code>, etc. run the script with <code>file*.text</code> as a com...
0
2016-07-29T23:23:41Z
[ "python", "csv", "extract", "multiple-columns" ]
Identifying a key in one dict, and using it to modify values of another dict
38,668,066
<p>For a text-based RPG I'm creating, I have dictionaries outlining various in-game religions, races, etc. Some values of these religions include buffs for player's stats, e.g.: </p> <pre><code>religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 'abili...
0
2016-07-29T21:58:40Z
38,668,154
<p>This adds a method to <code>Player</code> that assigns the values from your dictionary to player stats. It uses <code>get</code> to ensure that the value is in the dictionary and that it contains the field <code>buffs</code>. If so, it gets the values for <code>intelligence</code> and <code>defense</code> and adds...
1
2016-07-29T22:07:02Z
[ "python", "dictionary" ]
Identifying a key in one dict, and using it to modify values of another dict
38,668,066
<p>For a text-based RPG I'm creating, I have dictionaries outlining various in-game religions, races, etc. Some values of these religions include buffs for player's stats, e.g.: </p> <pre><code>religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 'abili...
0
2016-07-29T21:58:40Z
38,668,177
<p>Here is a sketch of how you would go about this:</p> <pre><code>religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 'abilities': [...], 'description': '...'}} buffs = religion_Dict['Way of the White']['buffs'] f...
2
2016-07-29T22:09:42Z
[ "python", "dictionary" ]
Identifying a key in one dict, and using it to modify values of another dict
38,668,066
<p>For a text-based RPG I'm creating, I have dictionaries outlining various in-game religions, races, etc. Some values of these religions include buffs for player's stats, e.g.: </p> <pre><code>religion_Dict = {'Way of the White': {'buffs': {'intelligence': 5, 'defense': 3}, 'abili...
0
2016-07-29T21:58:40Z
38,668,184
<pre><code>self.stats = religion_Dict['Way of the White']['buffs'] </code></pre>
0
2016-07-29T22:10:21Z
[ "python", "dictionary" ]
Temp Conversation fahrenheit to celsius
38,668,343
<p>I am trying to convert Temperature from fahrenheit to celsius and vice-versa. The ">>>>" which converts fahrenheit to Celsius doesn't function while the Celsius do Fahrenheit button functions. Please assist, I think I have been looking at the code for too long that's why I can't figure it out. </p> <pre><code>from...
-1
2016-07-29T22:26:46Z
38,668,435
<p>Your issue has to do with how division works in Python 2.</p> <p>Compare:</p> <pre><code>a=(5/9) b=(5/9.0) </code></pre> <p>In the first case, the result is an integer. In the second case, it is a float. If you divide two integers, it will return an integer that is rounded down, in your case to 0, resulting in a ...
3
2016-07-29T22:36:11Z
[ "python", "python-2.7", "tkinter" ]
Memory Usage, Filling Pandas DataFrame using Dict vs using key and value Lists
38,668,376
<p>I am making a package that reads a binary file and returns data that can be used to initialize a <code>DataFrame</code>, I am now wondering if it is best to return a <code>dict</code> or two lists (one that holds the keys and one that holds the values). </p> <p>The package I am making is not supposed to be entirely...
3
2016-07-29T22:30:40Z
38,669,276
<p>I made memory profiling of 1M rows. The winning structure is to use array.array for every numerical index and a list for strings (147MB data and 310MB conversion to pandas).</p> <p>According to Python manual </p> <blockquote> <p>Arrays are sequence types and behave very much like lists, except that the type of...
3
2016-07-30T00:40:50Z
[ "python", "performance", "list", "pandas", "dictionary" ]
Memory Usage, Filling Pandas DataFrame using Dict vs using key and value Lists
38,668,376
<p>I am making a package that reads a binary file and returns data that can be used to initialize a <code>DataFrame</code>, I am now wondering if it is best to return a <code>dict</code> or two lists (one that holds the keys and one that holds the values). </p> <p>The package I am making is not supposed to be entirely...
3
2016-07-29T22:30:40Z
38,669,402
<p>Here are the benchmarks using <code>memory_profiler</code>:</p> <pre><code>Filename: testdict.py Line # Mem usage Increment Line Contents ================================================ 4 66.2 MiB 0.0 MiB @profile 5 def testdict(): 6 7 66.2 Mi...
0
2016-07-30T01:04:48Z
[ "python", "performance", "list", "pandas", "dictionary" ]
Need help outtping json with python
38,668,389
<p>Im in need of help outputting the json key with python. I tried to output the name "carl".</p> <p>Python code : </p> <pre><code> from json import loads import json,urllib2 class yomamma: def __init__(self): url = urlopen('http://localhost/name.php').read() name = loads(url) print "Hello" (nam...
1
2016-07-29T22:31:44Z
38,668,426
<p>I'll just assume the PHP code works correctly, I don't know PHP very well.</p> <p>On the client, I recommend using <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> (installable through <code>pip install requests</code>):</p> <pre><code>import requests r = requests.get(...
1
2016-07-29T22:35:28Z
[ "php", "python", "json" ]
Need help outtping json with python
38,668,389
<p>Im in need of help outputting the json key with python. I tried to output the name "carl".</p> <p>Python code : </p> <pre><code> from json import loads import json,urllib2 class yomamma: def __init__(self): url = urlopen('http://localhost/name.php').read() name = loads(url) print "Hello" (nam...
1
2016-07-29T22:31:44Z
38,668,470
<p>try this:</p> <pre><code>import json person_data = json.loads(url) print "Hello {}".format(person_data["person_one"]) </code></pre>
0
2016-07-29T22:40:33Z
[ "php", "python", "json" ]
how to share a javascript websocket instance with multiple html files
38,668,391
<p>I am using websockets in javascript and python flask. </p> <p>I have a websocket server to which i connect my webpage using javascript websockets. The "/" contains a form that contain the ip address of the websocket server, and "/connectToServer" route will establish a websocket connection with the server. </p> <p...
-1
2016-07-29T22:31:55Z
38,669,022
<p>You would need something to make your page persistent. </p> <p>Client-side libraries such as <a href="https://angularjs.org/" rel="nofollow">Angular</a> or <a href="https://vuejs.org/" rel="nofollow">Vue</a> (just two random examples) will do the job. </p> <p>However you should look into a tutorial or something si...
0
2016-07-29T23:56:45Z
[ "javascript", "python", "flask", "websocket" ]
PIL not saving PNG images correctly on windows
38,668,429
<p>I am trying to save an image as a PNG using PIL on python. It works great on any Linux machine I try, but when I try a Windows machine the output images is completely transparent. If I try to save it as a JPEG it works fine. Any ideas?</p> <pre><code>bg1 = Image.new('RGBA', screen_size, (255,255,255,0)) ... bg1.sav...
0
2016-07-29T22:35:53Z
39,329,317
<p>When you create the new image, the fourth component of your RGBA values is the alpha. By setting it to 0 you are telling every pixel to be completely transparent. Try setting it to 255 if you don't actually want any transparency:</p> <pre><code>bg1 = Image.new('RGBA', screen_size, (255,255,255,255)) </code></pre>
0
2016-09-05T11:09:40Z
[ "python", "python-imaging-library", "pillow" ]
Efficient way to find the shortest distance between two arrays?
38,668,482
<p>I am trying to find the shortest distance between two sets of arrays. The x- arrays are identical and just contain integers. Here is an example of what I am trying to do:</p> <pre><code>import numpy as np x1 = x2 = np.linspace(-1000, 1000, 2001) y1 = (lambda x, a, b: a*x + b)(x1, 2, 1) y2 = (lambda x, a, b: a*(x-2)...
0
2016-07-29T22:41:55Z
38,668,562
<p>This is a difficult problem, and it may help if you are willing to accept approximations. I would check out something like Spottify's <a href="https://github.com/spotify/annoy" rel="nofollow">annoy</a>.</p>
0
2016-07-29T22:51:43Z
[ "python", "arrays", "numpy", "runtime", "ipython" ]
Efficient way to find the shortest distance between two arrays?
38,668,482
<p>I am trying to find the shortest distance between two sets of arrays. The x- arrays are identical and just contain integers. Here is an example of what I am trying to do:</p> <pre><code>import numpy as np x1 = x2 = np.linspace(-1000, 1000, 2001) y1 = (lambda x, a, b: a*x + b)(x1, 2, 1) y2 = (lambda x, a, b: a*(x-2)...
0
2016-07-29T22:41:55Z
38,668,619
<p>Your problem could also be represented as 2d collision detection, so a <a href="https://en.wikipedia.org/wiki/Quadtree" rel="nofollow">quadtree</a> might help. Insertion and querying both run in O(log n) time, so the whole search would run in O(n log n). </p> <p>One more suggestion, since sqrt is monotonic, you can...
1
2016-07-29T22:58:14Z
[ "python", "arrays", "numpy", "runtime", "ipython" ]
Efficient way to find the shortest distance between two arrays?
38,668,482
<p>I am trying to find the shortest distance between two sets of arrays. The x- arrays are identical and just contain integers. Here is an example of what I am trying to do:</p> <pre><code>import numpy as np x1 = x2 = np.linspace(-1000, 1000, 2001) y1 = (lambda x, a, b: a*x + b)(x1, 2, 1) y2 = (lambda x, a, b: a*(x-2)...
0
2016-07-29T22:41:55Z
38,670,721
<p><code>scipy</code> has a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>cdist</code> function</a> which calculates distance between all pairs of points:</p> <pre><code>from scipy.spatial.distance import cdist import numpy as np x1 = x2 = np.lin...
1
2016-07-30T05:42:55Z
[ "python", "arrays", "numpy", "runtime", "ipython" ]
Return all keys along with value in nested dictionary
38,668,680
<p>I am working on getting all text that exists in several <code>.yaml</code> files placed into a new singular YAML file that will contain the English translations that someone can then translate into Spanish.</p> <p>Each YAML file has a lot of nested text. I want to print the full 'path', aka all the keys, along with...
1
2016-07-29T23:07:58Z
38,668,875
<p>What you're wanting to do is flatten nested dictionaries. This would be a good place to start: <a href="http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys">Flatten nested Python dictionaries, compressing keys</a></p> <p>In fact, I think the code snippet in the top answer...
0
2016-07-29T23:33:56Z
[ "python", "dictionary", "recursion", "pyyaml" ]
Return all keys along with value in nested dictionary
38,668,680
<p>I am working on getting all text that exists in several <code>.yaml</code> files placed into a new singular YAML file that will contain the English translations that someone can then translate into Spanish.</p> <p>Each YAML file has a lot of nested text. I want to print the full 'path', aka all the keys, along with...
1
2016-07-29T23:07:58Z
38,668,894
<p>Keep a simple list of strings, being the most recent key at each indentation depth. When you progress from one line to the next with no change, simply change the item at the end of the list. When you "out-dent", pop the last item off the list. When you indent, append to the list.</p> <p>Then, each time you hit a...
0
2016-07-29T23:35:59Z
[ "python", "dictionary", "recursion", "pyyaml" ]
Return all keys along with value in nested dictionary
38,668,680
<p>I am working on getting all text that exists in several <code>.yaml</code> files placed into a new singular YAML file that will contain the English translations that someone can then translate into Spanish.</p> <p>Each YAML file has a lot of nested text. I want to print the full 'path', aka all the keys, along with...
1
2016-07-29T23:07:58Z
38,670,751
<p>Walking over nested dictionaries begs for recursion and by handing in the "prefix" to "path" this prevents you from having to do any manipulation on the segments of your path (as @Prune) suggests.</p> <p>There are a few things to keep in mind that makes this problem interesting:</p> <ul> <li>because you are using ...
0
2016-07-30T05:46:52Z
[ "python", "dictionary", "recursion", "pyyaml" ]
Tokenizing a huge quantity of text in python
38,668,717
<p>I have a huge list of text files to tokenize. I have the following code which works for a small dataset. I am having trouble using the same procedure with a huge dataset, however. I am giving the example of a small dataset as below.</p> <pre><code>In [1]: text = [["It works"], ["This is not good"]] In [2]: tokens...
0
2016-07-29T23:13:17Z
38,668,948
<p>You could create a <code>set</code> of unique words, then loop through and count each of those...</p> <pre><code>#! /usr/bin/env python text = [["It works works"], ["It is not good this"]] SplitList = [x[0].split(" ") for x in text] FlattenList = sum(SplitList,[]) # "trick" to flatten a list UniqueList = list...
1
2016-07-29T23:44:18Z
[ "python", "string", "nlp", "tokenize" ]
Tokenizing a huge quantity of text in python
38,668,717
<p>I have a huge list of text files to tokenize. I have the following code which works for a small dataset. I am having trouble using the same procedure with a huge dataset, however. I am giving the example of a small dataset as below.</p> <pre><code>In [1]: text = [["It works"], ["This is not good"]] In [2]: tokens...
0
2016-07-29T23:13:17Z
38,670,117
<p>There are lots of available tokenizers that are optimized. I would look at <code>CountVectorizer</code> in <code>sklearn</code>, which is built for counting tokens. </p> <p>You could also use <code>nltk</code> or <code>textblob</code>, if you want more options. The latter is faster, in my experience.</p>
0
2016-07-30T03:36:10Z
[ "python", "string", "nlp", "tokenize" ]
Pandas drop the first few rows contain nan in each group
38,668,737
<p>I have a panel data, I would like to drop the first (few) row(s) which contain NaN in each group. (Or some general method which could drop based on the index within the group and other conditions.)</p> <pre><code>df = pd.DataFrame( {'ID': [10001, 10001, 10001, 10002, 10002, 10002, 10003, 10003, 10003, 10003], 'PRI...
2
2016-07-29T23:16:07Z
38,668,904
<p>This is a way to do it:</p> <pre><code>notnull = df.PRICE.notnull() protected = df.index &gt; df.PRICE.last_valid_index() df[notnull | protected] </code></pre> <p><a href="http://i.stack.imgur.com/2dew3.png" rel="nofollow"><img src="http://i.stack.imgur.com/2dew3.png" alt="enter image description here"></a></p>
2
2016-07-29T23:37:47Z
[ "python", "pandas", "panel" ]
Pandas drop the first few rows contain nan in each group
38,668,737
<p>I have a panel data, I would like to drop the first (few) row(s) which contain NaN in each group. (Or some general method which could drop based on the index within the group and other conditions.)</p> <pre><code>df = pd.DataFrame( {'ID': [10001, 10001, 10001, 10002, 10002, 10002, 10003, 10003, 10003, 10003], 'PRI...
2
2016-07-29T23:16:07Z
38,672,921
<p>alternatve approach using custom ranking:</p> <pre><code>In [49]: %paste df[df.assign(x=np.where(pd.isnull(df.PRICE), 1, np.nan)) .groupby('ID').x.cumsum().fillna(np.inf) &gt; 1 ] ## -- End pasted text -- Out[49]: ID PRICE date 2 10001 11.500 19920106 3 10001 14.310 19920107 4 10002 15.125...
0
2016-07-30T10:34:55Z
[ "python", "pandas", "panel" ]
Pandas drop the first few rows contain nan in each group
38,668,737
<p>I have a panel data, I would like to drop the first (few) row(s) which contain NaN in each group. (Or some general method which could drop based on the index within the group and other conditions.)</p> <pre><code>df = pd.DataFrame( {'ID': [10001, 10001, 10001, 10002, 10002, 10002, 10003, 10003, 10003, 10003], 'PRI...
2
2016-07-29T23:16:07Z
38,685,680
<p>Thank you for your helps, but I think neither of the answers fit my task. </p> <p>I figured out a solution myself, by creating a subindex column.</p> <pre><code>df = pd.DataFrame( {'ID': [10001, 10001, 10001, 10001, 10002, 10002, 10002, 10003, 10003, 10003, 10003], 'PRICE': [None, 11.5, None, 14.31, 15.125, 14.44...
0
2016-07-31T15:47:33Z
[ "python", "pandas", "panel" ]
Nested "ifs" on pandas df columns
38,668,788
<p>I have a pandas df called data.</p> <p>I want to do something like:</p> <pre><code>for i in range(data["col1"].count()): if data["col1"][i] &gt; 25: count1 += 1 if data["col2"][i] &gt; 35: count2 += 1 </code></pre> <p>and possibly with more columns so that I can keep track of when several conditio...
3
2016-07-29T23:22:38Z
38,668,851
<p>This is a better way to go:</p> <pre><code>cond1 = data.col1 &gt; 25 cond2 = data.col2 &gt; 35 count1 = cond1.sum() count2 = (cond1 &amp; cond2).sum() </code></pre>
4
2016-07-29T23:30:24Z
[ "python", "pandas" ]
Nested "ifs" on pandas df columns
38,668,788
<p>I have a pandas df called data.</p> <p>I want to do something like:</p> <pre><code>for i in range(data["col1"].count()): if data["col1"][i] &gt; 25: count1 += 1 if data["col2"][i] &gt; 35: count2 += 1 </code></pre> <p>and possibly with more columns so that I can keep track of when several conditio...
3
2016-07-29T23:22:38Z
38,668,953
<pre><code>count1 = df[df["col1"] &gt; 25].count().values count2 = df[(df["col1"]&gt; 25) &amp; (df["col2"]&gt;35)].count().values print count1 print count2 </code></pre>
1
2016-07-29T23:44:47Z
[ "python", "pandas" ]
PEG Online Judge Coding
38,668,807
<p>I am solving a problem on the PEG Online Judge, which is a site where you can solve lots of problems for practice and fun.</p> <p>I am having trouble with one in particular. I have posted there for help but am not receiving any.</p> <p>It is the Caporegime problem: <a href="http://wcipeg.com/problem/capos" rel="n...
-2
2016-07-29T23:24:18Z
38,718,477
<p>Ok, so I've finally solved this.</p> <p>Basically I needed to use a DFS approach, it can't really be solved (withing the online Judge's memory and time constraints) via BFS.</p> <p>The advantage of DFS is twofold: 1) I can reach a solution (not the best solution) fairly quickly and use this to prune the tree, to g...
0
2016-08-02T10:54:40Z
[ "python", "algorithm", "data-structures", "breadth-first-search" ]
constrain a series or array to a range of values
38,668,814
<p>I have a series of values that I want to have constrained to be within +1 and -1.</p> <pre><code>s = pd.Series(np.random.randn(10000)) </code></pre> <p>I know I can use <code>apply</code>, but is there a simple vectorized approach?</p> <pre><code>s_ = s.apply(lambda x: min(max(x, -1), 1)) s_.head() 0 -0.256117...
3
2016-07-29T23:25:23Z
38,668,821
<p>Use nested <code>np.where</code></p> <pre><code>pd.Series(np.where(s &lt; -1, -1, np.where(s &gt; 1, 1, s))) </code></pre> <hr> <h3>Timing</h3> <p><a href="http://i.stack.imgur.com/Auz4d.png" rel="nofollow"><img src="http://i.stack.imgur.com/Auz4d.png" alt="enter image description here"></a></p>
2
2016-07-29T23:26:04Z
[ "python", "numpy", "pandas" ]
constrain a series or array to a range of values
38,668,814
<p>I have a series of values that I want to have constrained to be within +1 and -1.</p> <pre><code>s = pd.Series(np.random.randn(10000)) </code></pre> <p>I know I can use <code>apply</code>, but is there a simple vectorized approach?</p> <pre><code>s_ = s.apply(lambda x: min(max(x, -1), 1)) s_.head() 0 -0.256117...
3
2016-07-29T23:25:23Z
38,668,858
<p>Use <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.Series.clip.html" rel="nofollow"><code>clip</code></a>:</p> <pre><code>s = s.clip(-1,1) </code></pre> <p>Example Input:</p> <pre><code>s = pd.Series([-1.2, -0.5, 1, 1.1]) 0 -1.2 1 -0.5 2 1.0 3 1.1 </code></pre> <p>Exampl...
4
2016-07-29T23:31:47Z
[ "python", "numpy", "pandas" ]
constrain a series or array to a range of values
38,668,814
<p>I have a series of values that I want to have constrained to be within +1 and -1.</p> <pre><code>s = pd.Series(np.random.randn(10000)) </code></pre> <p>I know I can use <code>apply</code>, but is there a simple vectorized approach?</p> <pre><code>s_ = s.apply(lambda x: min(max(x, -1), 1)) s_.head() 0 -0.256117...
3
2016-07-29T23:25:23Z
38,668,861
<p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> Series method:</p> <pre><code>In [11]: s[s.between(-1, 1)] Out[11]: 0 -0.256117 1 0.879797 3 -0.711397 4 -0.400339 5 0.667196 ... </code></pre> <p>Note: Thi...
1
2016-07-29T23:32:07Z
[ "python", "numpy", "pandas" ]
constrain a series or array to a range of values
38,668,814
<p>I have a series of values that I want to have constrained to be within +1 and -1.</p> <pre><code>s = pd.Series(np.random.randn(10000)) </code></pre> <p>I know I can use <code>apply</code>, but is there a simple vectorized approach?</p> <pre><code>s_ = s.apply(lambda x: min(max(x, -1), 1)) s_.head() 0 -0.256117...
3
2016-07-29T23:25:23Z
38,669,142
<p>One more suggestion:</p> <pre><code>s[s&lt;-1] = -1 s[s&gt;1] = 1 </code></pre>
0
2016-07-30T00:15:01Z
[ "python", "numpy", "pandas" ]
Queue implementation in python gives error on size
38,669,099
<p>I'm new to Python, thus the question. This is my implementation of a Queue</p> <pre><code>class Queue: def __init__(self): self.top = None self.marker = None self.size = 0 def push(self, item): self.size += 1 curr = Node(item) if self.top is None: ...
0
2016-07-30T00:07:00Z
38,669,127
<p>You gave an attribute and a method the same name, <strong>size</strong>. This confuses name resolution (to you; the interpreter has its rules tightly in place). Check your name resolution precedence; I think you'll find that the attribute takes precedence in this case. Thus, <strong>queue.size</strong> resolves t...
1
2016-07-30T00:12:46Z
[ "python", "queue" ]
Can set accept-language header but not Connection header? PhantomJS (Selenium Webdriver with Python)
38,669,108
<p>I'm able to set the Accept-Language header , but somehow I'm unable to set the Connection header to "keep-alive": </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders...
5
2016-07-30T00:08:38Z
39,131,180
<p>Looks like the default header for phantomjs connection is Keep-alive, the site you are using to view headers does not show the Connection header, even when not using PhantomJS. If you look at your request using Fiddler, you can see that it has the connection keep-alive header</p> <p>GET /headers HTTP/1.1 Accept: ...
2
2016-08-24T19:02:41Z
[ "python", "selenium", "http-headers", "phantomjs" ]
Python Subprocess Failure After A Certain Quantity of Data
38,669,125
<p>I am using Python and Java together for some scientific computing. Python sends permutations to the Java code to be processed. I use the subprocess object with piped data in and out. This system works great up until about 75k permuations. At that point it crashes. The strangest thing is how consistently it occurs at...
2
2016-07-30T00:12:25Z
38,670,281
<p>Some things to try:</p> <ol> <li>Change BATCH_SIZE to something very small. Does the program still crash? Does the program crash after the same number of iterations through the loop as before, or does it crash after the same number of records have been processed?</li> </ol> <p>I suspect you are leaking a thread on...
2
2016-07-30T04:15:13Z
[ "python", "multithreading", "pipe", "subprocess" ]
Authorizing a python script to access the GData API without the OAuth2 user flow
38,669,200
<p>I'm writing a small python script that will retrieve a list of my Google Contacts (using the <a href="https://developers.google.com/google-apps/contacts/v3/" rel="nofollow">Google Contacts API</a>) and will randomly suggest one person for me to contact (good way to automate keeping in touch with friends!)</p> <p>Th...
0
2016-07-30T00:24:30Z
38,669,860
<p>The implementation you're describing invokes the full "three-legged" OAuth handshake, which requires explicit user consent. If you don't need user consent, you can instead utilize "two-legged" OAuth via a <a href="https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances" rel="nofollo...
1
2016-07-30T02:38:29Z
[ "python", "gdata", "oauth2" ]