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
Tree structure for expectiminimax algorithm
38,621,382
<p>So I don't have much formal computer science education, so I apologize in advance if this is a stupid question. </p> <p>I'm currently writing a dice poker game in Python. The rules are <em>not</em> like <a href="http://witcher.wikia.com/wiki/Dice_poker_in_The_Witcher" rel="nofollow">the game found in The Witcher 2<...
1
2016-07-27T19:15:24Z
38,621,566
<p>As far as I can see the layering is correct. I did something similar some time ago and I think you can implement it without the tree datastructure, it should be doable and is likely more cleaner since you don't need a chance type.</p>
0
2016-07-27T19:26:05Z
[ "python", "tree", "artificial-intelligence", "minimax" ]
"Literally" convert a String into a bytearray
38,621,499
<p>I have a small server sending raw data with a socket in python which only accepts bytearrays as input. In this bytearray I have to include mac-addresses. These mac-addresses come from a json-file, imported as a string. e.g "00 11 22 33 44 55" (actually without the spaces)</p> <p>what i am searching for is an easy w...
1
2016-07-27T19:21:57Z
38,621,747
<p>Just split the string up into chunks of 2 characters, and interpret the hex value.</p> <pre><code>def str2bytes(string): return tuple(int(string[i:i+2], 16) for i in range(0, len(string), 2)) print str2bytes("001122334455") #(0, 17, 34, 51, 68, 85) </code></pre> <p>If you are looking to have a string...
1
2016-07-27T19:36:56Z
[ "python", "python-3.x" ]
"Literally" convert a String into a bytearray
38,621,499
<p>I have a small server sending raw data with a socket in python which only accepts bytearrays as input. In this bytearray I have to include mac-addresses. These mac-addresses come from a json-file, imported as a string. e.g "00 11 22 33 44 55" (actually without the spaces)</p> <p>what i am searching for is an easy w...
1
2016-07-27T19:21:57Z
38,621,816
<p>Your conversion isn't so literal as you think.</p> <p>String "00112233445566" is 12 characters long, this why it converts to 12 bytes array.</p> <p>Your mac looks like hex encoded byte string, so probably you can use this:</p> <pre><code>bytes.fromhex( "001122334455" ) </code></pre> <p>It will create byte sequen...
2
2016-07-27T19:41:02Z
[ "python", "python-3.x" ]
"Literally" convert a String into a bytearray
38,621,499
<p>I have a small server sending raw data with a socket in python which only accepts bytearrays as input. In this bytearray I have to include mac-addresses. These mac-addresses come from a json-file, imported as a string. e.g "00 11 22 33 44 55" (actually without the spaces)</p> <p>what i am searching for is an easy w...
1
2016-07-27T19:21:57Z
38,621,826
<p>This is actually built-in! It's <a href="https://docs.python.org/3/library/binascii.html#binascii.unhexlify" rel="nofollow"><code>binascii.unhexlify</code></a>.</p> <pre><code>import binascii binascii.unhexlify('001122334455') </code></pre>
0
2016-07-27T19:41:32Z
[ "python", "python-3.x" ]
"Literally" convert a String into a bytearray
38,621,499
<p>I have a small server sending raw data with a socket in python which only accepts bytearrays as input. In this bytearray I have to include mac-addresses. These mac-addresses come from a json-file, imported as a string. e.g "00 11 22 33 44 55" (actually without the spaces)</p> <p>what i am searching for is an easy w...
1
2016-07-27T19:21:57Z
38,621,830
<p><a href="https://docs.python.org/3/library/binascii.html#binascii.a2b_hex" rel="nofollow">https://docs.python.org/3/library/binascii.html#binascii.a2b_hex</a></p> <pre><code>import binascii def str2bytes(string): return binascii.a2b_hex(string) print(str2bytes("001122334455")) </code></pre>
0
2016-07-27T19:41:47Z
[ "python", "python-3.x" ]
python take input when number of input is not specified
38,621,513
<p>I am new to python and trying to solve a problem in SPOJ ,</p> <p>In this question number of input(maximum 10 is specified, how ever it could be anything between 1 to 10) is not specified hence it gives NZEC error</p> <p>I tried this:</p> <pre><code>t = 10 while(t&gt;0): t = t - 1 n = raw_input() if(le...
-1
2016-07-27T19:22:42Z
38,621,838
<p>Solved Use </p> <pre><code>try: while True: n = int(raw_input()) #do something except: pass </code></pre>
0
2016-07-27T19:42:20Z
[ "python", "eof" ]
Pandas : saving Series of dictionaries to disk
38,621,539
<p>I have a python pandas Series of dictionaries :</p> <pre><code>id dicts 1 {'5': 1, '8': 20, '1800': 2} 2 {'2': 2, '8': 1, '1000': 25, '1651': 1} ... ... ... ... ... ... 20000000 {'2': 1, '10': 20} </code></pre> <p>The (key, value) in the dictionaries r...
3
2016-07-27T19:24:24Z
38,625,568
<p>I'm curious as to how your <code>Series</code> only takes up 500MB. If you are using the <code>.memory_usage</code> method, this will only return the total memory used by the each python object reference, which is all your Series is storing. That doesn't account for the actual memory of the dictionaries. Rough calcu...
2
2016-07-28T01:07:23Z
[ "python", "pandas", "dictionary", "scipy", "sparse-matrix" ]
Compare Across Arrays by Index in Python
38,621,581
<p>I'm looking to compare values of several arrays by index.</p> <p>For example, if I have</p> <pre><code>a = [1, 1, 1, 1, 1, 1] b = [2, 2, 5, 5, 5, 2] c = [3, 3, 3, 3, 3, 3] </code></pre> <p>I'd like to be able to determine that index 2 of array b is out of range of a and c.</p> <p>Even more so, I'd like it to out...
0
2016-07-27T19:27:03Z
38,621,763
<p>What about this:</p> <pre><code>a = [1, 1, 1, 1, 1, 1] b = [2, 2, 5, 5, 5, 2] c = [3, 3, 3, 3, 3, 3] a = np.array(a) b = np.array(b) c = np.array(c) out_of_range = (b &lt; a)|(b &gt; c) # array([False, False, True, True, True, False], dtype=bool) third_in_a_row = [i for i in xrange(2, len(a)) if out_of_range[...
0
2016-07-27T19:37:49Z
[ "python", "arrays", "numpy", "indexing" ]
Compare Across Arrays by Index in Python
38,621,581
<p>I'm looking to compare values of several arrays by index.</p> <p>For example, if I have</p> <pre><code>a = [1, 1, 1, 1, 1, 1] b = [2, 2, 5, 5, 5, 2] c = [3, 3, 3, 3, 3, 3] </code></pre> <p>I'd like to be able to determine that index 2 of array b is out of range of a and c.</p> <p>Even more so, I'd like it to out...
0
2016-07-27T19:27:03Z
38,621,817
<p>Here is solution using <code>groupby</code> from <code>itertools</code> which groups the in-range and out-of-range sequence consecutively and then we can loop through the iterator, and check if the group is out of range and size is larger than or equal to <code>3</code>, if it is, add 3 to the index, find the value ...
0
2016-07-27T19:41:03Z
[ "python", "arrays", "numpy", "indexing" ]
Compare Across Arrays by Index in Python
38,621,581
<p>I'm looking to compare values of several arrays by index.</p> <p>For example, if I have</p> <pre><code>a = [1, 1, 1, 1, 1, 1] b = [2, 2, 5, 5, 5, 2] c = [3, 3, 3, 3, 3, 3] </code></pre> <p>I'd like to be able to determine that index 2 of array b is out of range of a and c.</p> <p>Even more so, I'd like it to out...
0
2016-07-27T19:27:03Z
38,622,058
<p>Here's a vectorized way using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>np.convolve</code></a> -</p> <pre><code># Get the index of first such occurance idx = np.where(np.convolve(b&gt;(a+c),[1]*3)&gt;=3)[0][0] # Index into b and get the tuple of index an...
1
2016-07-27T19:54:32Z
[ "python", "arrays", "numpy", "indexing" ]
Find the set of elements in a list without sorting in Python
38,621,615
<p>I have a list of elements 1,...,K with repeats. For example for K=4 :</p> <pre><code>[4 2 1 1 2 1 1 3 2 ] </code></pre> <p>I want to find the sequence that 1,...,K is appeared in the list (without sorting). For example for the above sequence, the result would be </p> <pre><code>[4, 2 ,1 ,3 ] </code></pre> <p>...
-2
2016-07-27T19:28:43Z
38,621,716
<p>The normal list-deduping would probably be good enough:</p> <pre><code>def f7(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] </code></pre> <p><a href="http://stackoverflow.com/a/480227/748858">reference</a></p> <p>However, this is by nature <code>O(N)<...
1
2016-07-27T19:35:32Z
[ "python", "set" ]
Find the set of elements in a list without sorting in Python
38,621,615
<p>I have a list of elements 1,...,K with repeats. For example for K=4 :</p> <pre><code>[4 2 1 1 2 1 1 3 2 ] </code></pre> <p>I want to find the sequence that 1,...,K is appeared in the list (without sorting). For example for the above sequence, the result would be </p> <pre><code>[4, 2 ,1 ,3 ] </code></pre> <p>...
-2
2016-07-27T19:28:43Z
38,621,732
<pre><code>from collections import OrderedDict list_numbers=[4,2,1,1,2,1,1,3,2] print list(OrderedDict.fromkeys(list_numbers)) </code></pre> <p>This gives the desired output - [4, 2, 1, 3]</p>
1
2016-07-27T19:36:10Z
[ "python", "set" ]
Find the set of elements in a list without sorting in Python
38,621,615
<p>I have a list of elements 1,...,K with repeats. For example for K=4 :</p> <pre><code>[4 2 1 1 2 1 1 3 2 ] </code></pre> <p>I want to find the sequence that 1,...,K is appeared in the list (without sorting). For example for the above sequence, the result would be </p> <pre><code>[4, 2 ,1 ,3 ] </code></pre> <p>...
-2
2016-07-27T19:28:43Z
38,622,121
<p>Here is another way, which assumes that all numbers in the range 1,...,k appear (as per the problem description):</p> <pre><code>def inOrder(nums): k = max(nums) indices = [nums.index(n) for n in range(1,k+1)] return [n for i,n in sorted(zip(indices,range(1,k+1)))] </code></pre> <p>For example</p> <pr...
0
2016-07-27T19:58:13Z
[ "python", "set" ]
Find the set of elements in a list without sorting in Python
38,621,615
<p>I have a list of elements 1,...,K with repeats. For example for K=4 :</p> <pre><code>[4 2 1 1 2 1 1 3 2 ] </code></pre> <p>I want to find the sequence that 1,...,K is appeared in the list (without sorting). For example for the above sequence, the result would be </p> <pre><code>[4, 2 ,1 ,3 ] </code></pre> <p>...
-2
2016-07-27T19:28:43Z
38,630,522
<p>This will be O(k). </p> <p>It will go through the list. For each element, if it's the first time that element appears, it will add it to the list.</p> <p>If there's a possibility that there are numbers in the list larger than k, or other non integer elements, add an extra check that it's an integer less than k. Th...
0
2016-07-28T08:05:56Z
[ "python", "set" ]
Pandas Pivot Time-series by year
38,621,652
<p>Hello and thanks in advance for any help. I have a simple dataframe with two columns. I did not set an index explicitly, but I believe a dataframe gets an integer index that I see along the left side of the output. Question below:</p> <pre><code>df = pandas.DataFrame(res) df.columns = ['date', 'pb'] df['date'] =...
3
2016-07-27T19:31:35Z
38,621,739
<p>Using the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow"><code>.dt accessor</code></a> you can create columns for year and month and then pivot on those:</p> <pre><code>df['Year'] = df['date'].dt.year df['Month'] = df['date'].dt.month pd.pivot_table(df,index='Month',col...
4
2016-07-27T19:36:37Z
[ "python", "pandas" ]
Pandas Pivot Time-series by year
38,621,652
<p>Hello and thanks in advance for any help. I have a simple dataframe with two columns. I did not set an index explicitly, but I believe a dataframe gets an integer index that I see along the left side of the output. Question below:</p> <pre><code>df = pandas.DataFrame(res) df.columns = ['date', 'pb'] df['date'] =...
3
2016-07-27T19:31:35Z
38,622,023
<p>Using <code>stack</code> instead of <code>pivot</code></p> <pre><code>df = pd.DataFrame( dict(date=pd.date_range('2013-01-01', periods=42, freq='M'), pb=np.random.rand(42))) df.set_index([df.date.dt.month, df.date.dt.year]).pb.unstack() </code></pre> <p><a href="http://i.stack.imgur.com/omc...
3
2016-07-27T19:52:59Z
[ "python", "pandas" ]
string comparison not recognizing match
38,621,676
<p>I have a list of urls in 'origFile' that will be augmented and written into 'readyFile'. I want to add urls to 'readyFile' only if they are not already in the 'readyFile'. </p> <pre><code>with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile : for line in origFile: ...
1
2016-07-27T19:32:39Z
38,621,752
<p>By writing <code>readyFile.write(...)</code> your next <code>readyFile.read()</code> call will be overwritten. You should save your readyFile content into a variable right after the <code>with</code> statement:</p> <pre><code>with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile ...
1
2016-07-27T19:37:07Z
[ "python", "string", "comparison" ]
string comparison not recognizing match
38,621,676
<p>I have a list of urls in 'origFile' that will be augmented and written into 'readyFile'. I want to add urls to 'readyFile' only if they are not already in the 'readyFile'. </p> <pre><code>with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile : for line in origFile: ...
1
2016-07-27T19:32:39Z
38,621,778
<p>Your condition doesn't work as you expect because the <code>read()</code> method will return the whole file as a string. You need to check the membership between an iterable of urls.</p> <p>And instead of looping over the file and check the membership for all the urls you can find the difference using <code>set.dif...
0
2016-07-27T19:38:51Z
[ "python", "string", "comparison" ]
How do I get python code to execute properly from a button click when an alert is included as action from the button click?
38,621,677
<p>I have been having trouble getting alerts to work with an html button press that also calls a url. Describing the problem in more detail, I have a button that when pressed calls a url which from my urls.py file and views.py file calls some python code that plays a video but when I include an alert to trigger when th...
0
2016-07-27T19:32:41Z
38,621,792
<p>if you want to execute server side and client side code you need to use XHR or simply <a href="http://www.w3schools.com/ajax/" rel="nofollow">Ajax</a></p> <p><code>&lt;a href=''&gt;&lt;/a&gt;</code> will redirect page to <code>href</code>'s url, for this you need to add 'return false' to your JavaScript click metho...
0
2016-07-27T19:39:41Z
[ "javascript", "python", "html", "django" ]
Logistic Regression Python
38,621,685
<p>I have been trying to implement logistic regression for a classification problem, but it is giving me really bizarre results. I have gotten decent results with gradient boosting and random forests so I thought of getting to basic and see what best can I achieve. Can you help me point out what am I doing wrong that ...
0
2016-07-27T19:33:26Z
38,633,268
<p>You are not configuring the C parameter - well, technically you are, but only to the default value - which is one of the usual suspects for overfitting. You can have a look at <a href="http://scikit-learn.org/stable/modules/grid_search.html#grid-search" rel="nofollow">GridSearchCV</a> and play around a bit with seve...
0
2016-07-28T10:06:30Z
[ "python", "logistic-regression", "data-science" ]
PyQt5 pip installation error 13. Permission denied
38,621,689
<p>I'm trying to install PyQt5 with the command <code>pip install PyQt5</code></p> <p>but I get an error instead.</p> <p>I use Python 3.5, windows 10.</p> <p>error:</p> <pre><code>C:\WINDOWS\system32&gt;pip install PyQt5 Collecting PyQt5 Using cached PyQt5-5.7-cp35-none-win_amd64.whl Collecting sip (from PyQt5) ...
0
2016-07-27T19:33:42Z
39,791,527
<p>With different Windows (8.2) and different PyQt (4-4) I had the same problem. What worked for me was: Run taks manager and see if there are any Python tasks running. If there are (there were for me) kill them, as they (probably) lock the sip.pyd file. Then try to use "pip install" ("successfully installed" in my cas...
1
2016-09-30T12:26:35Z
[ "python", "pip" ]
GetPixel memory leak in Python
38,621,724
<p>I have a script that sits outside a game, reads pixels, and reacts to that information by "pressing keys", "clicking", etc. So to get the pixels, I am using code like this</p> <pre><code>def function(): a = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) return a </code></pre> <p>in ord...
2
2016-07-27T19:35:51Z
38,677,186
<p>You should call <a href="http://docs.activestate.com/activepython/3.2/pywin32/win32gui__ReleaseDC_meth.html" rel="nofollow">win32gui.ReleaseDC</a> for each call of <a href="http://docs.activestate.com/activepython/3.2/pywin32/win32gui__GetDC_meth.html" rel="nofollow">win32gui.GetDC</a> as explained in <a href="https...
0
2016-07-30T18:27:06Z
[ "python", "memory", "pixel", "getpixel" ]
Sklearn: find mean centroid location for clusters?
38,621,791
<pre><code>import pandas as pd, numpy as np, scipy import sklearn.feature_extraction.text as text from sklearn import decomposition descs = ["You should not go there", "We may go home later", "Why should we do your chores", "What should we do"] vectorizer = text.CountVectorizer() dtm = vectorizer.fit_transform(descs...
0
2016-07-27T19:39:32Z
38,626,076
<p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html" rel="nofollow">docs</a> of <code>sklearn.decomposition.NMF</code> explain how to get the coordinates of the centroid of each cluster:</p> <blockquote> <p><strong>Attributes:</strong> &nbsp;&nbsp;&nbsp; <strong>components...
1
2016-07-28T02:16:27Z
[ "python", "scikit-learn" ]
Replacing "/" with "\" doesn't work
38,621,822
<p>I am trying to replace <code>/</code> with <code>\</code> as below, but it doesn't work, why is that?</p> <pre><code>str = "images/companyPkg/Pkg/nib64/" replaced_str = str.replace('//','\\') print replaced_str </code></pre>
0
2016-07-27T19:41:15Z
38,621,849
<p><code>'/'</code> does not need to be doubled. <code>'\'</code> is doubled because strings cannot end with <code>'\'</code>:</p> <pre><code>s = "images/companyPkg/Pkg/nib64/" replaced_str = s.replace('/','\\') </code></pre> <p>Don't assign anything to the name <code>str</code>, <code>str</code> is a builtin (class ...
8
2016-07-27T19:43:07Z
[ "python" ]
Replacing "/" with "\" doesn't work
38,621,822
<p>I am trying to replace <code>/</code> with <code>\</code> as below, but it doesn't work, why is that?</p> <pre><code>str = "images/companyPkg/Pkg/nib64/" replaced_str = str.replace('//','\\') print replaced_str </code></pre>
0
2016-07-27T19:41:15Z
38,621,899
<p>You don't need to escape the <code>/</code> in python just the <code>\</code> so the following line should do the trick:</p> <pre><code>replaced_str = str.replace('/', '\\') </code></pre>
2
2016-07-27T19:45:22Z
[ "python" ]
Replacing "/" with "\" doesn't work
38,621,822
<p>I am trying to replace <code>/</code> with <code>\</code> as below, but it doesn't work, why is that?</p> <pre><code>str = "images/companyPkg/Pkg/nib64/" replaced_str = str.replace('//','\\') print replaced_str </code></pre>
0
2016-07-27T19:41:15Z
38,622,199
<p>You should double the back slash <code>\</code> because it is the escape character and used to provide a special meaning to the certain characters as for example <code>n</code> is <strong>simple 'n'</strong> but <code>\n</code> is a <strong>new line</strong>, but forward slash <code>/</code> is a simple character so...
0
2016-07-27T20:03:01Z
[ "python" ]
Find duplicates in python list of dictionaries
38,621,915
<p>I have kind of dictionary below: </p> <pre><code>a = [{'un': 'a', 'id': "cd"}, {'un': 'b', 'id': "cd"},{'un': 'b', 'id': "cd"}, {'un': 'c', 'id': "vd"}, {'un': 'c', 'id': "a"}, {'un': 'c', 'id': "vd"}, {'un': 'a', 'id': "cm"}] </code></pre> <p>I need to find the duplicates of dictionaries by 'un' key, for e...
2
2016-07-27T19:46:21Z
38,622,067
<p>You can use another dictionary in order to categorize your dictionaries based on <code>'un'</code> key then choose the expected items based on <code>id</code>:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; &gt;&gt;&gt; for i in a: ... ...
0
2016-07-27T19:55:10Z
[ "python", "list", "python-2.7", "dictionary" ]
Find duplicates in python list of dictionaries
38,621,915
<p>I have kind of dictionary below: </p> <pre><code>a = [{'un': 'a', 'id': "cd"}, {'un': 'b', 'id': "cd"},{'un': 'b', 'id': "cd"}, {'un': 'c', 'id': "vd"}, {'un': 'c', 'id': "a"}, {'un': 'c', 'id': "vd"}, {'un': 'a', 'id': "cm"}] </code></pre> <p>I need to find the duplicates of dictionaries by 'un' key, for e...
2
2016-07-27T19:46:21Z
38,622,184
<p>you were pretty much on the right track with a defaultdict... here's roughly how I would write it.</p> <pre><code>from collections import defaultdict a = [{'un': 'a', 'id': "cd"}, {'un': 'b', 'id': "cd"},{'un': 'b', 'id': "cd"}, {'un': 'c', 'id': "vd"}, {'un': 'c', 'id': "a"}, {'un': 'c', 'id': "vd"}, {'un': 'a'...
0
2016-07-27T20:01:31Z
[ "python", "list", "python-2.7", "dictionary" ]
How to split a math formula that is composed of variables that contain dashes
38,621,962
<p>Trying to split this line:</p> <pre><code>formula='%abc-def%+%hij-klm%/%opq+rst%-%uvw-xyz% </code></pre> <p>The variable are contained with the <code>"%"</code> signs and must remain intact. </p> <p>I want to split on <code>+-/*</code> without splitting the variable due to the <code>'-'</code> in the name.</p> <...
1
2016-07-27T19:49:14Z
38,622,156
<p>You can prevent <code>re.compile("%[\+\/\-\*]%").split(formula)</code> from dropping the <code>%</code> characters by using lookarounds:</p> <pre><code>re.compile(r"(?&lt;=%)[+/*-](?=%)").split(formula) </code></pre> <p>Another solution would be to split on <code>[+/*-]</code> but only if followed by an even numbe...
0
2016-07-27T20:00:10Z
[ "python", "regex", "split" ]
How to split a math formula that is composed of variables that contain dashes
38,621,962
<p>Trying to split this line:</p> <pre><code>formula='%abc-def%+%hij-klm%/%opq+rst%-%uvw-xyz% </code></pre> <p>The variable are contained with the <code>"%"</code> signs and must remain intact. </p> <p>I want to split on <code>+-/*</code> without splitting the variable due to the <code>'-'</code> in the name.</p> <...
1
2016-07-27T19:49:14Z
38,622,169
<p>A 2-step solution:</p> <pre><code>import re tempList = re.split("(\-|\+|\/|\*)(?=%)",'%abc-def%+%hij-klm%/%opq+rst%-%uvw-xyz%') finalList = [x for x in tempList if "%" in x] ['%abc-def%', '%hij-klm%', '%opq+rst%', '%uvw-xyz%'] </code></pre> <p>I hope this helps.</p>
0
2016-07-27T20:00:55Z
[ "python", "regex", "split" ]
Import package from adjacent module works in Py2 but not in Py3
38,621,975
<p>I'm still getting used to structuring python projects and relative imports, I thought I understood relative imports mostly until I ran into an issue when testing on Py3.</p> <p>I have a project that is structure like so:</p> <pre><code>scriptA.py package/__init__.py scriptB.py scriptC.py </code...
0
2016-07-27T19:50:15Z
38,623,466
<p><strong>No module named 'scriptB'</strong></p> <p>Looks like a path error. Check your path statement. The path statement in Windows can be accessed by typing "system" into start menu search bar. From there you can access "Environment Variables", one of which is the "path" statement. There you can see different...
0
2016-07-27T21:27:01Z
[ "python", "python-3.x", "packages", "python-2.x", "importerror" ]
Import package from adjacent module works in Py2 but not in Py3
38,621,975
<p>I'm still getting used to structuring python projects and relative imports, I thought I understood relative imports mostly until I ran into an issue when testing on Py3.</p> <p>I have a project that is structure like so:</p> <pre><code>scriptA.py package/__init__.py scriptB.py scriptC.py </code...
0
2016-07-27T19:50:15Z
38,624,524
<p>So the problem was that the imports in <code>__init__.py</code> should have been relative imports i.e.:</p> <pre><code>from .scriptB import functionB from .scriptC import functionC </code></pre> <p>I guess this is one of the differences between importing a module and a python package. It seems that in Py3.5 relati...
0
2016-07-27T22:57:28Z
[ "python", "python-3.x", "packages", "python-2.x", "importerror" ]
Validation on CreateView and UpdateView in django always being triggered, even when model doesn't/shouldn't
38,622,020
<p>I am not sure why adding widgets in my GroupForm form in forms.py caused my validations to go haywire. Before that they were respecting my models, now after adding widget attrs for everything it no longer respects the models and says a field is required for everything. Is there some other item I missed when defini...
0
2016-07-27T19:52:37Z
38,627,053
<p>It's not because you added the widgets, it's because you actually redefined the fields and while redefining them, you did not respect your model's requirements. For example in your model </p> <pre><code> mailing_address = models.ForeignKey(..., null=True, blank=True) </code></pre> <p>mailing address is allowed to ...
1
2016-07-28T04:22:03Z
[ "python", "django", "validation", "django-models", "django-forms" ]
Plot histogram of a list of strings in Python
38,622,082
<p>I have a very long list of IDs (IDs are string values. I want to plot a histogram of this list. There are some codes in other threads on stackoverflow for plotting a histogram but the histogram I want should look like this picture (i.e. highest values are in the left side and the values gradually decrease when x-axi...
1
2016-07-27T19:56:07Z
38,622,519
<p>how about something along these lines...</p> <pre><code>from collections import Counter import matplotlib.pyplot as plt import numpy as np counts = Counter(['a','a','a','c','a','a','c','b','b','d', 'd','d','d','d','b']) common = counts.most_common() labels = [item[0] for item in common] number = [item[1] for item ...
0
2016-07-27T20:22:38Z
[ "python", "matplotlib", "histogram" ]
Is it really necessary to hash the same for classes that compare the same?
38,622,200
<p>Reading <a href="https://stackoverflow.com/a/1608882/143211">this answer</a> it seems, that if <code>__eq__</code> is defined in custom class, <code>__hash__</code> needs to be defined as well. This is understandable.<br> However it is not clear, why - effectively - <code>__eq__</code> should be same as <code>self._...
3
2016-07-27T20:03:02Z
38,622,299
<p>The problem is that it does not make sense, hash is used to do efficient bucketing of objects. Consequently, when you have a set, which is implemented as a hash table, each hash points to a bucket, which is usually a list of elements. In order to check if an element is in the set (or other hash based container) you ...
5
2016-07-27T20:09:12Z
[ "python", "class", "hash", "equivalence" ]
Is it really necessary to hash the same for classes that compare the same?
38,622,200
<p>Reading <a href="https://stackoverflow.com/a/1608882/143211">this answer</a> it seems, that if <code>__eq__</code> is defined in custom class, <code>__hash__</code> needs to be defined as well. This is understandable.<br> However it is not clear, why - effectively - <code>__eq__</code> should be same as <code>self._...
3
2016-07-27T20:03:02Z
38,622,907
<p>It is possible to implement your class like this and <em>not</em> have any problems. However, you have to be 100% sure that no two different objects will ever produce the same hash. Consider the following example:</p> <pre><code>class Foo: def __init__(self, name, value): self.name= name self.va...
-1
2016-07-27T20:46:54Z
[ "python", "class", "hash", "equivalence" ]
Python block thread if list is empty
38,622,284
<p>Is there a way to make a thread go to sleep if the list is empty and wake it up again when there are items? I don't want to use Queues since I want to be able to index into the datastructure.</p>
4
2016-07-27T20:08:26Z
38,622,859
<p>I would go with this:</p> <pre><code>import threading class MyList (list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cond = threading.Condition() def append(self, item): with self._cond: super().append(item) self._cond.not...
1
2016-07-27T20:43:41Z
[ "python", "multithreading", "list" ]
Python block thread if list is empty
38,622,284
<p>Is there a way to make a thread go to sleep if the list is empty and wake it up again when there are items? I don't want to use Queues since I want to be able to index into the datastructure.</p>
4
2016-07-27T20:08:26Z
38,638,174
<p>Yes, the solution will probably involve a <a href="https://docs.python.org/3/library/threading.html#condition-objects" rel="nofollow"><code>threading.Condition</code></a> variable as you note in comments.</p> <p>Without more information or a code snippet, it's difficult to know what API suits your needs. How are y...
1
2016-07-28T13:39:29Z
[ "python", "multithreading", "list" ]
Creating a max function from scratch (python)
38,622,287
<p>So I'm trying to create a function that determines the maximum of a set of values, from scratch. </p> <p>I'm not sure how to make the function change the new value of Max after a new Max has been found, I'm also not sure if my usage of args is correct. </p> <pre><code>def Maximum(*args): Max = 0 for item i...
0
2016-07-27T20:08:37Z
38,622,335
<p>You've got one line of code backwards. Your if statement is effectively saying that if item is greater than Max, set item to Max. You need to flip that to say if item is greater than Max, set Max to item.</p> <pre><code>if item &gt; Max: Max = item return Max </code></pre> <p>Also, I'm not an expert in Python,...
1
2016-07-27T20:11:39Z
[ "python", "python-2.7", "function", "max" ]
Creating a max function from scratch (python)
38,622,287
<p>So I'm trying to create a function that determines the maximum of a set of values, from scratch. </p> <p>I'm not sure how to make the function change the new value of Max after a new Max has been found, I'm also not sure if my usage of args is correct. </p> <pre><code>def Maximum(*args): Max = 0 for item i...
0
2016-07-27T20:08:37Z
38,622,611
<p>*args = list of arguments -as positional arguments</p> <p>You are passing a list as an argument here. So your code should look something like this -</p> <pre><code>def maximum(nums): Max = 0 for item in nums: if item &gt; Max: Max=item return Max List = [1,5,8,77,24,95] print maximum(Li...
0
2016-07-27T20:28:11Z
[ "python", "python-2.7", "function", "max" ]
How to make Wagtail search case-insensitive
38,622,289
<p>I use Wagtail serach:</p> <pre><code>query = self.request.query_params questions = models.Questions.objects.filter( answer__isnull=False, owner__isnull=False).exclude(answer__exact='') s = get_search_backend() results = s.search(query[u'question'], questions) </code></pre> <p>And this is how I set up the i...
3
2016-07-27T20:08:39Z
38,665,074
<p>With Wagtail's elasticsearch backend, fields indexed with <code>partial_match=True</code> are tokenized in <a href="https://github.com/torchbox/wagtail/blob/v1.5.3/wagtail/wagtailsearch/backends/elasticsearch.py#L623" rel="nofollow">lowercase</a>. So to accomplish case-insensitive search all you need to do is lowerc...
3
2016-07-29T18:10:37Z
[ "python", "django", "search", "elasticsearch", "wagtail" ]
How can I ask for user input using Python 3.x?
38,622,296
<p>I'm creating an assignment for school.</p> <p>First create the pseudocode, etc</p> <p>Then write a compare function that <code>returns 1 if a &gt; b , 0 if a == b , and -1 if a &lt; b</code></p> <p>I've written that part</p> <pre><code>def compare(a, b): return (a &gt; b) - (a &lt; b) </code></pre> <p>BUT ...
-6
2016-07-27T20:09:00Z
38,622,371
<p>Since you're using Python 3.x, you can use:</p> <pre><code>def compare(a, b): a = int(input("Insert value A: ")) b = int(input("Insert value B: ")) return (a &gt; b) - (a &lt; b) </code></pre> <p>Since Python 3.x doesn't evaluate and/or convert the data type, you have to explicitly convert to <code>int...
0
2016-07-27T20:13:41Z
[ "python", "python-3.x", "input" ]
How can I ask for user input using Python 3.x?
38,622,296
<p>I'm creating an assignment for school.</p> <p>First create the pseudocode, etc</p> <p>Then write a compare function that <code>returns 1 if a &gt; b , 0 if a == b , and -1 if a &lt; b</code></p> <p>I've written that part</p> <pre><code>def compare(a, b): return (a &gt; b) - (a &lt; b) </code></pre> <p>BUT ...
-6
2016-07-27T20:09:00Z
38,622,448
<p>Use the command:</p> <pre><code> variable = input("You can write something here:" ) </code></pre> <p>Then, when compiling the .py file, the terminal will show the message:</p> <pre><code> You can write something here: </code></pre> <p>Where you can put your input as easy as type and enter.</p> <p>And mayb...
0
2016-07-27T20:17:26Z
[ "python", "python-3.x", "input" ]
How can I execute JavaScript code from Python?
38,622,385
<p>Lets say that I have this code inside a JavaScript file:</p> <pre><code>var x = 10; x = 10 - 5; console.log(x); function greet() { console.log("Hello World!"); } greet() </code></pre> <p>How would I use Python to execute this code and <em>"print"</em> <code>x</code> and <code>Hello World!</code>?<br /> Here is s...
2
2016-07-27T20:14:49Z
38,623,079
<p>The module <code>Naked</code> does exactly this. <code>pip install Naked</code> (or install from source if you prefer) and import the library shell functions as follows:</p> <pre><code>from Naked.toolshed.shell import execute_js, muterun_js response = muterun_js('file.js') if response.exitcode == 0: print(respon...
3
2016-07-27T20:59:42Z
[ "javascript", "python", "python-3.x", "python-3.5" ]
python2.7 - store boolean values as individual bits when writing to disk
38,622,386
<p>I'm writing code that converts integers into padded 8-bit strings. I would then like to write those strings to a binary file. I am having problems figuring out the proper <code>dtype</code> to be used with the numpy array that I am currently using.</p> <p>In the following code when I have <code>bin_data</code> vari...
3
2016-07-27T20:14:51Z
38,622,864
<ol> <li>The reason that bool is always returning true is that a[j] is a nonempty <strong>string</strong>. You need to cast a[j] to an int before testing with bool (and also before assigning it as an entry to a numpy bool array).</li> <li>You can just call numpy.packbits to compress your boolean array into a uint8 arra...
5
2016-07-27T20:44:10Z
[ "python", "numpy" ]
Change True/False value to discrete value in pandas dataframe with np.where()
38,622,487
<p>I am trying to assign a state name to a list of university names: </p> <pre><code>df = pd.DataFrame({'College': pd.Series(['University of Michigan', 'University of Florida', 'Iowa State'])}) State = ['Michigan', 'Iowa'] df['State'] = np.where(df['College'].str.contains('|'.join(State)), 'state','--') </code></p...
3
2016-07-27T20:20:00Z
38,622,524
<p>You could use <code>str.extract</code> here, instead of <code>np.where</code>:</p> <pre><code>In [290]: df['State'] = df['College'].str.extract('({})'.format('|'.join(State)), expand=True) In [291]: df Out[291]: College State 0 University of Michigan Michigan 1 University of Florida ...
3
2016-07-27T20:22:47Z
[ "python", "pandas", "contains", "assign", "extraction" ]
Change True/False value to discrete value in pandas dataframe with np.where()
38,622,487
<p>I am trying to assign a state name to a list of university names: </p> <pre><code>df = pd.DataFrame({'College': pd.Series(['University of Michigan', 'University of Florida', 'Iowa State'])}) State = ['Michigan', 'Iowa'] df['State'] = np.where(df['College'].str.contains('|'.join(State)), 'state','--') </code></p...
3
2016-07-27T20:20:00Z
38,622,590
<pre><code>States = [ 'Washington' 'Wisconsin' 'West Virginia' 'Florida' 'Wyoming' 'New Hampshire' 'New Jersey' 'New Mexico' 'National' 'North Carolina' 'North Dakota' 'Nebraska' 'New York' 'Rhode Island' 'Nevada' 'Guam' 'Colorado' 'California' 'Georgia' 'Connecticut' 'Ok...
2
2016-07-27T20:26:41Z
[ "python", "pandas", "contains", "assign", "extraction" ]
Maven build with Java: How to execute script located in resources?
38,622,523
<p>I am building my Java project with Maven and I have a script file that ends up in the <code>target/classes/resources</code> folder. While I can access the file itself via <code>this.getClass.getResource("/lookUpScript.py").getPath()</code>, I cannot execute a shell command with <code>"." + this.getClass.getResource(...
1
2016-07-27T20:22:45Z
38,622,730
<p>The maven path for all the artifacts is not the same that gets generated when you run it or export the project. You can check this by exporting the project as Jar/War/Ear file and viewing it via winRAR or any other tool.</p> <p>The resources should be in jar parallel to com directory if its a jar project, but you c...
1
2016-07-27T20:36:04Z
[ "java", "python", "shell", "maven" ]
Installed Python with 32 bit install, appears as 64 bit
38,622,585
<p>I need to run the 32 bit version of Python. I thought that was what I had running on my machine, as that is the installer I downloaded and when I rerun the installer is refers to the currently installed version of Python as "Python 3.5 32-Bit". </p> <p>However when I run <code>platform.architecture()</code> it stat...
3
2016-07-27T20:26:22Z
38,622,996
<p>You can determine if your Python is truly 64bit by running this code and looking at Task Manager in Windows (or its equivalent in Linux) and seeing what is the maximum allocated memory for the program. If it is 2GB (it could be 3GB for some cases I am not sure) then it is Python 32bit. Otherwise 64bit. On my compute...
2
2016-07-27T20:53:30Z
[ "python" ]
Installed Python with 32 bit install, appears as 64 bit
38,622,585
<p>I need to run the 32 bit version of Python. I thought that was what I had running on my machine, as that is the installer I downloaded and when I rerun the installer is refers to the currently installed version of Python as "Python 3.5 32-Bit". </p> <p>However when I run <code>platform.architecture()</code> it stat...
3
2016-07-27T20:26:22Z
38,623,318
<p>This sounds like you might have multiple instances of Python installed on your machine. Verify that you're calling the correct one by calling it explicitly from its full path, and noting if its still saying 64-bit or 32-bit.</p> <p>Moving forward, using a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollo...
3
2016-07-27T21:15:27Z
[ "python" ]
mysql source command do nothing inside docker container
38,622,594
<h1>Description</h1> <p>I'm running docker container with mysql in it and I want to run python script after mysql started, which will apply dump on it.</p> <p>Here is a snippet of <strong>Dockerfile</strong>:</p> <pre><code>FROM mysql:5.6 RUN apt-get update &amp;&amp; \ apt-get install -y python ADD apply_dump...
1
2016-07-27T20:26:59Z
38,662,417
<p>Try passing your source SQL file into the MySQL command like this, instead of using the <code>-e</code> flag:</p> <pre><code>subprocess.call(["mysql", "--user=root", "--password=root", "test_db", "&lt;", "/tmp/%s" % dumpSqlFile]) </code></pre> <p>This will call import your SQL file using the widely used syntax:</p...
0
2016-07-29T15:26:33Z
[ "python", "mysql", "docker" ]
Execute IPython notebook cell from python script
38,622,610
<p>In the IPython notebook, you can execute an outside script, say <code>test.py</code>, using the run magic:</p> <pre><code>%run test.py </code></pre> <p>Is there a way to do the opposite, i.e. given an IPython notebook, accessing and then running a particular cell inside it from a python script?</p>
2
2016-07-27T20:28:11Z
38,645,985
<p>The file with extention "ipynb" of Jupyter (or IPython) is a JSON file. And the cells are under the name "cells" ["cells"]. Then you choose the number of the cell [0] and to get the source choose "source" ["source"]. In return you get an array with one element so you need to get the first element [0].</p> <pre><cod...
1
2016-07-28T20:18:07Z
[ "python", "ipython" ]
Get list of missing documents from MongodDB
38,622,666
<p>First mongodb project so it's probably obvious but my google fu is insufficient or I'm approaching it wrong.</p> <p>I have a collection in mongodb. Each document has an <code>id</code> field that is unique. In my program I end up with a list of these ids and I want to make a slow expensive call to an api if I don...
1
2016-07-27T20:32:36Z
38,623,536
<p>Using pymongo you can check if id is <a href="https://docs.mongodb.com/manual/reference/operator/query/in/" rel="nofollow">in</a> list or <a href="https://docs.mongodb.com/manual/reference/operator/query/nin/" rel="nofollow">nin</a>:</p> <pre><code>db.items.find({'id': {"$in":ids}}, {id:1}) </code></pre> <p>or not...
0
2016-07-27T21:32:40Z
[ "python", "mongodb" ]
python - couldn't open a file using radare2: invalid option -- '0'
38,622,681
<p>I have installed radare2 using pip install and then in the python shell I gave the followig lines of code</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import r2pipe &gt;&gt;&gt; r = r2pipe.open...
1
2016-07-27T20:33:40Z
38,623,148
<p>Here's what I did:</p> <ol> <li><p>go to <a href="https://github.com/radare/radare2" rel="nofollow">https://github.com/radare/radare2</a>, clone the project to my laptop and install it by <code>sys/install.sh</code> (radare2 README contains all instructions)</p></li> <li><p>pip install r2pipe (I have python 2.7.6 o...
1
2016-07-27T21:03:34Z
[ "python" ]
Still confused about reference counting
38,622,715
<p>Out of curiosity, I am trying to understand how reference counting works in Python. These two entries: </p> <ul> <li><a href="http://stackoverflow.com/q/38253757/3001761">Python Ref Counts to Object</a></li> <li><a href="http://stackoverflow.com/q/510406/3001761">Is there a way to get the current ref count of an ob...
1
2016-07-27T20:35:21Z
38,622,937
<ol> <li><code>gc.get_referrers</code> only returns objects the cycle-detecting GC knows about. Objects that couldn't possibly be involved in a reference cycle don't need to be tracked by the cycle detector, so they might not show up in the <code>get_referrers</code> list.</li> <li><p>With <a href="https://hg.python.or...
0
2016-07-27T20:49:05Z
[ "python", "reference", "counting" ]
JaqvaScript SyntaxError: JSON.parse: unexpected character line 1
38,622,741
<p>In Python I load a variable with data then convert it to json with this code.</p> <pre><code>jsVar = (json.dumps(jsPass)) </code></pre> <p>which produces this output. {"TT1004": [[1004, 45.296109039999997, -75.926546579999993, 66.996664760000002, 150, false]], "TT1001": [[1001, 45.296471220000001, -75.92388128999...
1
2016-07-27T20:36:43Z
38,622,845
<p>I 've tested quickly with JSONlint so you definitely get valid json already. There is no need to normalize this with <code>JSON.parse()</code> since it is already fine. Only thing you have to do is:</p> <pre><code>var myVar2 = jsVar; </code></pre> <p>If you check <code>console.log(myVar2.TT1001);</code> will prese...
0
2016-07-27T20:43:02Z
[ "javascript", "python", "json" ]
JaqvaScript SyntaxError: JSON.parse: unexpected character line 1
38,622,741
<p>In Python I load a variable with data then convert it to json with this code.</p> <pre><code>jsVar = (json.dumps(jsPass)) </code></pre> <p>which produces this output. {"TT1004": [[1004, 45.296109039999997, -75.926546579999993, 66.996664760000002, 150, false]], "TT1001": [[1001, 45.296471220000001, -75.92388128999...
1
2016-07-27T20:36:43Z
38,622,873
<p>Your data is already parsed and you can simply use it like javascript object. if your data is like </p> <pre><code>"{"TT1004":[[1004,45.29610904,-75.92654658,66.99666476,150,false]],"TT1001":[[1001,45.29647122,-75.92388129,64.61642341,150,false]],"TT1003":[[1003,45.29610938,-75.92654338,67.24002542,150,false]],"TT1...
0
2016-07-27T20:44:30Z
[ "javascript", "python", "json" ]
JaqvaScript SyntaxError: JSON.parse: unexpected character line 1
38,622,741
<p>In Python I load a variable with data then convert it to json with this code.</p> <pre><code>jsVar = (json.dumps(jsPass)) </code></pre> <p>which produces this output. {"TT1004": [[1004, 45.296109039999997, -75.926546579999993, 66.996664760000002, 150, false]], "TT1001": [[1001, 45.296471220000001, -75.92388128999...
1
2016-07-27T20:36:43Z
38,622,939
<p>Your data is already a JavaScript object. You can do something like this if you aren't sure whether the object you're getting back is already a valid JavaScript object.</p> <pre><code>if(typeof data != 'object') { var data = JSON.parse(data); } </code></pre>
-1
2016-07-27T20:49:11Z
[ "javascript", "python", "json" ]
What are the implications of Python integers not being limited by 32 or 64 bit size?
38,622,776
<p>There's a bit manipulation problem that asks you to sum up two integers without using + or - operators. Below is the code in Java:</p> <pre><code>public int getSum(int a, int b) { while (b != 0) { int carry = a &amp; b; a = a ^ b; b = carry &lt;&lt; 1; } return a; } </code></pre>...
2
2016-07-27T20:39:36Z
38,622,812
<p>the implications are that you must <strong>know</strong> and <strong>enforce</strong> your own integer widths when computing checksums</p> <p>you make it the size you want </p> <pre><code>carry = (a &amp; b)&amp;255 a = (a ^ b)&amp;255 b = (carry &lt;&lt; 1)&amp;255 </code></pre> <p>would be one byte wide integer...
3
2016-07-27T20:41:28Z
[ "python", "integer", "bit-manipulation" ]
Add columns to a pivot table (pandas)
38,622,801
<p>I know in R I can use tidyr for the following:</p> <pre><code>data_wide &lt;- spread(data_protein, Fraction, Count) </code></pre> <p>and data_wide will inherit all the columns from data_protein that are not spread.</p> <pre><code>Protein Peptide Start Fraction Count 1 A 122 F1 1 1 ...
3
2016-07-27T20:40:46Z
38,622,949
<p>try this:</p> <pre><code>In [144]: df Out[144]: Protein Peptide Start Fraction Count 0 1 A 122 F1 1 1 1 A 122 F2 2 2 1 B 230 F1 3 3 1 B 230 F2 4 In [145]: df.pivot_table(index=['Protein','Peptide','Star...
1
2016-07-27T20:49:59Z
[ "python", "pandas", "dataframe", "pivot-table", "tidyr" ]
Add columns to a pivot table (pandas)
38,622,801
<p>I know in R I can use tidyr for the following:</p> <pre><code>data_wide &lt;- spread(data_protein, Fraction, Count) </code></pre> <p>and data_wide will inherit all the columns from data_protein that are not spread.</p> <pre><code>Protein Peptide Start Fraction Count 1 A 122 F1 1 1 ...
3
2016-07-27T20:40:46Z
38,623,264
<p>Using <code>stack</code>:</p> <pre><code>df.set_index(df.columns[:4].tolist()) \ .Count.unstack().reset_index() \ .rename_axis(None, axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/WvvP2.png" rel="nofollow"><img src="http://i.stack.imgur.com/WvvP2.png" alt="enter image description here"></a></p>
2
2016-07-27T21:11:49Z
[ "python", "pandas", "dataframe", "pivot-table", "tidyr" ]
Python - xlutils "filter.py" syntax error - print repr(self.name)
38,622,807
<p>I developing a script that will eventually use a pdfminer package to convert .pdfs to .txt files. In preparing the the subject files for use, I am having to import copy from xlutils.copy</p> <p>from xlutils.copy import copy, I run into a syntax error from one of the copy.py associated python files (<em>line 699</e...
1
2016-07-27T20:41:02Z
38,902,811
<p>In python3, the print command is significantly different. in particular you can't say <code>print x</code>. you have to say <code>print(x)</code>. See <a href="https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function" rel="nofollow">https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function</a></p>...
0
2016-08-11T17:38:21Z
[ "python", "xlutils" ]
How to split a list of numbers based on the distance of consecutive elements in Python?
38,622,868
<p>Given a list of numbers, how can I split it whenever the distance of two adjacent elements is larger than <em>n</em>?</p> <p><strong>Input:</strong></p> <pre><code>n = 3 l = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] </code></pre> <p><strong>Output:</strong></p> <pre><code>[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]...
0
2016-07-27T20:44:24Z
38,622,869
<p><strong>Code</strong></p> <pre><code>from boltons import iterutils def grouponpairs(l, f): groups = [] g = [] pairs = iterutils.pairwise(l + [None]) for a, b in pairs: g.append(a) if b is None: continue if not f(a, b): groups.append(g) g =...
1
2016-07-27T20:44:24Z
[ "python", "list", "split" ]
How to split a list of numbers based on the distance of consecutive elements in Python?
38,622,868
<p>Given a list of numbers, how can I split it whenever the distance of two adjacent elements is larger than <em>n</em>?</p> <p><strong>Input:</strong></p> <pre><code>n = 3 l = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] </code></pre> <p><strong>Output:</strong></p> <pre><code>[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]...
0
2016-07-27T20:44:24Z
38,623,043
<p>You can do it using zip:</p> <pre><code># initialization &gt;&gt;&gt; lst = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] &gt;&gt;&gt; n = 3 </code></pre> <p>Find splitting locations using zip:</p> <pre><code>&gt;&gt;&gt; indices = [i + 1 for (x, y, i) in zip(lst, lst[1:], range(len(lst))) if n &lt; abs(x - y)] </code></pr...
3
2016-07-27T20:56:55Z
[ "python", "list", "split" ]
How to split a list of numbers based on the distance of consecutive elements in Python?
38,622,868
<p>Given a list of numbers, how can I split it whenever the distance of two adjacent elements is larger than <em>n</em>?</p> <p><strong>Input:</strong></p> <pre><code>n = 3 l = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] </code></pre> <p><strong>Output:</strong></p> <pre><code>[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]...
0
2016-07-27T20:44:24Z
38,623,101
<p>Here's a more primitive piece of code that achieves what you want to do, even though it is not efficient (see Reut Sharabani's answer for a more efficient solution.)</p> <pre><code># Input list l = [1, 6, 5, 3, 5, 0, -3, -5, 2] # Difference to split list with n = 3 output = [] t = [] for i in range(1, len(l)): ...
1
2016-07-27T21:00:49Z
[ "python", "list", "split" ]
How to split a list of numbers based on the distance of consecutive elements in Python?
38,622,868
<p>Given a list of numbers, how can I split it whenever the distance of two adjacent elements is larger than <em>n</em>?</p> <p><strong>Input:</strong></p> <pre><code>n = 3 l = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] </code></pre> <p><strong>Output:</strong></p> <pre><code>[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]...
0
2016-07-27T20:44:24Z
38,623,590
<pre><code>n = 3 a = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8] b = [abs(i - j) &gt; n for i, j in zip(a[:-1], a[1:])] m = [i + 1 for i, j in enumerate(b) if j is True] m = [0] + m + [len(a)] result = [a[i: j] for i, j in zip(m[:-1], m[1:])] print(result) </code></pre>
0
2016-07-27T21:35:41Z
[ "python", "list", "split" ]
Python binding of functions within a c++ program
38,622,890
<p>I have a program written in c++ that functions on it's own, however we want to make it accessible to Python. Specifically, we have several functions that are more efficient in c++, but we do a lot of other things with the output using Python scripts. I don't want to rewrite the whole of main() in Python as we make u...
0
2016-07-27T20:45:52Z
38,624,911
<p>We have an extensive c++ library which we made available to python through use of a python wrapper class which calls an interface that we defined in boost python. </p> <p>One python class handles all the queries in a pythonic manner, by calling a python extension module written in c++ with boost python. The python ...
1
2016-07-27T23:42:32Z
[ "python", "c++", "boost", "boost-python", "python-bindings" ]
How do I login to the Django Rest browsable API when I have a custom auth model?
38,623,002
<p>I have a custom user model as follows in <code>account/models.py</code></p> <pre><code>from django.contrib.auth.modles import AbstractUser from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from django.db import models from django.dispatch import receiver from django.co...
1
2016-07-27T20:53:39Z
38,626,166
<p>I've ran into this before too and from what I remember it's because the built-in DRF auth form is not using TokenAuthentication, but rather SessionAuthentication. Try adding <code>rest_framework.authentication.SessionAuthentication</code> to your <code>DEFAULT_AUTHENTICATION_CLASSES</code> tuple</p>
0
2016-07-28T02:26:38Z
[ "python", "django", "rest", "login" ]
Why is numpy's root failing?
38,623,076
<ul> <li><em>Why is my answer from <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html" rel="nofollow"><code>np.roots</code></a> different from <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyroots.html" rel="nofollow"><code>np.polynomial.polynomial...
2
2016-07-27T20:59:37Z
38,623,178
<p>The code in <code>numpy.polynomial</code> is newer than <code>numpy.roots</code> (and <code>numpy.poly1d</code>, etc). In the new polynomial code, the convention for the order of the coefficients was changed. In the new code, the coefficients are given in increasing order, while in the old code, the highest order ...
4
2016-07-27T21:05:36Z
[ "python", "numpy", "polynomial-math", "polynomials" ]
Tweepy - API.Search
38,623,102
<p>I want to be able to run a search for keywords (<code>ContinuousDelivery</code> in this example) and have it return the date created, text and screen name of tweets containing the keyword and store it into a CSV which will ultimately be ported to a relational database. </p> <ol> <li><p>I can get the created and tex...
1
2016-07-27T21:00:52Z
38,662,431
<p>To get the author's screenname use tweet.author.screen_name. The profile is it's own object inside the tweet.</p>
0
2016-07-29T15:27:09Z
[ "python", "twitter", "tweepy" ]
VSCode -- how to set working directory for debug
38,623,138
<p>I'm starting to use vscode for Python. I have a simple test program. I want to run it under debug and I need to set the working directory for the run. </p> <p>How/where do I do that?</p>
2
2016-07-27T21:03:05Z
38,623,229
<p>You can set up current working directory for debugged program using <code>cwd</code> argument in <code>launch.json</code></p>
0
2016-07-27T21:09:43Z
[ "python", "vscode" ]
VSCode -- how to set working directory for debug
38,623,138
<p>I'm starting to use vscode for Python. I have a simple test program. I want to run it under debug and I need to set the working directory for the run. </p> <p>How/where do I do that?</p>
2
2016-07-27T21:03:05Z
38,637,243
<p>All you need to do is configure the cwd setting in launch.json file as follows: <code> { "name": "Python", "type": "python", "pythonPath":"python", .... "cwd": "&lt;Path to the directory&gt;" .... } </code></p> <p>More information about this can be found here: <a href="https://github.com/Do...
1
2016-07-28T13:04:05Z
[ "python", "vscode" ]
Terminal hangs after sshing via python subprocess
38,623,221
<p>I've been working on this for a long time, and any help would be appreciated.</p> <p>What I am trying to do here is ssh to a testing server, then cd .., and then print a list of the directories in that folder through python. This code is my best attempt:</p> <pre><code>def subprocess_cmd(command): process = su...
2
2016-07-27T21:08:57Z
38,637,265
<p>If you want just to list directory contents, you can send some command over SSH.</p> <p>Bash:</p> <pre><code>ssh 192.168.122.24 ls /tmp </code></pre> <p>or if you want to use "cd" as in your question:</p> <pre><code>ssh 192.168.122.24 "cd /tmp; ls" </code></pre> <p>Python script example:</p> <pre><code>import ...
1
2016-07-28T13:04:54Z
[ "python", "bash", "ssh", "subprocess" ]
KeyError: 'plotly_domain'
38,623,249
<p>I am running the code from <a href="https://plot.ly/~jackp/16625/" rel="nofollow">here</a>:</p> <pre><code>import plotly import plotly.plotly as py from plotly.tools import FigureFactory as FF import numpy as np import pandas as pd print(plotly.__version__) dataframe = pd.DataFrame(np.random.randn(100, 3), ...
2
2016-07-27T21:10:47Z
38,623,309
<p>Based on this answer, try using <code>py.plot</code> instead of <code>py.iplot</code>.</p> <p><a href="https://stackoverflow.com/questions/34929778/keyerror-plotly-domain-when-using-plotly-to-do-scatter-plot-in-python">KeyError: &#39;plotly_domain&#39; when using plotly to do scatter plot in python</a></p> <p>The ...
2
2016-07-27T21:15:09Z
[ "python", "python-3.x", "plot", "plotly", "keyerror" ]
Reading a portion of a large xlsx file with python
38,623,368
<p>I have a large .xlsx file with 1 million rows. I don't want to open the whole file in one go. I was wondering if I can read a chunk of the file, process it and then read the next chunk? (I prefer to use pandas for it.)</p>
1
2016-07-27T21:19:34Z
38,623,540
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">read_excel()</a> method:</p> <pre><code>chunksize = 10**5 for chunk in pd.read_excel(filename, chunksize=chunksize): # process `chunk` DF </code></pre> <p>if your excel file has multiple sheets, ta...
1
2016-07-27T21:32:52Z
[ "python", "pandas" ]
Reading a portion of a large xlsx file with python
38,623,368
<p>I have a large .xlsx file with 1 million rows. I don't want to open the whole file in one go. I was wondering if I can read a chunk of the file, process it and then read the next chunk? (I prefer to use pandas for it.)</p>
1
2016-07-27T21:19:34Z
38,623,545
<p>Yes. Pandas supports chunked reading. You would go about reading an excel file like so.</p> <pre><code>import pandas as pd xl = pd.ExcelFile("myfile.xlsx") for sheet_name in xl.sheet_names: reader = xl.parse(sheet_name, chunksize=1000): for chunk in reader: #parse chunk here </code></pre>
2
2016-07-27T21:33:00Z
[ "python", "pandas" ]
Nested for loop on tupled coordinates
38,623,400
<p>I need to write a code that will eventually read in coordinates from across multiple tables of big data stored in excel sheets but first I wanted to learn to write a nested for loop to analyze the tuples in the code below.</p> <p>All I can find for nested for loops don't have anything like this so I thought it coul...
0
2016-07-27T21:21:23Z
38,623,585
<p><strong>For-loops in general</strong> :<br> You choose one variable as an iterator (can be anything, but shouldn't be something that is used elsewhere at the same time) which iterates through an iterable (e.g. a list). In my example below, i and j are the iterators while range(10) is the object they iterate through....
2
2016-07-27T21:35:16Z
[ "python", "for-loop", "math", "coordinates", "nested-loops" ]
Nested for loop on tupled coordinates
38,623,400
<p>I need to write a code that will eventually read in coordinates from across multiple tables of big data stored in excel sheets but first I wanted to learn to write a nested for loop to analyze the tuples in the code below.</p> <p>All I can find for nested for loops don't have anything like this so I thought it coul...
0
2016-07-27T21:21:23Z
38,623,930
<p>Assuming you're getting your data in as tuples:</p> <pre><code># convert file1 and file2 to lists of 2d points # this is quite sloppy and I'll tidy it up when I get home from work xs = [[float(pq.split(',')[0]),float(pq.split(',')[1])] for pq in list(file1)] ys = [[float(pq.split(',')[0]),float(pq.split(',')[1])] f...
1
2016-07-27T22:01:51Z
[ "python", "for-loop", "math", "coordinates", "nested-loops" ]
Nested for loop on tupled coordinates
38,623,400
<p>I need to write a code that will eventually read in coordinates from across multiple tables of big data stored in excel sheets but first I wanted to learn to write a nested for loop to analyze the tuples in the code below.</p> <p>All I can find for nested for loops don't have anything like this so I thought it coul...
0
2016-07-27T21:21:23Z
38,623,996
<p>You represent your tuples as strings which is very inconvenient to work with. "Real" tuples are generally better to start off.</p> <pre><code>file1 = [(1.36, 7.11), (1.38, 7.12), (1.5, -7.14), (8.7, 3.33)] file2 = [(1.46, 7.31), (1.47, 7.32), (1.49, -7.34), (8.56, 3.13)] </code></pre> <p>The next question is, how ...
1
2016-07-27T22:07:46Z
[ "python", "for-loop", "math", "coordinates", "nested-loops" ]
Questions on use ginput and print the results with python
38,623,495
<p>I would like to use <code>ginput</code> function in python to get two points from the figure and get the closest int value and save the array. The code is shown below:</p> <pre><code>from __future__ import print_function from pylab import plot, ginput, show, axis import matplotlib.pyplot as plt import numpy as np ...
1
2016-07-27T21:29:16Z
38,623,561
<p>In Python 3, <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">print()</a> is a function, therefore it requires parentheses around its input argument like any other function.</p>
1
2016-07-27T21:33:58Z
[ "python" ]
Visualisation with Python
38,623,570
<p>I want to plot the data from a connected device (which count number of steps) used by 100 users. I got about 4000 records for each user.</p> <p>So I plot each point mannualy in a picture of size 100*4000 using the package PIL : <code>Image.putpixel((CurrentTimePx,CurrentRowPx),(CurrentActivityPixelIntensity,0,0))</...
0
2016-07-27T21:34:15Z
38,623,687
<p>Try using matplotlib instead of PIL.</p> <p>Matplotlib:</p> <p><a href="http://matplotlib.org/" rel="nofollow">http://matplotlib.org/</a></p> <p>Specifically about bar charts (I think this is what you want):</p> <p><a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">http://matplotlib.o...
1
2016-07-27T21:42:17Z
[ "python", "image", "visualization" ]
Visualisation with Python
38,623,570
<p>I want to plot the data from a connected device (which count number of steps) used by 100 users. I got about 4000 records for each user.</p> <p>So I plot each point mannualy in a picture of size 100*4000 using the package PIL : <code>Image.putpixel((CurrentTimePx,CurrentRowPx),(CurrentActivityPixelIntensity,0,0))</...
0
2016-07-27T21:34:15Z
38,623,714
<p>I would put these data in a (100, 4000) numpy array and plot it using <code>matplotlib</code>. For example:</p> <pre><code>import matplotlib.pyplot as plt # TODO: Put data in numpy array X # TODO: Define the image size you want in my_size (eg, my_size=(10, 20)) plt.figure(figsize=my_size) plt.imshow(X, interpolatio...
1
2016-07-27T21:44:31Z
[ "python", "image", "visualization" ]
Comparing values in different time frames (after resample and rolling in Pandas)
38,623,737
<p>I have fast timeframe (tick data) and want to check if the value is equal to maximum price of rolling max on 1 minute timeframe.</p> <p>Tick data are:</p> <pre><code>2016-06-27 08:30:00 4243.00 2016-06-27 08:30:00 4243.00 2016-06-27 08:30:00 4243.00 2016-06-27 08:30:00 4243.00 2016-06-27 08:30:00 42...
0
2016-07-27T21:46:43Z
38,647,845
<p>If I understand correctly what you're asking, you may want to use <code>Series.asof</code>, which returns last valid value and can take a list-like argument. I assume <code>ntick</code> (and also <code>rol</code>) has a sorted <code>DatetimeIndex</code> as an index.</p> <pre><code>rol2 = rol.squeeze().asof(ntick.in...
1
2016-07-28T22:37:28Z
[ "python", "pandas" ]
duplicated outputs of np.apply_along_axis when a dict is returned
38,623,768
<p>Check this piece of code snippet,</p> <pre><code>import numpy as np a = np.arange(20).reshape(2,10) # the result is right if there is only 1 key func = lambda x: dict(k1=len(x)) print np.apply_along_axis(func, -1, a) out[1]: [[{'k1': 10}] [{'k1': 10}]] # but if there are more than 1 key in the return...
0
2016-07-27T21:49:03Z
38,627,495
<p>It seems like <code>np.apply_along_axis</code> is trying to figure out what the resulting shape should be, based on the result of calling <code>func</code>. If your input array has shape <code>(n, m)</code> and your <code>func</code> returns something with length <code>k</code>, then <code>np.apply_along_axis(func,...
1
2016-07-28T05:06:57Z
[ "python", "numpy", "dictionary" ]
ImportError: cannot import name 'tree' for sklearn
38,623,912
<p>I've recently installed Scipy, Numpy and Scikit-learn by using pip, but when I run the program below </p> <pre><code>from sklearn import tree features = [[140, 1], [130, 1], [150, 1], [170, 1]] #input labels = [0, 0, 1, 1] #output clf = tree.DecisionTreeClassifier() clf = clf.fit(features, labels) #fit = find p...
0
2016-07-27T22:00:11Z
38,624,095
<p>The solution is to rename your "sklearn.py" under the "Machine Learning" folder to any other name but not "sklearn.py".</p> <p>Why? That's the mechanism of Python modules searching sequence. Try prepend these lines to your "sklearn.py":</p> <pre><code>import sys print(sys.path) </code></pre> <p>You'll find the fi...
0
2016-07-27T22:16:28Z
[ "python", "numpy", "scikit-learn", "importerror" ]
string compared to list in a dict
38,623,921
<p>I will be entering a large data set of strs to compare to a dict with lists. For example, the str 'phd' will be compared against strs from this dict</p> <pre><code> edu_options = {'Completed College' : [ 'bachelor', 'ba', 'be', 'bs'....], 'Grad School' : ['phd','doctor'...] } </code></pre> <p>i...
0
2016-07-27T22:00:45Z
38,624,765
<p>I'm not sure if I understand what you should return when you find a match in a list, maybe the key of that list?</p> <p>In that case, this should work:</p> <pre><code>&gt;&gt;&gt; edu_options = {'Completed College' : [ 'bachelor', 'ba', 'be', 'bs'], 'Grad Shool': ['phd', 'doctor']} &gt;&gt;&gt; cleaned_string = 'p...
1
2016-07-27T23:25:39Z
[ "python", "dictionary", "comparison" ]
Python 2.7.12 Matplotlib x11 forwarding not showing or throwing multiple errors
38,623,934
<p>I am logging in to a remote linux machine from windows 7 via putty. In the settings I enabled the X11 forwarding option, and added the -X flag when loging in to the ssh server. On this server I run the following python code:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib matplotlib.use('Agg')...
0
2016-07-27T22:02:02Z
38,635,174
<p>I got it figured out: </p> <p>at first it is like "tcaswell" said, you can´t use the <code>'Agg'</code> backend with interactive windows. This error gets fixed by just deleting the first two lines of code. The second problem is, that by the <code>plt.figure(1)</code> comand a new figure 1 is created but in the <co...
0
2016-07-28T11:34:41Z
[ "python", "python-2.7", "matplotlib", "x11", "x11-forwarding" ]
How to auto tweet from sqlite?
38,623,945
<p>I have a db.sqlite file that is updated live. If a certain value is saved within DB I would like to create a tweet based around this value. Any recommendations on the best way to do this please. </p>
-1
2016-07-27T22:03:18Z
38,623,975
<p>I'm not sure if you can do it directly in sqlite (even if you could, sounds like it would be a very bad decision to shift so much logic into a database unless extremely necessary)</p> <p>You can create tweets from Python though:</p> <p><a href="https://pypi.python.org/pypi/twitter" rel="nofollow">https://pypi.pyth...
0
2016-07-27T22:05:50Z
[ "python", "sqlite", "twitter" ]
Python - Formatting Data into Excel Spreadsheet Using pandas
38,623,948
<p>I want two columns of data the team name and the line. However all my input is just placed into cell B1. (Note that was with the commented out code at the bottom of my snippet). I think I need to iterate through my lists with for loops to get all the teams down the A column, and lines down the B column, but just can...
1
2016-07-27T22:03:22Z
38,624,783
<p>Here you should not do this because you're making lists of lists:</p> <pre><code>data = {'Team':[team], 'line' : [line]} # ... </code></pre> <p>Instead do:</p> <pre><code>data = {'Team': team, 'line': line} # ... </code></pre>
1
2016-07-27T23:27:42Z
[ "python", "excel", "pandas", "beautifulsoup" ]
youtube-dl download videos with formatid
38,623,977
<blockquote> <p>------------------------------Format Numbers----------------------------------------------------------------------</p> <ul> <li>249 webm audio only DASH audio 52k , opus @ 50k, 629.08KiB</li> <li>250 webm audio only DASH audio 69k , opus @ 70k, 811.98KiB</li>...
0
2016-07-27T22:05:50Z
38,624,425
<p>If you really want format 22, then indeed, pass in a <code>format</code> key of <code>22</code>. You can use <code>/best</code> to fall back to the best video format if 22 is not available:</p> <pre><code>ydl_opts = { 'format': '22/best', ... </code></pre>
1
2016-07-27T22:47:11Z
[ "python", "youtube", "embedding", "youtube-dl", "python-embedding" ]
Get substring between strings from a python list
38,623,983
<p>How to get the content between strings <code>&amp;quot</code> and <code>autoRefresh</code> which will be <code>/commander/link/jobDetails/jobs/a2537f238-8622-11ee-a1a0-f0921c14c828?</code> from a list as below, I just need the first match (there could be multiple matches).</p> <pre><code>['something', 'something', ...
0
2016-07-27T22:06:31Z
38,624,035
<p>You need to iterate over the list, checking each string:</p> <pre><code>big_list = ['something', 'something', ' something top.window.location.href = &amp;quot;/commander/link/jobDetails/jobs/a2537f238-8622-11ee-a1a0-f0921c14c828?autoRefresh=0&amp;amp;s=Jobs&amp;quot;;"&gt;','something'] def get_all_subs(lst, pat, ...
0
2016-07-27T22:10:43Z
[ "python" ]
Get substring between strings from a python list
38,623,983
<p>How to get the content between strings <code>&amp;quot</code> and <code>autoRefresh</code> which will be <code>/commander/link/jobDetails/jobs/a2537f238-8622-11ee-a1a0-f0921c14c828?</code> from a list as below, I just need the first match (there could be multiple matches).</p> <pre><code>['something', 'something', ...
0
2016-07-27T22:06:31Z
38,624,165
<p>You may use the following:</p> <pre><code>re.search(r'(?&lt;=&amp;quot).*?(?=autoRefresh)', ''.join(YourList)) </code></pre>
0
2016-07-27T22:22:59Z
[ "python" ]
Jinja: Check if variable is iterable
38,623,993
<p>Is there a way in Jinja to check if a variable is iterable? I'm working with Django and depening on whether I use <code>objects.filter</code> or <code>objects.get</code> the <code>response</code> is send to the jinja template is could be iterable or not. </p> <p>I tried the following:</p> <pre><code>{% extends 'he...
0
2016-07-27T22:07:33Z
38,624,197
<p>Try:</p> <p><code>{% if iterable(response) %} </code></p>
1
2016-07-27T22:26:38Z
[ "python", "django", "jinja2" ]
Tuple Comparison with Integers
38,624,020
<p>I am trying to do tuple comparison. I expected 2 as a result, but this bit of code prints out 0. Why?</p> <pre><code>tup1 = (1, 2, 3, 4, 5) tup2 = (2, 7, 9, 8, 5) count = 0 if tup1[0:5] == tup2[0]: count + 1 elif tup1[0:5] == tup2[1]: count + 1 elif tup1[0:5] == tup2[2]: count + 1 elif tup1[0:5] == tup...
2
2016-07-27T22:09:39Z
38,624,054
<p>You can do what you intend with a set intersection:</p> <pre><code>len(set(tup1) &amp; set(tup2)) </code></pre> <p>The <em>intersection</em> returns the common items in both tuples:</p> <pre><code>&gt;&gt;&gt; set(tup1) &amp; set(tup2) {2, 5} </code></pre> <p>Calling <code>len</code> on the result of the interse...
3
2016-07-27T22:12:39Z
[ "python", "integer", "comparison", "tuples" ]
Tuple Comparison with Integers
38,624,020
<p>I am trying to do tuple comparison. I expected 2 as a result, but this bit of code prints out 0. Why?</p> <pre><code>tup1 = (1, 2, 3, 4, 5) tup2 = (2, 7, 9, 8, 5) count = 0 if tup1[0:5] == tup2[0]: count + 1 elif tup1[0:5] == tup2[1]: count + 1 elif tup1[0:5] == tup2[2]: count + 1 elif tup1[0:5] == tup...
2
2016-07-27T22:09:39Z
38,624,092
<p>You are comparing one slice of one tuple (e.g tup1[0:5]) to one element of the other one which happens to be an integer. Therefore, the result of the comparison will always result in "False". To check, whether an element of tup2 is situated also in tup1 as well, you may use intersection or the following:</p> <pre>...
0
2016-07-27T22:16:25Z
[ "python", "integer", "comparison", "tuples" ]
Tuple Comparison with Integers
38,624,020
<p>I am trying to do tuple comparison. I expected 2 as a result, but this bit of code prints out 0. Why?</p> <pre><code>tup1 = (1, 2, 3, 4, 5) tup2 = (2, 7, 9, 8, 5) count = 0 if tup1[0:5] == tup2[0]: count + 1 elif tup1[0:5] == tup2[1]: count + 1 elif tup1[0:5] == tup2[2]: count + 1 elif tup1[0:5] == tup...
2
2016-07-27T22:09:39Z
38,624,401
<p>Your code fails as you are comparing a tuple to an integer, even if you use in as below you would still need to use <code>+=</code> <code>count + 1</code> does not update the count variable: </p> <pre><code>count = 0 for ele in tup2: if ele in tup1: count += 1 </code></pre> <p>You can do it in linear ...
0
2016-07-27T22:44:41Z
[ "python", "integer", "comparison", "tuples" ]
Assign to masked numpy array without removing mask?
38,624,029
<p>I would like to assign to (a slice of) a masked numpy array but not modify the mask. (Assignment normally clears the mask (unless it is "hard"), which seems completely contrary to the point of masking, but that's what we've got to work with.) I would also like this routine to work for plain unmasked arrays.</p> <...
2
2016-07-27T22:10:25Z
38,624,075
<p>In researching the question, I found an answer:</p> <pre><code>np.copyto(a, -1, where=a &lt; 2) </code></pre>
0
2016-07-27T22:14:46Z
[ "python", "numpy" ]
Assign to masked numpy array without removing mask?
38,624,029
<p>I would like to assign to (a slice of) a masked numpy array but not modify the mask. (Assignment normally clears the mask (unless it is "hard"), which seems completely contrary to the point of masking, but that's what we've got to work with.) I would also like this routine to work for plain unmasked arrays.</p> <...
2
2016-07-27T22:10:25Z
38,624,143
<p>I think what you want can be done by:</p> <pre><code>a.data[a &lt; 2] = -1 </code></pre>
2
2016-07-27T22:20:12Z
[ "python", "numpy" ]
Converting list Dict's to DataFrame: Pandas
38,624,151
<p>I'm doing some web-scraping and I'm storing the variables of interest in form of:</p> <pre><code>a = {'b':[100, 200],'c':[300, 400]} </code></pre> <p>This is for one page, where there were two <code>b</code>'s and two <code>c</code>'s. The next page could have three of each, where I'd store them as:</p> <pre><cod...
2
2016-07-27T22:21:25Z
38,624,388
<p>What about simply merging the dictionaries in each step?</p> <pre><code>import pandas as pd def merge_dicts(trg, src): for k, v in src.items(): trg[k].extend(v) a = {'b':[100, 200],'c':[300, 400]} b = {'b':[300, 400, 500],'c':[500, 600, 700]} merge_dicts(a, b) print(a) # {'c': [300, 400, 500, 600, ...
0
2016-07-27T22:43:20Z
[ "python", "pandas", "dictionary", "dataframe" ]
Converting list Dict's to DataFrame: Pandas
38,624,151
<p>I'm doing some web-scraping and I'm storing the variables of interest in form of:</p> <pre><code>a = {'b':[100, 200],'c':[300, 400]} </code></pre> <p>This is for one page, where there were two <code>b</code>'s and two <code>c</code>'s. The next page could have three of each, where I'd store them as:</p> <pre><cod...
2
2016-07-27T22:21:25Z
38,624,739
<p>Try this change the keys for clarity:</p> <pre><code>a = {'e':[100, 200],'f':[300, 400]} b = {'e':[300, 400, 500],'f':[500, 600, 700]} c = {'e':[300, 400, 500],'f':[500, 600, 700]} listDicts = [a,b,c] dd= {} for x in listDicts: for k in listDicts[0].keys(): try: dd[k] = dd[k] + x[k] except:...
1
2016-07-27T23:22:29Z
[ "python", "pandas", "dictionary", "dataframe" ]