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
listlengths
1
5
Script execution time on different computers (python 3.5, miniconda)
38,737,144
<p>I was faced with the following problem: on a computer (number 2) script execution time is significantly greater than on another computer (computer 1).</p> <ul> <li>Computer 1 - i3 - 4170 CPU @ 3.7 GHz (4 core), 4GB RAM (Execution time 9.5 minutes)</li> <li>Computer 2 - i7 - 3.07GHz (8 core), 8GB RAM (Execution time 15-17 minutes)</li> </ul> <p>I use Python to process Excel files. I import for these three libraries:</p> <ul> <li><code>xlrd</code>, <code>xlsxwriter</code>, <code>win32com</code></li> </ul> <p>Why is the execution time different? How can I fix it?</p>
0
2016-08-03T07:31:21Z
38,737,237
<p>It runs on single core, the computer1 has higher clock rate = faster single threaded processing.</p>
1
2016-08-03T07:35:15Z
[ "python", "excel", "python-3.5", "execution-time", "miniconda" ]
Script execution time on different computers (python 3.5, miniconda)
38,737,144
<p>I was faced with the following problem: on a computer (number 2) script execution time is significantly greater than on another computer (computer 1).</p> <ul> <li>Computer 1 - i3 - 4170 CPU @ 3.7 GHz (4 core), 4GB RAM (Execution time 9.5 minutes)</li> <li>Computer 2 - i7 - 3.07GHz (8 core), 8GB RAM (Execution time 15-17 minutes)</li> </ul> <p>I use Python to process Excel files. I import for these three libraries:</p> <ul> <li><code>xlrd</code>, <code>xlsxwriter</code>, <code>win32com</code></li> </ul> <p>Why is the execution time different? How can I fix it?</p>
0
2016-08-03T07:31:21Z
38,737,662
<p>As explained in a comment, Python uses the <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock" rel="nofollow">Global Interpreter Lock (GIL)</a>. As stated on the Wiki: "An interpreter that uses GIL always allows <strong>exactly one thread</strong> to execute at a time, <strong>even if run on a multi-core processor</strong>".</p> <p>Your i3 processor may 'only' have 4 cores instead of the 8 cores in your i7, but Python will only use 1 thread at a time: so the faster the core, the faster your script is executed. As explained on <a href="http://www.computerhope.com/jargon/c/clockspe.htm" rel="nofollow">this page</a>: "The CPU speed determines how many calculations it can perform in one second of time. The higher the speed, the more calculations it can perform, thus making the computer faster."</p>
0
2016-08-03T07:57:08Z
[ "python", "excel", "python-3.5", "execution-time", "miniconda" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside the quotes ',' does not end the key.</p> <pre><code>key1=value1,key2="value2,still_value2" </code></pre> <p>This last part has made it tricky for me to use split or re.split, resorting to for i in range for loops :(.</p> <p>Can anyone demonstrate a clean way to do this?</p> <p>It is OK to assume quotes happen only in values, and that there is no whitespace or non alphanumeric characters.</p>
3
2016-08-03T07:35:59Z
38,738,277
<p>I'm not sure that it does not look like piece of C breakfast and that it is quite elegant :)</p> <pre><code>data = {} original = 'key1=value1,key2="value2,still_value2"' converted = '' is_open = False for c in original: if c == ',' and not is_open: c = '\n' elif c in ('"',"'"): is_open = not is_open converted += c for item in converted.split('\n'): k, v = item.split('=') data[k] = v </code></pre>
2
2016-08-03T08:25:58Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside the quotes ',' does not end the key.</p> <pre><code>key1=value1,key2="value2,still_value2" </code></pre> <p>This last part has made it tricky for me to use split or re.split, resorting to for i in range for loops :(.</p> <p>Can anyone demonstrate a clean way to do this?</p> <p>It is OK to assume quotes happen only in values, and that there is no whitespace or non alphanumeric characters.</p>
3
2016-08-03T07:35:59Z
38,738,409
<p>Using some regex magic from <a href="http://stackoverflow.com/questions/16710076/python-split-a-string-respect-and-preserve-quotes">Split a string, respect and preserve quotes</a>, we can do:</p> <pre><code>import re string = 'key1=value1,key2="value2,still_value2"' key_value_pairs = re.findall(r'(?:[^\s,"]|"(?:\\.|[^"])*")+', string) for key_value_pair in key_value_pairs: key, value = key_value_pair.split("=") </code></pre> <p>Per BioGeek, my attempt to guess, I mean interpret the regex Janne Karila used: The pattern breaks strings on commas but respects double quoted sections (potentially with commas) in the process. It has two separate options: runs of characters that don't involve quotes; and double quoted runs of characters where a double quote finishes the run unless it's (backslash) escaped:</p> <pre><code>(?: # parenthesis for alternation (|), not memory [^\s,"] # any 1 character except white space, comma or quote | # or "(?:\\.|[^"])*" # a quoted string containing 0 or more characters # other than quotes (unless escaped) )+ # one or more of the above </code></pre>
5
2016-08-03T08:32:07Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside the quotes ',' does not end the key.</p> <pre><code>key1=value1,key2="value2,still_value2" </code></pre> <p>This last part has made it tricky for me to use split or re.split, resorting to for i in range for loops :(.</p> <p>Can anyone demonstrate a clean way to do this?</p> <p>It is OK to assume quotes happen only in values, and that there is no whitespace or non alphanumeric characters.</p>
3
2016-08-03T07:35:59Z
38,738,508
<p>I came up with this regular expression solution:</p> <pre><code>import re match = re.findall(r'([^=]+)=(("[^"]+")|([^,]+)),?', 'key1=value1,key2=value2,key3="value3,stillvalue3",key4=value4') </code></pre> <p>And this makes "match":</p> <pre><code>[('key1', 'value1', '', 'value1'), ('key2', 'value2', '', 'value2'), ('key3', '"value3,stillvalue3"', '"value3,stillvalue3"', ''), ('key4', 'value4', '', 'value4')] </code></pre> <p>Then you can make a for loop to get keys and values:</p> <pre><code>for m in match: key = m[0] value = m[1] </code></pre>
3
2016-08-03T08:37:03Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside the quotes ',' does not end the key.</p> <pre><code>key1=value1,key2="value2,still_value2" </code></pre> <p>This last part has made it tricky for me to use split or re.split, resorting to for i in range for loops :(.</p> <p>Can anyone demonstrate a clean way to do this?</p> <p>It is OK to assume quotes happen only in values, and that there is no whitespace or non alphanumeric characters.</p>
3
2016-08-03T07:35:59Z
38,738,754
<p>Based on several other answers, I came up with the following solution:</p> <pre><code>import re import itertools data = 'key1=value1,key2="value2,still_value2"' # Based on Alan Moore's answer on http://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python def split_on_non_quoted_equals(string): return re.split('''=(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', string) def split_on_non_quoted_comma(string): return re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', string) split1 = split_on_non_quoted_equals(data) split2 = map(lambda x: split_on_non_quoted_comma(x), split1) # 'Unpack' the sublists in to a single list. Based on Alex Martelli's answer on http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python flattened = [item for sublist in split2 for item in sublist] # Convert alternating elements of a list into keys and values of a dictionary. Based on Sven Marnach's answer on http://stackoverflow.com/questions/6900955/python-convert-list-to-dictionary d = dict(itertools.izip_longest(*[iter(flattened)] * 2, fillvalue="")) </code></pre> <p>The resulting <code>d</code> is the following dictionary:</p> <pre><code>{'key1': 'value1', 'key2': '"value2,still_value2"'} </code></pre>
1
2016-08-03T08:48:45Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside the quotes ',' does not end the key.</p> <pre><code>key1=value1,key2="value2,still_value2" </code></pre> <p>This last part has made it tricky for me to use split or re.split, resorting to for i in range for loops :(.</p> <p>Can anyone demonstrate a clean way to do this?</p> <p>It is OK to assume quotes happen only in values, and that there is no whitespace or non alphanumeric characters.</p>
3
2016-08-03T07:35:59Z
38,738,997
<p>I would advise against using regular expressions for this task, because the language you want to parse is not regular.</p> <p>You have a character string of multiple key value pairs. The best way to parse this is not to match patterns on it, but to properly tokenize it.</p> <p>There is a module in the Python standard library, called <code>shlex</code>, that mimics the parsing done by POSIX shells, and that provides a lexer implementation that can easily be customized to your needs.</p> <pre><code>from shlex import shlex def parse_kv_pairs(text, item_sep=",", value_sep="="): """Parse key-value pairs from a shell-like text.""" # initialize a lexer, in POSIX mode (to properly handle escaping) lexer = shlex(text, posix=True) # set ',' as whitespace for the lexer # (the lexer will use this character to separate words) lexer.whitespace = item_sep # include '=' as a word character # (this is done so that the lexer returns a list of key-value pairs) # (if your option key or value contains any unquoted special character, you will need to add it here) lexer.wordchars += value_sep # then we separate option keys and values to build the resulting dictionary # (maxsplit is required to make sure that '=' in value will not be a problem) return dict(word.split(value_sep, maxsplit=1) for word in lexer)) </code></pre> <p><strong>Example run :</strong></p> <pre><code>parse_kv_pairs( 'key1=value1,key2=\'value2,still_value2,not_key1="not_value1"\'' ) </code></pre> <p><strong>Output :</strong></p> <pre><code>{'key1': 'value1', 'key2': 'value2,still_value2,not_key1="not_value1"'} </code></pre> <p><strong>EDIT:</strong> I forgot to add that the reason I usually stick with shlex rather than using regular expressions (which are faster in this case) is that it gives you less surprises, especially if you need to allow more possible inputs later on. I never found how to properly parse such key-value pairs with regular expressions, there will always be inputs (ex: <code>A="B=\"1,2,3\""</code>) that will trick the engine. </p> <p>If you do not care about such inputs, (or, put another way, if you can ensure that your input follows the definition of a regular language), regular expressions are perfectly fine.</p> <p><strong>EDIT2:</strong> <code>split</code> has a <code>maxsplit</code> argument, that is much more cleaner to use than splitting/slicing/joining. Thanks to @cdlane for his sound input !</p>
2
2016-08-03T09:00:01Z
[ "python", "parsing" ]
Redis - Pyredis iterating through results from SINTER on SET
38,737,271
<p>I have 2 SET structures with the following values added:</p> <pre><code>r.sadd("clONE", 'abc') r.sadd("clONE", 'def') r.sadd("clONE", 'ghi') r.sadd("TWO", 'abc') r.sadd("TWO", 'def') print(r.sinter("clONE", "TWO")) OUTPUT: set(['abc', 'def']) </code></pre> <p>How do I get the value 'abc' and the 'def' out of the SET() using pyredis? I tried using array syntax by specifying array index[0] but got the following error</p> <pre><code>print(r.sinter("clONE", "TWO")[0]) TypeError: 'set' object does not support indexing </code></pre>
0
2016-08-03T07:37:01Z
38,738,248
<p>sets are not indexed. The order depends on the internal hash. Never rely on the order in a set, even if it appears logical.</p> <p>You can do the following:</p> <pre><code>s = r.sinter("clONE", "TWO") # iterate through the set, unsorted for i in s: print(i) </code></pre> <p>or</p> <pre><code>l = sorted(s) # returns a sorted list (alphanum) print(l[0]) # will print 'abc' </code></pre>
1
2016-08-03T08:24:21Z
[ "python", "redis" ]
How can I use global variable in python class?
38,737,314
<p>the Java code runs, while python code not, why? How can I access global variable inside class in Python?</p> <p><strong>Python code:</strong></p> <pre><code>Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None previous = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if not self.isValidBST(root.left): return False if previous!=None and previous &gt;= root.val: return False previous = root.val return self.isValidBST(root.right) </code></pre> <blockquote> <p>Line 20: UnboundLocalError: local variable 'previous' referenced before assignment.</p> </blockquote> <p><strong>Java code:</strong></p> <pre><code> public class Solution { private Integer previous = null; public boolean isValidBST(TreeNode root) { if(root == null){ return true; } if(!isValidBST(root.left)){ return false; } if(previous != null &amp;&amp; previous&gt;=root.val){ return false; } previous = root.val; return isValidBST(root.right); } } </code></pre>
1
2016-08-03T07:39:06Z
38,737,429
<p>Try this instead: </p> <pre><code> class Solution(object): previous = None def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if not self.isValidBST(root.left): return False if self.previous!=None and self.previous &gt;= root.val: return False self.previous = root.val return self.isValidBST(root.right) </code></pre> <p>Note the <code>previous</code> is now inside the class, and uses <code>self.previous</code> to access it </p> <p>Edit: To pass it to outside you would need to pass the Solution Object </p> <pre><code>solution = Solution() #perform something to assign a previous node test = Test() test.getPrev(solution) class Test(object): def getPrev(self, solution): print solution.previous </code></pre>
0
2016-08-03T07:45:34Z
[ "java", "python" ]
How can I use global variable in python class?
38,737,314
<p>the Java code runs, while python code not, why? How can I access global variable inside class in Python?</p> <p><strong>Python code:</strong></p> <pre><code>Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None previous = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if not self.isValidBST(root.left): return False if previous!=None and previous &gt;= root.val: return False previous = root.val return self.isValidBST(root.right) </code></pre> <blockquote> <p>Line 20: UnboundLocalError: local variable 'previous' referenced before assignment.</p> </blockquote> <p><strong>Java code:</strong></p> <pre><code> public class Solution { private Integer previous = null; public boolean isValidBST(TreeNode root) { if(root == null){ return true; } if(!isValidBST(root.left)){ return false; } if(previous != null &amp;&amp; previous&gt;=root.val){ return false; } previous = root.val; return isValidBST(root.right); } } </code></pre>
1
2016-08-03T07:39:06Z
38,738,029
<p>You should simply use global keyword. As previous = None is defined outside class Solution, so to use same variable inside class, add a line.</p> <pre><code>global previous if previous!=None and previous &gt;= root.val: your logic </code></pre> <p>this will do your work. </p>
0
2016-08-03T08:13:15Z
[ "java", "python" ]
replacing the values in a numpy array with the values of another array against value of one array as index in another
38,737,403
<p>I want to change the values in a numpy <strong>array(x)</strong> corresponding to the value in numpy <strong>array(y)</strong> at <code>index = x[index]</code></p> <p>A numpy array <code>x = [1,2,3,4,0,1,2,3]</code> another Numpy Array <code>y = [3,4,0,1,2]</code></p> <pre><code>for i in range(len(x)): x[i] = y[x[i]] </code></pre> <p>Is there any faster way to do this?</p>
0
2016-08-03T07:43:49Z
38,737,460
<p>Use:</p> <pre><code>x = y[x] </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.array( [1,2,3,4,0,1,2,3] ) &gt;&gt;&gt; y = np.array( [3,4,0,1,2] ) &gt;&gt;&gt; y[x] array([4, 0, 1, 2, 3, 4, 0, 1]) </code></pre> <p>Or, to demonstrate assignment:</p> <pre><code>&gt;&gt;&gt; x = y[x] &gt;&gt;&gt; x array([4, 0, 1, 2, 3, 4, 0, 1]) </code></pre>
0
2016-08-03T07:47:21Z
[ "python", "numpy" ]
how ctypes bitfields really work?
38,737,497
<p>In python, using ctypes, following is legal:</p> <pre><code>from ctypes import * class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] p = POINT(10,20) sum = p.x + p.y </code></pre> <p>But how this works? I mean how p.x is perfectly legal? What kind of trick provides this? thanks.</p>
0
2016-08-03T07:48:50Z
38,738,032
<p>When you initialize an instance of a subclass the <code>Structure</code> class it reads the <code>_fields_</code> and associates attributes based on the field names in that list. </p> <p>This is all done in C, so if you want to see exactly how it is done you need to use the source, in particular the definition of the <code>Struct_type</code>, and the <code>_init_pos_args</code> function <a href="https://github.com/python/cpython/blob/master/Modules/_ctypes/_ctypes.c#L4021" rel="nofollow">https://github.com/python/cpython/blob/master/Modules/_ctypes/_ctypes.c#L4021</a></p>
2
2016-08-03T08:13:17Z
[ "python", "bit-fields" ]
what is the difference in ways setting indexes
38,737,528
<p>What is the difference between how I set index of the data frame?</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>I get following error:</p> <pre><code>Shape of passed values is (2, 3), indices imply (2, 1) </code></pre> <p>If I do following ways it's working ok:</p> <pre><code>df2 = pd.DataFrame(data=data, columns=['key', 'amount']) df2.set_index(['key'], inplace=True) </code></pre> <p>What is the difference between the ways I set the indexes ?</p>
2
2016-08-03T07:50:29Z
38,737,661
<p>In the first way:</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>You are specifying the index to be a single value of <code>'key'</code>. Said another way, there will be a single row whose label is <code>'key'</code>.</p> <p>In the second way:</p> <pre><code>df2 = pd.DataFrame(data=data, columns=['key', 'amount']) df2.set_index(['key'], inplace=True) </code></pre> <p>You've specified a column named <code>'key'</code> that may contain many rows. You subsequently instruct <code>df2</code> to make it's index equal to the entire column named <code>'key'</code>.</p>
2
2016-08-03T07:57:03Z
[ "python", "pandas", "dataframe" ]
what is the difference in ways setting indexes
38,737,528
<p>What is the difference between how I set index of the data frame?</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>I get following error:</p> <pre><code>Shape of passed values is (2, 3), indices imply (2, 1) </code></pre> <p>If I do following ways it's working ok:</p> <pre><code>df2 = pd.DataFrame(data=data, columns=['key', 'amount']) df2.set_index(['key'], inplace=True) </code></pre> <p>What is the difference between the ways I set the indexes ?</p>
2
2016-08-03T07:50:29Z
38,737,690
<p>On the one hand, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>pd.Dataframe</code></a> expects index to be an array, and will be used as index for the rows, for example :</p> <pre><code>In [17]: data Out[17]: [['A', 5], ['B', 6], ['C', 7]] In [18]: df = pd.DataFrame(data=data, index=['a', 'b', 'c']) In [19]: df Out[19]: 0 1 a A 5 b B 6 c C 7 </code></pre> <p>This is not what you are trying to achieve.</p> <p>On the other hand <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html#pandas.DataFrame.set_index" rel="nofollow"><code>DataFrame.set_index</code></a> sets one (or more) column(s) to <strong>become</strong> the index, which is what you want to do in this case.</p>
2
2016-08-03T07:58:35Z
[ "python", "pandas", "dataframe" ]
Sorting words in query in alphabetical order and remove duplicate words from individual rows
38,737,561
<p>I want to sort the words of a given query from each row of Pandas DataFrame and then remove duplicates from them. How can I perform this task on each row separately like : Given DataFrame :</p> <pre><code>Sr.No | Query ------------- 1. war gears of war 2. call of duty 3. legend of troy legend 4. resident evil </code></pre> <p>Resultant DataFrame should be :</p> <pre><code>Sr.No | Query ------------- 1. gears of war 2. call duty of 3. legend of troy 4. evil resident </code></pre> <p>I am using split function to firstly split the words of each row of the data frame but it is not working. </p> <pre><code>for i in range(0,42365): temp2.iloc[[i]]=list(str(temp2.iloc[[i]]).split()) print(temp2.iloc[[i]]) </code></pre> <p>I get the following error: </p> <blockquote> <p>cannot set using a list-like indexer with a different length than the value.</p> </blockquote>
1
2016-08-03T07:51:57Z
38,737,751
<p>You can first create <code>Series</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p> <pre><code>s = df.col.str.split(expand=True).stack() print (s) 0 0 war 1 gears 2 of 3 war 1 0 call 1 of 2 duty 2 0 legend 1 of 2 troy 3 legend 3 0 resident 1 evil dtype: object </code></pre> <p>Then <code>groupby</code> by first level and apply <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html" rel="nofollow"><code>sort_values</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>. Last <code>join</code> all words:</p> <pre><code>print (s.groupby(level=0).apply(lambda x: ' '.join(x.sort_values().drop_duplicates()))) 0 gears of war 1 call duty of 2 legend of troy 3 evil resident dtype: object </code></pre>
1
2016-08-03T08:00:57Z
[ "python", "pandas" ]
Sorting words in query in alphabetical order and remove duplicate words from individual rows
38,737,561
<p>I want to sort the words of a given query from each row of Pandas DataFrame and then remove duplicates from them. How can I perform this task on each row separately like : Given DataFrame :</p> <pre><code>Sr.No | Query ------------- 1. war gears of war 2. call of duty 3. legend of troy legend 4. resident evil </code></pre> <p>Resultant DataFrame should be :</p> <pre><code>Sr.No | Query ------------- 1. gears of war 2. call duty of 3. legend of troy 4. evil resident </code></pre> <p>I am using split function to firstly split the words of each row of the data frame but it is not working. </p> <pre><code>for i in range(0,42365): temp2.iloc[[i]]=list(str(temp2.iloc[[i]]).split()) print(temp2.iloc[[i]]) </code></pre> <p>I get the following error: </p> <blockquote> <p>cannot set using a list-like indexer with a different length than the value.</p> </blockquote>
1
2016-08-03T07:51:57Z
38,737,858
<h3>Setup</h3> <pre><code>df = pd.DataFrame([ ['war gears of war'], ['call of duty'], ['legend of troy legend'], ['resident evil'], ], pd.Index(['1.', '2.', '3.', '4.'], name='Sr.No'), ['Query']) df </code></pre> <p><a href="http://i.stack.imgur.com/bh9IF.png" rel="nofollow"><img src="http://i.stack.imgur.com/bh9IF.png" alt="enter image description here"></a></p> <h3>Solution</h3> <pre><code>df.Query.str.split().apply(lambda x: sorted(set(x))).str.join(' ').to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/IMgp4.png" rel="nofollow"><img src="http://i.stack.imgur.com/IMgp4.png" alt="enter image description here"></a></p>
3
2016-08-03T08:05:42Z
[ "python", "pandas" ]
Import set of builtin functions from a python file to another python file
38,737,599
<p>I have set of inbuilt functions in 'pythonfile1.py' located at '/Users/testuser/Documents', the file contains</p> <pre><code>import os import sys import time </code></pre> <p>Now i want to import 'pythonfile1.py' to 'pythonfile2.py', which is located at '/Users/testuser/Documents/execute' I have tried with my following code and it didn't work:</p> <pre><code>import sys sys.path[0:0] = '/Users/testuser/Documents' import pythonfile1.py print os.getcwd() </code></pre> <p>I want it to print the current working directory </p>
1
2016-08-03T07:53:51Z
38,737,730
<p>if you want to import stuff from another file, you should use python modules.</p> <p>If you will create file named <strong>init</strong>.py then the execute folder becomes a module. After that you can use</p> <pre><code>from .pythonfile1 import function_name </code></pre> <p>or you can use</p> <pre><code>from .pythonfile1 import * </code></pre> <p>which imports all, but better solution is name everything you want to use explicitly</p> <p>you can find more about modules in <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow">documentation</a></p>
0
2016-08-03T08:00:06Z
[ "python", "file" ]
Import set of builtin functions from a python file to another python file
38,737,599
<p>I have set of inbuilt functions in 'pythonfile1.py' located at '/Users/testuser/Documents', the file contains</p> <pre><code>import os import sys import time </code></pre> <p>Now i want to import 'pythonfile1.py' to 'pythonfile2.py', which is located at '/Users/testuser/Documents/execute' I have tried with my following code and it didn't work:</p> <pre><code>import sys sys.path[0:0] = '/Users/testuser/Documents' import pythonfile1.py print os.getcwd() </code></pre> <p>I want it to print the current working directory </p>
1
2016-08-03T07:53:51Z
38,739,470
<p>Your question is a bit unclear. Basically, there are two things 'wrong'. </p> <ul> <li><p>First, your import statement is broken:</p> <pre><code>import pythonfile1.py </code></pre> <p>This specifies a <strong>file</strong> name, not a <strong>module</strong> name - modules don't contain dots and extensions. This is important because dots indicate <em>sub</em>-modules of packages. Your statement is trying to import module <code>py</code> from package <code>pythonfile1</code>. Change it to</p> <pre><code>import pythonfile1 </code></pre></li> <li><p>Second, there's no need to fetch builtins from another module. You can just import them again.</p> <pre><code># pythonfile1 import os print 'pythonfile1', os.getcwd() # assuming py2 syntax # pythonfile2 import os print 'pythonfile2', os.getcwd() </code></pre> <p>If you <em>really</em> want to use <code>os</code> from <code>pythonfile1</code>, you can do so:</p> <pre><code># pythonfile2 import os import pythonfile1 print 'pythonfile2', os.getcwd() print 'pythonfile1-&gt;2', pythonfile1.os.getcwd() </code></pre> <p>Note that <code>os</code> and <code>pythonfile1.os</code> in <code>pythonfile2</code> are the exact same module.</p></li> </ul>
1
2016-08-03T09:20:15Z
[ "python", "file" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,737,942
<p>Here: </p> <pre><code>items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] def check_list(items): for item in items: if item[2] != 0: return False return True print(check_list(items)) </code></pre> <p>If you want to make it a bit more generic:</p> <pre><code>def my_all(enumerable, condition): for item in enumerable: if not condition(item): return False return True print(my_all(items, lambda x: x[2]==0) </code></pre>
1
2016-08-03T08:10:00Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,737,947
<p>Try This:-</p> <pre><code>prinBool = True for item in items: if item[2] != 0: prinBool = False break print prinBool </code></pre>
0
2016-08-03T08:10:11Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,737,985
<p>You could use a <code>for</code> loop with the <code>else</code> clause:</p> <pre><code>for item in items: if item[2] != 0: print False break else: print True </code></pre> <p>The statements after <code>else</code> are executed when the items of a sequence are exhausted, i.e. when the loop wasn't terminated by a <code>break</code>.</p>
0
2016-08-03T08:11:40Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,738,199
<p>Do you mean something like this?</p> <pre><code>for item in items: for x in range (0,3): if item[x] == 0: print "True" </code></pre>
-1
2016-08-03T08:21:27Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,738,231
<p>With <code>functools</code>, it will be easier : </p> <pre><code>from functools import reduce items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] f = lambda y,x : y and x[2] == 0 reduce(f,items) </code></pre>
0
2016-08-03T08:23:19Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:</p> <pre><code>&gt;&gt;&gt; items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] &gt;&gt;&gt; all(item[2] == 0 for item in items) False </code></pre> <p>But when I want to use the similar method to check all elements in a for loop like this</p> <pre><code>&gt;&gt;&gt; for item in items: &gt;&gt;&gt; if item[2] == 0: &gt;&gt;&gt; do sth &gt;&gt;&gt; elif all(item[1] != 0) &gt;&gt;&gt; do sth </code></pre> <p>The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?</p>
-3
2016-08-03T08:06:21Z
38,738,276
<p>If you want to have an <code>if</code> and an <code>else</code>, you can still use the <code>any</code> method:</p> <pre><code>if any(item[2] == 0 for item in items): print('There is an item with item[2] == 0') else: print('There is no item with item[2] == 0') </code></pre> <p>The <code>any</code> comes from <a href="http://stackoverflow.com/a/10666320/5488275">this answer</a>.</p>
1
2016-08-03T08:25:58Z
[ "python", "list", "for-loop" ]
TypeError: list indices must be integers, not str (boolean convertion actually)
38,737,955
<pre><code>import nltk import random from nltk.corpus import movie_reviews documents=[(list(movie_reviews.words(fileid)),category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1]) all_words=[] for w in movie_reviews.words(): all_words.append(w.lower()) all_words=nltk.FreqDist(all_words) word_features = list(all_words.keys())[:3000] def find_features(document): words = set(document) features=[] for w in word_features: features[w]= (w in words) return features print((find_features(movie_reviews.words('neg/cv000_29416.txt')))) featuresets = [(find_features(rev), category) for (rev,category) in documents] </code></pre> <hr> <p>After run, I am getting the error</p> <pre><code>features[w]= (w in words) TypeError: list indices must be integers, not str </code></pre> <p>Please help me to solve it...</p>
1
2016-08-03T08:10:31Z
38,738,209
<p><code>features</code> must be initialized to a <code>dict</code> rather than a <code>list</code>. </p> <p>The error was because <code>word_features</code> is a list of <em>strings</em> which you were trying to index using a list and lists can't have string indices.</p> <pre><code>features={} for w in word_features: features[w] = (w in words) </code></pre>
2
2016-08-03T08:21:58Z
[ "python", "find", "movie", "review" ]
TypeError: list indices must be integers, not str (boolean convertion actually)
38,737,955
<pre><code>import nltk import random from nltk.corpus import movie_reviews documents=[(list(movie_reviews.words(fileid)),category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1]) all_words=[] for w in movie_reviews.words(): all_words.append(w.lower()) all_words=nltk.FreqDist(all_words) word_features = list(all_words.keys())[:3000] def find_features(document): words = set(document) features=[] for w in word_features: features[w]= (w in words) return features print((find_features(movie_reviews.words('neg/cv000_29416.txt')))) featuresets = [(find_features(rev), category) for (rev,category) in documents] </code></pre> <hr> <p>After run, I am getting the error</p> <pre><code>features[w]= (w in words) TypeError: list indices must be integers, not str </code></pre> <p>Please help me to solve it...</p>
1
2016-08-03T08:10:31Z
38,738,263
<p>You have tried to index a list <code>features</code> with a string and it is not possible with python. <strong>List indices can only be integers</strong>. What you need is a <code>dictionary</code>. </p> <p>Try using a <code>defaultdict</code> meaning that even if a key is not found in the dictionary, instead of a <code>KeyError</code> being thrown, a new entry is created</p> <pre><code>from collections import defaultdict features = defaultdict() for w in word_features: features[w] = [w in words] </code></pre>
3
2016-08-03T08:25:26Z
[ "python", "find", "movie", "review" ]
Most reliable way to automatically choose line styles in matplotlib in combination with seaborn
38,738,019
<p>I'm looking for a reliable way to automatically choose line styles for my plots. Right now I have 8 lines for a plot and I hope it is feasible to automatically choose line styles that are distinguishable from each other. </p> <p>As of now, I have basically two ways. Setting markers or defining styles. Both seem to have some problems with seaborn. The first is to use a cycler:</p> <pre><code>plt.rc('axes', prop_cycle=cycler('linestyle', ['-', '--', ':', '-.'])) </code></pre> <p>If I use that, either it overrides seaborn settings, or it gets overwritten by seaborn, depending which one I set first. The other way I found in one of the examples and sets the markers for the lines:</p> <pre><code>def makeStyles(): markers = [] for m in Line2D.markers: try: if len(m) == 1 and m != ' ': markers.append(m) except TypeError: pass styles = markers + [ r'$\lambda$', r'$\bowtie$', r'$\circlearrowleft$', r'$\clubsuit$', r'$\checkmark$'] return styles </code></pre> <p>The problem here is, that quite some of the markers seem to be the same, which is just a line without a marker. </p> <p>Is there any other way that works reliable and works with seaborn?</p>
6
2016-08-03T08:13:01Z
39,107,966
<p>If you want to keep the rcParams that you have in matplotlib and are using the latest version of seaborn (>= 0.7.1), the easiest way is to use <code>import seaborn.apionly</code> as explained in <a href="https://stanford.edu/~mwaskom/software/seaborn/whatsnew.html" rel="nofollow">what's new</a></p>
0
2016-08-23T18:05:43Z
[ "python", "matplotlib", "seaborn" ]
Where to activate my proxy setting in my django app
38,738,151
<p>I am trying send an activation mail to the users in my django app. I am developing in my company and it has proxy. So, when i try to send email to the user, it gives connection timeout error. But when i try it in my home it works perfectly. I have got the proxy settings from my company but I am confused where to update the proxy settings for my django app. Any help on how to make this work ?</p>
0
2016-08-03T08:18:51Z
38,739,319
<p>Looks like you want to use HTTP proxy to access external SMTP server. It is feasible if your proxy server supports Socks or CONNECT methods. Consider using this libraries to wrap your smtp-related code:</p> <ol> <li><a href="http://socksipy.sourceforge.net/" rel="nofollow">http://socksipy.sourceforge.net/</a></li> <li><a href="https://gist.github.com/frxstrem/4487802" rel="nofollow">https://gist.github.com/frxstrem/4487802</a></li> </ol>
1
2016-08-03T09:14:22Z
[ "python", "django", "proxy" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,634
<p>Just take the length of your list and subtract the index from that...</p> <pre><code>L = range(5) for i, n in L: my_i = len(L) -1 - i ... </code></pre> <p>Or if you really need a generator:</p> <pre><code>def reverse_enumerate(L): # Only works on things that have a len() l = len(L) for i, n in enumerate(L): yield l-i-1, n </code></pre> <p><code>enumerate()</code> can't possibly do this, as it works with generic iterators. For instance, you can pass it infinite iterators, that don't even have a "reverse index".</p>
1
2016-08-03T08:42:35Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,652
<p>How about using zip instead with a reversed range?</p> <pre><code>&gt;&gt;&gt; zip(range(9, -1, -1), range(10)) [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] &gt;&gt;&gt; def reversedEnumerate(l): return zip(range(len(l)-1, -1, -1), l) &gt;&gt;&gt; reversedEnumerate(range(10)) [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] </code></pre> <p>As @julienSpronk suggests, use <code>izip</code> to get a generator, also <code>xrange</code>:</p> <pre><code>import itertools &gt;&gt;&gt; import itertools &gt;&gt;&gt; def reversedEnumerate(l): ... return itertools.izip(xrange(len(l)-1, -1, -1), l) ... &gt;&gt;&gt; reversedEnumerate(range(10)) &lt;itertools.izip object at 0x03749760&gt; &gt;&gt;&gt; for i in reversedEnumerate(range(10)): ... print i ... (9, 0) (8, 1) (7, 2) (6, 3) (5, 4) (4, 5) (3, 6) (2, 7) (1, 8) (0, 9) </code></pre>
8
2016-08-03T08:43:26Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,731
<p>I don't know if this solution is better for you, but at least it's shorter:</p> <pre><code>&gt;&gt;&gt; [(4 - x, x) for x in range(5)] [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre>
3
2016-08-03T08:47:57Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,806
<p>Assuming your list is not long and you will not run into performance errors, you may use <code>list(enumerate(range(5)[::-1]))[::-1]</code>.</p> <p>Test:</p> <p><code>&gt;&gt;&gt; list(enumerate(range(5)[::-1]))[::-1] [(0, 4), (1, 3), (2, 2), (3, 1), (4, 0)]</code></p>
1
2016-08-03T08:50:55Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,812
<p>Actually I'm using the same logic as @RemcoGerlich did, but I use <code>list comprehension</code> directly, which make the code now become 1-liner:</p> <pre><code>def generatelist(x): return [(x-1-i,n) for i,n in enumerate(range(x))] </code></pre> <p>Regarding the dilemma of choosing <code>generator</code> or <code>list comprehension</code>, <a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">here</a> is the suggested way:</p> <blockquote> <p>Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.</p> </blockquote>
2
2016-08-03T08:51:15Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enumerate(range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] </code></pre> <p>However I want to reverse the index provided by enumerate so that I get:</p> <pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>So far I have the following code:</p> <pre><code>reversed(list(enumerate(reversed(range(5))))) </code></pre> <p>I was just wondering if there was a neater way to do this?</p>
5
2016-08-03T08:38:41Z
38,738,832
<p>If you're going to re-use it several times, you can make your own generator:</p> <pre><code>def reverse_enum(lst): for j, item in enumerate(lst): yield len(lst)-1-j, item print list(reverse_enum(range(5))) # [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>or</p> <pre><code>def reverse_enum(lst): return ((len(lst)-1-j, item) for j, item in enumerate(lst)) </code></pre>
0
2016-08-03T08:52:21Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Stream a huge Excel file, creating it on the fly?
38,738,655
<p>I'm writing a web application that might sometimes output dozens of thousands of rows (or even more) in an Excel file. openpyxl was chosen for Excel output preparation, but I'm not sure if I could read the data from the database and output it at the same time. Is there a way to do that? Here's an example of what I mean in CSV:</p> <pre><code>def csv_view(request, iterator, keys): """A view that streams a large CSV file.""" class Echo(object): """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def get_iter(): writer = csv.writer(Echo()) yield writer.writerow(keys) for row in iterator: yield writer.writerow(row) response = StreamingHttpResponse(get_iter(), content_type="text/csv") response['Content-Disposition'] = 'attachment; filename="output.csv"' return response </code></pre>
2
2016-08-03T08:43:33Z
38,739,666
<p>openpyxl already provides a <code>write-only</code> mode designed for streaming use. However, as all XSLX files are actually zip files and, as the zip format does not allow streaming, it is not possible to stream XLSX files while they are being written.</p>
1
2016-08-03T09:29:31Z
[ "python", "excel", "streaming", "bigdata", "openpyxl" ]
How to drawing shapes using XLSXWriter
38,738,706
<p>I wana draw some simple shapes in excel file like as "arrow, line, rectangle, oval" using XLSXWriter, but i can find any example to do it. Is it possible ? If not, what library of python can do that ? Thanks!</p>
2
2016-08-03T08:46:35Z
38,740,317
<blockquote> <p>is it possible?</p> </blockquote> <p>Unfortunately not. Shapes aren't supported in XlsxWriter, apart from Textbox. </p>
0
2016-08-03T09:58:36Z
[ "python", "xlsxwriter" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>I want to add a service with this format : </p> <p><code>{ "uri": "http://www.google.fr" "expected_code": 200 }</code></p> <p>So it will have this format :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 }, { "uri": "http://www.google.fr" "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>But I can not do this... I try with .append() but it's in local, json.dumps() but i can not go further than the first indent...</p> <p>This is what I try with .append() :</p> <pre><code>with open('Example_of_configuration', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}') </code></pre> <p>Somebody know how to do ?</p> <p>Thanks in advance</p>
0
2016-08-03T08:46:54Z
38,739,072
<p>You're appending a string value instead of the dictionary. Instead of:</p> <pre><code>dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}') </code></pre> <p>Do</p> <pre><code>dic['Servers_011'][0]['services'].append({"uri":"http://www.google.com", "expected_code": 200}) # as a dict with two keys, without quotes </code></pre> <p>Or like the old version:</p> <pre><code>dic['Servers_011'][0]['services'].append(structure) </code></pre> <p>(without quotes)</p> <p>Using <code>dic</code> as an example:</p> <pre><code>&gt;&gt;&gt; dic['Servers_011'][0]['services'] # before [{'expected_code': 200, 'uri': 'http://www.google.fr/1'}, {'expected_code': 200, 'uri': 'http://www.google.fr/2'}] &gt;&gt;&gt; dic['Servers_011'][0]['services'].append({"uri":"http://www.google.com", "expected_code": 200}) &gt;&gt;&gt; dic['Servers_011'][0]['services'] # after [{'expected_code': 200, 'uri': 'http://www.google.fr/1'}, {'expected_code': 200, 'uri': 'http://www.google.fr/2'}, {'expected_code': 200, 'uri': 'http://www.google.com'}] &gt;&gt;&gt; </code></pre> <p>And then you can (over)write it back to the same file, as per @julien-spronck's answer:</p> <pre><code>with open('test.json', 'w') as f: json.dump(dic, f) </code></pre>
0
2016-08-03T09:02:53Z
[ "python", "json" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>I want to add a service with this format : </p> <p><code>{ "uri": "http://www.google.fr" "expected_code": 200 }</code></p> <p>So it will have this format :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 }, { "uri": "http://www.google.fr" "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>But I can not do this... I try with .append() but it's in local, json.dumps() but i can not go further than the first indent...</p> <p>This is what I try with .append() :</p> <pre><code>with open('Example_of_configuration', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}') </code></pre> <p>Somebody know how to do ?</p> <p>Thanks in advance</p>
0
2016-08-03T08:46:54Z
38,739,127
<pre><code>with open('test.json', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append({"uri": "http://www.google.com", "expected_code": 200}) with open('test.json', 'w') as f: json.dump(dic, f) </code></pre>
0
2016-08-03T09:06:10Z
[ "python", "json" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>I want to add a service with this format : </p> <p><code>{ "uri": "http://www.google.fr" "expected_code": 200 }</code></p> <p>So it will have this format :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/1", "expected_code": 200 }, { "uri": "http://www.google.fr/2", "expected_code": 200 }, { "uri": "http://www.google.fr" "expected_code": 200 } ] }, { "hostname": "nsc-srv-b.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google.fr/3", "expected_code": 200 }, { "uri": "http://www.google.fr/4", "expected_code": 200 } ] } ] } </code></pre> <p>But I can not do this... I try with .append() but it's in local, json.dumps() but i can not go further than the first indent...</p> <p>This is what I try with .append() :</p> <pre><code>with open('Example_of_configuration', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}') </code></pre> <p>Somebody know how to do ?</p> <p>Thanks in advance</p>
0
2016-08-03T08:46:54Z
38,739,510
<p>You are doing the correct thing.But problem was like passing as a string.A small change is needed.Just remove the single quote while passing the structure. Ultimately you want in the form of dict but you are passing as a string. That's obviously not possible.Please see the below to :</p> <pre><code>with open('Example_of_configuration', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append({"uri":"http://www.google.com", "expected_code": 200}) </code></pre> <p>I hope it will work.</p>
0
2016-08-03T09:21:53Z
[ "python", "json" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function itself including the base case. How do I do that?</p> <pre><code>def gray_code(g,n): k=len(g) if n&lt;=0: return else: for i in range (k-1,-1,-1): char='1'+g[i] g.append(char) for i in range (k-1,-1,-1): g[i]='0'+g[i] gray_code(g,n-1) def main(): n=int(raw_input()) g=['0','1'] gray_code(g,n-1) if n&gt;=1: for i in range (len(g)): print g[i], main() </code></pre> <p>Is the recurrence relation of this algorithm <code>T(n)=T(n-1)+n</code> ?</p>
0
2016-08-03T08:52:31Z
38,739,120
<pre><code>def gray_code(n): def gray_code_recurse (g,n): k=len(g) if n&lt;=0: return else: for i in range (k-1,-1,-1): char='1'+g[i] g.append(char) for i in range (k-1,-1,-1): g[i]='0'+g[i] gray_code_recurse (g,n-1) g=['0','1'] gray_code_recurse(g,n-1) return g def main(): n=int(raw_input()) g = gray_code (n) if n&gt;=1: for i in range (len(g)): print g[i], main() </code></pre>
1
2016-08-03T09:05:45Z
[ "python", "algorithm", "recursion", "gray-code" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function itself including the base case. How do I do that?</p> <pre><code>def gray_code(g,n): k=len(g) if n&lt;=0: return else: for i in range (k-1,-1,-1): char='1'+g[i] g.append(char) for i in range (k-1,-1,-1): g[i]='0'+g[i] gray_code(g,n-1) def main(): n=int(raw_input()) g=['0','1'] gray_code(g,n-1) if n&gt;=1: for i in range (len(g)): print g[i], main() </code></pre> <p>Is the recurrence relation of this algorithm <code>T(n)=T(n-1)+n</code> ?</p>
0
2016-08-03T08:52:31Z
38,739,875
<p>It's relatively easy to do if you implement the function iteratively (even if it's defined recursively). This will often execute more quickly as it generally requires fewer function calls.</p> <pre><code>def gray_code(n): if n &lt; 1: g = [] else: g = ['0', '1'] n -= 1 while n &gt; 0: k = len(g) for i in range(k-1, -1, -1): char = '1' + g[i] g.append(char) for i in range(k-1, -1, -1): g[i] = '0' + g[i] n -= 1 return g def main(): n = int(raw_input()) g = gray_code(n) print ' '.join(g) main() </code></pre>
1
2016-08-03T09:38:56Z
[ "python", "algorithm", "recursion", "gray-code" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function itself including the base case. How do I do that?</p> <pre><code>def gray_code(g,n): k=len(g) if n&lt;=0: return else: for i in range (k-1,-1,-1): char='1'+g[i] g.append(char) for i in range (k-1,-1,-1): g[i]='0'+g[i] gray_code(g,n-1) def main(): n=int(raw_input()) g=['0','1'] gray_code(g,n-1) if n&gt;=1: for i in range (len(g)): print g[i], main() </code></pre> <p>Is the recurrence relation of this algorithm <code>T(n)=T(n-1)+n</code> ?</p>
0
2016-08-03T08:52:31Z
38,745,459
<p>Generating Gray codes is easier than you think. The secret is that the Nth gray code is in the bits of N^(N>>1)</p> <p>So:</p> <pre><code>def main(): n=int(raw_input()) for i in range(0, 1&lt;&lt;n): gray=i^(i&gt;&gt;1) print "{0:0{1}b}".format(gray,n), main() </code></pre>
2
2016-08-03T13:46:05Z
[ "python", "algorithm", "recursion", "gray-code" ]
Why my view is not found in django rest framework?
38,738,883
<p>I am working on mezzanine rest api and adding some more views to be able to work easily. I coded one view and made its serializer but when trying to hit from postman, I am getting error not found 404</p> <p><code>Views.py</code></p> <pre><code>@csrf_exempt @api_view(['POST']) def create_site_record(request): serializer = SiteModelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) </code></pre> <p><code>serializers.py</code></p> <pre><code>class SiteModelSerializer(serializers.Serializer): title = serializers.CharField(required=True, max_length=100) tagline = serializers.CharField(required=True, max_length=100) domain = serializers.CharField(required=True, max_length=100) def create(self, validated_data): return Site.objects.create(**validated_data) </code></pre> <p><code>urls.py</code></p> <pre><code>router = routers.DefaultRouter(trailing_slash=False) router.register(r'users', UserViewSet) router.register(r'pages', PageViewSet) router.register(r'posts', PostViewSet) router.register(r'categories', CategoryViewSet) # router.register(r'create_site', create_site_record, 'sitess') router.register(r'site', SiteViewSet, SiteViewSet.as_view({'get': 'retrieve'})) urlpatterns = [ url(r'^create/(?P&lt;pk&gt;[0-9]+)$', create_site_record), # I have tried registering this view in router also but no luck url(r'^', include(router.urls)), url(r'^docs/', include('rest_framework_swagger.urls')), url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), ] </code></pre> <p>I am trying to hit this endpoint : <code>http://localhost:8000/api/create_site/</code> with payload : <code>{ "title": "Test", "tagling": "sdhjshjd", "domain": "test:8000" }</code></p> <p>Getting error : <code>Not Found: /api/create_site/</code> What I am doing wrong?</p>
2
2016-08-03T08:54:34Z
38,739,074
<p>It looks like a problem with your url path. There is no need to have the digit capture for a create endpoint, since that is generally used for referencing an existing object. Try changing the path to <code>url(r'^create/$', create_site_record)</code> and send the POST request to<code>http://localhost:8000/api/create/</code>.</p>
1
2016-08-03T09:03:17Z
[ "python", "django", "django-rest-framework" ]
How to implement a mouse hovering callback on canvas items in tkinter?
38,738,915
<p>I used the code below which I found on internet to implement a mouse hovering action in python:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size) self.scale.bind('&lt;ButtonRelease&gt;', self.show) self.canvas.bind('&lt;Motion&gt;', self.motion) self.board = [] self.array = np.zeros((self.scale.get(),self.scale.get())).tolist() self.canvas.pack() self.scale.pack() def motion(self,event): if self.canvas.find_withtag(CURRENT): current_color = self.canvas.itemcget(CURRENT, 'fill') self.canvas.itemconfig(CURRENT, fill="cyan") self.canvas.update_idletasks() self.canvas.after(150) self.canvas.itemconfig(CURRENT, fill=current_color) def show(self,event): self.canvas.delete('all') x = 50 y = 50 row = [] self.board.clear() for i in range(self.scale.get()): row = [] for j in range(self.scale.get()): rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red') x += 50 row.append(rectangle) x -= j*50 y +=50 self.board.append(row) print(self.board) root = Tk() a = rect(root) root.mainloop() </code></pre> <p>The problem with the execution is that the color of the item changes to blue only for a limited time. </p> <p>I need the color of each item in the canvas to be changed whenever I enter its zone and remain blue until the mouse is leaving the item.</p>
2
2016-08-03T08:56:02Z
38,740,329
<p>I changed <code>motion</code> method and added <code>self.last = None</code> to <code>__init__</code> method:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size) self.scale.bind('&lt;ButtonRelease&gt;', self.show) self.canvas.bind('&lt;Motion&gt;', self.motion) self.board = [] self.array = np.zeros((self.scale.get(),self.scale.get())).tolist() self.canvas.pack() self.scale.pack() self.last = None def motion(self, event): temp = self.canvas.find_withtag(CURRENT) if temp == self.last: self.canvas.itemconfig(CURRENT, fill="cyan") self.canvas.update_idletasks() else: self.canvas.itemconfig(self.last, fill="red") self.last = temp def show(self,event): self.canvas.delete('all') x = 50 y = 50 row = [] self.board.clear() for i in range(self.scale.get()): row = [] for j in range(self.scale.get()): rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red') x += 50 row.append(rectangle) x -= j*50 y +=50 self.board.append(row) print(self.board) root = Tk() a = rect(root) root.mainloop() </code></pre>
0
2016-08-03T09:59:14Z
[ "python", "tkinter", "tkinter-canvas", "mousehover" ]
How to implement a mouse hovering callback on canvas items in tkinter?
38,738,915
<p>I used the code below which I found on internet to implement a mouse hovering action in python:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size) self.scale.bind('&lt;ButtonRelease&gt;', self.show) self.canvas.bind('&lt;Motion&gt;', self.motion) self.board = [] self.array = np.zeros((self.scale.get(),self.scale.get())).tolist() self.canvas.pack() self.scale.pack() def motion(self,event): if self.canvas.find_withtag(CURRENT): current_color = self.canvas.itemcget(CURRENT, 'fill') self.canvas.itemconfig(CURRENT, fill="cyan") self.canvas.update_idletasks() self.canvas.after(150) self.canvas.itemconfig(CURRENT, fill=current_color) def show(self,event): self.canvas.delete('all') x = 50 y = 50 row = [] self.board.clear() for i in range(self.scale.get()): row = [] for j in range(self.scale.get()): rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red') x += 50 row.append(rectangle) x -= j*50 y +=50 self.board.append(row) print(self.board) root = Tk() a = rect(root) root.mainloop() </code></pre> <p>The problem with the execution is that the color of the item changes to blue only for a limited time. </p> <p>I need the color of each item in the canvas to be changed whenever I enter its zone and remain blue until the mouse is leaving the item.</p>
2
2016-08-03T08:56:02Z
38,740,334
<p>You can pass the argument <code>activefill</code> when creating your rectangle.</p> <p>From <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_rectangle-method" rel="nofollow">effboot.org</a>:</p> <blockquote> <p>Fill color to use when the mouse pointer is moved over the item, if different from fill.</p> </blockquote> <p>To do so, replace:</p> <pre><code>rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red') </code></pre> <p>By:</p> <pre><code>rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red', activefill='cyan') </code></pre> <p>This removes the need to bind <code>Motion</code> to your canvas, and also makes the code noticebly shorter:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size) self.scale.bind('&lt;ButtonRelease&gt;', self.show) self.board = [] self.array = np.zeros((self.scale.get(),self.scale.get())).tolist() self.canvas.pack() self.scale.pack() def show(self,event): self.canvas.delete('all') x = 50 y = 50 row = [] self.board.clear() for i in range(self.scale.get()): row = [] for j in range(self.scale.get()): rectangle = self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red', activefill='cyan') x += 50 row.append(rectangle) x -= j*50 y +=50 self.board.append(row) print(self.board) root = Tk() a = rect(root) root.mainloop() </code></pre>
3
2016-08-03T09:59:30Z
[ "python", "tkinter", "tkinter-canvas", "mousehover" ]
PyQt - Hide MainWindow and show QDialog without the taskbar icon disappearing
38,739,009
<p>I've been using the code from this example <a href="http://stackoverflow.com/questions/22538247/pyqt-how-to-hide-qmainwindow">PyQt: How to hide QMainWindow</a>:</p> <pre><code>class Dialog_02(QtGui.QMainWindow): def __init__(self, parent): super(Dialog_02, self).__init__(parent) # ensure this window gets garbage-collected when closed self.setAttribute(QtCore.Qt.WA_DeleteOnClose) ... def closeAndReturn(self): self.close() self.parent().show() class Dialog_01(QtGui.QMainWindow): ... def callAnotherQMainWindow(self): self.hide() self.dialog_02 = Dialog_02(self) self.dialog_02.show() </code></pre> <p>It works, however when opening a second window, the window's task bar icon doesn't show. I've tried using QtGui.QDialog for the Dialog_02 as well but that gives me the same result.</p> <p>How do I go about solving this?</p> <p>Edit: I'm on Windows 10</p>
0
2016-08-03T09:00:23Z
38,749,079
<p>Just guessing (because I don't know what platform you're on, and I don't use a task-bar myself, so I cant really test it), but try getting rid of the parent:</p> <pre><code>class Dialog_02(QtGui.QMainWindow): def __init__(self, other_window): super(Dialog_02, self).__init__() # ensure this window gets garbage-collected when closed self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self._other_window = other_window ... def closeAndReturn(self): self.close() self._other_window.show() </code></pre>
1
2016-08-03T16:29:15Z
[ "python", "pyqt", "pyside" ]
How to group each block's data together instead of being grouped by the their xpath?
38,739,014
<p>Let's say I'm scraping data from structure that looks like this:</p> <pre><code>&lt;div id="main"&gt; &lt;span class="name"&gt;$somename&lt;/span&gt; &lt;span class="email"&gt;$someemial&lt;/span&gt; &lt;span class="phone"&gt;$phone&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The scrapy code that I'm using is something like:</p> <pre><code>d.add_xpath('name', '//div[@id="main"]/span[@class="name"]') d.add_xpath('name', '//div[@id="main"]/span[@class="email"]') d.add_xpath('name', '//div[@id="main"]/span[@class="phone"]') </code></pre> <p>The results I'm getting are grouped this way:</p> <pre><code>name1 name2 name3 and so on... then: email1 email2 email3 and so on... and finally: phone1 phone2 phone3 and so on... </code></pre> <p>The but what I want is to group the data like this:</p> <pre><code>name1 email1 phone1 name2 email2 phone2 name3 email3 phone3 and so on ... </code></pre> <p>How how can I do that with scrapy?</p> <p>Thanks in advance</p>
1
2016-08-03T09:00:32Z
38,740,063
<p>I'd suggest using a zipped variable for it. Something like this: </p> <pre><code>for sel in xpath('//body'): name = sel.xpath('//div[@id="main"]/span[@class="name"]') email = sel.xpath('//div[@id="main"]/span[@class="email"]') phone = sel.xpath('//div[@id="main"]/span[@class="phone"]') result = zip(name, email, phone) for name, email, phone in result: item['name'] = name item['email'] = email item['phone'] = phone yield item </code></pre>
1
2016-08-03T09:47:04Z
[ "python", "scrapy" ]
How to group each block's data together instead of being grouped by the their xpath?
38,739,014
<p>Let's say I'm scraping data from structure that looks like this:</p> <pre><code>&lt;div id="main"&gt; &lt;span class="name"&gt;$somename&lt;/span&gt; &lt;span class="email"&gt;$someemial&lt;/span&gt; &lt;span class="phone"&gt;$phone&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The scrapy code that I'm using is something like:</p> <pre><code>d.add_xpath('name', '//div[@id="main"]/span[@class="name"]') d.add_xpath('name', '//div[@id="main"]/span[@class="email"]') d.add_xpath('name', '//div[@id="main"]/span[@class="phone"]') </code></pre> <p>The results I'm getting are grouped this way:</p> <pre><code>name1 name2 name3 and so on... then: email1 email2 email3 and so on... and finally: phone1 phone2 phone3 and so on... </code></pre> <p>The but what I want is to group the data like this:</p> <pre><code>name1 email1 phone1 name2 email2 phone2 name3 email3 phone3 and so on ... </code></pre> <p>How how can I do that with scrapy?</p> <p>Thanks in advance</p>
1
2016-08-03T09:00:32Z
38,743,544
<p>This is more of a python question. For this kinds of data structure the best way to accomplish this is by using dictionaries:</p> <pre><code>dictExample={} dictExample['name']=sel.xpath('//div[@id="main"]/span[@class="name"]') dictExample['email']=sel.xpath('//div[@id="main"]/span[@class="email"]') dictExample['phone']=sel.xpath('//div[@id="main"]/span[@class="phone"]') </code></pre> <p>By doing <code>print dictExample</code> it will return the following results:</p> <pre><code>{'phone': '872934987', 'name': 'Rafael Alonso', 'email': 'example@example.com'} </code></pre> <p>Now if you want to have multiple dictionaries just append them into a list:</p> <pre><code>listExample=[] for i in range(0,5): listExample.append(dictExample) </code></pre>
1
2016-08-03T12:22:23Z
[ "python", "scrapy" ]
access site behind login.microsoftonline oatuth2 with python requests
38,739,057
<p>trying to login login to a website hosted behind login.microsoftonline.com (think this a Azure cloud deployment) oauth2 site with python requests</p> <p>How should i go about structuring the request?</p>
0
2016-08-03T09:02:10Z
38,970,981
<p>@chris, I see you want to access a website via construct a request with access token which got by authentication with OAuth2 on Azure. Please follow the <a href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-protocols-oauth-code/#register-your-application-with-your-ad-tenant" rel="nofollow">tutorial</a> to know the OAuth 2.0 authorization flow and how to do it step by step.</p> <p>Please try to access site manually by browser and use Fiddler to catch the parameters which required in Python request.</p>
0
2016-08-16T09:16:52Z
[ "python", "azure", "python-requests" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"third")]=2 </code></pre> <p>What I would like now is a dict with the following structure: Keys are "first" "second" "third", values are the numbers --> start: if first entry in tuple > 0</p> <pre><code>dict_1 ={"first": [4,34,3], "second": [6,45,1], "third": [7,66,2]} </code></pre> <p>I tried it with: </p> <pre><code>for key, value in dict.iteritems(): if key[0] &lt;=0: .. .. </code></pre> <p>But that changes the order and does not work really properly. Would be great if anyone would suggest a simple method to handle such things.</p> <p>Thank you very much</p>
2
2016-08-03T09:05:28Z
38,739,340
<p>Why do you want to keep the order ? I suggest you to use this kind of loop</p> <pre><code>dict_r = {} dict_r["first"] = [] dict_r["second"] = [] dict_r["third"] = [] for i in range (0,3): dict_r["first"].append(dict[i,"first"]) dict_r["second"].append(dict[i,"second"]) dict_r["third"].append(dict[i,"third"]) </code></pre> <p><strong>Update</strong></p> <p>if you don't know how many items are in the dict</p> <pre><code>dict_r = {} dict_r["first"] = [] dict_r["second"] = [] dict_r["third"] = [] for key, value in dict.iteritems(): if key[0] &lt;=0: dict_r[key[1]].append(value) </code></pre>
2
2016-08-03T09:15:10Z
[ "python", "dictionary" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"third")]=2 </code></pre> <p>What I would like now is a dict with the following structure: Keys are "first" "second" "third", values are the numbers --> start: if first entry in tuple > 0</p> <pre><code>dict_1 ={"first": [4,34,3], "second": [6,45,1], "third": [7,66,2]} </code></pre> <p>I tried it with: </p> <pre><code>for key, value in dict.iteritems(): if key[0] &lt;=0: .. .. </code></pre> <p>But that changes the order and does not work really properly. Would be great if anyone would suggest a simple method to handle such things.</p> <p>Thank you very much</p>
2
2016-08-03T09:05:28Z
38,739,417
<p>I will do something like that (using <a class='doc-link' href="http://stackoverflow.com/documentation/python/498/collections/1636/collections-defaultdict#t=201608030921439071977">defaultdict</a> for convenient):</p> <pre><code>from collections import defaultdict new_dict = defaultdict(list) for (x,k),v in sorted(old_dict.items()): # iterating over the sorted dictionary if x &gt;= 0: new_dict[k].append(v) dict(new_dict) #output: {'second': [6, 45, 1], 'first': [4, 34, 3], 'third': [7, 66, 2]} </code></pre> <p>BTW, don't name your dictionary <code>dict</code>, it's shadowing python <code>dict</code> type.</p>
1
2016-08-03T09:18:28Z
[ "python", "dictionary" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"third")]=2 </code></pre> <p>What I would like now is a dict with the following structure: Keys are "first" "second" "third", values are the numbers --> start: if first entry in tuple > 0</p> <pre><code>dict_1 ={"first": [4,34,3], "second": [6,45,1], "third": [7,66,2]} </code></pre> <p>I tried it with: </p> <pre><code>for key, value in dict.iteritems(): if key[0] &lt;=0: .. .. </code></pre> <p>But that changes the order and does not work really properly. Would be great if anyone would suggest a simple method to handle such things.</p> <p>Thank you very much</p>
2
2016-08-03T09:05:28Z
38,739,820
<pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"third")]=2 dict_1 = {} for num,txt in sorted(dict.keys()): if num &gt;= 0: val = dict[(num,txt)] if txt in dict_1: dict_1[txt].append(val) else: dict_1[txt] = [val] print dict_1 </code></pre>
0
2016-08-03T09:36:06Z
[ "python", "dictionary" ]
Python/Pandas Iterating through columns
38,739,196
<p>I have a DataFrame which looks like this (with many additional columns)</p> <pre><code> age1 age2 age3 age 4 \ Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 9 </code></pre> <p>I am trying write a loop that sums each column with the previous ones before it and returns it to a new DataFrame. I have started out, simply, with this:</p> <pre><code>New = pd.DataFrame() New[0] = SFH2.ix[:,0] for x in SFH2: ls = [x,x+1] B = SFH2[ls].sum(axis=1) New[x] = B print(New) </code></pre> <p>and the error I get is </p> <pre><code> ls = [x,x+1] TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>I know that int and str are different objects, but how can I overcome this, or is there a different way to iterate through columns? Thanks!</p>
4
2016-08-03T09:09:14Z
38,739,320
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow"><code>add</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow"><code>shift</code></a>ed <code>DataFrame</code>:</p> <pre><code>print (df.shift(-1,axis=1)) age1 age2 age3 age4 Id# 1001 6.0 2.0 8.0 NaN 1002 6.0 1.0 0.0 NaN 1003 9.0 7.0 5.0 NaN 1004 12.0 5.0 9.0 NaN print (df.add(df.shift(-1,axis=1), fill_value=0)) age1 age2 age3 age4 Id# 1001 11.0 8.0 10.0 8.0 1002 13.0 7.0 1.0 0.0 1003 19.0 16.0 12.0 5.0 1004 21.0 17.0 14.0 9.0 </code></pre> <p>If need shift with <code>1</code> (default parameter, omited):</p> <pre><code>print (df.shift(axis=1)) age1 age2 age3 age4 Id# 1001 NaN 5.0 6.0 2.0 1002 NaN 7.0 6.0 1.0 1003 NaN 10.0 9.0 7.0 1004 NaN 9.0 12.0 5.0 print (df.add(df.shift(axis=1), fill_value=0)) age1 age2 age3 age4 Id# 1001 5.0 11.0 8.0 10.0 1002 7.0 13.0 7.0 1.0 1003 10.0 19.0 16.0 12.0 1004 9.0 21.0 17.0 14.0 </code></pre>
2
2016-08-03T09:14:24Z
[ "python", "loops", "pandas", "dataframe", "iteration" ]
Python/Pandas Iterating through columns
38,739,196
<p>I have a DataFrame which looks like this (with many additional columns)</p> <pre><code> age1 age2 age3 age 4 \ Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 9 </code></pre> <p>I am trying write a loop that sums each column with the previous ones before it and returns it to a new DataFrame. I have started out, simply, with this:</p> <pre><code>New = pd.DataFrame() New[0] = SFH2.ix[:,0] for x in SFH2: ls = [x,x+1] B = SFH2[ls].sum(axis=1) New[x] = B print(New) </code></pre> <p>and the error I get is </p> <pre><code> ls = [x,x+1] TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>I know that int and str are different objects, but how can I overcome this, or is there a different way to iterate through columns? Thanks!</p>
4
2016-08-03T09:09:14Z
38,739,650
<p>It sounds like <code>cumsum</code> is what you are looking for:</p> <pre><code>In [5]: df Out[5]: age1 age2 age3 age4 Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 9 In [6]: df.cumsum(axis=1) Out[6]: age1 age2 age3 age4 Id# 1001 5 11 13 21 1002 7 13 14 14 1003 10 19 26 31 1004 9 21 26 35 </code></pre>
2
2016-08-03T09:28:58Z
[ "python", "loops", "pandas", "dataframe", "iteration" ]
How to install gensim on windows
38,739,250
<p>Not able to install gensim on windows.Please help me I need to gensim Immediately and tell me installation steps with More details and other software that needs to be installed before it. thanks</p>
0
2016-08-03T09:11:31Z
38,739,531
<p>Gensim depends on scipy and numpy.You must have them installed prior to installing gensim.Simple way to install gensim in windows is, open cmd and type</p> <p>pip install -U gensim</p> <p>Or download gensim for windows from</p> <p><a href="https://pypi.python.org/pypi/gensim" rel="nofollow">https://pypi.python.org/pypi/gensim</a><br> then run<br> python setup.py test<br> python setup.py install</p>
0
2016-08-03T09:22:43Z
[ "python", "gensim" ]
How to install gensim on windows
38,739,250
<p>Not able to install gensim on windows.Please help me I need to gensim Immediately and tell me installation steps with More details and other software that needs to be installed before it. thanks</p>
0
2016-08-03T09:11:31Z
38,758,779
<p>I struggled with this a bit today trying to figure out if I needed a python 2.7 environment or if I could use my 3.5. I ended up doing this from an Anaconda 3.5 install:</p> <p>conda install -c anaconda gensim=0.12.4</p> <p>After a few hours of trying various things, suddenly it all worked on 3.5. My error was that it kept failing to install Scipy. I tried starting over with the conda install and just worked.</p> <p>See: <a href="https://anaconda.org/anaconda/gensim" rel="nofollow">https://anaconda.org/anaconda/gensim</a></p>
0
2016-08-04T04:59:45Z
[ "python", "gensim" ]
Receiving data from com port by pyserial
38,739,336
<p>I can't receive data from com port by pyserial! I have compiled program that send data and receive answer from controller correctly! I used comport monitor program to spy request and answer from controller:<a href="http://i.stack.imgur.com/7lOt5.png" rel="nofollow">correct send and answer</a></p> <p>But when I send the same request i get nothing((<a href="http://i.stack.imgur.com/HFfr7.png" rel="nofollow">my request without answer</a> My Python prog:</p> <pre><code>#!/usr/bin/env python import sys, os import serial, time from serial import * ser = serial.Serial( port='COM7', baudrate=4800, bytesize=5,#18, parity='N', stopbits=1, timeout=5, xonxoff=0,# rtscts=0,# writeTimeout = 1#1 myz= '\x10\x02\x00\x00\x01\x4e\xf0\x04\x01\xff\x10\x17\x02\x4e\xf0\x04\x02\xff\x10\x17\x10\x03\xff' while True: ser.write(myz) #send data ser.readline() </code></pre> <p>I was trying different speeds(4800,9600) and got nothing((( Can anybody tell me where I get mistayke?</p>
0
2016-08-03T09:14:55Z
38,740,027
<p>You'll not receive your own message on the com port you write it to. Either connect the other side of the cable to a different port, or communicate with a device that will answer you.</p>
0
2016-08-03T09:45:31Z
[ "python", "serial-port", "pyserial" ]
How to set Python Tornado pretty log
38,739,384
<p>I write log from tornado like this:</p> <pre><code>app_log = logging.getLogger("tornado.application") </code></pre> <p>And logs output without color:</p> <pre><code>[W 160803 17:04:32 test:68] warn [E 160803 17:04:32 test:69] error [I 160803 17:04:32 test:72] info </code></pre> <p>Even I call <code>enable_pretty_logging()</code> it is still no color.</p>
0
2016-08-03T09:16:55Z
38,757,469
<p>Color is used when two conditions are met:</p> <ul> <li>stderr is a tty (i.e. not redirected to a file or pipe)</li> <li>the <code>curses</code> module believes that color is supported (based on the <code>TERM</code> environment variable)</li> </ul> <p>If <code>TERM</code> is unset, try setting <code>TERM=ansi</code>. </p>
0
2016-08-04T02:17:43Z
[ "python", "logging", "tornado" ]
Django error: render_to_response() got an unexpected keyword argument 'context_instance'
38,739,422
<p>After upgrading to Django 1.10, I get the error <code>render_to_response() got an unexpected keyword argument 'context_instance'</code>.</p> <p>My view is as follows:</p> <pre><code>from django.shortcuts import render_to_response from django.template import RequestContext def my_view(request): context = {'foo': 'bar'} return render_to_response('my_template.html', context, context_instance=RequestContext(request)) </code></pre> <p>Here is the full traceback:</p> <pre><code>Traceback: File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/alasdair/.virtualenvs/django110/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/alasdair/dev/rtr/rtr/urls.py" in my_view 26. return render_to_response('my_template.html', context, context_instance=RequestContext(request)) Exception Type: TypeError at / Exception Value: render_to_response() got an unexpected keyword argument 'context_instance' </code></pre>
7
2016-08-03T09:18:34Z
38,739,423
<p>The <code>context_instance</code> parameter in <code>render_to_response</code> was <a href="https://docs.djangoproject.com/en/1.10/releases/1.8/#dictionary-and-context-instance-arguments-of-rendering-functions">deprecated in Django 1.8</a>, and removed in Django 1.10.</p> <p>The solution is to switch to the <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#django.shortcuts.render"><code>render</code></a> shortcut, which automatically uses a <code>RequestContext</code>.</p> <p>Update your imports and view as follows. Note that <code>render</code> takes the <code>request</code> object as its first argument.</p> <pre><code>from django.shortcuts import render def my_view(request): context = {'foo': 'bar'} return render(request, 'my_template.html', context) </code></pre> <p>The <code>render</code> shortcut was introduced in Django 1.3, so this change is compatible with older versions of Django.</p>
23
2016-08-03T09:18:34Z
[ "python", "django" ]
Is it possible to mix Eve (Python) Mongo schemata and Eve SQLAlchemy schemata?
38,739,457
<p>I want to create an API which on one side can use the normal mongodb interface for storing documents but on the other side access user data which is stored in a SQL database.</p> <p>Therefore: Is it possible to mix Eve Mongo and <a href="https://eve-sqlalchemy.readthedocs.io/en/stable/tutorial.html" rel="nofollow">Eve SQLAlchemy</a> schemata as illustrated below?</p> <pre><code>DOMAIN={ 'people': People._eve_schema['people'], 'data': data, } </code></pre>
1
2016-08-03T09:19:43Z
38,761,803
<p>No, currently that's not possible since you can either use the default mongo data engine <em>or</em> switch it with the Eve-Sqlalchemy engine.</p>
0
2016-08-04T08:06:54Z
[ "python", "sqlalchemy", "eve" ]
need help : python3.5.2 & pygame
38,739,472
<p>I'm from Taiwan, and I need help to install pygame.<br> I've been trying for a long time.<br> <a href="http://i.stack.imgur.com/Pr63F.png" rel="nofollow">pygame file</a><br> <a href="http://i.stack.imgur.com/rhwJp.png" rel="nofollow">cmd result</a><br> I want to ask if I download the right pygame file. If not please tell me which is the correct one.<br> My computer: Win10 ; 64 byte ; python 3.5.2 Thanks a lot</p>
2
2016-08-03T09:20:19Z
38,739,808
<p><strong>Option 1:</strong> You have a 32bit install of Python (even if your Windows is 64-bit).</p> <p>You can check if this is the case by looking at the output of </p> <pre><code>import struct;print(struct.calcsize("P") * 8) </code></pre> <p>if so, you will need to download the 32bit version of pygame not the 64-bit one.</p> <p><strong>Option 2:</strong> Less likely, but it could be an issue with pip, check if you have the latest version installed and install it with:</p> <pre><code>python -m pip install --upgrade pip </code></pre>
0
2016-08-03T09:35:33Z
[ "python", "pygame" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> which is a number just before the line ends.</p> <p>Here is what I have tried so far.</p> <pre><code>import sys import re with open("Xavier.txt") as f: for line in f: match1 = re.search(r'((\w+_\w+)|(\d+$))',line) if match1: print match1.groups() </code></pre> <p>However, everytime I run this script, I always get <code>drmanhattan</code> as output and not <code>drmanhattan 362</code>.</p> <p>Is it because of <code>|</code> sign? </p> <p>How do I tell regex to catch <code>this group and that group</code> ?</p> <p>I have already consulted <a href="http://stackoverflow.com/questions/2554185/match-groups-in-python">this</a> and <a href="http://www.thegeekstuff.com/2014/07/python-regex-examples/" rel="nofollow">this</a> links however, it did not solve my problem.</p>
0
2016-08-03T09:25:39Z
38,739,709
<p><code>|</code> mean OR so your regex catch <code>(\w+_\w+)</code> OR <code>(\d+$)</code></p> <p>Maybe you want something like this :</p> <pre><code>((\w+_\w+).*?(\d+$)) </code></pre>
1
2016-08-03T09:31:11Z
[ "python", "regex", "python-2.7" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> which is a number just before the line ends.</p> <p>Here is what I have tried so far.</p> <pre><code>import sys import re with open("Xavier.txt") as f: for line in f: match1 = re.search(r'((\w+_\w+)|(\d+$))',line) if match1: print match1.groups() </code></pre> <p>However, everytime I run this script, I always get <code>drmanhattan</code> as output and not <code>drmanhattan 362</code>.</p> <p>Is it because of <code>|</code> sign? </p> <p>How do I tell regex to catch <code>this group and that group</code> ?</p> <p>I have already consulted <a href="http://stackoverflow.com/questions/2554185/match-groups-in-python">this</a> and <a href="http://www.thegeekstuff.com/2014/07/python-regex-examples/" rel="nofollow">this</a> links however, it did not solve my problem.</p>
0
2016-08-03T09:25:39Z
38,739,745
<pre><code>line = 'Passed dangerb.xavier64.423181.r000.drmanhattan_resources.log Aug 23 04:19:37 84526 362' match1 = re.search(r'(\w+_\w+).*?(\d+$)', line) if match1: print match1.groups() # ('drmanhattan_resources', '362') </code></pre> <p>If you have a <code>test.txt</code> file that contains the following lines:</p> <blockquote> <p>Passed dangerb.xavier64.423181.r000.drmanhattan_resources.log Aug 23 04:19:37 84526 362 Passed dangerb.xavier64.423181.r000.drmanhattan_resources.log Aug 23 04:19:37 84526 363 Passed dangerb.xavier64.423181.r000.drmanhattan_resources.log Aug 23 04:19:37 84526 361</p> </blockquote> <p>you can do:</p> <pre><code>with open('test.txt', 'r') as fil: for line in fil: match1 = re.search(r'(\w+_\w+).*?(\d+)\s*$', line) if match1: print match1.groups() # ('drmanhattan_resources', '362') # ('drmanhattan_resources', '363') # ('drmanhattan_resources', '361') </code></pre>
1
2016-08-03T09:32:50Z
[ "python", "regex", "python-2.7" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> which is a number just before the line ends.</p> <p>Here is what I have tried so far.</p> <pre><code>import sys import re with open("Xavier.txt") as f: for line in f: match1 = re.search(r'((\w+_\w+)|(\d+$))',line) if match1: print match1.groups() </code></pre> <p>However, everytime I run this script, I always get <code>drmanhattan</code> as output and not <code>drmanhattan 362</code>.</p> <p>Is it because of <code>|</code> sign? </p> <p>How do I tell regex to catch <code>this group and that group</code> ?</p> <p>I have already consulted <a href="http://stackoverflow.com/questions/2554185/match-groups-in-python">this</a> and <a href="http://www.thegeekstuff.com/2014/07/python-regex-examples/" rel="nofollow">this</a> links however, it did not solve my problem.</p>
0
2016-08-03T09:25:39Z
38,739,853
<p>With <code>re.search</code> you only get the first match, if any, and with <code>|</code> you tell <code>re</code> to look for <em>either</em> this <em>or</em> that pattern. As suggested in other answers, you could replace the <code>|</code> with <code>.*</code> to match "anything in between" those two pattern. Alternatively, you could use <code>re.findall</code> to get all matches:</p> <pre><code>&gt;&gt;&gt; line = "passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362" &gt;&gt;&gt; re.findall(r'\w+_\w+|\d+$', line) ['drmanhattan_resources', '362'] </code></pre>
1
2016-08-03T09:37:42Z
[ "python", "regex", "python-2.7" ]
Protobuf3: Serialize a Python object to JSON
38,739,603
<p>According to <a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow">the manual</a>, Protobuf 3.0.0 supports JSON serialization:</p> <blockquote> <p>A well-defined encoding in JSON as an alternative to binary proto encoding.</p> </blockquote> <p><strong>What have I tried</strong></p> <ul> <li><code>json.dumps(instance)</code> which raised <code>TypeError(repr(o) + " is not JSON serializable")</code></li> <li>Looked for a <code>instance.to_json()</code> (or alike) function</li> <li>Searched the Python docs</li> </ul> <p><strong>How do I serialize a Python proto object to JSON?</strong></p>
1
2016-08-03T09:26:22Z
38,740,630
<p>There is a function 'MessageToJson' in the json_format module. This function can be used to serialize the message.</p>
2
2016-08-03T10:11:10Z
[ "python", "json", "serialization", "protocol-buffers-3" ]
Protobuf3: Serialize a Python object to JSON
38,739,603
<p>According to <a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow">the manual</a>, Protobuf 3.0.0 supports JSON serialization:</p> <blockquote> <p>A well-defined encoding in JSON as an alternative to binary proto encoding.</p> </blockquote> <p><strong>What have I tried</strong></p> <ul> <li><code>json.dumps(instance)</code> which raised <code>TypeError(repr(o) + " is not JSON serializable")</code></li> <li>Looked for a <code>instance.to_json()</code> (or alike) function</li> <li>Searched the Python docs</li> </ul> <p><strong>How do I serialize a Python proto object to JSON?</strong></p>
1
2016-08-03T09:26:22Z
38,741,473
<h1>Caveats</h1> <p>I have mistakingly installed <code>protobuf3</code> - I thought it the, well, <code>protobuf3</code> Python package, but it's an unofficial <strong>Python 3 protobuf 2 package</strong>, not the other way around. Remove it before you start.</p> <h1>Solution</h1> <p>After some trial and error, the following solution works. Feel free to post better / official ones if you have any.</p> <h2>Prerequisite: Protobuf 3</h2> <ul> <li>Remove <code>protobuf2</code> (I used <code>brew uninstall</code>). Make sure <code>protoc</code> does not appear in the path.</li> <li>Install the <a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow"><code>protobuf3</code></a> binaries. There is no homebrew package yet, so I used OSX binaries <code>protoc-3.0.0-osx-x86_64.zip</code>. The <code>make</code> script is also an option. <ul> <li>Copy the content of the <code>bin</code> directory to <code>/usr/local/bin</code></li> <li>Copy the content of the <code>include</code> to <code>/usr/local/include</code></li> </ul></li> <li>Make sure protobuf3 is installed - <code>protoc --version</code> should show <code>libprotoc 3.0.0</code>.</li> </ul> <h2>Python installation</h2> <ul> <li>Create a virtual environment</li> <li>Download the <a href="https://github.com/google/protobuf" rel="nofollow">master branch of <code>protobuf</code></a> to <code>/tmp</code></li> <li>Activate the virtual environment</li> <li><code>cd protobuf-master/python &amp;&amp; setup.py install</code></li> </ul> <h2>Code</h2> <p>The relevant function is <code>MessageToJson</code> in the <code>google.protobuf.json_format module</code>:</p> <pre><code>from google.protobuf import json_format o = SomeProtobufClass() print json_format.MessageToJson(o) { ... } </code></pre>
1
2016-08-03T10:49:55Z
[ "python", "json", "serialization", "protocol-buffers-3" ]
pyyaml 3.11 pass dictionary to iterator?
38,739,689
<p>I use following YAML data:</p> <pre><code>Document: InPath: /home/me OutPath: /home/me XLOutFile: TestFile1.xlsx Sheets: - Sheet: Test123 InFile: Test123.MQSC Server: Testsystem1 - Sheet: Test345 InFile: Test345.MQSC Server: Testsystem2 Title: A: "Server Name" B: "MQ Version" C: "Broker Version" Fields: A: ServerName B: MQVersion C: BrokerVersion </code></pre> <p>and following code:</p> <pre><code>import yaml class cfgReader(): def __init__(self): self.stream = "" self.ymldata = "" self.ymlkey = "" self.ymld = "" def read(self,infilename): self.stream = self.stream = file(infilename, 'r') #Read the yamlfile self.ymldata = yaml.load(self.stream) #Instanciate yaml object and parse the input "stream". def docu(self): print self.ymldata print self.ymldata['Sheets'] for self.ymlkey in self.ymldata['Document']: #passes String to iterator print self.ymlkey for sheets in self.ymldata['Sheets']: #passes Dictionary to iterator print sheets['Sheet'] for title in self.ymldata['Title']: print title for fields in self.ymldata['Fields']: print fields </code></pre> <p>The <code>print</code> output is:</p> <pre><code>{'Fields': {'A': 'ServerName', 'C': 'BrokerVersion', 'B': 'MQVersion'}, 'Document': {'XLOutFile': 'TestFile1.xlsx', 'InPath': '/home/me', 'OutPath': '/home/me'}, 'Sheets': [{'Sheet': 'Test123', 'InFile': 'Test123.MQSC', 'Server': 'Testsystem1'}, {'Sheet': 'Test345', 'InFile': 'Test345.MQSC', 'Server': 'Testsystem2'}], 'Title': {'A': 'Server Name', 'C': 'Broker Version', 'B': 'MQ Version'}} [{'Sheet': 'Test123', 'InFile': 'Test123.MQSC', 'Server': 'Testsystem1'}, {'Sheet': 'Test345', 'InFile': 'Test345.MQSC', 'Server': 'Testsystem2'}] X I O Test123 Test345 A C B A C B </code></pre> <p>I could not find out how to control the way data is passed to the iterator. What I want is to pass it as dictionaries so that I can access the value through the key. This works for "Sheets" but I don't understand why. The documentation was not describing it clearly : <a href="http://pyyaml.org/wiki/PyYAMLDocumentation" rel="nofollow">http://pyyaml.org/wiki/PyYAMLDocumentation</a></p>
4
2016-08-03T09:30:16Z
38,741,944
<p>In your code <code>self.ymldata['Sheets']</code> is a list of dictionaries because your YAML source for that:</p> <pre><code> - Sheet: Test123 InFile: Test123.MQSC Server: Testsystem1 - Sheet: Test345 InFile: Test345.MQSC Server: Testsystem2 </code></pre> <p>is a sequence of mappings (and this is the value for the key <code>Sheets</code> of the top-level mapping in your YAML file).</p> <p>The values for the other top-level keys are all mappings (and not sequences of mappings), which get loaded as Python <code>dict</code>. And if you iterate over a <code>dict</code> as you do, you get the <code>key</code> values.</p> <p>If you don't want to iterate over these dictionaries then you should not start a <code>for</code> loop. You might want to test what the value for a toplevel keys is and then act accordingly, e.g. to print out all dictionaries loaded from the YAML file except for the top-level mapping do:</p> <pre><code>import ruamel.yaml as yaml class CfgReader(): def __init__(self): self.stream = "" self.ymldata = "" self.ymlkey = "" self.ymld = "" def read(self, infilename): self.stream = open(infilename, 'r') # Read the yamlfile self.ymldata = yaml.load(self.stream) # Instanciate yaml object and parse the input "stream". def docu(self): for k in self.ymldata: v = self.ymldata[k] if isinstance(v, list): for elem in v: print(elem) else: print(v) cfg_reader = CfgReader() cfg_reader.read('in.yaml') cfg_reader.docu() </code></pre> <p>which prints:</p> <pre><code>{'InFile': 'Test123.MQSC', 'Sheet': 'Test123', 'Server': 'Testsystem1'} {'InFile': 'Test345.MQSC', 'Sheet': 'Test345', 'Server': 'Testsystem2'} {'B': 'MQVersion', 'A': 'ServerName', 'C': 'BrokerVersion'} {'B': 'MQ Version', 'A': 'Server Name', 'C': 'Broker Version'} {'XLOutFile': 'TestFile1.xlsx', 'InPath': '/home/me', 'OutPath': '/home/me'} </code></pre> <p>Please also note some general things, you should be aware off</p> <ul> <li>I use ruamel.yaml (disclaimer: I am the author of that package), which supports YAML 1.2 (PyYAML supports the 1.1 standard from 2005). For your purposes they act the same.</li> <li>don't use <code>file()</code> it is not available in Python3, use <code>open()</code></li> <li>assigning the same value twice to the same attribute makes no sense (<code>self.stream = self.stream = ...</code>)</li> <li><p>your opened file/stream never gets closed, you might want to consider using</p> <pre><code>with open(infilename) as self.stream: self.ymldata = yaml.load(self.stream) </code></pre></li> <li><p>class names, by convention, should start with an upper case character.</p></li> </ul>
2
2016-08-03T11:12:17Z
[ "python", "python-2.7", "dictionary", "iterator", "pyyaml" ]
Install Python package: "Package missing in current win-64 channels"
38,739,694
<p>I want to install GSEApy on Anaconda (I use 64bit Windows 10).<br> <a href="https://bioconda.github.io/recipes/gseapy/README.html" rel="nofollow">https://bioconda.github.io/recipes/gseapy/README.html</a><br> <a href="https://anaconda.org/bioconda/gseapy" rel="nofollow">https://anaconda.org/bioconda/gseapy</a> </p> <p>But I get this error:</p> <pre><code>C:\Windows\system32&gt;conda install gseapy Using Anaconda Cloud api site https:// api.anaconda.org Fetching package metadata ........... Solving package specifications: . Error: Package missing in current win-64 channels: - gseapy You can search for packages on anaconda.org with anaconda search -t conda gseapy </code></pre> <p>How can I solve this?</p>
4
2016-08-03T09:30:33Z
38,739,991
<p>You need to use a channel that has a win-64 version. Use:</p> <pre><code>conda install -c bioninja gseapy </code></pre> <p>The option <code>-c</code> or <code>--channel</code> allows to specify a channel. You can also add a channel permanently via:</p> <pre><code>conda config --add channels bioninja </code></pre> <p>This creates a file <code>.condarc</code> in your home directory (on Windows <code>C:\Users\&lt;username&gt;</code>): </p> <pre><code>channels: - bioninja - defaults </code></pre> <p>You can modify this file manually. The order of the channels determines their precedence. </p> <p><strong>Note</strong>: Files with a leading <code>.</code> might not be displayed by certain file browsers. You might need to change settings to display these files accordingly.</p> <p>You can find out if a package exits for your platform by searching on <a href="https://anaconda.org/" rel="nofollow">Anaconda</a>. Just type <code>gseapy</code> in the search field and you should see the <a href="https://anaconda.org/search?q=gseapy" rel="nofollow">available packages</a>. The column "Platforms" shows if a "win-64" version exists.</p> <p><a href="http://i.stack.imgur.com/bLx7k.png" rel="nofollow"><img src="http://i.stack.imgur.com/bLx7k.png" alt="enter image description here"></a></p>
2
2016-08-03T09:43:58Z
[ "python", "packages", "anaconda", "conda" ]
Install Python package: "Package missing in current win-64 channels"
38,739,694
<p>I want to install GSEApy on Anaconda (I use 64bit Windows 10).<br> <a href="https://bioconda.github.io/recipes/gseapy/README.html" rel="nofollow">https://bioconda.github.io/recipes/gseapy/README.html</a><br> <a href="https://anaconda.org/bioconda/gseapy" rel="nofollow">https://anaconda.org/bioconda/gseapy</a> </p> <p>But I get this error:</p> <pre><code>C:\Windows\system32&gt;conda install gseapy Using Anaconda Cloud api site https:// api.anaconda.org Fetching package metadata ........... Solving package specifications: . Error: Package missing in current win-64 channels: - gseapy You can search for packages on anaconda.org with anaconda search -t conda gseapy </code></pre> <p>How can I solve this?</p>
4
2016-08-03T09:30:33Z
38,998,705
<p>Now you could install lastest gseapy through bioconda, too </p> <pre><code>conda install -c bioconda gseapy </code></pre>
0
2016-08-17T13:54:12Z
[ "python", "packages", "anaconda", "conda" ]
How to bring keyboard focus to QTextEdit in PyQt?
38,739,714
<p>I've inserted a simple <code>QTextEdit</code> widget into my PyQt user interface. When the user wants to type text into that widget, he has to click on it. My program should be able to make this happen automatically at certain occasions, such that the user can start typing text into that <code>QTextEdit</code> widget without the need for clicking on it.</p> <p>I already got somewhere, but the issue is still not solved completely. When my program calls the <code>focus()</code> function, the cursor will start blinking at the end of the last line. But typing on your keyboard doesn't insert any text.</p> <pre><code> class myTextField(QPlainTextEdit): def __init__(self): super(myTextField, self).__init__() ... def focus(self): self.focusInEvent(QFocusEvent( QEvent.FocusIn )) # Now the cursor blinks at the end of the last line. # But typing on your keyboard doesn't insert any text. # You still got to click explicitly onto the widget.. ... ### </code></pre> <p>Any help is greatly appreciated :-)</p>
1
2016-08-03T09:31:15Z
38,740,228
<p>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setFocus" rel="nofollow"><code>setFocus()</code></a> method.</p> <pre><code>def focus(self): self.setFocus() </code></pre>
1
2016-08-03T09:54:20Z
[ "python", "python-3.x", "pyqt", "pyqt5" ]
'str' object has no attribute 'message_from_bytes'
38,739,739
<p>I have a piece of code to get emails from messages from my inbox (gmail). Getting emails work correct when I print <code>email_from</code> but I would like to do some operation on data split name and email etc. but then code broke after print first loop step and I got the error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\loc\Desktop\extract_gmail.py", line 24, in &lt;module&gt; email_message_raw = email.message_from_bytes(data[0][1]) AttributeError: 'str' object has no attribute 'message_from_bytes' </code></pre> <p>Can you give me some advice how to solve this problem?</p> <p><strong>Code:</strong></p> <pre><code>import imaplib import email from email.header import Header, decode_header, make_header # Connection settings HOST = 'imap.gmail.com' USERNAME = '***' PASSWORD = '***' m = imaplib.IMAP4_SSL(HOST, 993) m.login(USERNAME, PASSWORD) m.select('INBOX') result, data = m.uid('search', None, "ALL") if result == 'OK': for num in data[0].split()[:5]: result, data = m.uid('fetch', num, '(RFC822)') if result == 'OK': # Get raw message email_message_raw = email.message_from_bytes(data[0][1]) # Decode headers email_from = str(make_header(decode_header(email_message_raw['From']))) # Print each name and email name, email = email_from.split('&lt;') email.replace("&gt;", "") print(name + "|" + email) # When i swap to just print email_from then works # print(email_from) # Close server connection m.close() m.logout() </code></pre>
1
2016-08-03T09:32:19Z
38,739,949
<p>In your code you replaced the email variable..</p> <p>Try this...</p> <pre><code>import imaplib import email from email.header import Header, decode_header, make_header # Connection settings HOST = 'imap.gmail.com' USERNAME = '***' PASSWORD = '***' m = imaplib.IMAP4_SSL(HOST, 993) m.login(USERNAME, PASSWORD) m.select('INBOX') result, data = m.uid('search', None, "ALL") if result == 'OK': for num in data[0].split()[:5]: result, data = m.uid('fetch', num, '(RFC822)') if result == 'OK': # Get raw message email_message_raw = email.message_from_bytes(data[0][1]) # Decode headers email_from = str(make_header(decode_header(email_message_raw['From']))) # Print each name and email name, email_addr = email_from.split('&lt;') email_addr.replace("&gt;", "") print(name + "|" + email_addr) # When i swap to just print email_from then works # print(email_from) # Close server connection m.close() m.logout() </code></pre>
3
2016-08-03T09:42:09Z
[ "python", "gmail-imap" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} </code></pre> <p>What I want to do is compare both dictionaries both by keys and by values, so that I can see the differences between both dicts, e.g. are there different prices, is a product missing in <code>productData_1</code> or <code>_2</code>? </p> <p>I know that I have to iterate over both dicts in some way but I can't figure out how to do it. </p>
0
2016-08-03T09:41:22Z
38,740,115
<p>In Python 3.5:</p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} keys = set (productData_1.keys () + productData_2.keys ()) for key in keys: try: if productData_1 [key] != productData_2 [key]: print ('Mismatch at key {}'.format (key)) except: print ('Entry missing at key {}'.format (key)) </code></pre>
0
2016-08-03T09:49:15Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} </code></pre> <p>What I want to do is compare both dictionaries both by keys and by values, so that I can see the differences between both dicts, e.g. are there different prices, is a product missing in <code>productData_1</code> or <code>_2</code>? </p> <p>I know that I have to iterate over both dicts in some way but I can't figure out how to do it. </p>
0
2016-08-03T09:41:22Z
38,740,125
<pre><code>for key in productData_1.keys()|productData_2.keys(): if key not in productData_1: print('{} missing from productData_1!'.format(key)) continue if key not in productData_2: print('{} missing from productData_2!'.format(key)) continue print('Difference in prices for key "{}": {}'.format(key,abs(int(productData_1[key])-int(productData_2[key])))) </code></pre> <p>This code will print if a key is missing from either dict and print the absolute difference between values for each key.</p> <p><code>productData_1.keys()|productData_2.keys()</code> will return the union of dictionary keys.</p>
0
2016-08-03T09:49:42Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} </code></pre> <p>What I want to do is compare both dictionaries both by keys and by values, so that I can see the differences between both dicts, e.g. are there different prices, is a product missing in <code>productData_1</code> or <code>_2</code>? </p> <p>I know that I have to iterate over both dicts in some way but I can't figure out how to do it. </p>
0
2016-08-03T09:41:22Z
38,740,269
<pre><code>keys_unique_to_1 = [key for key in productData_1 if key not in productData_2] keys_unique_to_2 = [key for key in productData_2 if key not in productData_1] common_keys = [key for key in productData_1 if key in productData_2] diff = {key: int(productData_1[key]) - int(productData_2[key]) for key in common_keys} print 'Keys unique to 1: ', keys_unique_to_1 # Keys unique to 1: ['product_4'] print 'Keys unique to 2: ', keys_unique_to_2 # Keys unique to 2: [] print 'Difference: ', diff # Difference: {'product_1': 0, 'product_3': -2, 'product_2': 0} </code></pre>
0
2016-08-03T09:56:01Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} </code></pre> <p>What I want to do is compare both dictionaries both by keys and by values, so that I can see the differences between both dicts, e.g. are there different prices, is a product missing in <code>productData_1</code> or <code>_2</code>? </p> <p>I know that I have to iterate over both dicts in some way but I can't figure out how to do it. </p>
0
2016-08-03T09:41:22Z
38,740,327
<p>There's a good page <a href="http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python">here</a> on this issue. You can loop through both your dictionaries and compare their values. The example hereunder shows how you can print the keys for which your values are equal.</p> <p>=========================================================================</p> <p>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'}</p> <p><strong>For Python 2.x-</strong></p> <pre><code>for key_1, value_1 in productData_1.iteritems(): for key_2, value_2 in productData_2.iteritems(): if value_1 == value_2: print("key_1" + str(key_1)) print("key_2" + str(key_2)) </code></pre> <p><strong>For Python 3.x-</strong></p> <pre><code>for key_1, value_1 in productData_1.items(): for key_2, value_2 in productData_2.items(): if value_1 == value_2: print("key_1" + str(key_1)) print("key_2" + str(key_2)) </code></pre>
0
2016-08-03T09:59:07Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} </code></pre> <p>What I want to do is compare both dictionaries both by keys and by values, so that I can see the differences between both dicts, e.g. are there different prices, is a product missing in <code>productData_1</code> or <code>_2</code>? </p> <p>I know that I have to iterate over both dicts in some way but I can't figure out how to do it. </p>
0
2016-08-03T09:41:22Z
38,740,508
<pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} matched_keys = [] unmatched_keys = [] matched_value = [] unmatched_value = [] for ind,value in productData_1.items(): if ind in productData_2.keys(): matched_keys.append( ind ) if value in productData_2.values(): matched_value.append( value ) else: unmatched_value.append( value ) else: unmatched_keys.append( ind ) if value in productData_2.values(): matched_value.append( value ) else: unmatched_value.append( value ) print matched_keys print unmatched_keys print matched_value print unmatched_value </code></pre>
0
2016-08-03T10:06:14Z
[ "python", "dictionary" ]
Does ply's YACC support the Extended Backus-Naur Form?
38,740,061
<p><a href="http://www.dabeaz.com/ply/PLYTalk.pdf" rel="nofollow">The examples I've seen</a> always use the "simple" BNF. Here's an example of a part of my silly development:</p> <pre><code>def p_expression(p): """expression : NUMBER | NAME | NEGATION | INCREMENT | DECREMENT | expression operator expression""" if __name__ == "__main__": lex.lex() yacc.yacc() data = "32 &lt;+&gt; 10 |" result = yacc.parse(data) </code></pre> <p>What if I want to parse a math expression with parenthesis and the whole recursive hell of it <a href="http://stackoverflow.com/a/9786085/1795924">just like in this answer that uses the extended one</a>? Is it possible?</p>
0
2016-08-03T09:47:02Z
38,747,805
<p>No, PLY (like yacc) does not support extended BNF.</p> <p>The page you refer to provides a strategy for constructing <em>top-down</em> parsers, while the parsers built by yacc (as well as Bison, PLY and other derivatives) build bottom-up parsers. The advantage of a bottom-up parser is that the grammar used to parse bears a closer correspondence to the actual grammatical structure of the language, and thus can be used directly to build an AST (abstract syntax tree).</p> <p>Arithmetic expression grammars in BNF are generally quite simple (although not quite as simple as the ambiguous grammar in your question), particularly if you use the operator precedence declarations provided by yacc (and PLY).</p>
1
2016-08-03T15:27:16Z
[ "python", "parsing", "yacc", "bnf", "ply" ]
Python subprocess.check_call() not recognising pushd and popd
38,740,215
<p>I'm on Ubuntu 15.04 (not by choice obviously) and Python 3.4.3 and I'm trying to execute something like the following.</p> <pre><code>subprocess.check_call("pushd /tmp", shell=True) </code></pre> <p>I need the <code>shell=True</code> because the actual code I'm trying to execute contains wildcards that need to be interpreted. However, this gives me the following error.</p> <pre><code>/usr/lib/python3.4/subprocess.py in check_call(*popenargs, **kwargs) 559 if cmd is None: 560 cmd = popenargs[0] --&gt; 561 raise CalledProcessError(retcode, cmd) 562 return 0 563 CalledProcessError: Command 'pushd /tmp' returned non-zero exit status 127 </code></pre> <p>I've tried doing the same thing on my Mac (El Capitan and Python 3.5.1) and it works perfectly. I've also tried executing <code>subprocess.check_call("ls", shell=True)</code> on the Ubuntu 15.04 with Python 3.4.3 (for sanity check), and it works fine. As a final sanity check, I've tried the command <code>pushd /tmp &amp;&amp; popd</code> in Bash on the Ubuntu 15.04 and that works fine too. So somehow, on (my) Ubuntu 15.04 with Python 3.4.3, <code>subprocess.check_call()</code> does not recognise <code>pushd</code> and <code>popd</code>! Why?</p>
0
2016-08-03T09:53:54Z
38,740,640
<p>You have two problems with your code. The first one is that the shell used by default is <code>/bin/sh</code> which doesn't support <code>pushd</code> and <code>popd</code>. In your question you failed to provide the whole error output, and at the top of it you should see the line:</p> <pre><code>/bin/sh: 1: popd: not found </code></pre> <p>The next time rememeber to post the <em>whole</em> error message, and not just the portion that <em>you</em> (incorrectly) think is relevant.</p> <p>You can fix this by telling the <code>subprocess</code> module which shell to use via the <code>executable</code> argument:</p> <pre><code>&gt;&gt;&gt; subprocess.check_call('pushd ~', shell=True, executable='/bin/bash') ~ ~ 0 </code></pre> <p>The second problem is that even with this you will get an error if you use multiple <code>check_call</code> calls:</p> <pre><code>&gt;&gt;&gt; subprocess.check_call('pushd ~', shell=True, executable='/bin/bash') ~ ~ 0 &gt;&gt;&gt; subprocess.check_call('popd', shell=True, executable='/bin/bash') /bin/bash: riga 0: popd: stack delle directory vuoto Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.5/subprocess.py", line 581, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'popd' returned non-zero exit status 1 </code></pre> <p>This is because every call to <code>check_call</code> starts a <strong>new</strong> subshells, and thus it doesn't matter whether you previously called <code>pushd</code> because the directory stack will always be empty.</p> <p>Note that if you try to combine <code>pushd</code> and <code>popd</code> in a single call they <em>do</em> work:</p> <pre><code>&gt;&gt;&gt; subprocess.check_call('pushd ~ &amp;&amp; popd', shell=True, executable='/bin/bash') ~ ~ ~ 0 </code></pre> <p>Now fact is, if you were thinking of using <code>pushd</code> and <code>popd</code> in that way from python... they are <em>useless</em>. That's because you can specify the current working directory via the <code>cwd</code> argument, and so you can keep track of the stack of working directories from python without having to rely on <code>pushd</code> and <code>popd</code>:</p> <pre><code>current_working_dirs = [] def pushd(dir): current_working_dirs.append(os.path.realpath(os.path.expanduser(dir))) def popd(): current_working_dirs.pop() def run_command(cmdline, **kwargs): return subprocess.check_call(cmdline, cwd=current_working_dirs[-1], **kwargs) </code></pre> <p>Replace <code>check_call('pushd xxx')</code> with <code>pushd('xxx')</code> and <code>check_call('popd')</code> with <code>popd</code> and use <code>run_command(...)</code> instead of <code>check_call(...)</code>.</p> <hr> <p>As you suggest a more elegant solution would be to use a context manager:</p> <pre><code>class Pwd: dir_stack = [] def __init__(self, dirname): self.dirname = os.path.realpath(os.path.expanduser(self.dirname)) def __enter__(self): Pwd.dir_stack.append(self.dirname) return self def __exit__(self, type, value, traceback): Pwd.dir_stack.pop() def run(self, cmdline, **kwargs): return subprocess.check_call(cmdline, cwd=Pwd.dir_stack[-1], **kwargs) </code></pre> <p>used as:</p> <pre><code>with Pwd('~') as shell: shell.run(command) with Pwd('/other/directory') as shell: shell.run(command2) # runs in '/other/directory' shell.run(command3) # runs in '~' </code></pre>
2
2016-08-03T10:11:34Z
[ "python", "bash", "python-3.x", "subprocess", "ubuntu-15.04" ]
How to define a triple layer dictionary in python?
38,740,300
<p>I want to create the following structure for a dictionary:</p> <pre><code>{ id1: {id2: {id3: [] }}} </code></pre> <p>That would be a triple dictionary that will finally point to a list.</p> <p>I use the following code to initiate it in Python:</p> <pre><code>for i in range(2160): for j in range(2160): for k in range(2160): subnetwork.update({i: {j: {k: [] }}}) </code></pre> <p>This code takes too much time to execute. It is of Big-O(N^3) complexity.</p> <p>Are there any ways to speed-up this process? Serializing maybe the data structure and retrieving it from hard drive is faster?</p> <p>What data structures can achieve similar results? Would a flat dictionary using three-element tuples as keys serve my purpose?</p>
3
2016-08-03T09:57:48Z
38,740,548
<p>Do you really need 10 billion entries (2,160 ** 3 == 10,077,696,000) in this structure? It's unlikely that any disk-based solution will be quicker than a memory-based one, but at the same time your program might be exceeding the bounds of real memory, causing "page thrashing" to occur.</p> <p>Without knowing anything about your intended application it's hard to propose a suitable solution. What is it that you are trying to do?</p> <p>For example, if you don't need to randomly look up items you might consider a flat dictionary using three-element tuples as keys. But since you don't tell use what you are trying to do anything more would probably be highly speculative.</p>
2
2016-08-03T10:07:55Z
[ "python", "dictionary", "optimization", "data-structures" ]
Django Mezzanine ImportError: No module named apps
38,740,421
<p>I had a working mezzanine project configured with apache and mod_wsgi. I tried to added an app to the project and restarted apache and suddenly the project is throwing the error even after undoing the changes. Getting the same error when I'm trying to run python manage.py check:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 284, in execute self.validate() File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 310, in validate num_errors = get_validation_errors(s, app) File "/usr/lib/python2.7/dist-packages/django/core/management/validation.py", line 34, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/usr/lib/python2.7/dist-packages/django/db/models/loading.py", line 196, in get_app_errors self._populate() File "/usr/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate self.load_app(app_name, True) File "/usr/lib/python2.7/dist-packages/django/db/models/loading.py", line 97, in load_app app_module = import_module(app_name) File "/usr/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/mezzanine/boot/__init__.py", line 16, in &lt;module&gt; from django.apps import apps ImportError: No module named apps </code></pre> <p>Path to django: "/usr/local/lib/python2.7/dist-packages/django", and it has folder named "apps" and "<strong>init</strong>.py" file exists inside the folder.</p> <p>I then created a whole new mezzanine project and ran python manage.py check, and getting the same error. It means not any mezzanine project is working. I tried updating and reinstalling django and mezzanine but no use. On the other hand, a simple django project is running fine. It seems there is some problem with mezzanine. I went through the other related questions but couldn't get it resolved. Any help would be much appreciated. Thanks in advance.</p>
1
2016-08-03T10:03:02Z
38,747,153
<p>You say you have a folder named <code>apps</code> in your Django installation, but the traceback shows it is executing code that was removed in 1.7, the same version that introduced <code>django.apps</code>. Your installation is most likely corrupt and has files from different versions.</p> <p>Uninstall Django from your Python installation, and completely remove the <code>/usr/local/lib/python2.7/dist-pacakges/django/</code> folder. Then, reinstall a Django version that is compatible with your version of Mezzanine.</p> <p>It seems that you've installed Django into your global Python installation. This can easily cause such problems when multiple projects need to use different versions of python packages. It is recommended to use a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtual environment</a> to manage requirements for your projects in an isolated environment and prevent such conflicts. </p>
0
2016-08-03T14:58:28Z
[ "python", "django", "mezzanine" ]
How to split dataframe according to intersection point in Python?
38,740,423
<p>I am working on a project which is aiming to show difference between good form and bad form of an exercise. To do this we collected the acceleration data with wrist based accelerometer. <a href="http://i.stack.imgur.com/bZg1U.png" rel="nofollow"><img src="http://i.stack.imgur.com/bZg1U.png" alt="enter image description here"></a>The image above shows 2 set of a fitness execise (bench press). Each set has 10 repetitions. And the image below shows 10 repetitions of 1 set.<a href="http://i.stack.imgur.com/l9IEN.png" rel="nofollow"><img src="http://i.stack.imgur.com/l9IEN.png" alt="enter image description here"></a>I have a raw data set which consist of 10 set of an execises. What I want to do is splitting the raw data to 10 parts which will contain the part between 2 black line in the image above so I can analyze the data easily. My supervisor gave me a starting point which is choosing cutpoint in the each set. He said take a cutpoint, find the first interruption time start cutting at 3 sec before that time and count to 10 and finish cutting.</p> <p>This an idea that I don't know how to apply. At least, if you can tell how to cut a dataframe according to cutpoint I would be greatful.</p>
0
2016-08-03T10:03:04Z
38,791,129
<p>Well, I found another way to detect periodic parts of my accelerometer data. So, Here is my code:</p> <pre><code>import numpy as np from peakdetect import peakdetect import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib import style from pandas import DataFrame as df style.use('ggplot') def get_periodic(path): periodics = [] data_frame = df.from_csv(path) data_frame.columns = ['z', 'y', 'x'] if path.__contains__('1'): if path.__contains__('bench'): bench_press_1_week = data_frame.between_time('11:24', '11:52') peak_indexes = get_peaks(bench_press_1_week.y, lookahead=3000) for i in range(0, len(peak_indexes)): time_indexes = bench_press_1_week.index.tolist() start_time = time_indexes[0] periodic_start = start_time.to_datetime() + dt.timedelta(0, peak_indexes[i] / 100) periodic_end = periodic_start + dt.timedelta(0, 60) periodic = bench_press_1_week.between_time(periodic_start.time(), periodic_end.time()) periodics.append(periodic) return periodics def get_peaks(data, lookahead): peak_indexes = [] correlation = np.correlate(data, data, mode='full') realcorr = correlation[correlation.size / 2:] maxpeaks, minpeaks = peakdetect(realcorr, lookahead=lookahead) for i in range(0, len(maxpeaks)): peak_indexes.append(maxpeaks[i][0]) return peak_indexes def show_segment_plot(data, periodic_area, exercise_name): plt.figure(8) gs = gridspec.GridSpec(7, 2) ax = plt.subplot(gs[:2, :]) plt.title(exercise_name) ax.plot(data) k = 0 for i in range(2, 7): for j in range(0, 2): ax = plt.subplot(gs[i, j]) title = "{} {}".format(k + 1, ".Set") plt.title(title) ax.plot(periodic_area[k]) k = k + 1 plt.show() </code></pre> <p>Firstly, <a href="http://stackoverflow.com/questions/8006466/detecting-periodic-data-from-the-phones-accelerometer">this</a> question gave me another perspective for my problem. The image below shows the raw accelerometer data of bench press with 10 sets. Here it has 3 axis(x,y,z) and it's major axis is y(Blue on the image).<a href="http://i.stack.imgur.com/jGBom.png" rel="nofollow"><img src="http://i.stack.imgur.com/jGBom.png" alt="enter image description here"></a></p> <p>I used autocorrelation function for detecting the periodic parts, <a href="http://i.stack.imgur.com/hEzEZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/hEzEZ.png" alt="enter image description here"></a> In the image above every peak represents 1 set of execises. With <a href="https://gist.github.com/endolith/250860" rel="nofollow">this</a> peak detection algorithm I found each peak's x-axis value,</p> <pre><code>In[196]: maxpeaks Out[196]: [[16204, 32910.14013671875], [32281, 28726.95849609375], [48515, 24583.898681640625], [64436, 22088.130859375], [80335, 19582.248291015625], [96699, 16436.567626953125], [113081, 12100.027587890625], [129027, 8098.98486328125], [145184, 5387.788818359375]] </code></pre> <p>Basically, each x-value represent samples. My sampling frequency was 100Hz so 16204/100 = 162,04 seconds. To find the time of periodic part I added 162,04 sec to started time. Each bench press took aproximatelly 1 min and in this example, exercise's starting time was 11:24, for first periodic part's start time is 11:26 and ending time is 1 min after.<a href="http://i.stack.imgur.com/mp4Vm.png" rel="nofollow"><img src="http://i.stack.imgur.com/mp4Vm.png" alt="enter image description here"></a> There is some lag but yes best solution that I found is this.</p>
0
2016-08-05T14:00:12Z
[ "python", "pandas", "dataframe" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7,8],[10,11]] </code></pre> <p>The input list will always contain positive ints sorted in increasing order. I tried some of the code from <a href="http://stackoverflow.com/questions/5850986/joining-elements-of-a-list-python">here</a>.</p> <pre><code>initerator = iter(inputList) outputList = [c + next(initerator, "") for c in initerator] </code></pre> <p>Although I can concat every two entries in the list, I cannot seem to add a suitable <code>if</code> in the list comprehension.</p> <p>Python version = 3.4</p>
1
2016-08-03T10:03:05Z
38,740,829
<p>Nice way (found the "splitting" indices and then <a class='doc-link' href="http://stackoverflow.com/documentation/python/1494/list-slicing-selecting-parts-of-lists/4863/selecting-a-sublist-from-a-list#t=201608031037013525241">slice</a> the list accordingly):</p> <pre><code>input = [1,2,4,6,7,8,10,11] idx = [0] + [i+1 for i,(x,y) in enumerate(zip(input,input[1:])) if x+1!=y] + [len(input)] [ input[u:v] for u,v in zip(idx, idx[1:]) ] #output: [[1, 2], [4], [6, 7, 8], [10, 11]] </code></pre> <p>using <a href="https://docs.python.org/3.5/library/functions.html#enumerate" rel="nofollow">enumerate()</a> and <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow">zip()</a>.</p>
0
2016-08-03T10:20:55Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7,8],[10,11]] </code></pre> <p>The input list will always contain positive ints sorted in increasing order. I tried some of the code from <a href="http://stackoverflow.com/questions/5850986/joining-elements-of-a-list-python">here</a>.</p> <pre><code>initerator = iter(inputList) outputList = [c + next(initerator, "") for c in initerator] </code></pre> <p>Although I can concat every two entries in the list, I cannot seem to add a suitable <code>if</code> in the list comprehension.</p> <p>Python version = 3.4</p>
1
2016-08-03T10:03:05Z
38,741,384
<p>Unless you have to have a one-liner, you could use a simple generator function, combining elements until you hit a non consecutive element:</p> <pre><code>def consec(lst): it = iter(lst) prev = next(it) tmp = [prev] for ele in it: if prev + 1 != ele: yield tmp tmp = [ele] else: tmp.append(ele) prev = ele yield tmp </code></pre> <p>Output:</p> <pre><code>In [2]: lst = [1, 2, 4, 6, 7, 8, 10, 11] In [3]: list(consec(lst)) Out[3]: [[1, 2], [4], [6, 7, 8], [10, 11]] </code></pre>
0
2016-08-03T10:46:08Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7,8],[10,11]] </code></pre> <p>The input list will always contain positive ints sorted in increasing order. I tried some of the code from <a href="http://stackoverflow.com/questions/5850986/joining-elements-of-a-list-python">here</a>.</p> <pre><code>initerator = iter(inputList) outputList = [c + next(initerator, "") for c in initerator] </code></pre> <p>Although I can concat every two entries in the list, I cannot seem to add a suitable <code>if</code> in the list comprehension.</p> <p>Python version = 3.4</p>
1
2016-08-03T10:03:05Z
38,742,081
<p>Simplest version I have without any imports:</p> <pre><code>def mergeAdjNum(l): r = [[l[0]]] for e in l[1:]: if r[-1][-1] == e - 1: r[-1].append(e) else: r.append([e]) return r </code></pre> <p>About 33% faster than one liners.</p> <p>This one handles the character prefix grouping mentioned in a comment:</p> <pre><code>def groupPrefStr(l): pattern = re.compile(r'([a-z]+)([0-9]+)') r = [[l[0]]] pp, vv = re.match(pattern, l[0]).groups() vv = int(vv) for e in l[1:]: p,v = re.match(pattern, e).groups() v = int(v) if p == pp and v == vv + 1: r[-1].append(e) else: pp, vv = p, v r.append([e]) return r </code></pre> <p>This is way slower than the number only one. Knowing the exact format of the prefix (only one char ?) could help avoid using the re module and speed things up.</p>
0
2016-08-03T11:18:54Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
Transform numpy array to RGB image array
38,740,495
<p>Consider the following code:</p> <pre><code>import numpy as np rand_matrix = np.random.rand(10,10) </code></pre> <p>which generates a 10x10 random matrix.</p> <p>Following code to display as colour map:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(rand_matrix) plt.show() </code></pre> <p>I would like to get the RGB numpy array (no axis) from the object obtained from plt.imshow</p> <p>In other words, if I save the image generated from plt.show, I would like to get the 3D RGB numpy array obtained from:</p> <pre><code>import matplotlib.image as mpimg img=mpimg.imread('rand_matrix.png') </code></pre> <p>But without the need to save and load the image, which is computationally very expensive.</p> <p>Thank you.</p>
0
2016-08-03T10:05:49Z
38,740,915
<p>You can save time by saving to a <code>io.BytesIO</code> instead of to a file:</p> <pre><code>import io import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from PIL import Image def ax_to_array(ax, **kwargs): fig = ax.figure frameon = ax.get_frame_on() ax.set_frame_on(False) with io.BytesIO() as memf: extent = ax.get_window_extent() extent = extent.transformed(fig.dpi_scale_trans.inverted()) plt.axis('off') fig.savefig(memf, format='PNG', bbox_inches=extent, **kwargs) memf.seek(0) arr = mpimg.imread(memf)[::-1,...] ax.set_frame_on(frameon) return arr.copy() rand_matrix = np.random.rand(10,10) fig, ax = plt.subplots() ax.imshow(rand_matrix) result = ax_to_array(ax) # view using matplotlib plt.show() # view using PIL result = (result * 255).astype('uint8') img = Image.fromarray(result) img.show() </code></pre> <p><a href="http://i.stack.imgur.com/yW3Hc.png" rel="nofollow"><img src="http://i.stack.imgur.com/yW3Hc.png" alt="enter image description here"></a></p>
1
2016-08-03T10:24:31Z
[ "python", "image", "numpy", "rgb" ]
Python in C++ or C++ pure for file templates manipulation?
38,740,520
<p>(I don't know if I can post such a question here)</p> <p>I have a problem for which I need a suggestion. I've a C++ code that derive several parameters (which are numbers basically). Such numbers have to be used to generate further code, of which I have templates, as very trivial example a template could look as something like:</p> <pre><code>#define PAR1 &lt;PAR1&gt; #define PAR2 &lt;PAR2&gt; //other parameters, function declaration, tables and so on... </code></pre> <p>In the example above , and all the possible others are derived by the C++ code mentioned above.</p> <p>What would be, in your opinion, a good approach to achieve the parameter replacement?</p> <p>I was thinking at two solutions, but I don't know which one would be the best: 1. I could write several python scripts (as many as I need) for string replacement for given parameters, such scripts has to be called in the C++ application once the parameters have been derived. 2. Reading the stream of the template file, look for the position of the parameters to be replaced and the replace it.</p> <p>The first solution would require to call the pythons script from the C++ application and I don't know how to do that, I've been looking at some solution, and to be honest I don't know how simple it is.</p> <p>The second solution is C++ file manipulation, which could be a bit of a pain in my specific case?</p> <p>Since what I'm up to is the easiest way to achieve my goal which one would you suggest?</p> <p>Thx</p> <p>Update: I'm trying to be a bit more specific by posting a trivial example. A possible template, extremely minimal, could be the following:</p> <pre><code>//header_template.h #ifndef HEADER_H #define HEADER_H #include &lt;stdio.h&gt; #define A &lt;A&gt; #define B &lt;B&gt; #define C &lt;C&gt; void func1(); void func2(); void func3(); #endif </code></pre> <p>The source file //src.c #include "header.h"</p> <pre><code>void func1() { int i, my_array1[A]; for(i = 0; i &lt; A; i++) { my_array1[i] = do_something(i); } //other processing; } void func2() { int i, j, my_matrix[A][B]; for(i = 0; i &lt; A; i++) { for(j = 0; j &lt; B; j++) { my_matrix[i][j] = do_something_2(i,j); } } } void func3() { int i; int my_array[A + B + C]; for(i = 0; i &lt; A + B + C; i++) { my_array[i] = do_something_else(i); } } </code></pre> <p>The parameters <code>A, B, C</code> are derived by some other processing operations prior the code generation, what I want to achieve is something like:</p> <pre><code>//header.h #ifndef HEADER_H #define HEADER_H #include &lt;stdio.h&gt; #define A 17 #define B 9 #define C 37 void func1(); void func2(); void func3(); #endif </code></pre> <p>My question is: doing text replacement using python is very easy, in C++ is not that easy. The processing of the parameters A,B and C is done by something implemented in C++, I need to extend such program for for such replacement, given the fact I've been using C++ so far is it better to develop small python programs and then call such scripts in the C++ program or is it better just to implement functions in C++ for the replacement?</p> <p>The example I made can sound trivial, which is true, however the actual code I'm dealing with, and I'm posting larger of course so what I'm asking is what you would do in such a case.</p>
1
2016-08-03T10:06:52Z
38,740,743
<p>Although I am a Python enthusiast, I think for this one you should stay within C++ (since it seems you have already a significant amount of C++ code) and use a decent library like Boost. You could consider using Cython as a bridge, but my estimation is that it would be overkill.</p>
1
2016-08-03T10:16:42Z
[ "python", "c++", "file" ]
Is plug-in based approach considered good practice for GUI app development in PyQt?
38,740,649
<p>I'm thinking of using a plug-in based UI architecture to develop my PyQt project, i.e. create a skeleton main window which will dynamically load all the other UI components and these UI components will be made as PyQt plugins. </p> <p>Since I'm quite new to PyQt, I'm wondering if this is a good practice that people tend to follow in GUI app development.</p> <p>Any better alternative approaches are welcome!</p>
1
2016-08-03T10:12:11Z
38,787,357
<p>A plugin based architecture is a very powerful way to design scalable, maintainable, extensible software. If you intend to build software where you consider certain parts of it should be plugins just go for it because in python implementing plugins is straightforward.</p> <p>Of course, all depends what type of software you're gonna be building and the size of it, if I'm gonna build very small software with a fixed rigid set of requirements, having just a good set of custom widgets and using the builtin Qt ones could be a fast way to deliver the product. If the software is not gonna be so small you can also decide to use patterns like <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">mvc</a></p> <p>But I think the most important advice I can give here is having in mind the <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">zen of python</a> and also consider <a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)" rel="nofollow">important principles in software engineering</a>.</p> <p>As I've said at the beginning of this post, if you just want to implement a plugin based approach, there are dozens of python frameworks out there, here's a little list:</p> <ul> <li><a href="https://pypi.python.org/pypi/extensions" rel="nofollow">extensions</a></li> <li><a href="https://www.riverbankcomputing.com/software/dip/download" rel="nofollow">dip</a></li> <li><a href="https://github.com/kovidgoyal/calibre" rel="nofollow">calibre</a></li> <li><a href="http://yapsy.sourceforge.net/" rel="nofollow">yapsy</a></li> <li><a href="http://pluginbase.pocoo.org/" rel="nofollow">pluginbase</a></li> <li><a href="https://github.com/benhoff/pluginmanager" rel="nofollow">pluginmanager</a></li> <li><a href="https://github.com/daltonmatos/plugnplay#readme" rel="nofollow">plugnplay</a></li> <li><a href="https://github.com/ccoughlin/NDIToolbox" rel="nofollow">NDIToolbox</a></li> <li><a href="https://github.com/dae/anki/" rel="nofollow">anki</a></li> <li><a href="https://github.com/ironfroggy/straight.plugin" rel="nofollow">straight.plugin</a></li> <li><a href="https://pypi.python.org/pypi/pluggy" rel="nofollow">pluggy</a></li> <li><a href="https://github.com/edgewall/trac" rel="nofollow">trac</a></li> <li><a href="https://github.com/HackEdit" rel="nofollow">HackEdit</a></li> <li><a href="http://docs.enthought.com/envisage" rel="nofollow">envisage</a></li> <li><a href="https://github.com/openstack/stevedore" rel="nofollow">stevedore</a></li> <li><a href="https://github.com/PyUtilib/pyutilib/" rel="nofollow">pyutilib</a></li> </ul> <p>As a personal advice I can give you, I would focus on <a href="https://github.com/enthought/envisage" rel="nofollow">envisage</a>, it provides several examples using PyQt and the architecture has very similar concepts to Eclipse, I must say it's a really powerful framework. If you feel the framework is too heavy for you in the above list you'll find something much lighter like straight.plugin or pluginbase.</p>
0
2016-08-05T10:46:45Z
[ "python", "python-2.7", "pyqt" ]
How to make python import an identically named module from the local directory instead site-packages?
38,740,672
<p>I'm a bit confused on how python separates between modules installed in site-packages and modules in the local directory if they have identical names and what's the best way to make python import the module from the local directory instead of the installed one. </p> <p>Basically I have a command line app and I'm using this to install it with setup.py </p> <pre><code>setup( name='app', version='0.5.2', packages=find_packages(), entry_points={ 'console_scripts': [ 'katana = app.main:main' ] } ) </code></pre> <p>The problem I having is that when I'm run main.py from my source folder and do:</p> <pre><code>import app.script_A </code></pre> <p>instead of src/scriptA.py (same folder as main.py) it imports the installed module from</p> <pre><code>/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/app-0.5.2-py3.5.egg!/app/scriptA.py </code></pre> <p>So what is the proper way to solve this, if I want to still be able to install the module system wide with setuptools, but when running the main.py from the source folder manually I want it to import all the modules from that folder instead of Library?</p>
0
2016-08-03T10:13:19Z
38,740,880
<p>The easiest way to nominate additional directories to be searched when trying to import modules is to add them to the <code>sys.path</code> list.</p> <p>The interpreter looks at an environment variable called <code>$PYTHONPATH</code>, which should be a colon-separated (Windows: semi-colon separated) list of directories, each of which will be added to <code>sys.path</code> if it exists.</p> <p>You can find more on module imports <a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">in the documentation</a>.</p>
0
2016-08-03T10:23:25Z
[ "python", "setuptools" ]
How to make python import an identically named module from the local directory instead site-packages?
38,740,672
<p>I'm a bit confused on how python separates between modules installed in site-packages and modules in the local directory if they have identical names and what's the best way to make python import the module from the local directory instead of the installed one. </p> <p>Basically I have a command line app and I'm using this to install it with setup.py </p> <pre><code>setup( name='app', version='0.5.2', packages=find_packages(), entry_points={ 'console_scripts': [ 'katana = app.main:main' ] } ) </code></pre> <p>The problem I having is that when I'm run main.py from my source folder and do:</p> <pre><code>import app.script_A </code></pre> <p>instead of src/scriptA.py (same folder as main.py) it imports the installed module from</p> <pre><code>/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/app-0.5.2-py3.5.egg!/app/scriptA.py </code></pre> <p>So what is the proper way to solve this, if I want to still be able to install the module system wide with setuptools, but when running the main.py from the source folder manually I want it to import all the modules from that folder instead of Library?</p>
0
2016-08-03T10:13:19Z
38,741,016
<p>if scriptA.py is in the same directory of main.py can't you just <code>import .scriptA</code> ?</p> <p>The <code>.</code> is a shortcut that tells python to search in current package before rest of the <code>PYTHONPATH</code></p>
0
2016-08-03T10:29:10Z
[ "python", "setuptools" ]
Python simple brackets parser
38,740,853
<p>I basically have a file with this structure: </p> <pre><code>root \ { field1 { subfield_a { "value1" } subfield_b { "value2" } subfield_c { "value1" "value2" "value3" } subfield_d { } } field2 { subfield_a { "value1" } subfield_b { "value1" } subfield_c { "value1" "value2" "value3" "value4" "value5" } subfield_d { } } } </code></pre> <p>I want to parse this file with python to get a multidimensional array that contains all the values of a specific subfield (for examples subfield_c). E.g. :</p> <pre><code>tmp = magic_parse_function("subfield_c",file) print tmp[0] # [ "value1", "value2", "value3"] print tmp[1] # [ "value1", "value2", "value3", "value4", "value5"] </code></pre> <p>I'm pretty sure I've to use the pyparsing class, but I don't where to start to set the regex (?) expression. Can someone give me some pointers ? </p>
0
2016-08-03T10:22:10Z
38,933,432
<p>You can let pyparsing take care of the matching and iterating over the input, just define what you want it to match, and pass it the body of the file as a string:</p> <pre><code>def magic_parse_function(fld_name, source): from pyparsing import Keyword, nestedExpr # define parser parser = Keyword(fld_name).suppress() + nestedExpr('{','}')("content") # search input string for matching keyword and following braced content matches = parser.searchString(source) # remove quotation marks return [[qs.strip('"') for qs in r[0].asList()] for r in matches] # read content of file into a string 'file_body' and pass it to the function tmp = magic_parse_function("subfield_c",file_body) print(tmp[0]) print(tmp[1]) </code></pre> <p>prints:</p> <pre><code>['value1', 'value2', 'value3'] ['value1', 'value2', 'value3', 'value4', 'value5'] </code></pre>
1
2016-08-13T13:53:43Z
[ "python", "parsing" ]
XGBoost difference in train and test features after converting to DMatrix
38,740,885
<p>Just wondering how is possible next case:</p> <pre><code> def fit(self, train, target): xgtrain = xgb.DMatrix(train, label=target, missing=np.nan) self.model = xgb.train(self.params, xgtrain, self.num_rounds) </code></pre> <p><a href="http://i.stack.imgur.com/8GQ0v.png" rel="nofollow"><img src="http://i.stack.imgur.com/8GQ0v.png" alt="enter image description here"></a> I passed the train dataset as <strong>csr_matrix</strong> with 5233 columns, and after converting to DMatrix I got 5322 features.</p> <p>Later on predict step, I got an error as cause of above bug :(</p> <pre><code> def predict(self, test): if not self.model: return -1 xgtest = xgb.DMatrix(test) return self.model.predict(xgtest) </code></pre> <p><a href="http://i.stack.imgur.com/YyEoK.png" rel="nofollow"><img src="http://i.stack.imgur.com/YyEoK.png" alt="enter image description here"></a></p> <blockquote> <p>Error: ... training data did not have the following fields: f5232</p> </blockquote> <p>How can I guarantee correct converting my <strong>train/test</strong> datasets to DMatrix? </p> <p>Are there any chance to use in Python something similar to R?</p> <pre><code># get same columns for test/train sparse matrixes col_order &lt;- intersect(colnames(X_train_sparse), colnames(X_test_sparse)) X_train_sparse &lt;- X_train_sparse[,col_order] X_test_sparse &lt;- X_test_sparse[,col_order] </code></pre> <p>My approach doesn't work, unfortunately:</p> <pre><code>def _normalize_columns(self): columns = (set(self.xgtest.feature_names) - set(self.xgtrain.feature_names)) | \ (set(self.xgtrain.feature_names) - set(self.xgtest.feature_names)) for item in columns: if item in self.xgtest.feature_names: self.xgtest.feature_names.remove(item) else: # seems, it's immutable structure and can not add any new item!!! self.xgtest.feature_names.append(item) </code></pre>
1
2016-08-03T10:23:37Z
38,875,449
<p>This situation can happen after one-hot encoding. For example,</p> <pre><code>ar = np.array([ [1, 2], [1, 0] ]) enc = OneHotEncoder().fit(ar) ar2 = enc.transform(ar) b = np.array([[1, 0]]) b2 = enc.transform(b) xgb_ar = xgb.DMatrix(ar2) xgb_b = xgb.DMatrix(b2) print(b2.shape) # (1, 3) print(xgb_b.num_col()) # 2 </code></pre> <p>So, when you have all zero column in sparse matrix, DMatrix drop this column (I think, because this column is useless for XGBoost)</p> <p>Usually, I add a fake row to matrix which contents 1 in all columns.</p>
1
2016-08-10T13:54:31Z
[ "python", "python-2.7", "numpy", "machine-learning", "xgboost" ]
XGBoost difference in train and test features after converting to DMatrix
38,740,885
<p>Just wondering how is possible next case:</p> <pre><code> def fit(self, train, target): xgtrain = xgb.DMatrix(train, label=target, missing=np.nan) self.model = xgb.train(self.params, xgtrain, self.num_rounds) </code></pre> <p><a href="http://i.stack.imgur.com/8GQ0v.png" rel="nofollow"><img src="http://i.stack.imgur.com/8GQ0v.png" alt="enter image description here"></a> I passed the train dataset as <strong>csr_matrix</strong> with 5233 columns, and after converting to DMatrix I got 5322 features.</p> <p>Later on predict step, I got an error as cause of above bug :(</p> <pre><code> def predict(self, test): if not self.model: return -1 xgtest = xgb.DMatrix(test) return self.model.predict(xgtest) </code></pre> <p><a href="http://i.stack.imgur.com/YyEoK.png" rel="nofollow"><img src="http://i.stack.imgur.com/YyEoK.png" alt="enter image description here"></a></p> <blockquote> <p>Error: ... training data did not have the following fields: f5232</p> </blockquote> <p>How can I guarantee correct converting my <strong>train/test</strong> datasets to DMatrix? </p> <p>Are there any chance to use in Python something similar to R?</p> <pre><code># get same columns for test/train sparse matrixes col_order &lt;- intersect(colnames(X_train_sparse), colnames(X_test_sparse)) X_train_sparse &lt;- X_train_sparse[,col_order] X_test_sparse &lt;- X_test_sparse[,col_order] </code></pre> <p>My approach doesn't work, unfortunately:</p> <pre><code>def _normalize_columns(self): columns = (set(self.xgtest.feature_names) - set(self.xgtrain.feature_names)) | \ (set(self.xgtrain.feature_names) - set(self.xgtest.feature_names)) for item in columns: if item in self.xgtest.feature_names: self.xgtest.feature_names.remove(item) else: # seems, it's immutable structure and can not add any new item!!! self.xgtest.feature_names.append(item) </code></pre>
1
2016-08-03T10:23:37Z
38,887,112
<p>One another possibility is to have one feature level exclusively in training data not in testing data. This situation happens mostly while post one hot encoding whose resultant is big matrix have level for each level of categorical features. In your case it looks like "f5232" is either exclusive in training or test data. If either case model scoring likely to throw error (in most implementations of ML packages) because:</p> <ol> <li>If exclusive to training: Model object will have reference of this feature in model equation. While scoring it will throw error saying I am not able to find this column.</li> <li>If exclusive to test (lesser likely as test data is usually smaller than training data): Model object will NOT have reference of this feature in model equation. While scoring it will throw error saying I got this column but model equation don't have this column. This is also lesser likely because most implementations are cognizant of this case.</li> </ol> <p>Solutions:</p> <ol> <li>The best "automated" solution is to keep only those columns, which are common to both training and test post one hot encoding. </li> <li>For adhoc analysis if you can not afford to drop the level of feature because of its importance then do stratified sampling to ensure that all level of feature gets distributed to training and test data.</li> </ol>
1
2016-08-11T04:08:16Z
[ "python", "python-2.7", "numpy", "machine-learning", "xgboost" ]
What mistake am I making in my code?
38,740,997
<p>For some reason my code doesn't seem to add to q, it prints out 0 for q even though there are 11 lines in the csv file, all I want to check if the csv file is empty, the code doesn't work in my script, but in the python console it works fine.</p> <pre><code>with open('File.csv', 'r') as FILE: q=0;LS = reader(FILE, delimiter=',') for i in LS: q+=1 print q </code></pre> <p>Can anybody tell me what mistake I making? I am really confused.</p>
1
2016-08-03T10:28:19Z
38,741,286
<p>The <code>i</code> is iterating through the rows in <code>LS</code>, so if you have a file with 1 line it will be 1, if you have an empty file it will be 0, etc... I suspect your file is empty, or the opening did not succeed.</p>
1
2016-08-03T10:41:41Z
[ "python", "csv", "with-statement" ]
What mistake am I making in my code?
38,740,997
<p>For some reason my code doesn't seem to add to q, it prints out 0 for q even though there are 11 lines in the csv file, all I want to check if the csv file is empty, the code doesn't work in my script, but in the python console it works fine.</p> <pre><code>with open('File.csv', 'r') as FILE: q=0;LS = reader(FILE, delimiter=',') for i in LS: q+=1 print q </code></pre> <p>Can anybody tell me what mistake I making? I am really confused.</p>
1
2016-08-03T10:28:19Z
38,741,359
<p>Are you sure the file name is correct and in the same folder? I ran your script with a csv file I quickly made (contents: 1,2) and it outputted 1 as expected. Also make sure that your example code can be executed by itself, so include <code>from csv import reader</code> in the future.</p>
2
2016-08-03T10:44:52Z
[ "python", "csv", "with-statement" ]
Reading excel and storing data with xlrd
38,741,099
<p>I have this data in excel sheet </p> <pre><code>FT_NAME FC_NAME C_NAME FT_NAME1 FC1 C1 FT_NAME2 FC21 C21 FC22 C22 FT_NAME3 FC31 C31 FC32 C32 FT_NAME4 FC4 C4 </code></pre> <p>where column names are </p> <blockquote> <p>FT_NAME,FC_NAME,C_NAME</p> </blockquote> <p>and I want to store this values in a data structure for further use, currently I am trying to store them in a list of list but could not do so with following code</p> <pre><code>i=4 oc=sheet.cell(i,8).value fcl,ocl=[],[] while oc: ft=sheet.cell(i,6).value fc=sheet.cell(i,7).value oc=sheet.cell(i,8).value if ft: self.foreign_tables.append(ft) fcl.append(fc) ocl.append(oc) self.foreign_col.append(fcl) self.own_col.append(ocl) fcl,ocl=[],[] else: fcl.append(fc) ocl.append(oc) i+=1 </code></pre> <p>i expect output as </p> <pre><code>ft=[FT_NAME1,FT_NAME2,FT_NAME3,FT_NAME4] fc=[FC1, [FC21,FC22],[FC31,FC32],FC4] oc=[C1,[C21,C22],[C31,C32],C4] </code></pre> <p>could anyone please help for better pythonic solution ?</p>
0
2016-08-03T10:32:55Z
38,741,855
<p>You can use <code>pandas</code>. It reads the data into a DataFrame which is essentially a big dictionary. </p> <pre><code>import pandas as pd data =pd.read_excel('file.xlsx', 'Sheet1') data = data.fillna(method='pad') print(data) </code></pre> <p>it gives the following output:</p> <pre><code> FT_NAME FC_NAME C_NAME 0 FT_NAME1 FC1 C1 1 FT_NAME2 FC21 C21 2 FT_NAME2 FC22 C22 3 FT_NAME3 FC31 C31 4 FT_NAME3 FC32 C32 5 FT_NAME4 FC4 C4 </code></pre> <p>To get the sublist structure try using this function:</p> <pre><code>def group(data): output = [] names = list(set(data['FT_NAME'].values)) names.sort() output.append(names) headernames = list(data.columns) headernames.pop(0) for ci in list(headernames): column_group = [] column_data = data[ci].values for name in names: column_group.append(list(column_data[data['FT_NAME'].values == name])) output.append(column_group) return output </code></pre> <p>If you call it like this:</p> <pre><code>ft, fc, oc = group(data) print(ft) print(fc) print(oc) </code></pre> <p>you get the following output:</p> <pre><code>['FT_NAME1', 'FT_NAME2', 'FT_NAME3', 'FT_NAME4'] [['FC1'], ['FC21', 'FC22'], ['FC31', 'FC32'], ['FC4']] [['C1'], ['C21', 'C22'], ['C31', 'C32'], ['C4']] </code></pre> <p>which is what you want except for the single element now also being in a list.</p> <p>It is not the cleanest method but it gets the job done.</p> <p>Hope it helps.</p>
0
2016-08-03T11:07:06Z
[ "python", "xlrd" ]
Python: count specific occurrences in a dictionary
38,741,110
<p>Say I have a dictionary like this:</p> <pre><code>d={ '0101001':(1,0.0), '0101002':(2,0.0), '0101003':(3,0.5), '0103001':(1,0.0), '0103002':(2,0.9), '0103003':(3,0.4), '0105001':(1,0.0), '0105002':(2,1.0), '0105003':(3,0.0)} </code></pre> <p>Considering that the first four digits of each key consitute the identifier of a "slot" of elements (e.g., '0101', '0103', '0105'), how can I count the number of occurrences of <code>0.0</code> for each slot?</p> <p>The intended outcome is a dict like this:</p> <pre><code>result={ '0101': 2, '0103': 1, '0105': 2} </code></pre> <p>Apologies for not being able to provide my attempt as I don't really know how to do this.</p>
0
2016-08-03T10:33:19Z
38,741,203
<p>Use a <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow">Counter</a>, add the first four digits of the key if the value is what you're looking for:</p> <pre><code>from collections import Counter counts = Counter() for key, value in d.items(): if value[1] == 0.0: counts[key[:4]] += 1 print counts </code></pre>
3
2016-08-03T10:37:45Z
[ "python", "dictionary", "find-occurrences" ]
Python: count specific occurrences in a dictionary
38,741,110
<p>Say I have a dictionary like this:</p> <pre><code>d={ '0101001':(1,0.0), '0101002':(2,0.0), '0101003':(3,0.5), '0103001':(1,0.0), '0103002':(2,0.9), '0103003':(3,0.4), '0105001':(1,0.0), '0105002':(2,1.0), '0105003':(3,0.0)} </code></pre> <p>Considering that the first four digits of each key consitute the identifier of a "slot" of elements (e.g., '0101', '0103', '0105'), how can I count the number of occurrences of <code>0.0</code> for each slot?</p> <p>The intended outcome is a dict like this:</p> <pre><code>result={ '0101': 2, '0103': 1, '0105': 2} </code></pre> <p>Apologies for not being able to provide my attempt as I don't really know how to do this.</p>
0
2016-08-03T10:33:19Z
38,741,555
<p>You can use a <a class='doc-link' href="http://stackoverflow.com/documentation/python/498/collections/1636/collections-defaultdict#t=201608031052568500106"><code>defaultdict</code></a>:</p> <pre><code>from _collections import defaultdict res = defaultdict(int) for k in d: if d[k][1] == 0.0: res[k[:4]] += 1 print(dict(res)) </code></pre> <p>When you do the <code>+=1</code>, if the key does not exist, it creates it with value <code>0</code> and then does the operation.</p>
2
2016-08-03T10:53:34Z
[ "python", "dictionary", "find-occurrences" ]
RQ Timeout does not kill multi-threaded jobs
38,741,173
<p>I'm having problems running multithreaded tasks using python RQ (tested on v0.5.6 and v0.6.0).</p> <p>Consider the following piece of code, as a simplified version of what I'm trying to achieve:</p> <h1>thing.py</h1> <pre><code>from threading import Thread class MyThing(object): def say_hello(self): while True: print "Hello World" def hello_task(self): t = Thread(target=self.say_hello) t.daemon = True # seems like it makes no difference t.start() t.join() </code></pre> <h1>main.py</h1> <pre><code>from rq import Queue from redis import Redis from thing import MyThing conn = Redis() q = Queue(connection=conn) q.enqueue(MyThing().say_hello, timeout=5) </code></pre> <p>When executing <code>main.py</code> (while rqworker is running in background), the job breaks as expected by timeout, within 5 seconds.</p> <p>Problem is, when I'm setting a task containing thread/s such as <code>MyThing().hello_task</code>, the thread runs forever and nothing happens when the 5 seconds timeout is over.</p> <p>How can I run a multithreaded task with RQ, such that the timeout will kill the task, its sons, grandsons and their wives?</p>
1
2016-08-03T10:36:26Z
38,747,032
<p>When you run <code>t.join()</code>, the <code>hello_task</code> thread blocks and waits until the <code>say_hello</code> thread returns - thus not receiving the timeout signal from rq. You can allow the main thread to run and properly receive the timeout signal by using <code>Thread.join</code> with a set amount of time to wait, while waiting for the thread to finish running. Like so:</p> <pre><code>def hello_task(self): t = Thread(target=self.say_hello) t.start() while t.isAlive(): t.join(1) # Block for 1 second </code></pre> <p>That way you could also catch the timeout exception and handle it, if you wish:</p> <pre><code>def hello_task(self): t = Thread(target=self.say_hello) t.start() try: while t.isAlive(): t.join(1) # Block for 1 second except JobTimeoutException: # From rq.timeouts.JobTimeoutException print "Thread killed due to timeout" raise </code></pre>
1
2016-08-03T14:52:40Z
[ "python", "multithreading", "python-2.7", "python-rq", "django-rq" ]
Pandas - How to rename a table name?
38,741,177
<p>I am trying create dynamic table names by using variable from the for loop. I am using Python 2.7.</p> <p>This is the function I intend to write:</p> <p>where columns can be parsed from the external sources.</p> <p>FUNCTION: </p> <pre><code>def cutoff(row): if (row['CourierCode']=='DP'): for TAT in range(5): row[eval("TAT + "+str(TAT))]=[row.taskcreateddate==row.ReturnPickupDate+ timedelta(days=TAT)] RefundwTaskData.apply(lambda row : func(cutoff),axis = 1) </code></pre>
0
2016-08-03T10:36:31Z
38,742,390
<p>In your case, if you do want to accomplish it this way use:</p> <pre><code>exec("CombinedDataProjected%s = %s" % (month, 'pd.DataFrame(CombinedData)')) </code></pre> <p>But this is a very poor way of executing in python since Python has perfectly good concepts for representing a bunch of variables --- lists and dictionaries!. I personally would have done it by using a dictionary in the following manner (no need to create a separate function)</p> <pre><code>CombinedDataProjected = {} months = [201501,201502,201503] #Some list of months for month in months: &lt;Some routines for creating CombinedData&gt; CombinedDataProjected[key] = CombinedData </code></pre>
1
2016-08-03T11:33:18Z
[ "python", "pandas", "dataframe", "rename" ]
Averaging pandas dataframes from certain columns
38,741,288
<p>I am new to pandas. I have several <code>dfs</code>. The data in column <code>0</code> is the <code>ID</code> and in columns <code>1-10</code> are probabilities. I want to take the column-wise average of columns <code>1-10</code> across the <code>dfs</code>. The rows may not be in the same order. </p> <p>Is there a better way to do it than sort each df on <code>ID</code> and then use the add/divide df functions? Any help appreciated.</p> <p>Thanks very much for your comments. To clarify, I need to average the 2 dfs <strong>element wise</strong>. I.e. (just showing 1 row of each df):</p> <pre><code>Df1: id132456, 1, 2, 3, 4 Df2: id132456, 2, 2, 3, 2 Averaged: id132456, 1.5, 2, 3, 3 </code></pre>
1
2016-08-03T10:41:52Z
38,741,412
<p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a>:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({0:[14254,25445,34555], 1:[1,2,3], 2:[1,1,1], 3:[1,2,0]}) print (df1) 0 1 2 3 0 14254 1 1 1 1 25445 2 1 2 2 34555 3 1 0 df2 = pd.DataFrame({0:[14254,25445,34555], 2:[1,0,0], 1:[1,0,1], 3:[1,2,0]}) print (df2) 0 1 2 3 0 14254 1 1 1 1 25445 0 0 2 2 34555 1 0 0 </code></pre> <pre><code>#list of all DataFrames dfs = [df1, df2] print (pd.concat(dfs, ignore_index=True)) 0 1 2 3 0 14254 1 1 1 1 25445 2 1 2 2 34555 3 1 0 3 14254 1 1 1 4 25445 0 0 2 5 34555 1 0 0 #select all columns without first print (pd.concat(dfs, ignore_index=True).ix[:,1:]) 1 2 3 0 1 1 1 1 2 1 2 2 3 1 0 3 1 1 1 4 0 0 2 5 1 0 0 </code></pre> <p>I am not sure what kind of mean need, so I add both:</p> <pre><code>#mean per rows print (pd.concat(dfs, ignore_index=True).ix[:,1:].mean(1)) 0 1.000000 1 1.666667 2 1.333333 3 1.000000 4 0.666667 5 0.333333 dtype: float64 #mean per columns print (pd.concat(dfs, ignore_index=True).ix[:,1:].mean()) 1 1.333333 2 0.666667 3 1.000000 dtype: float64 </code></pre> <hr> <p>Maybe you need something else:</p> <pre><code>dfs = [df1.set_index(0), df2.set_index(0)] print (pd.concat(dfs, ignore_index=True, axis=1)) 0 1 2 3 4 5 0 14254 1 1 1 1 1 1 25445 2 1 2 0 0 2 34555 3 1 0 1 0 0 print (pd.concat(dfs, ignore_index=True, axis=1).mean(1)) 0 14254 1.000000 25445 1.166667 34555 0.833333 dtype: float64 print (pd.concat(dfs, ignore_index=True, axis=1).mean()) 0 2.000000 1 1.000000 2 1.000000 3 0.666667 4 0.333333 5 1.000000 dtype: float64 </code></pre>
1
2016-08-03T10:47:21Z
[ "python", "pandas", "dataframe", "mean", "ensembles" ]