title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python Import Text Array with Numpy
39,229,830
<p>I have a text file that looks like this:</p> <pre><code>... 5 [0, 1] [512, 479] 991 10 [1, 0] [706, 280] 986 15 [1, 0] [807, 175] 982 20 [1, 0] [895, 92] 987 ... </code></pre> <p>Each column is tab separated, but there are arrays in some of the columns. Can I import these with <code>np.genfromtxt</code> in some way?</p> <p>The resulting unpacked lists should be, for example:</p> <pre><code>data1 = [..., 5, 10, 15, 20, ...] data2 = [..., [512, 479], [706, 280], ... ] (i.e. a 2D list) etc. </code></pre> <p>I tried </p> <p><code>data1, data2, data3, data4 = np.genfromtxt('data.txt', dtype=None, delimiter='\t', unpack=True)</code></p> <p>but <code>data2</code> and <code>data3</code> are lists containing 'nan'.</p>
0
2016-08-30T14:10:19Z
39,236,239
<p>As an alternative to <code>genfromtxt</code> you might try <code>fromregex</code>. You basically set up an analogy between regular expression groups and the fields of a numpy structured dtype.</p> <p>In this example, I parse out all numbers without worrying about whether they are single numbers or arrays. Then I switch to a dtype that specifies which columns have arrays.</p> <pre><code>import numpy as np # regular expression that will extract 6 numbers from each line re = 6 * r"(\d+)\D*" # dtype for a single number dt_num = np.int # structured dtype of 6 numbers dt = 6 * [('', dt_num)] # parse the file a = np.fromregex("data.txt", re, dt) # change to a more descriptive structured dtype a.dtype = [ ('data1', dt_num), ('data2', dt_num, (2,)), ('data3', dt_num, (2,)), ('data4', dt_num) ] print(a['data1']) print(a['data2']) print(a['data3']) print(a['data4']) </code></pre> <p>The nice thing about switching the dtype of a numpy array is that it does not have to process or make new copies of the data, it just reinterprets what you get when you access the data.</p> <p>One of the down sides of this solution is that building complex regular expressions and building structured dtypes can get ugly. And in this case, you have to keep the two in sync with each other.</p>
0
2016-08-30T20:07:30Z
[ "python", "arrays", "numpy", "genfromtxt" ]
How to open remote MySQL connection at a LAMP(Python) stack
39,229,914
<p>I am developing a django application where my MySQL database is present. My django application and database setup is on one machine.</p> <p>Now I have 2 other machines running a script which need to remotely connect to my MySQL database present in my main machine.</p> <p>So in my main machine. I have done this:</p> <pre><code>sudo nano /etc/mysql/my.cnf </code></pre> <p>Then changed </p> <pre><code>bind-address = 127.0.0.1 </code></pre> <p>to</p> <pre><code>bind-address = [my public ip address] </code></pre> <p>After that, I opened remote access to my database port through my firewall by running:</p> <pre><code>sudo ufw allow 3306/tcp sudo service ufw restart </code></pre> <p>After that, I ran my mysql and ran the following command:</p> <pre><code>CREATE USER newuser@[main machine ip address] IDENTIFIED BY 'my password'; GRANT ALL PRIVILEGES ON * . * TO newuser@[main machine ip address]; FLUSH PRIVILEGES; </code></pre> <p>Now when I try to connect to my database remotely from a desktop application using:</p> <p>username: newuser@[my public ip address] </p> <p>password: my_password </p> <p>port: 3306 </p> <p>database: my database name </p> <p>host: [my public ip address]</p> <p>It doesn't connect and gives our the error 'access denied'. Is there anything else that I need to do to make it working? Any idea?</p> <p><strong>UPDATE:</strong></p> <p>I have tried to connect through command line from my other server to the main server using:</p> <p><code>mysql -u newuser -p -h [my main server ip address</code>]</p> <p>And</p> <pre><code>mysql -u newuser@[my main server ip address] -p -h [my main server ip address] </code></pre> <p>It gives me this error: Host '[my local ip address]' is not allowed to connect to this MySQL server</p>
0
2016-08-30T14:13:24Z
39,230,020
<p>The setup you did to allow remote connections looks good (though you didn't mention restarting mysql, but I'll assume that was done). Also I'm assuming there's no NAT and all machines involved are directly connected to the internet (ifconfig shows a WAN ip).</p> <p>I'd recommend trying to connect with the mysql command line client - it may provide clearer error messages. Though 'access denied' generally means incorrect password. I <em>think</em> there is a different error message when the username@hostname isn't found.</p>
1
2016-08-30T14:17:33Z
[ "python", "mysql", "linux", "django", "database" ]
How to open remote MySQL connection at a LAMP(Python) stack
39,229,914
<p>I am developing a django application where my MySQL database is present. My django application and database setup is on one machine.</p> <p>Now I have 2 other machines running a script which need to remotely connect to my MySQL database present in my main machine.</p> <p>So in my main machine. I have done this:</p> <pre><code>sudo nano /etc/mysql/my.cnf </code></pre> <p>Then changed </p> <pre><code>bind-address = 127.0.0.1 </code></pre> <p>to</p> <pre><code>bind-address = [my public ip address] </code></pre> <p>After that, I opened remote access to my database port through my firewall by running:</p> <pre><code>sudo ufw allow 3306/tcp sudo service ufw restart </code></pre> <p>After that, I ran my mysql and ran the following command:</p> <pre><code>CREATE USER newuser@[main machine ip address] IDENTIFIED BY 'my password'; GRANT ALL PRIVILEGES ON * . * TO newuser@[main machine ip address]; FLUSH PRIVILEGES; </code></pre> <p>Now when I try to connect to my database remotely from a desktop application using:</p> <p>username: newuser@[my public ip address] </p> <p>password: my_password </p> <p>port: 3306 </p> <p>database: my database name </p> <p>host: [my public ip address]</p> <p>It doesn't connect and gives our the error 'access denied'. Is there anything else that I need to do to make it working? Any idea?</p> <p><strong>UPDATE:</strong></p> <p>I have tried to connect through command line from my other server to the main server using:</p> <p><code>mysql -u newuser -p -h [my main server ip address</code>]</p> <p>And</p> <pre><code>mysql -u newuser@[my main server ip address] -p -h [my main server ip address] </code></pre> <p>It gives me this error: Host '[my local ip address]' is not allowed to connect to this MySQL server</p>
0
2016-08-30T14:13:24Z
39,230,038
<p>instead of doing machine ip address, allow any host 'user'@'%' and see if it works.</p> <p>If it does, check the logs to see what your hostname is displayed to your server as.</p> <p>Changing bind address is not necessary. </p>
1
2016-08-30T14:18:33Z
[ "python", "mysql", "linux", "django", "database" ]
Can I use a builtin name as a method name of a Python class?
39,229,951
<p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p> <pre><code>class Entry(): # over-simplified but should be enough for the question def __init__(self, value): self.set(value) def set(self, value): self.value=value def add(self, value): self.value += value def sub(self, value): self.value -= value </code></pre> <p>The problem is with the "set" method but defining it as a class method should not clash with the "set()" builtin function.</p> <p>The <a href="https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments" rel="nofollow" title="Python Style Guide">Python Style Guide</a> states that argument names of functions and methods should not shadow built-in functions, but it's this the case for method names?</p> <p>Obviously I could choose another method name, but the question is more generic and valid for other possible method names (i.e. filter, sum, input).</p>
5
2016-08-30T14:14:32Z
39,230,013
<p>You are fine. You just don't want to overwrite the built-ins if they are a built-in method <em>__init__</em> <em>__iter__</em> etc unless you are implementing the functionality expected by those methods.</p> <p>You are "overwriting" a built in <em>function</em> as a class method, which means you aren't really overwriting anything. This is acceptable.</p>
1
2016-08-30T14:17:20Z
[ "python", "pep8" ]
Can I use a builtin name as a method name of a Python class?
39,229,951
<p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p> <pre><code>class Entry(): # over-simplified but should be enough for the question def __init__(self, value): self.set(value) def set(self, value): self.value=value def add(self, value): self.value += value def sub(self, value): self.value -= value </code></pre> <p>The problem is with the "set" method but defining it as a class method should not clash with the "set()" builtin function.</p> <p>The <a href="https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments" rel="nofollow" title="Python Style Guide">Python Style Guide</a> states that argument names of functions and methods should not shadow built-in functions, but it's this the case for method names?</p> <p>Obviously I could choose another method name, but the question is more generic and valid for other possible method names (i.e. filter, sum, input).</p>
5
2016-08-30T14:14:32Z
39,230,029
<p><a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Namespaces are one honking great idea</a> - same in this case, name <code>set</code> defined but it exists only in namespace limited to <code>Entry</code> class and does not clash with built-in function name.</p>
1
2016-08-30T14:18:02Z
[ "python", "pep8" ]
Can I use a builtin name as a method name of a Python class?
39,229,951
<p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p> <pre><code>class Entry(): # over-simplified but should be enough for the question def __init__(self, value): self.set(value) def set(self, value): self.value=value def add(self, value): self.value += value def sub(self, value): self.value -= value </code></pre> <p>The problem is with the "set" method but defining it as a class method should not clash with the "set()" builtin function.</p> <p>The <a href="https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments" rel="nofollow" title="Python Style Guide">Python Style Guide</a> states that argument names of functions and methods should not shadow built-in functions, but it's this the case for method names?</p> <p>Obviously I could choose another method name, but the question is more generic and valid for other possible method names (i.e. filter, sum, input).</p>
5
2016-08-30T14:14:32Z
39,234,005
<p>The whole thing about not shadowing builtin names is that you don't want to stop your self from being able to use them, so when your code does this:</p> <pre><code>x.set(a) #set the value to a b = set((1,2,3)) #create a set </code></pre> <p>you can still access the builtin <code>set</code> so there is no conflict, the only problem is if you wanted to use <code>set</code> <strong>inside the class definition</strong></p> <pre><code>class Entry(): def __init__(self, value): self.set(value) def set(self, value): self.value=value possible_values = set((1,2,3,4,5)) #TypeError: set() missing 1 required positional argument: 'value' </code></pre> <p>Inside the class definition - and there only - is the built in name shadowed, so you have to consider which you would rather settle for: the unlikely scenario where you try to use <code>set</code> inside the class definition and get an error or using a non-intuitive name for your method.</p> <p>Also note that if you like using method names that make sense to you and also want to use <code>set</code> in your class definition you can still access it with <code>builtins.set</code> for python 3 or <code>__builtin__.set</code> for python 2.</p>
2
2016-08-30T17:49:26Z
[ "python", "pep8" ]
Transform 1D List
39,229,972
<p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p> <pre><code>list_1d = [1,0,3,2,0] 1 0 3 2 0 </code></pre> <p>I need it to be transformed to, </p> <pre><code>0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 </code></pre> <p>I have created a 2D array of zeros, </p> <pre><code>array_2d = np.zeros((len(list_1d),4)) </code></pre> <p>Kindly appreciated. </p>
-1
2016-08-30T14:15:15Z
39,230,293
<p>assuming the wanted result in the question is not exact, you could do something like this:</p> <pre><code>list_1d = [1,0,3,2,0] x_size = max(list_1d) + 1 y_size = len(list_1d) matrix = [] for y in range(y_size): line = [] for x in range(x_size): line.append(1 if x == list_1d[y] else 0) matrix.append(line) print matrix </code></pre> <p>it prints <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0]]</code></p>
0
2016-08-30T14:30:02Z
[ "python", "arrays", "list", "numpy", "transform" ]
Transform 1D List
39,229,972
<p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p> <pre><code>list_1d = [1,0,3,2,0] 1 0 3 2 0 </code></pre> <p>I need it to be transformed to, </p> <pre><code>0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 </code></pre> <p>I have created a 2D array of zeros, </p> <pre><code>array_2d = np.zeros((len(list_1d),4)) </code></pre> <p>Kindly appreciated. </p>
-1
2016-08-30T14:15:15Z
39,230,363
<p>Here's a one liner</p> <pre><code>&gt;&gt;&gt; np.array([[ 1 if i == n else 0 for i in range(4)] for n in list_1d]) array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0]]) </code></pre> <p>It uses a nested couple of comprehensions to do what you need. The width of the array is hardwired (the <code>range(4)</code>)</p>
1
2016-08-30T14:32:52Z
[ "python", "arrays", "list", "numpy", "transform" ]
Transform 1D List
39,229,972
<p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p> <pre><code>list_1d = [1,0,3,2,0] 1 0 3 2 0 </code></pre> <p>I need it to be transformed to, </p> <pre><code>0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 </code></pre> <p>I have created a 2D array of zeros, </p> <pre><code>array_2d = np.zeros((len(list_1d),4)) </code></pre> <p>Kindly appreciated. </p>
-1
2016-08-30T14:15:15Z
39,230,521
<blockquote> <p>"I wanted to optimize code by not using a for loop since my list has millions of elements."</p> </blockquote> <p>In that case, use numpy:</p> <pre><code>&gt;&gt;&gt; list_1d = [1,0,3,2,0] &gt;&gt;&gt; mat = np.zeros((len(list_1d),4)) &gt;&gt;&gt; mat[range(len(list_1d)), list_1d] = 1 &gt;&gt;&gt; mat array([[ 0., 1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.], [ 0., 0., 1., 0.], [ 1., 0., 0., 0.]]) </code></pre> <p>Because this approach avoids looping at the python level, it should be fast even for large datasets.</p>
5
2016-08-30T14:39:13Z
[ "python", "arrays", "list", "numpy", "transform" ]
Transform 1D List
39,229,972
<p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p> <pre><code>list_1d = [1,0,3,2,0] 1 0 3 2 0 </code></pre> <p>I need it to be transformed to, </p> <pre><code>0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 </code></pre> <p>I have created a 2D array of zeros, </p> <pre><code>array_2d = np.zeros((len(list_1d),4)) </code></pre> <p>Kindly appreciated. </p>
-1
2016-08-30T14:15:15Z
39,230,711
<pre><code>list_1d = [1,0,3,2,0] </code></pre> <p>How tall should the matrix be?</p> <blockquote> <p><code>height</code> is the number of elements in the 1d list.</p> </blockquote> <pre><code>height = len(list_1d) </code></pre> <p>How wide should the matrix be?</p> <blockquote> <p><code>width</code> is the number of elements in each inner list.</p> </blockquote> <pre><code>width = max(list_1d) </code></pre> <p>What should the value of each inner list element be?</p> <blockquote> <p>0 most of the time.</p> </blockquote> <p>When should a matrix element not be zero?</p> <blockquote> <p>When its row is its original index and its column is its original value.</p> </blockquote> <p>Can you express that as a Boolean?</p> <pre><code>index == value </code></pre> <p>Can you express that as an int?</p> <blockquote> <p>Just cast the bool to an int.</p> </blockquote> <p>What is the definition of a row?</p> <pre><code>[int(value == index) for index in range(1 + width)] </code></pre> <p>What does it look like for all values?</p> <pre><code>[[int(value == index) for index in range(1 + width)] for value in list_1d] </code></pre> <p>Demonstrate:</p> <pre><code>&gt;&gt;&gt; width=max(list_1d) &gt;&gt;&gt; [[int(value == index) for index in range(1 + width)] for value in list_1d] [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0]] </code></pre>
0
2016-08-30T14:48:04Z
[ "python", "arrays", "list", "numpy", "transform" ]
Python: Correct Way to refer to index of unicode string
39,230,021
<p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p> <p>Right now my code is this:</p> <pre><code>for index, paragraph in enumerate(intro[2:-2]): intro[index] = bold_letters(paragraph, 1) def bold_letters(string, index): return "&lt;b&gt;"+string[0]+"&lt;/b&gt;"+string[index:] </code></pre> <p>And I'm getting output like this:</p> <pre><code>&lt;b&gt;?&lt;/b&gt;?רך האחד וישתבח הבורא בחכמתו ורצונו כל צבא השמים ארץ וימים אלה ואלונים. </code></pre> <p>It seems the unicode gets messed up when I try to insert the HTML tag. I tried messing with the insert position but didn't make any progress.</p> <p>Example desired output (hebrew goes right to left):</p> <pre><code>&gt;&gt;&gt;first_letter_bold("הקדמה") "הקדמ&lt;\b&gt;ה&lt;b&gt;" </code></pre> <p>BTW, this is for Python 2</p>
3
2016-08-30T14:17:36Z
39,230,141
<p>The behavior you're seeing suggests you have a byte string instead of a unicode string - your code should work if it was a unicode string, unicode string indexes work the same way as 'normal' ascii strings. In python 3, at least.</p>
2
2016-08-30T14:23:10Z
[ "python", "unicode", "python-2.x" ]
Python: Correct Way to refer to index of unicode string
39,230,021
<p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p> <p>Right now my code is this:</p> <pre><code>for index, paragraph in enumerate(intro[2:-2]): intro[index] = bold_letters(paragraph, 1) def bold_letters(string, index): return "&lt;b&gt;"+string[0]+"&lt;/b&gt;"+string[index:] </code></pre> <p>And I'm getting output like this:</p> <pre><code>&lt;b&gt;?&lt;/b&gt;?רך האחד וישתבח הבורא בחכמתו ורצונו כל צבא השמים ארץ וימים אלה ואלונים. </code></pre> <p>It seems the unicode gets messed up when I try to insert the HTML tag. I tried messing with the insert position but didn't make any progress.</p> <p>Example desired output (hebrew goes right to left):</p> <pre><code>&gt;&gt;&gt;first_letter_bold("הקדמה") "הקדמ&lt;\b&gt;ה&lt;b&gt;" </code></pre> <p>BTW, this is for Python 2</p>
3
2016-08-30T14:17:36Z
39,233,084
<p>You are right, indices work over each <code>byte</code> when you are dealing with <em>raw bytes</em> i.e <code>String</code> in <em>Python(2.x)</em>.</p> <p>To work seamlessly with Unicode data, you need to first let <em>Python(2.x)</em> know that you are dealing with <code>Unicode</code>, then do the string manipulation. You can finally convert it back to raw bytes to keep the behavior abstracted i.e you get <code>String</code> and you return <code>String</code>.</p> <p>Ideally you should convert all the data from <code>UTF8</code> raw encoding to <code>Unicode</code> object (I am assuming your source encoding is <code>Unicode UTF8</code> because that is the standard used by most applications these days) at the very beginning of your code and convert back to raw bytes at the fag end of code like saving to DB, responding to client etc. Some frameworks might handle that for you so that you don't have to worry. </p> <pre><code>def bold_letters(string, index): string = string.decode('utf8') string "&lt;b&gt;"+string[0]+"&lt;/b&gt;"+string[index:] return string.encode('utf8') </code></pre> <p>This will also work for <em>ASCII</em> because <em>UTF8</em> is a super-set of <em>ASCII</em>. You can understand how Unicode works and in Python specifically better by reading <a href="http://nedbatchelder.com/text/unipain.html" rel="nofollow">http://nedbatchelder.com/text/unipain.html</a></p> <p><em>Python 3.x</em> <code>String</code> is a <code>Unicode</code> object so you don't have to explicitly do anything.</p>
5
2016-08-30T16:53:13Z
[ "python", "unicode", "python-2.x" ]
Python: Correct Way to refer to index of unicode string
39,230,021
<p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p> <p>Right now my code is this:</p> <pre><code>for index, paragraph in enumerate(intro[2:-2]): intro[index] = bold_letters(paragraph, 1) def bold_letters(string, index): return "&lt;b&gt;"+string[0]+"&lt;/b&gt;"+string[index:] </code></pre> <p>And I'm getting output like this:</p> <pre><code>&lt;b&gt;?&lt;/b&gt;?רך האחד וישתבח הבורא בחכמתו ורצונו כל צבא השמים ארץ וימים אלה ואלונים. </code></pre> <p>It seems the unicode gets messed up when I try to insert the HTML tag. I tried messing with the insert position but didn't make any progress.</p> <p>Example desired output (hebrew goes right to left):</p> <pre><code>&gt;&gt;&gt;first_letter_bold("הקדמה") "הקדמ&lt;\b&gt;ה&lt;b&gt;" </code></pre> <p>BTW, this is for Python 2</p>
3
2016-08-30T14:17:36Z
39,237,624
<p>You should use Unicode strings. Byte strings in UTF-8 use a variable number of bytes per character. Unicode use one (at least those in the BMP on Python 2...the first 65536 characters):</p> <pre><code>#coding:utf8 s = u"הקדמה" t = u'&lt;b&gt;'+s[0]+u'&lt;/b&gt;'+s[1:] print(t) with open('out.htm','w',encoding='utf-8-sig') as f: f.write(t) </code></pre> <p>Output:</p> <pre><code>&lt;b&gt;ה&lt;/b&gt;קדמה </code></pre> <p>But my Chrome browser displays <code>out.htm</code> as:</p> <p><a href="http://i.stack.imgur.com/kJSju.png" rel="nofollow"><img src="http://i.stack.imgur.com/kJSju.png" alt="enter image description here"></a></p>
3
2016-08-30T21:48:44Z
[ "python", "unicode", "python-2.x" ]
passing a dictionary to all templates using context_processors
39,230,053
<p>I want to show my notification to all my templates. In my settings I have:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'helpers.views.notifications' , ], }, }, ] </code></pre> <p>helpers/views.py</p> <pre><code>def notifications(): notifications = {'A':'aaa' , 'B':'bbb' } return {'notifications': notifications } </code></pre> <p>I get nothing in my template - what am I doing wrong? in template :</p> <pre><code>{{notifications.A}} </code></pre>
1
2016-08-30T14:19:13Z
39,230,408
<p>Your <code>TEMPLATES</code> setting looks ok. In your context processor, you don't need to use <code>RequestContext</code>. Just return a dictionary. If you are using Django 1.9 or earlier, you <strong>must</strong> call the method <code>request.user.is_authenticated()</code> otherwise <code>request.user.is_authenticated</code> will always evaluate to True.</p> <pre><code>def notifications(request): if request.user.is_authenticated(): # Use request.user.is_authenticated for Django &gt;= 1.10 notifications = {'default: 'logged in', ... } else: notifications = {'default':'not logged in', ...} return {'notifications': notifications } </code></pre> <p>Then in your tempalate, you can access <code>{{ notifications.default }}</code></p>
2
2016-08-30T14:34:56Z
[ "python", "django", "python-3.x", "django-1.9" ]
Get file's links with google-drive-api python
39,230,197
<p>I've worked with <code>Google Drive</code> <code>Api</code> some time and I can't find the way to get the link for file's view on Drive pragramatically.<br> There is <code>function</code> which creates folder and returns its id, however additionally I need to return a <code>link</code> for <code>view</code> only. Thank you!</p> <pre><code>def create_folder(folder_name='no_name', parent_id=''): data = {'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder', 'parents': [parent_id], } new = DRIVE.files().create(body=data, fields='id').execute() return new.get('id') folder = create_folder('some_name', 'some_parent_id') </code></pre>
0
2016-08-30T14:25:53Z
39,253,486
<p>So, create folder and return a View link is possible by adding "webViewLink" to fields in method files().create(). The function will be the next:</p> <pre><code>def create_folder(parent_id, folder_name='no_name', ): data = {'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder', 'parents': ['{0}'.format(parent_id)], } new = DRIVE.files().create(body=data, fields='webViewLink, id').execute() return new.get('webViewLink') </code></pre>
0
2016-08-31T15:23:18Z
[ "python", "google-drive-sdk" ]
openpyxl module does not have attribute '__version__' when imported by pandas
39,230,220
<p>My traceback from running pandas takes me to: <br/> <code>site-packages\pandas\io\excel.py line 58, in get_writer AttributeError: 'module' object has no attribute '__version__'</code></p> <p>I found this link to a git issue in the PyInstaller repo <a href="https://github.com/pyinstaller/pyinstaller/issues/1890" rel="nofollow">https://github.com/pyinstaller/pyinstaller/issues/1890</a> and found my openpyxl version, manually added it into the get_writer method like so: </p> <pre><code>def get_writer(engine_name): if engine_name == 'openpyxl': try: import openpyxl #remove when conda update available openpyxl.__version__ = '2.3.2' # with version-less openpyxl engine # make sure we make the intelligent choice for the user if LooseVersion(openpyxl.__version__) &lt; '2.0.0': return _writers['openpyxl1'] elif LooseVersion(openpyxl.__version__) &lt; '2.2.0': return _writers['openpyxl20'] else: return _writers['openpyxl22'] except ImportError: # fall through to normal exception handling below pass try: return _writers[engine_name] except KeyError: raise ValueError("No Excel writer '%s'" % engine_name) </code></pre> <p>Still no dice. The line number given in the error traceback doesn't even change. I then updated the openpyxl version to 2.3.5, still receiving the error. The openpyxl <strong>init</strong> file has a <strong>version</strong> variable in it:</p> <pre><code>try: here = os.path.abspath(os.path.dirname(__file__)) src_file = os.path.join(here, ".constants.json") with open(src_file) as src: constants = json.load(src) __author__ = constants['__author__'] __author_email__ = constants["__author_email__"] __license__ = constants["__license__"] __maintainer_email__ = constants["__maintainer_email__"] __url__ = constants["__url__"] __version__ = constants["__version__"] except IOError: # packaged pass </code></pre> <p>Any known or potential fixes or workarounds?</p>
2
2016-08-30T14:26:36Z
39,396,636
<p>Edits were not making an impact because the process was compiled into an exe that these modules were running through. Exported the sections I needed outside of my anaconda environment and now the process works without a hitch. </p>
1
2016-09-08T17:05:22Z
[ "python", "pandas", "openpyxl", "conda" ]
Retrieve geocodes from Google API and append to original table - python
39,230,230
<p>I am trying to retrieve the geocodes of a bunch of addresses through the Google geocoding API and append them to my table with addresses.</p> <p>After spending two days reviewing the internet I coulnd´t find any simple way of doing while it shouldn´t be that hard. I am specially having problems parsing the json output and append it to my original table. I use python 3.5 on windows</p> <p>I originally got the data from a database which I added to a dataframe in python. But to paste it here it was easier to convert it to a dictionary and back to a dataframe:</p> <pre><code> data_dict={'street': {0: 'ROMULO', 1: 'SAN BARTOLOME', 2: 'GARBI', 3: 'SAN JOSE'}, 'concat': {0: '3+ROMULO+CALLE+ALMERIA', 1: '5+SAN BARTOLOME+CALLE+TOLEDO', 2: '48+GARBI+CALLE+CASTELLON', 3: '30+SAN JOSE+CALLE+SANTA CRUZ DE TENERIFE'}, 'number': {0: '3', 1: '5', 2: '48', 3: '30'}, 'province': {0: 'ALMERIA', 1: 'TOLEDO', 2: 'CASTELLON', 3: 'SANTA CRUZ DE TENERIFE'}, 'region': {0: 'ANDALUCIA', 1: 'CASTILLA LA MANCHA', 2: 'COMUNIDAD VALENCIANA', 3: 'CANARIAS'}} </code></pre> <p>Back to dataframe:</p> <pre><code>import pandas as pd table=pd.DataFrame.from_dict(data_dict) </code></pre> <p>Now I retrieve the data from the Google geocoding API:</p> <pre><code>import requests import json key="MyKey" jsonout=[] for i in table.loc[:,'concat']: try: url="https://maps.googleapis.com/maps/api/geocode/json?address=%s&amp;key=%s" % (i, key) response = requests.get(url) jsonf = response.json() jsonout.append(jsonf) except Exception: continue </code></pre> <p>I get this output:</p> <pre><code>jsonout=[{'results': [{'address_components': [{'long_name': '3', 'short_name': '3', 'types': ['street_number']}, {'long_name': 'Calle Rómulo', 'short_name': 'Calle Rómulo', 'types': ['route']}, {'long_name': 'Adra', 'short_name': 'Adra', 'types': ['locality', 'political']}, {'long_name': 'Almería', 'short_name': 'AL', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Andalucía', 'short_name': 'AL', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '04770', 'short_name': '04770', 'types': ['postal_code']}], 'formatted_address': 'Calle Rómulo, 3, 04770 Adra, Almería, Spain', 'geometry': {'location': {'lat': 36.7593, 'lng': -2.97818}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 36.76064898029149, 'lng': -2.976831019708498}, 'southwest': {'lat': 36.7579510197085, 'lng': -2.979528980291502}}}, 'partial_match': True, 'place_id': 'ChIJG39VNzNOcA0R2f8Ek3E12AY', 'types': ['street_address']}], 'status': 'OK'}, {'results': [{'address_components': [{'long_name': '5', 'short_name': '5', 'types': ['street_number']}, {'long_name': 'Calle de San Bartolomé', 'short_name': 'Calle de San Bartolomé', 'types': ['route']}, {'long_name': 'Toledo', 'short_name': 'Toledo', 'types': ['locality', 'political']}, {'long_name': 'Toledo', 'short_name': 'TO', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Castilla-La Mancha', 'short_name': 'CM', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '45002', 'short_name': '45002', 'types': ['postal_code']}], 'formatted_address': 'Calle de San Bartolomé, 5, 45002 Toledo, Spain', 'geometry': {'location': {'lat': 39.8549781, 'lng': -4.026267199999999}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 39.85632708029149, 'lng': -4.024918219708497}, 'southwest': {'lat': 39.85362911970849, 'lng': -4.027616180291502}}}, 'partial_match': True, 'place_id': 'ChIJ4bse1aALag0RJ5RxxfyDxUI', 'types': ['street_address']}], 'status': 'OK'}, {'results': [{'address_components': [{'long_name': '48', 'short_name': '48', 'types': ['street_number']}, {'long_name': 'Carrer de Garbí', 'short_name': 'Carrer de Garbí', 'types': ['route']}, {'long_name': 'Peníscola', 'short_name': 'Peníscola', 'types': ['locality', 'political']}, {'long_name': 'Castelló', 'short_name': 'Castelló', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Comunidad Valenciana', 'short_name': 'Comunidad Valenciana', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '12598', 'short_name': '12598', 'types': ['postal_code']}], 'formatted_address': 'Carrer de Garbí, 48, 12598 Peníscola, Castelló, Spain', 'geometry': {'location': {'lat': 40.3634529, 'lng': 0.3963583}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 40.3648018802915, 'lng': 0.397707280291502}, 'southwest': {'lat': 40.3621039197085, 'lng': 0.395009319708498}}}, 'partial_match': True, 'place_id': 'ChIJHVNHcelGoBIRogILRMno_wk', 'types': ['street_address']}, {'address_components': [{'long_name': '48', 'short_name': '48', 'types': ['street_number']}, {'long_name': 'Carrer Garbí', 'short_name': 'Carrer Garbí', 'types': ['route']}, {'long_name': 'Vila-real', 'short_name': 'Vila-real', 'types': ['locality', 'political']}, {'long_name': 'Castelló', 'short_name': 'Castelló', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Comunidad Valenciana', 'short_name': 'Comunidad Valenciana', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '12540', 'short_name': '12540', 'types': ['postal_code']}], 'formatted_address': 'Carrer Garbí, 48, 12540 Vila-real, Castelló, Spain', 'geometry': {'bounds': {'northeast': {'lat': 39.955829, 'lng': -0.110409}, 'southwest': {'lat': 39.9558231, 'lng': -0.1104261}}, 'location': {'lat': 39.9558231, 'lng': -0.110409}, 'location_type': 'RANGE_INTERPOLATED', 'viewport': {'northeast': {'lat': 39.9571750302915, 'lng': -0.109068569708498}, 'southwest': {'lat': 39.9544770697085, 'lng': -0.111766530291502}}}, 'partial_match': True, 'place_id': 'EjRDYXJyZXIgR2FyYsOtLCA0OCwgMTI1NDAgVmlsYS1yZWFsLCBDYXN0ZWxsw7MsIFNwYWlu', 'types': ['street_address']}], 'status': 'OK'}, {'results': [{'address_components': [{'long_name': '30', 'short_name': '30', 'types': ['street_number']}, {'long_name': 'Calle San José', 'short_name': 'Calle San José', 'types': ['route']}, {'long_name': 'Santa Cruz de la Palma', 'short_name': 'Santa Cruz de la Palma', 'types': ['locality', 'political']}, {'long_name': 'Santa Cruz de Tenerife', 'short_name': 'TF', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Canarias', 'short_name': 'CN', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '38700', 'short_name': '38700', 'types': ['postal_code']}], 'formatted_address': 'Calle San José, 30, 38700 Santa Cruz de la Palma, Santa Cruz de Tenerife, Spain', 'geometry': {'location': {'lat': 28.6864347, 'lng': -17.7624433}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 28.6877836802915, 'lng': -17.7610943197085}, 'southwest': {'lat': 28.6850857197085, 'lng': -17.7637922802915}}}, 'partial_match': True, 'place_id': 'ChIJ8ZFx6__rawwRV3dc118gEgE', 'types': ['street_address']}, {'address_components': [{'long_name': '30', 'short_name': '30', 'types': ['street_number']}, {'long_name': 'Calle San José', 'short_name': 'Calle San José', 'types': ['route']}, {'long_name': 'San Andrés', 'short_name': 'San Andrés', 'types': ['locality', 'political']}, {'long_name': 'Santa Cruz de Tenerife', 'short_name': 'Santa Cruz de Tenerife', 'types': ['administrative_area_level_4', 'political']}, {'long_name': 'Santa Cruz de Tenerife', 'short_name': 'TF', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Canarias', 'short_name': 'CN', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'Spain', 'short_name': 'ES', 'types': ['country', 'political']}, {'long_name': '38120', 'short_name': '38120', 'types': ['postal_code']}], 'formatted_address': 'Calle San José, 30, 38120 San Andrés, Santa Cruz de Tenerife, Spain', 'geometry': {'location': {'lat': 28.505875, 'lng': -16.1930036}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 28.5072239802915, 'lng': -16.1916546197085}, 'southwest': {'lat': 28.5045260197085, 'lng': -16.1943525802915}}}, 'partial_match': True, 'place_id': 'ChIJsfd-ITjKQQwRjFHLI0XPSok', 'types': ['street_address']}], 'status': 'OK'}] </code></pre> <p>What I finally would like to have is my original table dataframe with the lat and lng coordinates </p> <pre><code> (i['results'][0]['geometry']['location']['lat'], i['results'][0]['geometry']['location']['lng']) </code></pre> <p>and the formatted_address from the request.</p>
-1
2016-08-30T14:26:57Z
39,230,823
<p>I use <a href="https://pypi.python.org/pypi/geopy" rel="nofollow">this package</a> to do my geocoding, which takes care of parsing the JSON file.</p> <pre><code>from geopy.geocoders import GoogleV3 googleGeo = GoogleV3('googleKey') # create a geocoded list containing geocode objects geocoded = [] for address in mydata['location']: # assumes mydata is a pandas df geocoded.append(googleGeo.geocode(address)) # geocode function returns a geocoded object # append geocoded list to mydata mydata['geocoded'] = geocoded # create coordinates column mydata['coords'] = mydata['geocoded'].apply(lambda x: (x.latitude, x.longitude)) # if you want to split our your lat and long then do # mydata['lat'] = mydata['geocoded'].apply(lambda x: x.latitude) # mydata['long'] = mydata['geocoded'].apply(lambda x: x.longitude) </code></pre> <hr> <p>Based on the comment you shared, if you are using Google's API without an API key, then it might be beneficial to include a random pause between each geocode call.</p> <pre><code>from time import sleep from random import randint from geopy.geocoders import GoogleV3 googleGeo = GoogleV3() def geocode(address): location = googleGeo.geocode(address) sleep(randint(5,10)) # give the API a break return location </code></pre> <p>Then you use this custom function to do your geocoding</p> <hr> <p>Piggybacking on my earlier section, you can even utilize multiple map API services. This is the function I built for one of my projects, utilizing Nominatim's API first, and then falling back on Google's API if Nominatim either returns an error or returns nothing:</p> <pre><code>from geopy.geocoders import Nominatim, GoogleV3 from geopy.exc import GeocoderTimedOut, GeocoderAuthenticationFailure from random import randint from time import sleep nomiGeo = Nominatim() # Nominatim geolocator googleGeo = GoogleV3('myKey') # Google Maps v3 API geolocator def geocode(address): """Geocode an address. Args: address (str): the physical address Returns: dict: geocoded object """ location = None attempt = 0 useGoogle = False # set to True to use Google only while (location is None) and (attempt &lt;= 8): try: attempt += 1 if useGoogle: location = googleGeo.geocode(address, timeout=10) else: location = nomiGeo.geocode(address, timeout=10) if location is None: useGoogle = True location = googleGeo.geocode(address, timeout=10) sleep(randint(5, 10)) # Give the API a break except GeocoderAuthenticationFailure: print 'Error: GeocoderAuthenticationFailure while geocoding {} during attempt #{}'.format(address, attempt) if attempt % 2 == 0: # switch between services for every attempt useGoogle = True else: useGoogle = False sleep(60) except GeocoderTimedOut: sleep(randint(3, 5)) # Give API a break print 'Error: GeocoderTimedOut while geocoding {} during attempt #{}'.format(address, attempt) return location </code></pre> <p>Note that I also imported some exceptions specific to the package, because based on my experience with Nominatim, it can sometimes throw random errors and these were the two that I got. Also, from my experiences with the two APIs, Google seemed to be able to interpolate coordinates even if a certain address was not found, whereas Nominatim had to have the address in their database in order to return something.</p>
1
2016-08-30T14:54:09Z
[ "python", "google-maps", "geocoding" ]
Send a syn packet through http proxy in python 3
39,230,310
<p>I'm able to send a tcp syn packet through a socks, but what about HTTP proxies? Is it possible?</p> <p>This is the code with sock (it works):</p> <pre><code>p = bytes(IP(dst="DESTINATIONIP")/TCP(flags="S", sport=RandShort(), dport=80)) while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, socksip, sockport, True) s = socks.socksocket() s.connect((DESTINATIONIP,DESTINATIONPORT)) s.send(p) print ("Request Sent!") except: print ("An error occurred.") </code></pre>
0
2016-08-30T14:30:51Z
39,258,534
<p>I presume when you say "send a SYN packet" you mean "make a connection", since you can't send any bare IP-level packets via SOCKS, only make connections and send TCP / UDP payload.</p> <p>For http proxy, it's similar, you just use the http tunneling command "CONNECT", e.g. you send</p> <pre><code>CONNECT somewhere.example.com:443 HTTP/1.1 Host: somewhere.example.com etc </code></pre> <p>and wait for a </p> <pre><code>HTTP/1.1 200 Connection established etc </code></pre> <p>response. You will need to account for all the data in the http response message (up until you receive the end of the HTTP headers) so you don't mix that up with payload.</p>
0
2016-08-31T20:33:10Z
[ "python", "sockets", "python-3.x", "scapy", "http-proxy" ]
Looping over a dictionary to make multiple dictionaries
39,230,401
<p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p> <pre><code>dict1 = { 'Bob VS Sarah': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Bob VS Ann': { 'shepherd': 3, 'collie': 2, 'poodle': 1 }, 'Bob VS Jen': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 4 }, 'Sarah VS Ann': { 'shepherd': 4, 'collie': 6, 'poodle': 3 }, 'Sarah VS Jen': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Jen VS Bob': { 'shepherd': 4, 'collie': 8, 'poodle': 1 }, 'Jen VS Sarah': { 'shepherd': 7, 'collie': 9, 'poodle': 2 }, 'Jen VS Ann': { 'shepherd': 3, 'collie': 7, 'poodle': 2 }, 'Ann VS Bob': { 'shepherd': 6, 'collie': 2, 'poodle': 5 }, 'Ann VS Sarah': { 'shepherd': 0, 'collie': 2, 'poodle': 4 }, 'Ann VS Jen': { 'shepherd': 2, 'collie': 8, 'poodle': 2 }, 'Bob VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Sarah': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Ann VS Ann': { 'shepherd': 13, 'collie': 2, 'poodle': 4 }, 'Jen VS Jen': { 'shepherd': 9, 'collie': 7, 'poodle': 2 } } </code></pre> <p>This is what I want, for example, but to be able to loop through to make a dictionary for each dog:</p> <p>dict_shepherd = {'shepherd': 1,3,3,3,4,1,4,7,3,6,0,2,3,3,13,9}</p> <p>Note: I still have not touched base with pandas and prefer help without using them :) I will get to them one day.</p>
0
2016-08-30T14:34:44Z
39,230,481
<pre><code>dict_shepherd = {'shepherd': []} for name in dict1: dict_shepherd['shepherd'].append(dict1['shepherd']) </code></pre> <p>It's worth noting that standard dictionaries don't enforce any ordering of their contents, so looping through the items might not yield them in the same order as they are listed in your example.</p>
2
2016-08-30T14:37:41Z
[ "python", "dictionary" ]
Looping over a dictionary to make multiple dictionaries
39,230,401
<p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p> <pre><code>dict1 = { 'Bob VS Sarah': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Bob VS Ann': { 'shepherd': 3, 'collie': 2, 'poodle': 1 }, 'Bob VS Jen': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 4 }, 'Sarah VS Ann': { 'shepherd': 4, 'collie': 6, 'poodle': 3 }, 'Sarah VS Jen': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Jen VS Bob': { 'shepherd': 4, 'collie': 8, 'poodle': 1 }, 'Jen VS Sarah': { 'shepherd': 7, 'collie': 9, 'poodle': 2 }, 'Jen VS Ann': { 'shepherd': 3, 'collie': 7, 'poodle': 2 }, 'Ann VS Bob': { 'shepherd': 6, 'collie': 2, 'poodle': 5 }, 'Ann VS Sarah': { 'shepherd': 0, 'collie': 2, 'poodle': 4 }, 'Ann VS Jen': { 'shepherd': 2, 'collie': 8, 'poodle': 2 }, 'Bob VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Sarah': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Ann VS Ann': { 'shepherd': 13, 'collie': 2, 'poodle': 4 }, 'Jen VS Jen': { 'shepherd': 9, 'collie': 7, 'poodle': 2 } } </code></pre> <p>This is what I want, for example, but to be able to loop through to make a dictionary for each dog:</p> <p>dict_shepherd = {'shepherd': 1,3,3,3,4,1,4,7,3,6,0,2,3,3,13,9}</p> <p>Note: I still have not touched base with pandas and prefer help without using them :) I will get to them one day.</p>
0
2016-08-30T14:34:44Z
39,230,598
<p>You can solve it in general case for a variable number of keys in sub-dicts with a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(list)</code></a>:</p> <pre><code>from collections import defaultdict from pprint import pprint dict1 = # your dictionary of dictionaries here, removed to shorten the presented code d = defaultdict(list) for sub_dict in dict1.values(): for key, value in sub_dict.items(): d[key].append(value) pprint(dict(d)) </code></pre> <p>Which would produce:</p> <pre><code>{'collie': [2, 7, 8, 5, 2, 6, 5, 2, 2, 2, 2, 8, 9, 2, 2, 7], 'poodle': [2, 2, 1, 8, 2, 3, 8, 5, 4, 1, 2, 2, 2, 4, 4, 2], 'shepherd': [3, 9, 4, 1, 3, 4, 1, 6, 3, 3, 3, 2, 7, 0, 13, 3]} </code></pre>
2
2016-08-30T14:43:03Z
[ "python", "dictionary" ]
Looping over a dictionary to make multiple dictionaries
39,230,401
<p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p> <pre><code>dict1 = { 'Bob VS Sarah': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Bob VS Ann': { 'shepherd': 3, 'collie': 2, 'poodle': 1 }, 'Bob VS Jen': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 4 }, 'Sarah VS Ann': { 'shepherd': 4, 'collie': 6, 'poodle': 3 }, 'Sarah VS Jen': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Jen VS Bob': { 'shepherd': 4, 'collie': 8, 'poodle': 1 }, 'Jen VS Sarah': { 'shepherd': 7, 'collie': 9, 'poodle': 2 }, 'Jen VS Ann': { 'shepherd': 3, 'collie': 7, 'poodle': 2 }, 'Ann VS Bob': { 'shepherd': 6, 'collie': 2, 'poodle': 5 }, 'Ann VS Sarah': { 'shepherd': 0, 'collie': 2, 'poodle': 4 }, 'Ann VS Jen': { 'shepherd': 2, 'collie': 8, 'poodle': 2 }, 'Bob VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Sarah': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Ann VS Ann': { 'shepherd': 13, 'collie': 2, 'poodle': 4 }, 'Jen VS Jen': { 'shepherd': 9, 'collie': 7, 'poodle': 2 } } </code></pre> <p>This is what I want, for example, but to be able to loop through to make a dictionary for each dog:</p> <p>dict_shepherd = {'shepherd': 1,3,3,3,4,1,4,7,3,6,0,2,3,3,13,9}</p> <p>Note: I still have not touched base with pandas and prefer help without using them :) I will get to them one day.</p>
0
2016-08-30T14:34:44Z
39,230,649
<p>You can also get all the lists in one line using dictionary and list comprehensions:</p> <pre><code>ds = {type: [val[type] for val in dict1.values()] for type in ['shepherd', 'collie', 'poodle']} # {'collie': [2, 7, 8, 5, 2, 6, 5, 2, 2, 2, 2, 8, 9, 2, 2, 7], # 'poodle': [2, 2, 1, 8, 2, 3, 8, 5, 4, 1, 2, 2, 2, 4, 4, 2], # 'shepherd': [3, 9, 4, 1, 3, 4, 1, 6, 3, 3, 3, 2, 7, 0, 13, 3]} </code></pre> <p>However, the lists are in no particular order because a <code>dict</code> has no order.</p>
2
2016-08-30T14:45:23Z
[ "python", "dictionary" ]
Looping over a dictionary to make multiple dictionaries
39,230,401
<p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p> <pre><code>dict1 = { 'Bob VS Sarah': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Bob VS Ann': { 'shepherd': 3, 'collie': 2, 'poodle': 1 }, 'Bob VS Jen': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 4 }, 'Sarah VS Ann': { 'shepherd': 4, 'collie': 6, 'poodle': 3 }, 'Sarah VS Jen': { 'shepherd': 1, 'collie': 5, 'poodle': 8 }, 'Jen VS Bob': { 'shepherd': 4, 'collie': 8, 'poodle': 1 }, 'Jen VS Sarah': { 'shepherd': 7, 'collie': 9, 'poodle': 2 }, 'Jen VS Ann': { 'shepherd': 3, 'collie': 7, 'poodle': 2 }, 'Ann VS Bob': { 'shepherd': 6, 'collie': 2, 'poodle': 5 }, 'Ann VS Sarah': { 'shepherd': 0, 'collie': 2, 'poodle': 4 }, 'Ann VS Jen': { 'shepherd': 2, 'collie': 8, 'poodle': 2 }, 'Bob VS Bob': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Sarah VS Sarah': { 'shepherd': 3, 'collie': 2, 'poodle': 2 }, 'Ann VS Ann': { 'shepherd': 13, 'collie': 2, 'poodle': 4 }, 'Jen VS Jen': { 'shepherd': 9, 'collie': 7, 'poodle': 2 } } </code></pre> <p>This is what I want, for example, but to be able to loop through to make a dictionary for each dog:</p> <p>dict_shepherd = {'shepherd': 1,3,3,3,4,1,4,7,3,6,0,2,3,3,13,9}</p> <p>Note: I still have not touched base with pandas and prefer help without using them :) I will get to them one day.</p>
0
2016-08-30T14:34:44Z
39,230,844
<p>You can user defaultdict as follow</p> <pre><code>from collections import defaultdict dict1 = {'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8}, 'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1}, 'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2}, 'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle': 4}, 'Sarah VS Ann': {'shepherd': 4,'collie': 6,'poodle': 3}, 'Sarah VS Jen': {'shepherd': 1,'collie': 5,'poodle': 8}, 'Jen VS Bob': {'shepherd': 4,'collie': 8,'poodle': 1}, 'Jen VS Sarah': {'shepherd': 7,'collie': 9,'poodle': 2}, 'Jen VS Ann': {'shepherd': 3,'collie': 7,'poodle': 2}, 'Ann VS Bob': {'shepherd': 6,'collie': 2,'poodle': 5}, 'Ann VS Sarah': {'shepherd': 0,'collie': 2,'poodle': 4}, 'Ann VS Jen': {'shepherd': 2,'collie': 8,'poodle': 2}, 'Bob VS Bob': {'shepherd': 3,'collie': 2,'poodle': 2}, 'Sarah VS Sarah': {'shepherd': 3,'collie': 2,'poodle': 2}, 'Ann VS Ann': {'shepherd': 13,'collie': 2,'poodle': 4}, 'Jen VS Jen': {'shepherd': 9,'collie': 7,'poodle': 2}} def iter_dict(dict_, result=defaultdict(list)): # mutable as default value ot reuse result over the recursion for k, v in dict_.items(): if isinstance(v, dict): iter_dict(v) else: result[k].append(v) return result print(iter_dict(dict1)) </code></pre> <p>That will produce a dict with all expected results</p> <pre><code>defaultdict(&lt;class 'list'&gt;, {'shepherd': [3, 4, 9, 2, 3, 1, 0, 4, 1, 6, 3, 3, 13, 3, 3, 7], 'collie': [2, 8, 7, 8, 7, 5, 2, 6, 5, 2, 2, 2, 2, 2, 2, 9], 'poodle': [1, 1, 2, 2, 2, 8, 4, 3, 8, 5, 2, 2, 4, 2, 4, 2]}) </code></pre>
1
2016-08-30T14:54:58Z
[ "python", "dictionary" ]
Python List : Index out of Range
39,230,444
<p>I've been trying to create a program that has to read in a file, find the unique words and punctuation, put those to a list and then get the positions of each word and store them in a list. Then, using the lists the program will recreate the file. This is my code:</p> <pre><code>import time import re words = open('words.txt') sentence = words.read() uniquewords = [] positions = [] punctuation = re.findall(r"[\w']+|[.,!?;]", sentence) for word in punctuation: if word not in uniquewords: uniquewords.append(word) print("This file contains the words and punctuation ", uniquewords) positions = [uniquewords.index(word) for word in punctuation] recreated = " ".join([uniquewords[i] for i in positions]) print("In a list the text file words.txt can be shown as:") print(positions) print("Recreating sentence...") print(recreated) </code></pre> <p>The program above does what it needs to, except it produces the following output:</p> <blockquote> <p>This file contains the words and punctuation ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ',', '!'] </p> <p>In a list the text file words.txt can be shown as:</p> <p>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 8, 5, 6, 7, 3, 4, 10]</p> <p>Recreating sentence...</p> <p>Ask not what your country can do for you , Ask what you can do for your country !</p> </blockquote> <p>The positions list starts at 0, so as normal I tried just doing this:</p> <pre><code>positions = [uniquewords.index(word)+1 for word in punctuation] </code></pre> <p>However this produces the error</p> <pre><code> File "C:\Users\Sam\Desktop\COMPUTING TEMP FOLDER\task 3.py", line 13, in &lt;module&gt; recreated = " ".join([uniquewords[i] for i in positions]) File "C:\Users\Sam\Desktop\COMPUTING TEMP FOLDER\task 3.py", line 13, in &lt;listcomp&gt; recreated = " ".join([uniquewords[i] for i in positions]) IndexError: list index out of range </code></pre> <p><strong>How can I make the list start at 1 without getting this error? Any help would be greatly appreciated.</strong> </p> <p>Another small problem is that while the original string is </p> <p>"Ask not what your country can do for you, Ask what you can do for your country!"</p> <p>the actual output is instead </p> <p>Ask not what your country can do for you , Ask what you can do for your country !</p>
0
2016-08-30T14:36:31Z
39,230,696
<p>The problem is that you are incrementing every element of <code>positions</code> so that it displays as 1-indexed, then using that array when python is expecting 0-indexed. Try using:</p> <pre><code>recreated = " ".join([uniquewords[i-1] for i in positions]) </code></pre> <p>instead</p>
1
2016-08-30T14:47:49Z
[ "python" ]
Python List : Index out of Range
39,230,444
<p>I've been trying to create a program that has to read in a file, find the unique words and punctuation, put those to a list and then get the positions of each word and store them in a list. Then, using the lists the program will recreate the file. This is my code:</p> <pre><code>import time import re words = open('words.txt') sentence = words.read() uniquewords = [] positions = [] punctuation = re.findall(r"[\w']+|[.,!?;]", sentence) for word in punctuation: if word not in uniquewords: uniquewords.append(word) print("This file contains the words and punctuation ", uniquewords) positions = [uniquewords.index(word) for word in punctuation] recreated = " ".join([uniquewords[i] for i in positions]) print("In a list the text file words.txt can be shown as:") print(positions) print("Recreating sentence...") print(recreated) </code></pre> <p>The program above does what it needs to, except it produces the following output:</p> <blockquote> <p>This file contains the words and punctuation ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ',', '!'] </p> <p>In a list the text file words.txt can be shown as:</p> <p>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 8, 5, 6, 7, 3, 4, 10]</p> <p>Recreating sentence...</p> <p>Ask not what your country can do for you , Ask what you can do for your country !</p> </blockquote> <p>The positions list starts at 0, so as normal I tried just doing this:</p> <pre><code>positions = [uniquewords.index(word)+1 for word in punctuation] </code></pre> <p>However this produces the error</p> <pre><code> File "C:\Users\Sam\Desktop\COMPUTING TEMP FOLDER\task 3.py", line 13, in &lt;module&gt; recreated = " ".join([uniquewords[i] for i in positions]) File "C:\Users\Sam\Desktop\COMPUTING TEMP FOLDER\task 3.py", line 13, in &lt;listcomp&gt; recreated = " ".join([uniquewords[i] for i in positions]) IndexError: list index out of range </code></pre> <p><strong>How can I make the list start at 1 without getting this error? Any help would be greatly appreciated.</strong> </p> <p>Another small problem is that while the original string is </p> <p>"Ask not what your country can do for you, Ask what you can do for your country!"</p> <p>the actual output is instead </p> <p>Ask not what your country can do for you , Ask what you can do for your country !</p>
0
2016-08-30T14:36:31Z
39,230,759
<p>Please check the below code. I changed bit for recreating string to solve space issue along with the indexing problem you were facing.</p> <pre><code>import time import re words = open("val.txt",'r') sentence = words.readline() uniquewords = [] positions = [] punctuation = re.findall(r"[\w']+|[.,!?;]", sentence) for word in punctuation: if word not in uniquewords: uniquewords.append(word) print("This file contains the words and punctuation ", uniquewords) positions = [uniquewords.index(word)+1 for word in punctuation] #recreated = " ".join([uniquewords[i-1] for i in positions]) recreated = '' for i in positions: w = uniquewords[i-1] if w not in '.,!?;': w = ' ' + w recreated = (recreated + w).strip() print("In a list the text file words.txt can be shown as:") print(positions) print("Recreating sentence...") print(recreated) </code></pre> <p>Output:</p> <pre><code> C:\Users\dinesh_pundkar\Desktop&gt;python c.py ('This file contains the words and punctuation ', ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ',', '!']) In a list the text file words.txt can be shown as: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 3, 9, 6, 7, 8, 4, 5, 11] Recreating sentence... Ask not what your country can do for you, Ask what you can do for your country! </code></pre>
0
2016-08-30T14:50:31Z
[ "python" ]
Turning a list of key/value pairs into a pandas dataframe stored in a HDFStore
39,230,446
<p>There are questions similar to this, but none of them handle the case where my dataframe is inside an HDFStore.</p> <p>I need to turn a list of timestamp/key/value items into dataframes and store it as several dataframes each indexed on the timestamp, and then save it in an HDFStore.</p> <p>Example code:</p> <pre><code>from pandas import HDFStore from pandas import DataFrame store = HDFStore('xxx', driver="H5FD_CORE") for i, k, v in ((0, 'x', 5), (1, 'y', 6)): if k not in store: store[k] = DataFrame() store[k].set_value(i, 'value', v) </code></pre> <p>After this code runs, <code>store['x']</code> remains empty.</p> <pre><code>&gt;&gt;&gt; store['x'] Empty DataFrame Columns: [] Index: [] </code></pre> <p>So there is obviously some reason why that is not persisting, and it is also certainly the case that I just don't know how this stuff is supposed to work. I can certainly figure out the logic if I just understand how you append to tables/dataframes inside an HDFStore.</p> <p>I could also just keep the dataframes in memory, in some kind of dictionary, and just assign them to to the HDFStore right at the end. I somehow had this misguided idea that doing it this way will save memory, perhaps I am wrong about that too.</p>
0
2016-08-30T14:36:35Z
39,235,820
<p>I'd comment to get some clarification, but I don't have the rep yet. Without some more context, it's hard for me to say whether your approach is wise, but I'd inclined to say no in almost all cases. Correct me if I'm wrong, but what you're trying to do is:</p> <ul> <li>Given a list of iterables: <code>[(timeA, key1, value1), (timeB, key1, value2), (timeC, key2, value1)]</code></li> <li>You would want two df's in the HDFStore, where: <ul> <li><code>store[key1] = DataFrame([value1, value2], index=[timeA, timeB])</code></li> <li><code>store[key2] = DataFrame([value1], index=[timeC])</code></li> </ul></li> </ul> <p>Correct?</p> <p>If so, what I would recommend is some kind of "filtering" on your store key, creating dataframes, and then writing a whole dataframe to the store, like so:</p> <pre><code>dataTuples = [(0, 'x', 5), (1, 'y', 6), ...] # initializing the dict of lists, which will become a dict of df's sortedByStoreKey = {storeKey: [] for idx, storeKey, val in dataTuples} for idx, storeKey, val in dataTuples: sortedByStoreKey[storeKey].append([idx, storeKey]) # appending a 2-list to a list # this can all be done with dict comprehensions but this is more legible imo for storeKey, dfContents in sortedByStoreKey.items(): df = pd.DataFrame(dfContents, columns=['time', 'value']) df['time'] = pd.to_datetime(df['time']) # make sure this is read as a pd.DatetimeIndex (as you said you wanted) df.set_index('time', inplace=True) sortedByStoreKey[storeKey] = df # now we write full dataframes to HDFStore with pd.HDFStore('xxx') as store: for storeKey, df in sortedByStoreKey.values(): store[storeKey] = df </code></pre> <p>I'm quite confident there's a more efficient way to do this, both number-of-lines-wise and resources-wise, but this is what strikes me as the most pythonic. If the <code>dataTuples</code> object is HUGE (like >= RAM), then my answer may have to change. </p> <p>Generally speaking, the idea here is to create each of the dataframes in full before writing to the store. As I'm finishing up here, I'm realizing that you can do what you've chosen as well, and the piece that you are missing is the need to specify the store with a <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#table-format" rel="nofollow">table format</a>, which enables appending. Granted, appending one row at a time is probably not a good idea. </p>
0
2016-08-30T19:39:23Z
[ "python", "pandas", "hdf" ]
Plot google map as background
39,230,459
<p>I want to display Google map and I use this code :</p> <pre><code>url = "http://maps.googleapis.com/maps/api/staticmap?center=-30.027489,-51.229248&amp;size=800x800&amp;zoom=14&amp;sensor=false" im = Image.open(cStringIO.StringIO(urllib2.urlopen(url).read())) plt.imshow(im) plt.show() </code></pre> <p>this gives me:<a href="http://i.stack.imgur.com/zjshO.png" rel="nofollow"><img src="http://i.stack.imgur.com/zjshO.png" alt="enter image description here"></a></p> <p>Which I don't understand</p>
0
2016-08-30T14:37:04Z
39,252,096
<p>Take a look at the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">documentation of <code>imshow()</code></a> and specifically its <code>origin</code> argument which determines where the [0,0] index of the array is located in the plot.</p> <p>The line needs to be:</p> <pre><code>plt.imshow(im, origin='upper') </code></pre>
1
2016-08-31T14:16:26Z
[ "python", "image", "google-maps", "url" ]
Why my Element not in view when page scrolls by itself in selenium?
39,230,460
<p>Now, suppose my page have 10 clickable links with same class, one below another at some distance, such that only 1st 3 links are shown in current view, others are seen when i scroll down. Now, i have written a code to click on all of them. It clicks on first 3 and then selenium scrolls my page to show link 5 to 7, page is scrolling too much so as not to show link 4 and since code is trying to click link 4 which is not visible, my code gives error- Element is not visible.</p> <p>Code:</p> <pre><code>def AddConnection(self): mylist=self.driver.find_elements_by_xpath("//a[@class='primary-action-button label']") for x in mylist: x.click() </code></pre> <p>Full Error:</p> <pre><code>================================== FAILURES =================================== _____________________________ test_add_connection _____________________________ driver = &lt;selenium.webdriver.firefox.webdriver.WebDriver (session="3a05990c-13b -4418-baee-f0d54c611ff7")&gt; &gt; add.AddConnection() test_add_connection.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ PageSearchResults.py:24: in AddConnection x.click() c:\python27\lib\site-packages\selenium\webdriver\remote\webelement.py:73: in cl ck self._execute(Command.CLICK_ELEMENT) c:\python27\lib\site-packages\selenium\webdriver\remote\webelement.py:456: in _ xecute return self._parent.execute(command, params) c:\python27\lib\site-packages\selenium\webdriver\remote\webdriver.py:236: in ex cute self.error_handler.check_response(response) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x01E6ACB &gt; response = {'status': 500, 'value': '{"name":"clickElement","sessionId":"3a0599 c-13b8-4418-baee-f0d54c611ff7","status":13,"value...int (892.5, 12.199996948242 88). Other element would receive the click: &lt;div class=\"advanced-search-inner\ &gt;&lt;/div&gt;"}'} def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an err r. :Args: - response - The JSON response from the WebDriver server as a dict onary object. :Raises: If the response contains an error message. """ status = response.get('status', None) if status is None or status == ErrorCode.SUCCESS: return value = None message = response.get("message", "") screen = response.get("screen", "") stacktrace = None if isinstance(status, int): value_json = response.get('value', None) if value_json and isinstance(value_json, basestring): import json try: value = json.loads(value_json) status = value.get('error', None) if status is None: status = value["status"] message = value["value"] if not isinstance(message, basestring): value = message try: message = message['message'] except TypeError: message = None else: message = value.get('message', None) except ValueError: pass exception_class = ErrorInResponseException if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif status in ErrorCode.INVALID_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER: exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = WebDriverException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = WebDriverException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException else: exception_class = WebDriverException if value == '' or value is None: value = response['value'] if isinstance(value, basestring): if exception_class == ErrorInResponseException: raise exception_class(response, value) raise exception_class(value) if message == "" and 'message' in value: message = value['message'] screen = None if 'screen' in value: screen = value['screen'] stacktrace = None if 'stackTrace' in value and value['stackTrace']: stacktrace = [] try: for frame in value['stackTrace']: line = self._value_or_default(frame, 'lineNumber', '') file = self._value_or_default(frame, 'fileName', '&lt;anonymou &gt;') if line: file = "%s:%s" % (file, line) meth = self._value_or_default(frame, 'methodName', '&lt;anonym us&gt;') if 'className' in frame: meth = "%s.%s" % (frame['className'], meth) msg = " at %s (%s)" msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == ErrorInResponseException: raise exception_class(response, message) elif exception_class == UnexpectedAlertPresentException and 'alert' in alue: raise exception_class(message, screen, stacktrace, value['alert'].g t('text')) &gt; raise exception_class(message, screen, stacktrace) E WebDriverException: Message: Element is not clickable at point (892.5, 2.199996948242188). Other element would receive the click: &lt;div class="advanced search-inner"&gt;&lt;/div&gt; c:\python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py:194: We DriverException ========================== 1 failed in 40.13 seconds ========================== </code></pre>
0
2016-08-30T14:37:06Z
39,234,449
<p>Figured out the solution, by adding this code after every click.</p> <pre><code>self.driver.execute_script("window.scrollBy(0, 150);") </code></pre>
0
2016-08-30T18:15:11Z
[ "python", "selenium" ]
Why my Element not in view when page scrolls by itself in selenium?
39,230,460
<p>Now, suppose my page have 10 clickable links with same class, one below another at some distance, such that only 1st 3 links are shown in current view, others are seen when i scroll down. Now, i have written a code to click on all of them. It clicks on first 3 and then selenium scrolls my page to show link 5 to 7, page is scrolling too much so as not to show link 4 and since code is trying to click link 4 which is not visible, my code gives error- Element is not visible.</p> <p>Code:</p> <pre><code>def AddConnection(self): mylist=self.driver.find_elements_by_xpath("//a[@class='primary-action-button label']") for x in mylist: x.click() </code></pre> <p>Full Error:</p> <pre><code>================================== FAILURES =================================== _____________________________ test_add_connection _____________________________ driver = &lt;selenium.webdriver.firefox.webdriver.WebDriver (session="3a05990c-13b -4418-baee-f0d54c611ff7")&gt; &gt; add.AddConnection() test_add_connection.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ PageSearchResults.py:24: in AddConnection x.click() c:\python27\lib\site-packages\selenium\webdriver\remote\webelement.py:73: in cl ck self._execute(Command.CLICK_ELEMENT) c:\python27\lib\site-packages\selenium\webdriver\remote\webelement.py:456: in _ xecute return self._parent.execute(command, params) c:\python27\lib\site-packages\selenium\webdriver\remote\webdriver.py:236: in ex cute self.error_handler.check_response(response) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x01E6ACB &gt; response = {'status': 500, 'value': '{"name":"clickElement","sessionId":"3a0599 c-13b8-4418-baee-f0d54c611ff7","status":13,"value...int (892.5, 12.199996948242 88). Other element would receive the click: &lt;div class=\"advanced-search-inner\ &gt;&lt;/div&gt;"}'} def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an err r. :Args: - response - The JSON response from the WebDriver server as a dict onary object. :Raises: If the response contains an error message. """ status = response.get('status', None) if status is None or status == ErrorCode.SUCCESS: return value = None message = response.get("message", "") screen = response.get("screen", "") stacktrace = None if isinstance(status, int): value_json = response.get('value', None) if value_json and isinstance(value_json, basestring): import json try: value = json.loads(value_json) status = value.get('error', None) if status is None: status = value["status"] message = value["value"] if not isinstance(message, basestring): value = message try: message = message['message'] except TypeError: message = None else: message = value.get('message', None) except ValueError: pass exception_class = ErrorInResponseException if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif status in ErrorCode.INVALID_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER: exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = WebDriverException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = WebDriverException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException else: exception_class = WebDriverException if value == '' or value is None: value = response['value'] if isinstance(value, basestring): if exception_class == ErrorInResponseException: raise exception_class(response, value) raise exception_class(value) if message == "" and 'message' in value: message = value['message'] screen = None if 'screen' in value: screen = value['screen'] stacktrace = None if 'stackTrace' in value and value['stackTrace']: stacktrace = [] try: for frame in value['stackTrace']: line = self._value_or_default(frame, 'lineNumber', '') file = self._value_or_default(frame, 'fileName', '&lt;anonymou &gt;') if line: file = "%s:%s" % (file, line) meth = self._value_or_default(frame, 'methodName', '&lt;anonym us&gt;') if 'className' in frame: meth = "%s.%s" % (frame['className'], meth) msg = " at %s (%s)" msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == ErrorInResponseException: raise exception_class(response, message) elif exception_class == UnexpectedAlertPresentException and 'alert' in alue: raise exception_class(message, screen, stacktrace, value['alert'].g t('text')) &gt; raise exception_class(message, screen, stacktrace) E WebDriverException: Message: Element is not clickable at point (892.5, 2.199996948242188). Other element would receive the click: &lt;div class="advanced search-inner"&gt;&lt;/div&gt; c:\python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py:194: We DriverException ========================== 1 failed in 40.13 seconds ========================== </code></pre>
0
2016-08-30T14:37:06Z
39,254,311
<p>Try calling <code>x.location_once_scrolled_into_view</code> before you do x.click(). That should cause the element to scroll into view to be clicked.</p>
0
2016-08-31T16:05:47Z
[ "python", "selenium" ]
Having a special character such as a period in a python key
39,230,604
<p>I'm trying to generate sql insert statements using sqlalchemy like this.</p> <pre><code>def get_sql(self): """Returns SQL as String""" baz_ins = baz.insert().values( Id=self._id, Foo.Bar=self.foo_dot_bar, ) return str(baz_ins.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})) </code></pre> <p>This returns <code>keyword cannot be expression</code>. Escaping the period like <code>\.</code> also doesn't work.</p> <p>One solution I came up with is using <code>FooDOTBar instead of Foo.Bar</code> and then replacing all "DOT" with "." in the generated sql files, this corrupts some other data though and is not optimal. Any better suggestions to deal with this from the ground up?</p>
0
2016-08-30T14:43:27Z
39,234,745
<p>There's an alternate form of <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.ValuesBase.values" rel="nofollow"><code>.values</code></a> where you pass in a <code>dict</code> instead:</p> <pre><code>baz.insert().values({ "Id": self._id, "Foo.Bar": self.foo_dot_bar, }) </code></pre>
0
2016-08-30T18:33:31Z
[ "python", "sqlalchemy" ]
Having a special character such as a period in a python key
39,230,604
<p>I'm trying to generate sql insert statements using sqlalchemy like this.</p> <pre><code>def get_sql(self): """Returns SQL as String""" baz_ins = baz.insert().values( Id=self._id, Foo.Bar=self.foo_dot_bar, ) return str(baz_ins.compile(dialect=mysql.dialect(), compile_kwargs={"literal_binds": True})) </code></pre> <p>This returns <code>keyword cannot be expression</code>. Escaping the period like <code>\.</code> also doesn't work.</p> <p>One solution I came up with is using <code>FooDOTBar instead of Foo.Bar</code> and then replacing all "DOT" with "." in the generated sql files, this corrupts some other data though and is not optimal. Any better suggestions to deal with this from the ground up?</p>
0
2016-08-30T14:43:27Z
39,234,824
<p>In your query, <code>values</code> can be <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values" rel="nofollow">assigned with dictionary</a>. So you can do something like:</p> <pre><code>baz_ins = baz.insert().values({"Id": self._id, "Foo.Bar": self.foo_dot_bar}) </code></pre> <p>Check out the <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert" rel="nofollow">insert</a> documentation for more options</p>
0
2016-08-30T18:38:19Z
[ "python", "sqlalchemy" ]
Numpy vectorized zero-order interpolation
39,230,757
<p>I have an array</p> <pre><code>p = [[0.9, 0.95, 0.99], [0.89, 0.94, 0.98], [0.9, 0.95, 0.99], [0.91, 0.96, 0.97], ] </code></pre> <p>and a uniform random number for each row</p> <pre><code>r = [0.5, 0.9, 0.3, 0.99] </code></pre> <p>I want to know the last column index where p is still smaller than r, i.e.</p> <pre><code>c = [0, 1, 0, 3] </code></pre> <p>For the last case, no value is smaller. If one places a column of 1s at the end of p, this would be 3. A -1 is also acceptable for me.</p> <p>Naive solution:</p> <pre><code>c = [] for prow, ri in zip(p, r): ci = numpy.interp(ri, prow, arange(len(prow))) c.append(int(numpy.ceil(ci))) print c [0, 1, 0, 3] </code></pre> <p>But I am looking for a vectorised solution that is fast and works for large arrays (millions of rows, ~10 columns).</p> <p>I looked into these solutions:</p> <ul> <li>scipy.interpolate.interp1d(kind=zero) <ul> <li>this seems to require a outer python loop</li> </ul></li> <li>r > p and numpy.where <ul> <li>also seems to require a outer python loop</li> </ul></li> <li>using numpy.random.choice</li> </ul> <p>For the last one I would place (differential) probabilities instead of cumulative ones:</p> <pre><code>p = [[0.9, 0.05, 0.04], [0.89, 0.05, 0.04], [0.9, 0.05, 0.04], [0.91, 0.05, 0.01], ] </code></pre> <p>but numpy.random.choice does not support vectorization (<a href="https://github.com/numpy/numpy/issues/2724" rel="nofollow">1</a>, <a href="https://github.com/numpy/numpy/issues/5344" rel="nofollow">2</a>).</p> <p>Is numpy.vectorise the solution, or Cython? I am looking for a fast solution.</p>
2
2016-08-30T14:50:27Z
39,230,923
<p>Here's one vectorized solution using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>mask = (p &gt; r[:,None]) out = np.where(mask.any(1),mask.argmax(1),p.shape[1]) </code></pre> <p>Sample run -</p> <pre><code>In [50]: p Out[50]: array([[ 0.9 , 0.95, 0.99], [ 0.89, 0.94, 0.98], [ 0.9 , 0.95, 0.99], [ 0.91, 0.96, 0.97]]) In [51]: r Out[51]: array([ 0.5 , 0.9 , 0.3 , 0.99]) In [52]: mask = (p &gt; r[:,None]) # 2D Mask of row-wise comparisons In [53]: mask Out[53]: array([[ True, True, True], [False, True, True], [ True, True, True], [False, False, False]], dtype=bool) In [54]: np.where(mask.any(1),mask.argmax(1),p.shape[1]) Out[54]: array([0, 1, 0, 3]) </code></pre>
3
2016-08-30T14:58:45Z
[ "python", "numpy", "optimization", "vectorization" ]
How do i return the position of a word that appears twice in a string?
39,230,787
<p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the keyword appears twice. How do I get it so if the word appears twice then the program will print all positions of it? </p> <p>This is what i have so far:</p> <pre><code>#Start by making a string String = input("Please enter a set of string characters.\n") #Make the user choose a keyword Keyword = input("Please enter a keyword that we can tell you the position of.\n") #Split the string into single words assigning the position to the word after the space IndivualWords = String.split(' ') #Start an IF statement if Keyword in IndivualWords: #If the IF is true then access the index and assign the keyword a position pos = IndivualWords.index(Keyword) #Print the position of the word print (pos +1) else: #Print an error print("That word is not in the string.") </code></pre>
0
2016-08-30T14:51:50Z
39,230,960
<p>You could use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow">re.finditer</a>, here's a little example out of your example:</p> <pre><code>import re sentence = input("Enter a set of string characters:") keyword = input("Enter a keyword that we can tell you the position of:") for m in re.finditer(keyword, sentence): print('{0} found {1}-{2}'.format(keyword, m.start(), m.end())) </code></pre>
1
2016-08-30T14:59:56Z
[ "python", "string" ]
How do i return the position of a word that appears twice in a string?
39,230,787
<p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the keyword appears twice. How do I get it so if the word appears twice then the program will print all positions of it? </p> <p>This is what i have so far:</p> <pre><code>#Start by making a string String = input("Please enter a set of string characters.\n") #Make the user choose a keyword Keyword = input("Please enter a keyword that we can tell you the position of.\n") #Split the string into single words assigning the position to the word after the space IndivualWords = String.split(' ') #Start an IF statement if Keyword in IndivualWords: #If the IF is true then access the index and assign the keyword a position pos = IndivualWords.index(Keyword) #Print the position of the word print (pos +1) else: #Print an error print("That word is not in the string.") </code></pre>
0
2016-08-30T14:51:50Z
39,230,984
<p>using <code>enumerate()</code> in an example where "een" is the keyword, <code>line</code> the input :</p> <pre><code>keyword = "een" line = "een aap op een fiets" for index, word in enumerate(line.split()): if word == keyword: print(index) </code></pre>
4
2016-08-30T15:00:43Z
[ "python", "string" ]
How do i return the position of a word that appears twice in a string?
39,230,787
<p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the keyword appears twice. How do I get it so if the word appears twice then the program will print all positions of it? </p> <p>This is what i have so far:</p> <pre><code>#Start by making a string String = input("Please enter a set of string characters.\n") #Make the user choose a keyword Keyword = input("Please enter a keyword that we can tell you the position of.\n") #Split the string into single words assigning the position to the word after the space IndivualWords = String.split(' ') #Start an IF statement if Keyword in IndivualWords: #If the IF is true then access the index and assign the keyword a position pos = IndivualWords.index(Keyword) #Print the position of the word print (pos +1) else: #Print an error print("That word is not in the string.") </code></pre>
0
2016-08-30T14:51:50Z
39,231,002
<p>The <code>index</code> method, as you found, returns just the first match:</p> <pre><code>&gt;&gt;&gt; words = 'This is the time that the clock strikes'.split() &gt;&gt;&gt; words.index('the') 2 </code></pre> <p>This list comprehension will return the locations of all matches:</p> <pre><code>&gt;&gt;&gt; [i for i, word in enumerate(words) if word == 'the'] [2, 5] </code></pre> <p>If you want the list computed for all the words and formatted:</p> <pre><code>&gt;&gt;&gt; print('\n'.join('%-7s: %s' % (w, ' '.join(str(i) for i, word in enumerate(words) if word == w)) for w in words)) This : 0 is : 1 the : 2 5 time : 3 that : 4 the : 2 5 clock : 6 strikes: 7 </code></pre>
1
2016-08-30T15:01:25Z
[ "python", "string" ]
How do i return the position of a word that appears twice in a string?
39,230,787
<p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the keyword appears twice. How do I get it so if the word appears twice then the program will print all positions of it? </p> <p>This is what i have so far:</p> <pre><code>#Start by making a string String = input("Please enter a set of string characters.\n") #Make the user choose a keyword Keyword = input("Please enter a keyword that we can tell you the position of.\n") #Split the string into single words assigning the position to the word after the space IndivualWords = String.split(' ') #Start an IF statement if Keyword in IndivualWords: #If the IF is true then access the index and assign the keyword a position pos = IndivualWords.index(Keyword) #Print the position of the word print (pos +1) else: #Print an error print("That word is not in the string.") </code></pre>
0
2016-08-30T14:51:50Z
39,231,024
<p>You can use the regex method <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>finditer()</code></a></p> <pre><code>&gt;&gt;&gt; keyword = 'fox' &gt;&gt;&gt; s = 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.' &gt;&gt;&gt; from re import finditer &gt;&gt;&gt; print [match.start(0) for match in finditer(keyword, s)] [16, 61] </code></pre> <p>or if you need the ranges of the sub strings:</p> <pre><code>&gt;&gt;&gt; print [(match.start(0), match.end(0)) for match in re.finditer(keyword, s)] [(16, 19), (61, 64)] </code></pre>
1
2016-08-30T15:02:21Z
[ "python", "string" ]
Add a value to the end of a pandas index object
39,230,854
<p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p> <pre><code>import pandas as pd ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15]) indx = ser.index </code></pre> <p>Say I want to add the value 20 to the end of the index. This throws an error:</p> <pre><code>indx.append(20) </code></pre> <p>This returns [11,12,13,14,20,15]:</p> <pre><code>indx.insert(-1, 20) </code></pre> <p>This works but seems like a work-around:</p> <pre><code>indx.insert(len(indx), 20) </code></pre> <p>Is there something I'm missing? This is on pandas 0.18.1. Thanks.</p>
1
2016-08-30T14:55:36Z
39,231,155
<p>The method <code>append</code> takes another index as input, but <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#combining-joining-set-operations" rel="nofollow"><code>union</code></a> will work if you simply pass an array-like object: </p> <pre><code>indx.union([20]) </code></pre> <p>Note that index objects in pandas are immutable, so any such operation will return a new index rather than modifying the existing one.</p>
2
2016-08-30T15:09:12Z
[ "python", "pandas" ]
Add a value to the end of a pandas index object
39,230,854
<p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p> <pre><code>import pandas as pd ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15]) indx = ser.index </code></pre> <p>Say I want to add the value 20 to the end of the index. This throws an error:</p> <pre><code>indx.append(20) </code></pre> <p>This returns [11,12,13,14,20,15]:</p> <pre><code>indx.insert(-1, 20) </code></pre> <p>This works but seems like a work-around:</p> <pre><code>indx.insert(len(indx), 20) </code></pre> <p>Is there something I'm missing? This is on pandas 0.18.1. Thanks.</p>
1
2016-08-30T14:55:36Z
39,231,251
<p>You need to pass a collection of index values as parameter while appending to the given <code>index</code> object.</p> <pre><code>indx.append(pd.Index([20])) # Pass the values inside the list Int64Index([11, 12, 13, 14, 15, 20], dtype='int64') </code></pre>
2
2016-08-30T15:13:43Z
[ "python", "pandas" ]
Add a value to the end of a pandas index object
39,230,854
<p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p> <pre><code>import pandas as pd ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15]) indx = ser.index </code></pre> <p>Say I want to add the value 20 to the end of the index. This throws an error:</p> <pre><code>indx.append(20) </code></pre> <p>This returns [11,12,13,14,20,15]:</p> <pre><code>indx.insert(-1, 20) </code></pre> <p>This works but seems like a work-around:</p> <pre><code>indx.insert(len(indx), 20) </code></pre> <p>Is there something I'm missing? This is on pandas 0.18.1. Thanks.</p>
1
2016-08-30T14:55:36Z
39,231,255
<p>You may want to try these two options:</p> <pre><code>import pandas as pd import numpy as np ser.append(pd.Series([np.nan], index = [20])) # 11 1.0 # 12 2.0 # 13 3.0 # 14 4.0 # 15 5.0 # 20 NaN # dtype: float64 ser.set_value(20, np.nan) # 11 1.0 # 12 2.0 # 13 3.0 # 14 4.0 # 15 5.0 # 20 NaN # dtype: float64 </code></pre>
2
2016-08-30T15:13:58Z
[ "python", "pandas" ]
Predefined module aliases in Python?
39,231,138
<p>I'm developing a library of Python modules that is fairly deeply nested, e.g.:</p> <pre><code>\MyTools __init__.py \HydroTools __init__.py \bin \Code __init__.py hydro.py \TerraTools __init__.py \bin \Code __init__.py terra.py </code></pre> <p>Is there some way to define aliases for the modules ahead of time (maybe by modifying <strong>init</strong>.py?), so that instead of importing with...</p> <pre><code>from MyTools.HydroTools.Code import hydro from MyTools.TerraTools.Code import terra </code></pre> <p>...I could do something cleaner like</p> <pre><code>from MyTools import hydro, terra </code></pre>
1
2016-08-30T15:08:38Z
39,231,445
<p>You want to push these nested packages on top of your module namespace.</p> <p>In <code>MyTools/__init__.py</code> add:</p> <pre><code>from .HydroTools.Code import hydro from .TerraTools.Code import terra </code></pre>
3
2016-08-30T15:21:31Z
[ "python" ]
How do I pass grants with boto3's upload_file?
39,231,148
<p>I have a command using the AWS CLI</p> <pre><code>aws s3 cp y:/mydatafolder s3://&lt;bucket&gt;/folder/subfolder --recursive --grants read=uri=http://policyurl </code></pre> <p>The first part is easy to do in python, I can use <code>os.walk</code> to walk the folders and get the files and upload the file using the <code>boto3.s3client.upload_file</code> command. The second part I'm struggling with is the <code>--grants read</code> part. </p> <p>What boto3 function do I need to call to do this?</p> <p>Thanks</p>
0
2016-08-30T15:08:58Z
39,237,239
<p>In your <code>upload_file</code> call you will need to pass <code>GrantRead</code> in <code>ExtraArgs</code>. Generally speaking you can pass in any arguments that <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object" rel="nofollow"><code>put_object</code></a> would take this way. For example:</p> <pre><code>import boto3 s3 = boto3.client('s3') file_path = '/foo/bar/baz.txt' s3.upload_file( Filename=file_path, Bucket='&lt;bucket&gt;', Key='key', ExtraArgs={ 'GrantRead': 'uri="http://policyurl"' } ) </code></pre>
0
2016-08-30T21:18:22Z
[ "python", "python-2.7", "boto3" ]
python dictionary iteration for data frame filtering with multiple conditions
39,231,176
<p>I am basically trying to build basic search engine that returns results based on a parsed query.</p> <p>I have a dictionary that is user generated based on parsed input from their string:</p> <pre><code>input = {“color”: [“black”], “make”: [“honda”], “type”: [“”]} </code></pre> <p>I am then trying to use that input, to do a search and filter of a dataset (which I am currently storing as a pandas dataframe, so please advise if this is also not optimal).</p> <pre><code>list(df.column.values) = make,type,color,mpg,year honda,coupe,red,32,2014 bmw,suv,black,21,2012 honda,suv,black,24,2015 vw,sedan,black,31,2016 </code></pre> <p>I need to iterate over the valid values of my input dictionary (notice that ‘type’ doesn’t have a value) and filter based on what the user entered in, ‘color’ and ‘make’). Sometimes they might include the type and leave out the color, etc. so I might never have a value for every key in my dictionary;</p> <p>Sudo code:</p> <pre><code>for each valid value in my input dictionary: filter df by appropriate_column=appropriate_value </code></pre> <p>So given my input example, I would filter my df down to only entries that were ‘black’ and made by ‘honda’.</p>
0
2016-08-30T15:10:04Z
39,233,351
<p>Let <code>d</code> be your dict, then:</p> <pre><code>cond = [df[k].apply(lambda k: k in v if v != [''] else True) for k, v in d.items()] cond_total = functools.reduce(lambda x, y: x &amp; y, cond) print(df[cond_total]) </code></pre> <p>Output:</p> <pre><code> make type color mpg year 2 honda suv black 24 2015 </code></pre>
1
2016-08-30T17:09:42Z
[ "python", "pandas", "dictionary" ]
creating admin restricted urls
39,231,178
<p>so in my urls.py (outside django default admin section ) i want to restrict some urls only to admin so if i have this for logged users </p> <pre><code> from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^a1$',login_required( views.admin_area1 ), name='a1'), url(r'^a2$', login_required(views.admin_area2) , name='a2'), url(r'^a3', login_required(views.admin_area3) , name='a3'), ] </code></pre> <p>is there enyway torestrict these links to logged admins not just any logged user ? there is but <a href="http://stackoverflow.com/a/12003808/590589">according to this</a> i can use <code>user_passes_test</code> but i have to use it in view </p>
2
2016-08-30T15:10:15Z
39,231,312
<p>You can use the decorator returned by <code>user_passes_test(lambda u: u.is_superuser)</code> in the same way that you use <code>login_required</code>:</p> <pre><code>urlpatterns = [ url(r'^a1$', user_passes_test(lambda u: u.is_superuser)(views.admin_area1), name='a1'), ] </code></pre> <p>If you want to restrict access to admins, then it might be more accurate to use the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#the-staff-member-required-decorator" rel="nofollow"><code>staff_member_required</code></a> decorator (which checks the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_staff" rel="nofollow"><code>is_staff</code></a> flag) instead of checking the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_superuser" rel="nofollow"><code>is_superuser</code></a> flag.</p> <pre><code>from django.contrib.admin.views.decorators import staff_member_required urlpatterns = [ url(r'^a1$', staff_member_required(views.admin_area1), name='a1'), ... ] </code></pre>
7
2016-08-30T15:15:59Z
[ "python", "django", "django-1.9" ]
reading csv file from panda and plotting
39,231,188
<p>I have 1000 files in which the data is stored in comma separation. The description of a file is given below:</p> <p>The values are comma separated, <code>-9999</code> values should be ignored and if it can be read, all the values of row and column should be stored in numbers, as it has to used in plotting. The shape of file is [<strong>104 rows x 15 columns</strong>].</p> <p>The few lines of the files are as follows:</p> <pre><code>0, 9.8597e+00, 129.944, 1.071, 6.7433e-06, 1.0911e-05, -9999, -9999, 3.7134e-07, 3.5245e-05, -9999, -9999, 26.295, -86.822, -123.017 0, 8.7012e+00, 130.908, 0.966, 1.9842e-06, 1.0799e-05, -9999, -9999, 3.5888e-07, 7.8133e-05, -9999, -9999, 27.140, -86.818, -122.322 </code></pre> <p>After reading into numeric values, I need to plot it into subplot also. Like COl1 vs Col2 , Col3 vs col5 and so on....</p> <p>Any idea how to achieve it?</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df1=pd.read_csv("small_file_106.txt",header=1) print(df1) </code></pre>
0
2016-08-30T15:10:44Z
39,231,415
<p>I never used plot ,but following would be useful for the first question input the list of values to na_values and those will be considered as NA by pandas</p> <pre><code>pd.read_csv(File, sep=',',na_values=['-9999'],keep_default_na=False) </code></pre> <p>Also <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow">pd.to_numeric</a> is available to convert data to numeric</p> <pre><code>df.apply(lambda x: pd.to_numeric(x, errors='ignore')) </code></pre>
1
2016-08-30T15:20:34Z
[ "python" ]
reading csv file from panda and plotting
39,231,188
<p>I have 1000 files in which the data is stored in comma separation. The description of a file is given below:</p> <p>The values are comma separated, <code>-9999</code> values should be ignored and if it can be read, all the values of row and column should be stored in numbers, as it has to used in plotting. The shape of file is [<strong>104 rows x 15 columns</strong>].</p> <p>The few lines of the files are as follows:</p> <pre><code>0, 9.8597e+00, 129.944, 1.071, 6.7433e-06, 1.0911e-05, -9999, -9999, 3.7134e-07, 3.5245e-05, -9999, -9999, 26.295, -86.822, -123.017 0, 8.7012e+00, 130.908, 0.966, 1.9842e-06, 1.0799e-05, -9999, -9999, 3.5888e-07, 7.8133e-05, -9999, -9999, 27.140, -86.818, -122.322 </code></pre> <p>After reading into numeric values, I need to plot it into subplot also. Like COl1 vs Col2 , Col3 vs col5 and so on....</p> <p>Any idea how to achieve it?</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df1=pd.read_csv("small_file_106.txt",header=1) print(df1) </code></pre>
0
2016-08-30T15:10:44Z
39,233,336
<p>Once you've read the data in (Shijo's method looks good) the <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.pairplot.html" rel="nofollow">Seaborn library's pairplot</a> should generate the plot you want.</p>
0
2016-08-30T17:09:04Z
[ "python" ]
Finding a pattern in python using re (reggae)
39,231,204
<p>I'm trying to build a regular expression:</p> <pre><code>mystring = /some/path/with/%variable%/%inside%/%it%/ re.findall("[^\s%]+", allocine_spec[key]) </code></pre> <p>And this return the following:</p> <pre><code>['/some/path/', 'variable', '/', 'inside', '/', 'it'] </code></pre> <p>But I would like only:</p> <pre><code>['variable', 'inside', 'it'] </code></pre> <p>Is that possible using only re?</p>
2
2016-08-30T15:11:54Z
39,231,290
<p>You need a much simpler regex:</p> <pre><code>%([^%]+)% </code></pre> <p>See the <a href="https://regex101.com/r/iP1gV6/1">regex demo</a></p> <p>This will match a <code>%</code>, then capture 1+ chars other than <code>%</code> into Group 1 and then will match a trailing <code>%</code>. If your strings only contain word characters in between <code>%</code>, you may replace <code>[^%]+</code> with <code>\w+</code>.</p> <p>Note that <code>re.findall</code> returns only the captured substrings if capturing groups are defined in the pattern.</p> <p><a href="https://ideone.com/xDC4c0">Python demo</a>:</p> <pre><code>import re mystring = "/some/path/with/%variable%/%inside%/%it%/" print(re.findall("%([^%]+)%", mystring)) # =&gt; ['variable', 'inside', 'it'] </code></pre>
5
2016-08-30T15:14:57Z
[ "python", "regex", "python-2.7" ]
Compute y-value based on x-value and function - Python
39,231,282
<p>I'm currently trying to teach myself how to plot functions with matplotlib in Python, and I'm stuck on a rather simple task: <strong>Given a function f(x) = 2x +3, plot the coordinates in matplotlib.</strong> </p> <p>I have solved this the hard way, through <em>manual</em> calculation, creating a list of both the x- and y-values for x-values from -2 to 3.</p> <p><strong>The Hard Way</strong></p> <pre><code>import matplotlib.pyplot as plt x = range(-2, 4) y = [-1, 1, 3, 5, 7, 9] plt.plot(x, y, 'ro') plt.show() </code></pre> <p>This works!</p> <p><strong>However</strong>, is there a way to quickly obtain the y-values, based on x-values (from -2 to 3) and the function?</p> <pre><code>f(x) = 2x+3 </code></pre> <p>Any help is highly appreciated!</p>
-1
2016-08-30T15:14:43Z
39,231,408
<p>The <code>lambda</code> function would be very useful in this situation. You can declare your function using <code>f = lambda x: 2*x + 3</code>. The <code>map</code> function would be a good way to obtain all of your <code>y</code> values in a simple way: <code>y = map(f, x)</code>.</p> <p>Here is the documentation on <code>lambda</code> and <code>map</code>:</p> <p><a href="https://docs.python.org/2/reference/expressions.html#lambda" rel="nofollow">https://docs.python.org/2/reference/expressions.html#lambda</a> <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">https://docs.python.org/2/library/functions.html#map</a></p>
0
2016-08-30T15:20:07Z
[ "python", "function", "matplotlib", "range", "coordinates" ]
Compute y-value based on x-value and function - Python
39,231,282
<p>I'm currently trying to teach myself how to plot functions with matplotlib in Python, and I'm stuck on a rather simple task: <strong>Given a function f(x) = 2x +3, plot the coordinates in matplotlib.</strong> </p> <p>I have solved this the hard way, through <em>manual</em> calculation, creating a list of both the x- and y-values for x-values from -2 to 3.</p> <p><strong>The Hard Way</strong></p> <pre><code>import matplotlib.pyplot as plt x = range(-2, 4) y = [-1, 1, 3, 5, 7, 9] plt.plot(x, y, 'ro') plt.show() </code></pre> <p>This works!</p> <p><strong>However</strong>, is there a way to quickly obtain the y-values, based on x-values (from -2 to 3) and the function?</p> <pre><code>f(x) = 2x+3 </code></pre> <p>Any help is highly appreciated!</p>
-1
2016-08-30T15:14:43Z
39,231,458
<p>Here's an easy way to plot your function within a certain range <code>[A,B]</code>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def graph(formula, x_range): x = np.array(x_range) y = formula(x) plt.plot(x, y) plt.show() def f(x): return 2 * x + 3 A, B = -10, 10 graph(f, range(A, B)) </code></pre>
0
2016-08-30T15:21:51Z
[ "python", "function", "matplotlib", "range", "coordinates" ]
Ignoring Time gaps larger than x mins Matplotlib in Python
39,231,410
<p>I get data every 5 mins between 9:30am and 4pm. Most days I just plot live intraday data. However, sometimes I want a historical view of lets says 2+ days. The only problem is that during 4pm and 9:30 am I just get a line connecting the two data points. I would like that gap to disappear. My code and an example of what is happening are below;</p> <pre><code>fig = plt.figure() plt.ylabel('Bps') plt.xlabel('Date/Time') plt.title(ticker) ax = fig.add_subplot(111) myFmt = mdates.DateFormatter('%m/%d %I:%M') ax.xaxis.set_major_formatter(myFmt) line, = ax.plot(data['Date_Time'],data['Y'],'b-') </code></pre> <p><a href="http://i.stack.imgur.com/NcLrz.png" rel="nofollow"><img src="http://i.stack.imgur.com/NcLrz.png" alt="enter image description here"></a></p> <p>I want to keep the data as a time series so that when i scroll over it I can see the exact date and time.</p>
0
2016-08-30T15:20:15Z
39,235,253
<p>So it looks like you're using a pandas object, which is helpful. Assuming you have filtered out any time between 4pm and 9am in <code>data['Date_Time']</code>, I would make sure your index is reset via <code>data.reset_index()</code>. You'll want to use that integer index as the under-the-hood index that matplotlib actually uses to plot the timeseries. Then you can manually alter the tick labels themselves with <code>plt.xticks()</code> as seen in <a href="http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html" rel="nofollow">this demo case</a>. Put together, I would expect it to look something like this:</p> <pre><code>data = data.reset_index(drop=True) # just to remove that pesky column fig, ax = plt.subplots(1,1) ax.plot(data.index, data['Y']) plt.ylabel('Bps') plt.xlabel('Date/Time') plt.title(ticker) plt.xticks(data.index, data['Date_Time']) </code></pre> <p>I noticed the last statement in your question just after posting this. Unfortunately, this "solution" doesn't track the "x" variable in an interactive figure. That is, while the time axis labels adjust to your zoom, you can't know the time by cursor location, so you'd have to eyeball it up from the bottom of the figure. :/</p>
1
2016-08-30T19:04:44Z
[ "python", "matplotlib", "time-series", "graphing", "timeserieschart" ]
What is the best way to quote unquoted strings while leaving already quoted strings alone?
39,231,418
<p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map</a></p> <p>Some of the strings there are already quoted. Some of them are not. I need to quote all the strings and leave the already-quoted ones alone. For example, with the following almost-JSON-object:</p> <pre><code>marks = { lat = 36.103, long = 37.308, mark = m.gov_hill, marksize = 184, label = "[[Battle of Aleppo (2012–present)|Aleppo]]", link = "Battle of Aleppo (2012–present)", label_size = 0, position = "left" } </code></pre> <p>I need it to become this:</p> <pre><code>"marks" = { "lat" = 36.103, "long" = 37.308, "mark" = "m.gov_hill", "marksize" = 184, "label" = "[[Battle of Aleppo (2012–present)|Aleppo]]", "link" = "Battle of Aleppo (2012–present)", "label_size" = 0, "position" = "left" } </code></pre> <p>Essentially, anything that can become a string and is not already a string should be turned into a string. Also, I already have a sed command for turning the equals signs into colons as one of the steps to turning it into valid JSON, so no need to comment on that part of the process.</p> <p>Thanks in advance!</p>
0
2016-08-30T15:20:36Z
39,231,760
<p>This looks for any lines that does not already have any <code>"</code> characters. For those lines have an alphabetic character or an underline after the equal sign, then the quantity after the equal sign is placed in quotes:</p> <pre><code>$ sed -E '/"/!s/= +(.*[[:alpha:]_].*),/= "\1",/' file marks = { lat = 36.103, long = 37.308, mark = "m.gov_hill", marksize = 184, label = "[[Battle of Aleppo (2012–present)|Aleppo]]", link = "Battle of Aleppo (2012–present)", label_size = 0, position = "left" } </code></pre> <p>In more detail:</p> <ul> <li><p><code>-E</code></p> <p>This tells sed to use extended regular expressions.</p></li> <li><p><code>/"/!</code></p> <p>This tells sed to remove from consideration any line that already has double quotes.</p></li> <li><p><code>s/= +(.*[[:alpha:]_].*),/= "\1",/</code></p> <p>This substitute command puts the quantity after the equal sign in double quotes if the quantity has either an alphabetic character or an underline character.</p></li> </ul> <h3>Changing the file in place</h3> <p>To change a file in place, use the <code>-i</code> option:</p> <pre><code>sed -i.bak -E '/"/!s/= +(.*[[:alpha:]_].*),/= "\1",/' file </code></pre>
0
2016-08-30T15:36:24Z
[ "python", "json", "regex", "string", "sed" ]
What is the best way to quote unquoted strings while leaving already quoted strings alone?
39,231,418
<p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map</a></p> <p>Some of the strings there are already quoted. Some of them are not. I need to quote all the strings and leave the already-quoted ones alone. For example, with the following almost-JSON-object:</p> <pre><code>marks = { lat = 36.103, long = 37.308, mark = m.gov_hill, marksize = 184, label = "[[Battle of Aleppo (2012–present)|Aleppo]]", link = "Battle of Aleppo (2012–present)", label_size = 0, position = "left" } </code></pre> <p>I need it to become this:</p> <pre><code>"marks" = { "lat" = 36.103, "long" = 37.308, "mark" = "m.gov_hill", "marksize" = 184, "label" = "[[Battle of Aleppo (2012–present)|Aleppo]]", "link" = "Battle of Aleppo (2012–present)", "label_size" = 0, "position" = "left" } </code></pre> <p>Essentially, anything that can become a string and is not already a string should be turned into a string. Also, I already have a sed command for turning the equals signs into colons as one of the steps to turning it into valid JSON, so no need to comment on that part of the process.</p> <p>Thanks in advance!</p>
0
2016-08-30T15:20:36Z
39,231,885
<p>Process each line of text separately (assumes items do not span across lines)</p> <p>Strip off the trailing comma</p> <p>Split each line at the first equals sign</p> <p>For each sub-item produced by splitting:</p> <ul> <li>Strip off leading/trailing spaces</li> <li>If it's equal to <code>{</code> or <code>}</code>, leave it alone.</li> <li>If <code>int()</code> or <code>float()</code> succeed, leave it alone.</li> <li>If it starts with a quote, leave it alone (assumes no imbalanced quotes)</li> <li>Otherwise add quotes</li> </ul> <p>Reassemble the processed lines, adding the commas back as necessary</p>
0
2016-08-30T15:42:12Z
[ "python", "json", "regex", "string", "sed" ]
What is the best way to quote unquoted strings while leaving already quoted strings alone?
39,231,418
<p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map</a></p> <p>Some of the strings there are already quoted. Some of them are not. I need to quote all the strings and leave the already-quoted ones alone. For example, with the following almost-JSON-object:</p> <pre><code>marks = { lat = 36.103, long = 37.308, mark = m.gov_hill, marksize = 184, label = "[[Battle of Aleppo (2012–present)|Aleppo]]", link = "Battle of Aleppo (2012–present)", label_size = 0, position = "left" } </code></pre> <p>I need it to become this:</p> <pre><code>"marks" = { "lat" = 36.103, "long" = 37.308, "mark" = "m.gov_hill", "marksize" = 184, "label" = "[[Battle of Aleppo (2012–present)|Aleppo]]", "link" = "Battle of Aleppo (2012–present)", "label_size" = 0, "position" = "left" } </code></pre> <p>Essentially, anything that can become a string and is not already a string should be turned into a string. Also, I already have a sed command for turning the equals signs into colons as one of the steps to turning it into valid JSON, so no need to comment on that part of the process.</p> <p>Thanks in advance!</p>
0
2016-08-30T15:20:36Z
39,231,926
<p>With a regex as</p> <pre><code>(^[^\n\S]*|=\s*)(?![\d\s])(\w+[^,\s]*) </code></pre> <p>and a replacement of</p> <pre><code>\1"\2" </code></pre> <p>you would get <a href="https://regex101.com/r/mQ9rI9/1" rel="nofollow">these results</a>. You can switch from Python to any other flavor, if you think you will be using a different regex language/engine.</p>
1
2016-08-30T15:43:51Z
[ "python", "json", "regex", "string", "sed" ]
What is the best way to quote unquoted strings while leaving already quoted strings alone?
39,231,418
<p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map</a></p> <p>Some of the strings there are already quoted. Some of them are not. I need to quote all the strings and leave the already-quoted ones alone. For example, with the following almost-JSON-object:</p> <pre><code>marks = { lat = 36.103, long = 37.308, mark = m.gov_hill, marksize = 184, label = "[[Battle of Aleppo (2012–present)|Aleppo]]", link = "Battle of Aleppo (2012–present)", label_size = 0, position = "left" } </code></pre> <p>I need it to become this:</p> <pre><code>"marks" = { "lat" = 36.103, "long" = 37.308, "mark" = "m.gov_hill", "marksize" = 184, "label" = "[[Battle of Aleppo (2012–present)|Aleppo]]", "link" = "Battle of Aleppo (2012–present)", "label_size" = 0, "position" = "left" } </code></pre> <p>Essentially, anything that can become a string and is not already a string should be turned into a string. Also, I already have a sed command for turning the equals signs into colons as one of the steps to turning it into valid JSON, so no need to comment on that part of the process.</p> <p>Thanks in advance!</p>
0
2016-08-30T15:20:36Z
39,235,114
<pre><code>$ cat tst.awk /=/ { lhs = rhs = $0 sub(/[[:space:]]*=.*/,"",lhs) sub(/^[^=]+=[[:space:]]*/,"",rhs) sub(/[^[:space:]]+/,"\"&amp;\"",lhs) if ( rhs !~ /^([0-9]+\.?[0-9]*|".*"),?$/ ) { sub(/,?$/,"\"&amp;",rhs) rhs = "\"" rhs } $0 = lhs " = " rhs } { print } $ awk -f tst.awk file "marks" = "{" "lat" = 36.103, "long" = 37.308, "mark" = "m.gov_hill", "marksize" = 184, "label" = "[[Battle of Aleppo (2012–present)|Aleppo]]", "link" = "Battle of Aleppo (2012–present)", "label_size" = 0, "position" = "left" } </code></pre> <p>The above should work even for the non-trivial cases I mentioned in my comment under your question.</p>
0
2016-08-30T18:56:09Z
[ "python", "json", "regex", "string", "sed" ]
Error with Fibonacci sequence in python
39,231,469
<p>Edit - All fixed thank you </p> <pre><code>fib=[0,1] for i in range(0,700): fib.append(fib[len(fib)-2]+fib[len(fib)-1]) print(fib[len(fib)-1]) print('Do you want a range of numbers or single?') answer=input() if answer=='single': print('Which number?') number=int(input()) fib[number] elif answer=='range': print('From:') firstNumber=int(input()) print('To:') secondNumber=int(input()) fib[firstNumber:secondNumber] </code></pre> <p>I have been trying to create a Fibonacci sequence in python which allows you to choose either which number to show or what range of numbers to show (script above). However when i run the script it runs fine at the start, i get to the part when you enter the number you want (either a single number, or the to and from numbers) but when i do nothing happens and the script ends. I am very new to python (coming from html and css, and i CBA right now to code this in HTML xD). Could anyone help me?</p>
0
2016-08-30T15:22:22Z
39,231,936
<pre><code>fib=[0,1] for i in range(0,700): fib.append(fib[len(fib)-2]+fib[len(fib)-1]) print(fib[len(fib)-1]) answer=input('Do you want a range of numbers or single?') if answer=='single': number=int(input('Which number?[index]: ')) print(fib[number]) elif answer=='range': firstNumber=int(input('From[index]: ')) secondNumber=int(input('To[index]: ')) print(fib[firstNumber:secondNumber]) else: print('Error') </code></pre> <p>Maybe this will work for you</p>
2
2016-08-30T15:44:36Z
[ "python" ]
How to debug Protocol.dataReceived in Twisted
39,231,472
<p>I'm new to twisted and I'm having trouble to debug my code within the <code>dataReceived</code> method of the <code>twisted.internet.protocol.Protocol</code> object.</p> <p>Given some code like this</p> <pre><code>class Printer(Protocol): def dataReceived(self, data): print data # Works perfectly print toto # should trigger some error since "toto" is not defined ... response.deliverBody(Printer()) </code></pre> <p>I couldn't find a way to add an <code>Errback</code> on <code>dataReceived</code>. Is there a way ? an other way to debug its behavior ?</p> <p>Thanks in advance for your help.</p>
0
2016-08-30T15:22:28Z
39,234,703
<p>You can't catch errors from <code>dataReceived</code> directly since that function isn't a <code>deferred</code> user's generally have control over. You can only call <code>addErrback</code> on <code>deferred</code> objects. Here is an example of how to catch errors:</p> <pre><code>from twisted.internet.protocol import Protocol from twisted.internet.defer import Deferred class Printer(Protocol): def dataReceived(self, data): d = Deferred() d.addCallback(self.display_data) d.addErrback(self.error_func) d.callback(data) def display_data(self, data): print(data) print(toto) # this will raise NameError error def error_func(self, error): print('[!] Whoops here is the error: {0}'.format(error)) </code></pre> <p>A <code>deferred</code> is created in the <code>dataReceived</code> function which will print <code>data</code> and the invalid <code>toto</code> variables. An errorback function (ie. <code>self.error_func()</code>) is chained to catch errors that occur in <code>display_data()</code>. You should strive very hard to not have errors in the dataReceived function itself. This isn't always possible but one should try. Hope this helps</p>
1
2016-08-30T18:31:04Z
[ "python", "asynchronous", "twisted" ]
__init__() missing 1 required positional argument: 'quantity'
39,231,476
<p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p> <p>Thanks all :)</p> <pre><code>class Item(object): def __init__(self, name, style, quantity): self.name = name self.style = style self.quantity = quantity def itemadd(self): inventory.append(Item) class Weapon(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity,) def weaponadd(self): inventory.append(Weapon) class Ammo(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def ammoadd(self): inventory.append(Ammo) class Armour(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def armouradd(self): inventory.append(Armour) Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) </code></pre> <p>Edit: Thanks everyone, this question has been answered :)</p> <p>Edit 2: The lines affected with the error codes:</p> <pre><code>Traceback (most recent call last): File "C:\Stuff\SG\Work\Inventory.py", line 33, in &lt;module&gt; Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) File "C:\Stuff\SG\Work\Inventory.py", line 12, in __init__ Item.__init__(name, style, quantity,) TypeError: __init__() missing 1 required positional argument: 'quantity' </code></pre> <p>Sidenote: All answers below are correct</p>
0
2016-08-30T15:22:46Z
39,231,533
<p>Change </p> <pre><code>Item.__init__(name, style, quantity,) </code></pre> <p>for</p> <pre><code>super().__init__(name, style, quantity) </code></pre>
4
2016-08-30T15:25:25Z
[ "python", "python-3.x" ]
__init__() missing 1 required positional argument: 'quantity'
39,231,476
<p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p> <p>Thanks all :)</p> <pre><code>class Item(object): def __init__(self, name, style, quantity): self.name = name self.style = style self.quantity = quantity def itemadd(self): inventory.append(Item) class Weapon(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity,) def weaponadd(self): inventory.append(Weapon) class Ammo(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def ammoadd(self): inventory.append(Ammo) class Armour(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def armouradd(self): inventory.append(Armour) Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) </code></pre> <p>Edit: Thanks everyone, this question has been answered :)</p> <p>Edit 2: The lines affected with the error codes:</p> <pre><code>Traceback (most recent call last): File "C:\Stuff\SG\Work\Inventory.py", line 33, in &lt;module&gt; Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) File "C:\Stuff\SG\Work\Inventory.py", line 12, in __init__ Item.__init__(name, style, quantity,) TypeError: __init__() missing 1 required positional argument: 'quantity' </code></pre> <p>Sidenote: All answers below are correct</p>
0
2016-08-30T15:22:46Z
39,231,593
<p>Simply use <code>super</code> for inheritance in Python (read <a href="http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods">here</a> for more details):</p> <pre><code>class Weapon(Item): def __init__(self, name, style, quantity = 1): super(Weapon, self).__init__(name, style, quantity) </code></pre>
0
2016-08-30T15:28:49Z
[ "python", "python-3.x" ]
__init__() missing 1 required positional argument: 'quantity'
39,231,476
<p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p> <p>Thanks all :)</p> <pre><code>class Item(object): def __init__(self, name, style, quantity): self.name = name self.style = style self.quantity = quantity def itemadd(self): inventory.append(Item) class Weapon(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity,) def weaponadd(self): inventory.append(Weapon) class Ammo(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def ammoadd(self): inventory.append(Ammo) class Armour(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def armouradd(self): inventory.append(Armour) Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) </code></pre> <p>Edit: Thanks everyone, this question has been answered :)</p> <p>Edit 2: The lines affected with the error codes:</p> <pre><code>Traceback (most recent call last): File "C:\Stuff\SG\Work\Inventory.py", line 33, in &lt;module&gt; Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) File "C:\Stuff\SG\Work\Inventory.py", line 12, in __init__ Item.__init__(name, style, quantity,) TypeError: __init__() missing 1 required positional argument: 'quantity' </code></pre> <p>Sidenote: All answers below are correct</p>
0
2016-08-30T15:22:46Z
39,231,704
<p>You're missing <strong><code>self</code></strong> in the <code>Item._init__()</code>. You can either </p> <ol> <li><p>Add self:</p> <pre><code>class Weapon(Item): def __init__(self, name, style, quantity = 1): Item.__init__(self, name, style, quantity) </code></pre></li> <li><p>Use super: </p> <pre><code>class Weapon(Item): def __init__(self, name, style, quantity = 1): super(Weapon, self).__init__(name, style, quantity) </code></pre></li> </ol>
1
2016-08-30T15:34:02Z
[ "python", "python-3.x" ]
__init__() missing 1 required positional argument: 'quantity'
39,231,476
<p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p> <p>Thanks all :)</p> <pre><code>class Item(object): def __init__(self, name, style, quantity): self.name = name self.style = style self.quantity = quantity def itemadd(self): inventory.append(Item) class Weapon(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity,) def weaponadd(self): inventory.append(Weapon) class Ammo(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def ammoadd(self): inventory.append(Ammo) class Armour(Item): def __init__(self, name, style, quantity = 1): Item.__init__(name, style, quantity) def armouradd(self): inventory.append(Armour) Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) </code></pre> <p>Edit: Thanks everyone, this question has been answered :)</p> <p>Edit 2: The lines affected with the error codes:</p> <pre><code>Traceback (most recent call last): File "C:\Stuff\SG\Work\Inventory.py", line 33, in &lt;module&gt; Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1) File "C:\Stuff\SG\Work\Inventory.py", line 12, in __init__ Item.__init__(name, style, quantity,) TypeError: __init__() missing 1 required positional argument: 'quantity' </code></pre> <p>Sidenote: All answers below are correct</p>
0
2016-08-30T15:22:46Z
39,231,705
<p>Calling <code>Item.__init__</code> directly means you need to pass <code>self</code> as the first argument. Simply doing <code>Item.__init__(name, style, quantity)</code> means it thinks that <code>name</code> is the Item instance (self) and style is the name, quantity is the style and quantity is missing.</p> <p>So you can just specify <code>self</code> as the first argument:</p> <pre><code>Item.__init__(self,name, style, quantity) </code></pre> <p>Or since the <code>__init__</code> is in no way different you can just not override it at all:</p> <pre><code>class Armour(Item): #default to using Item.__init__, no problem here ## def __init__(self, name, style, quantity = 1): ## Item.__init__(name, style, quantity) </code></pre> <p>Although this means that <code>quantity</code> is now a required argument but I don't think that will be an issue.</p> <p>Or as others have already said you can use <code>super()</code> to figure out what methods it should use.</p>
1
2016-08-30T15:34:05Z
[ "python", "python-3.x" ]
How do I run one def function inside of a different def function in python?
39,231,512
<p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly. Here is my code:</p> <pre><code>import time timec = 0 timer = False print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed") timer = True attempt = input("The timer has started!\nType here: ") while timer == True: time.sleep(1) timec = timec +1 if attempt == "abcdefghijklmnopqrstuvwxyz": timer = False print("you completed the alphabet correctly in", timec,"seconds!") else: print("There was a mistake! \nTry again: ") </code></pre> <p>The issue is that it will not let me enter the alphabet. In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work. Any help is appreciated </p>
0
2016-08-30T15:24:31Z
39,231,641
<pre><code>import time start = time.time() attempt = input("Start typing now: ") finish = time.time() if attempt == "abcdefghijklmnopqrstuvwxyz": print "Well done, that took you %s seconds.", round(finish-start, 4) else: print "Sorry, there where errors." </code></pre>
2
2016-08-30T15:31:24Z
[ "python", "function", "time", "timer" ]
How do I run one def function inside of a different def function in python?
39,231,512
<p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly. Here is my code:</p> <pre><code>import time timec = 0 timer = False print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed") timer = True attempt = input("The timer has started!\nType here: ") while timer == True: time.sleep(1) timec = timec +1 if attempt == "abcdefghijklmnopqrstuvwxyz": timer = False print("you completed the alphabet correctly in", timec,"seconds!") else: print("There was a mistake! \nTry again: ") </code></pre> <p>The issue is that it will not let me enter the alphabet. In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work. Any help is appreciated </p>
0
2016-08-30T15:24:31Z
39,231,733
<p>Think carefuly about that you are dong</p> <ol> <li>You ask for a user-entered string</li> <li>While <code>timer</code> equals <code>True</code>, you sleep for one second and increase the count. In this loop, you do not change the <code>timer</code>.</li> </ol> <p>Obviously, once user stopped entering the alphabet and pressed enter, you start an infinite loop. Thus, nothing seems to happen.</p> <p>As other answers suggested, the best solution would be to save the time right before prompting user to enter the alphabet and compare it to the time after he finished.</p>
2
2016-08-30T15:35:04Z
[ "python", "function", "time", "timer" ]
How do I run one def function inside of a different def function in python?
39,231,512
<p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly. Here is my code:</p> <pre><code>import time timec = 0 timer = False print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed") timer = True attempt = input("The timer has started!\nType here: ") while timer == True: time.sleep(1) timec = timec +1 if attempt == "abcdefghijklmnopqrstuvwxyz": timer = False print("you completed the alphabet correctly in", timec,"seconds!") else: print("There was a mistake! \nTry again: ") </code></pre> <p>The issue is that it will not let me enter the alphabet. In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work. Any help is appreciated </p>
0
2016-08-30T15:24:31Z
39,232,098
<p>you could do something like: </p> <pre><code>import datetime alphabet = 'abcdefghijklmnopqrstuvwxyz' print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"') init_time = datetime.datetime.now() success_time = None while True: user_input = input('The timer has started!\nType here: ') if user_input == alphabet: success_time = datetime.datetime.now() - init_time break else: continue print('you did it in %s' % success_time) </code></pre>
0
2016-08-30T15:53:19Z
[ "python", "function", "time", "timer" ]
Python XML Parsing issue
39,231,535
<p>I have an XML as attached below and using python minidom to parse the build.xml. I am trying below python code to parse and retrieve the "name" and "value" tag. I am trying to retrieve the values for "SE_CONFIG","SE_ARCH","PREBUILDID" which have respective value install-csu,macosx,prebuild_7701.</p> <p>Having following challenges.</p> <ol> <li>What is better pythonic way to retrieve respective name and value pair</li> <li><p>How should I catch the exception if there is no "value"</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;build&gt; &lt;actions&gt; &lt;hudson.model.ParametersAction&gt; &lt;parameters&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;StartFrom&lt;/name&gt; &lt;description&gt;&amp;lt;h3&amp;gt;: Trigger downstreamfor this platform&amp;lt;br&amp;gt;&lt;/description&gt; &lt;value&gt;Fetch_Source&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;SE_CONFIG&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;install-csu&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;EMAIL_RCPT&lt;/name&gt; &lt;description&gt;Please enter your email address.&lt;/description&gt; &lt;value&gt;&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;SE_ARCH&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;macosx&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;PREBUILDID&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;prebuild_7701&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;RE_DESCRIPTION&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;BUILD_PRODUCT&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;release&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;/parameters&gt; &lt;/hudson.model.ParametersAction&gt; &lt;/actions&gt; &lt;number&gt;8065&lt;/number&gt; &lt;result&gt;SUCCESS&lt;/result&gt; &lt;duration&gt;3652965&lt;/duration&gt; &lt;charset&gt;US-ASCII&lt;/charset&gt; &lt;keepLog&gt;false&lt;/keepLog&gt; &lt;workspace&gt;/Users/someuser/workspace/build-mac&lt;/workspace&gt; &lt;hudsonVersion&gt;3.2.1&lt;/hudsonVersion&gt; &lt;scm class="hudson.scm.NullChangeLogParser"/&gt; &lt;culprits/&gt; &lt;/build&gt; </code></pre></li> </ol> <hr> <pre><code> import xml.dom.minidom DOMTree=xml.dom.minidom.parse("build.xml") collection=DOMTree.documentElement string_par=collection.getElementsByTagName("hudson.model.StringParameterValue") for each_node in string_par: print each_node.getElementsByTagName('name')[0].childNodes[0].nodeValue print each_node.getElementsByTagName('value')[0].childNodes[0].nodeValue StartFrom Fetch_Source SE_CONFIG install-csu EMAIL_RCPT Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module IndexError: list index out of range </code></pre>
0
2016-08-30T15:25:26Z
39,231,907
<p>Since you asked if there is another way, you can try using <strong>xml.etree.ElementTree</strong>. </p> <p>There is a cool example in the following link, the tags can be defined in the for loop:</p> <p><a href="http://chimera.labs.oreilly.com/books/1230000000393/ch06.html#_solution_96" rel="nofollow">http://chimera.labs.oreilly.com/books/1230000000393/ch06.html#_solution_96</a></p> <p>I hope it helps.</p>
3
2016-08-30T15:43:07Z
[ "python", "xml", "minidom" ]
Python XML Parsing issue
39,231,535
<p>I have an XML as attached below and using python minidom to parse the build.xml. I am trying below python code to parse and retrieve the "name" and "value" tag. I am trying to retrieve the values for "SE_CONFIG","SE_ARCH","PREBUILDID" which have respective value install-csu,macosx,prebuild_7701.</p> <p>Having following challenges.</p> <ol> <li>What is better pythonic way to retrieve respective name and value pair</li> <li><p>How should I catch the exception if there is no "value"</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;build&gt; &lt;actions&gt; &lt;hudson.model.ParametersAction&gt; &lt;parameters&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;StartFrom&lt;/name&gt; &lt;description&gt;&amp;lt;h3&amp;gt;: Trigger downstreamfor this platform&amp;lt;br&amp;gt;&lt;/description&gt; &lt;value&gt;Fetch_Source&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;SE_CONFIG&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;install-csu&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;EMAIL_RCPT&lt;/name&gt; &lt;description&gt;Please enter your email address.&lt;/description&gt; &lt;value&gt;&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;SE_ARCH&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;macosx&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;PREBUILDID&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;prebuild_7701&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;RE_DESCRIPTION&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;hudson.model.StringParameterValue&gt; &lt;name&gt;BUILD_PRODUCT&lt;/name&gt; &lt;description&gt;&lt;/description&gt; &lt;value&gt;release&lt;/value&gt; &lt;/hudson.model.StringParameterValue&gt; &lt;/parameters&gt; &lt;/hudson.model.ParametersAction&gt; &lt;/actions&gt; &lt;number&gt;8065&lt;/number&gt; &lt;result&gt;SUCCESS&lt;/result&gt; &lt;duration&gt;3652965&lt;/duration&gt; &lt;charset&gt;US-ASCII&lt;/charset&gt; &lt;keepLog&gt;false&lt;/keepLog&gt; &lt;workspace&gt;/Users/someuser/workspace/build-mac&lt;/workspace&gt; &lt;hudsonVersion&gt;3.2.1&lt;/hudsonVersion&gt; &lt;scm class="hudson.scm.NullChangeLogParser"/&gt; &lt;culprits/&gt; &lt;/build&gt; </code></pre></li> </ol> <hr> <pre><code> import xml.dom.minidom DOMTree=xml.dom.minidom.parse("build.xml") collection=DOMTree.documentElement string_par=collection.getElementsByTagName("hudson.model.StringParameterValue") for each_node in string_par: print each_node.getElementsByTagName('name')[0].childNodes[0].nodeValue print each_node.getElementsByTagName('value')[0].childNodes[0].nodeValue StartFrom Fetch_Source SE_CONFIG install-csu EMAIL_RCPT Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module IndexError: list index out of range </code></pre>
0
2016-08-30T15:25:26Z
39,243,890
<p>Get it done through ElementTree</p> <pre><code> doc =xml.etree.ElementTree.parse('build.xml') for node in doc.iter('hudson.model.StringParameterValue'): print str(node.find('name').text) + '\t' + str(node.find('value').text) </code></pre>
1
2016-08-31T07:59:26Z
[ "python", "xml", "minidom" ]
Cosine similarity yields 'nan' values pt.II
39,231,600
<p>This is the other side of this question: <a href="http://stackoverflow.com/questions/33651788/cosine-similarity-yields-nan-values">Cosine similarity yields &#39;nan&#39; values</a> . In that topic, auther coded the metrics by himself, but iam using scipy's cosine: (<code>ratings</code> is 71869x10000)</p> <pre><code>A = ratings[:,100] A = A.reshape(1,A.shape[0]) books_similarity = np.empty([1, ratings.shape[0]]) for book in range(10000): books_similarity[0,book] = -cosine(A, ratings[:,book].reshape(1,A.shape[1]))+1 </code></pre> <p>BUT it outputs: 0, one 1(for for itself) and NaN. So the solution in the topic i mentioned before, is not for me, becuase, iam using scipy. What should i do?</p> <p>P.S: then i delete "1" from array and do:</p> <pre><code>m = np.argmax(books_similarity) books_similarity[0,m] </code></pre> <p>It returns "NaN"</p> <p>P.S.S: First, i had a pickle file, decoded it into CSR, but then used numpy. I think, i should consider everything as np arrays, right?</p>
1
2016-08-30T15:29:04Z
39,232,797
<p>The cosine distance is not defined if one of the input vectors is all 0. <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html" rel="nofollow"><code>scipy.spatial.distance.cosine</code></a> returns <code>nan</code> in that case:</p> <pre><code>In [70]: a Out[70]: array([0, 1, 1, 1, 0, 0, 0, 1, 0, 0]) In [71]: b Out[71]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) In [72]: cosine(a, b) /Users/warren/miniconda3/lib/python3.5/site-packages/scipy/spatial/distance.py:329: RuntimeWarning: invalid value encountered in true_divide dist = 1.0 - np.dot(u, v) / (norm(u) * norm(v)) Out[72]: nan </code></pre> <p>This may be happening in your code. Before calling <code>cosine</code>, check that neither input is all 0.</p> <hr> <p>P.S. I haven't tried to decipher what you are doing with <code>A</code> and <code>ratings</code>, but I suspect you'll eventually want to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a> with the argument <code>method='cosine'</code>.</p>
1
2016-08-30T16:35:22Z
[ "python", "numpy", "scipy" ]
ConnectionError with Messenger bot
39,231,607
<p>I'm using messenger bot with pymessenger (here the link <a href="https://github.com/davidchua/pymessenger" rel="nofollow">https://github.com/davidchua/pymessenger</a> ). Sometimes, when I try to send messages to the user using the bot.send_text_message() or one of the other functions to send messages of the python package, I got the following error:</p> <pre><code> File "C:\Python27\lib\site-packages\pymessenger\bot.py", line 29, in send_text_message return self._send_payload(payload) File "C:\Python27\lib\site-packages\pymessenger\bot.py", line 76, in _send_payload result = requests.post(self.base_url, json=payload).json() File "C:\Python27\lib\site-packages\requests\api.py", line 111, in post return request('post', url, data=data, json=json, **kwargs) File "C:\Python27\lib\site-packages\requests\api.py", line 57, in request return session.request(method=method, url=url, **kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 585, in send r = adapter.send(request, **kwargs) File "C:\Python27\lib\site-packages\requests\adapters.py", line 467, in send raise ConnectionError(e, request=request) ConnectionError: HTTPSConnectionPool(host='graph.facebook.com', port=443): Max retries exceeded with url: /v2.6/me/messages?access_token=&lt;my_token&gt; (Caused by NewConnectionError('&lt;requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x00000000422A40B8&gt;: Failed to establish a new connection: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) </code></pre> <p>I thought that maybe I did too many requests to Facebook, but it's just me to use the bot and the number of requests I'm doing is the one of a normal chat so I guess it should be something else, but I don't get what. I'm using ngrok for the callbacks. </p>
0
2016-08-30T15:29:47Z
39,232,489
<p>try to catch the HTTPSConnectionPool exception and look into its args to see the details I mean something like</p> <pre><code>except HTTPSConnectionPool as e: e.args </code></pre>
0
2016-08-30T16:16:48Z
[ "python", "bots", "facebook-messenger" ]
Dynamic Variable Naming for tree[Python]
39,231,687
<p>I have made a tree structure for preorder traversal. And I can manually name all the variables.</p> <p>Is there a way to make a variable. I need a tree structure as follows:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... </code></pre> <p>and so on.</p> <pre><code>import time class Node: def __init__(self, data): self.data = data self.left = None self.right = None def fetch(root): if root is None: return x = [] x.append(root) while(len(x) &gt; 0): node = x.pop() print (node.data) if node.right is not None: x.append(node.right) if node.left is not None: x.append(node.left) root = Node(0) root.left = Node(1) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(5) root.right.right =Node(6) root.left.left.left=Node(7) root.left.left.right=Node(8) start_time=time.time() fetch(root) end_time=time.time() print ("Object time :"+str(end_time-start_time)) </code></pre> <p>I want to have 1M nodes. Which is not possible to type in manually. Could someone please suggest a function or way of doing it? Thanks!</p>
-1
2016-08-30T15:33:23Z
39,231,948
<p>It seems that you are going from left-to-right on the tree. If we represent the path in binary, the leftmost branch (on the forth layer down) as <code>0000</code> (<code>.left.left.left.left</code>) then then next number would be <code>0001</code> (<code>.left.left.left.right</code>). Then it would be <code>0010</code> (<code>.left.left.right.left</code>). This could be implemented like this:</p> <pre><code>root = Node(0) level = 1 branch = 0 for n in range(1, 1000001): *current_branch, final = '{:0{}b}'.format(branch, level) # Makes current_branch the binary equivalent of &lt;branch&gt; # padded with '0's to be &lt;level&gt; length # and final is the last digit place = root for direction in current_branch: # Iteratively gets the correct path down the tree # direction = ('left', 'right')[int(direction)] # '0' -&gt; 'left;' '1' -&gt; 'right' place = getattr(place, ('left', 'right')[int(direction)]) setattr(place, final, Node(n)) # Sets the final direction to the right Node branch += 1 if branch &gt;= 2 ** level: # If the branch is to the right of the right-most branch branch = 0 level += 1 # Reset the branch and go a level deeper </code></pre>
0
2016-08-30T15:45:16Z
[ "python", "variables", "dynamic", "tree", "traversal" ]
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list
39,231,826
<p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numbers of indices.</p> <pre><code>INPUT 'ABCDE', list_of_configurations OUTPUT ['ABCDE'] ['A', 'BCDE'] ['AB', 'CDE'] ... ... ['A', 'B', 'C', 'D', 'E'] </code></pre> <p>Final note, I want it be dynamic in that it can apply to a string of 5 characters or a string of 9 characters. I was trying to figure this out but I think it is beyond my current skill level.</p>
3
2016-08-30T15:39:15Z
39,232,117
<p>That is a classic brute force problem. You have to generate all options of where you can split the string. You can either split it between each two letters or not. </p> <p>For string of length n there are n - 1 places you can possibly split it</p> <pre><code>a b c d e ^ ^ ^ ^ </code></pre> <p>Thus, each binary (with only 0s (if you do not want to split string at that location) and 1s (if you want to split string at that location)) array of length <code>n - 1</code> corresponds to one possible split option. I.e.</p> <pre><code>[1, 0, 0, 0] &lt;=&gt; ['a', 'bcde'] [1, 0, 1, 0] &lt;=&gt; ['a', 'bc', 'de'] </code></pre> <p>From each array you can generate the splitting. Thus, the problem is equivalent to looping through all the possible binary arrays.</p> <p>You could do it using brute force recursion, but that is much easier to do just looping through the numbers from 0 to <code>2 ^ (n - 1)</code> and generating array based on binary representation of this number.</p> <p>With all this said, that is the code that solves your problem.</p> <pre><code>def gen_all_splits(s): result = [] for i in range(2 ** (len(s) - 1)): split = bin(i).replace('0b', '') split = '0' * (len(s) - len(split)) + split current_string_split = [''] for j in range(len(split)): if split[j] == '0': current_string_split[-1] += s[j] else: current_string_split.append(s[j]) result.append(current_string_split) return result print(gen_all_splits('abcdef')) </code></pre> <hr> <p>P.S. Thanks to comment, I just realized that I answered to broader problem that yours are. I will keep the answer, but you can use the piece relevant to generating the string by split configuration:</p> <pre><code> current_string_split = [''] for j in range(len(split)): if split[j] == '0': current_string_split[-1] += s[j] else: current_string_split.append(s[j]) </code></pre>
3
2016-08-30T15:54:37Z
[ "python", "string", "list" ]
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list
39,231,826
<p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numbers of indices.</p> <pre><code>INPUT 'ABCDE', list_of_configurations OUTPUT ['ABCDE'] ['A', 'BCDE'] ['AB', 'CDE'] ... ... ['A', 'B', 'C', 'D', 'E'] </code></pre> <p>Final note, I want it be dynamic in that it can apply to a string of 5 characters or a string of 9 characters. I was trying to figure this out but I think it is beyond my current skill level.</p>
3
2016-08-30T15:39:15Z
39,232,152
<p>If you want to apply that configuration list of lists containing possible "slices" of a string, here is a way to do it - basically, we take a slice and pass the rest of the string to the next step:</p> <pre><code>s = 'ABCDE' c = [[5], [4, 1], [3, 2], [1, 1, 1, 1, 1]] for item in c: result = [] s_copy = s for index in item: result.append(s_copy[:index]) s_copy = s_copy[index:] print(result) </code></pre> <p>Prints:</p> <pre><code>['ABCDE'] ['ABCD', 'E'] ['ABC', 'DE'] ['A', 'B', 'C', 'D', 'E'] </code></pre>
3
2016-08-30T15:56:27Z
[ "python", "string", "list" ]
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list
39,231,826
<p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numbers of indices.</p> <pre><code>INPUT 'ABCDE', list_of_configurations OUTPUT ['ABCDE'] ['A', 'BCDE'] ['AB', 'CDE'] ... ... ['A', 'B', 'C', 'D', 'E'] </code></pre> <p>Final note, I want it be dynamic in that it can apply to a string of 5 characters or a string of 9 characters. I was trying to figure this out but I think it is beyond my current skill level.</p>
3
2016-08-30T15:39:15Z
39,232,303
<p>The previous answer is correct, but Python allows us to write this in much more compact fashion:</p> <pre><code>def my_split(string, config): return [string[sum(config[:i]):sum(config[:i+1])] for i in range(len(config))] </code></pre> <p>To get the result for all configurations, you simply need to loop over the given configurations and call the my_split function.</p>
0
2016-08-30T16:04:50Z
[ "python", "string", "list" ]
How to write a txt with the following list using pandas?
39,231,865
<p>Hello I am using pandas to process a excel file my code looks as follows:</p> <pre><code>df = xl.parse("Sheet1") important_Parameters="bash generate.sh --companyCode"+" "+df[u'Company Code '].astype(str)+" "+"--isaADD"+df[u'TP Interchange Address '].astype(str)+" "+"--gsADD"+" "+df[u'TP Functional Group Address '].astype(str) print(important_Parameters) </code></pre> <p>Everything works well, when I print my code it looks fine, I wish to write a txt file with the contain of my object called:</p> <pre><code>important_Parameters </code></pre> <p>I tried with:</p> <pre><code>important_Parameters.to_pickle("important.txt") </code></pre> <p>but the result does not seem like the printing, I believe that is due to the way that I took to write in disk,</p> <p>I also tried with:</p> <pre><code>important_Parameters.to_string("importantParameters2.txt") </code></pre> <p>However this gave me a more friendly representation of the data but the result is including the number of the raw and also the rows's are not completed they look as follows:</p> <pre><code>bash generate.sh --companyCode 889009d --isaADD... </code></pre> <p>it is showing this ...</p> <p>I would like to appreciate any suggestion to produce a simple .txt file called importante.txt with my result, the containing of important_Parameters, thanks for the support</p> <p>I order to include more details my output looks like, I mean the result of the print:</p> <pre><code>0 bash generate.sh --companyCode 323232 --isaADD... 1 bash generate.sh --companyCode 323232 --isaADD... 2 bash generate.sh --companyCode 323232 --isaADD... </code></pre>
2
2016-08-30T15:41:17Z
39,231,987
<p>Panda dataframes have more than a few methods for saving to files. Have you tried <code>important_Parameters.to_csv("important.csv")</code>? I'm not certain what you want the output to look like.</p> <p>If you want it tab-separated, you can try: <code>important_Parameters.to_csv("important.csv", sep='\t')</code></p> <p>If the file absolutely must end in <code>.txt</code>, just change it to: <code>important_Parameters.to_csv("important.txt")</code>. CSVs are just specifically formatted text files so this shouldn't be a problem.</p>
2
2016-08-30T15:47:09Z
[ "python", "pandas" ]
How to get the absolute url in python
39,231,900
<p>I am currently working on a http server in python. I have subclassed BaseHttpRequestHandler to handler a get/post request. As per documentation, BaseHttpRequestHandler has an instance variable path, but how do i get the full request url</p> <p>Example <a href="http://www.cnn.com/index.html" rel="nofollow">http://www.cnn.com/index.html</a></p> <pre><code>Class handler(BaseHTTPRequestHandler): def do_GET(self): # This gives me /index.html print self.path </code></pre> <p>But is there a way I can get full url?</p>
0
2016-08-30T15:42:54Z
39,232,224
<p>You can get the server name (and port, if the server is on a specific port) via <code>self.server.server_name</code> and <code>self.server.server_port</code>. Then just concatenate them - assuming you have a port, and that the server name doesn't include a trailing '/' (can't check at the moment, myself):</p> <pre><code>full_url = ''.join([name, ':', port, '/', path]) </code></pre> <p>If you don't have a port specified:</p> <pre><code>full_url = '/'.join([name, path]) </code></pre> <p>In both cases, <code>path</code> is self.path, and <code>name</code> and <code>port</code> are as explained at the top.</p>
0
2016-08-30T15:59:39Z
[ "python", "python-2.7", "http", "http-headers" ]
Sympy coeff not consistent with as_independent
39,231,911
<p>I have the following snippet of code</p> <pre><code>import sympy a = sympy.symbols('a') b = sympy.symbols('b') c = sympy.symbols('c') print((a*b).coeff(c,0)) print((a*b).as_independent(c)[0]) </code></pre> <p>I don't understand why the two print statements print different output. According to the documentation of coeff:</p> <pre><code>You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None): &gt;&gt;&gt; (3 + 2*x + 4*x**2).coeff(x, 0) 3 </code></pre> <p>Is this a bug in sympy, or do I miss something?</p>
2
2016-08-30T15:43:21Z
39,399,240
<p>It's a bug. I have a pull request fixing it <a href="https://github.com/sympy/sympy/pull/11590" rel="nofollow">here</a>. </p>
1
2016-09-08T19:58:47Z
[ "python", "sympy" ]
Django AUTH_USER_MODEL not registering custom User class
39,231,917
<p>I've got this setup in my models</p> <p>from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models</p> <pre><code>class AccountManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): . . . def create_superuser(self, email, password, **kwargs): . . . class Account(AbstractBaseUser): . . . </code></pre> <p>In settings, I have done this:</p> <pre><code>AUTH_USER_MODEL = 'authentication.Account' </code></pre> <p>but I continue to get this error:</p> <pre><code>AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.Account' </code></pre> <p>Please I would like to know why and how to fix this</p>
0
2016-08-30T15:43:27Z
39,232,666
<p>Explicitly specify the manager inside your custom user model:</p> <pre><code>class Account(AbstractBaseUser): objects = AccountManager() .... </code></pre>
0
2016-08-30T16:28:07Z
[ "python", "django" ]
What's the correct way to access methods of a member variable in a class pointing to an object?
39,231,932
<p>What's the correct way to define/access methods of a member variable in a class pointing to an object?</p> <p>For example, I have a class <code>Foo</code> that has a method <code>foo_method</code>:</p> <pre><code>class Foo: def foo_method(self): return 'bar' </code></pre> <p>Now, in another class <code>Bar</code>, I'd like to store an object to this class (I do not want <code>Bar</code> to inherit <code>Foo</code>).</p> <p>What is the correct/recommended way to define class <code>Bar</code>?</p> <pre><code>class Bar: def __init__(self): self.foo = Foo() # OR class Bar: def __init__(self): self.foo = Foo() def bar_method(self): return self.foo.bar() </code></pre> <p>The former will allow me to use:</p> <pre><code>x = Bar() x.foo.foo_method() </code></pre> <p>But, with this I'm directly accessing methods of a member variable (strong coupling).</p> <p>The benefits I see with this approach are:</p> <ul> <li>I don't have to wrap every new method that gets added to class <code>Foo</code>.</li> <li><code>Bar</code> may contain more member variables pointing to other classes. Not wrapping them keeps <code>Bar</code> smaller and manageable in size.</li> <li>The auto-completion facility from IDE (PyCharm, etc.) or IPython helps inspect <code>bar</code> like a menu (<code>x.foo</code>) followed by a sub-menu (<code>x.foo.foo_method()</code>, <code>x.bar.foobar()</code>, etc.) making it easier to develop code.</li> <li>Functional programming look-n-feel (not sure if this a pro or con)</li> </ul> <p>The cons are strong coupling, not encapsulating internal details of <code>foo</code>, etc.</p> <p>I wanted to check if this a recommended practice? And/or if there are any guidelines related to this (kind of implementing a composite pattern)?</p> <p>Any inputs/pointers will be highly appreciated!</p>
0
2016-08-30T15:44:15Z
39,237,874
<p>There are no real guidelines, but if you make a <code>bar_method()</code> that explicitly calls <code>foo.bar()</code> and does nothing in between it's the exact same coupling and less convenient.</p> <p>Python's idioms include "<a href="http://docs.python-guide.org/en/latest/writing/style/#we-are-all-responsible-users" rel="nofollow">We are all responsible users</a>" and in that case, when encapsulation does not provide you any benefit, I personally wouldn't use proxy functions. Leaving it as is results in smaller code which is easier to maintain and is more accessible. Auto-completion as you mentioned is just an added bonus.</p>
2
2016-08-30T22:12:16Z
[ "python", "design-patterns", "python-3.5", "composition" ]
keras: multiple w_constraints
39,231,977
<p>I want a set of weights to be constrained to have a fixed norm (as in <code>unitnorm</code>) and non-negative values (as in <code>nonneg</code>). This pair of constraints is useful in some kinds of optical modeling.</p> <p>I'm not a Python expert, so I tried <code>W_constraint = nonneg(), W_constraint = maxnorm(1))</code> and got <code>SyntaxError: keyword argument repeated</code>. Is there a better way? Thanks in advance!</p>
0
2016-08-30T15:46:38Z
39,259,405
<p>If you look at the topology.py file in the keras source code it has a property:</p> <pre><code> @property def constraints(self): cons = {} for layer in self.layers: for key, value in layer.constraints.items(): if key in cons: raise Exception('Received multiple constraints ' 'for one weight tensor: ' + str(key)) cons[key] = value return cons </code></pre> <p>which raises an exception when multiple constraints are received for one weight tensor. I think the best way to do this would be to implement a custom constraint (say nonneg_and_maxnorm?), you can see examples of implemented constraints in constraints.py in the keras source code.</p>
1
2016-08-31T21:37:12Z
[ "python", "constraints", "keras" ]
How to map results of `dask.DataFrame` to csvs
39,231,984
<p>I create a dataframe with <code>df=dask.DataFrame.read_csv('s3://bucket/*.csv')</code>. When i execute a <code>df[df.a.isnull()].compute</code> operation, i get a set of rows returned that match the filter criteria. I would like to know which files do these returned rows belong in so that i could investigate why such records have null values. The <code>DataFrame</code> has billions of rows and the records with the missing values are in single digits. Is there an efficient way to do so?</p>
1
2016-08-30T15:46:53Z
39,232,198
<p>If your CSV files are small then I recommend creating one partition per file</p> <pre><code>df = dd.read_csv('s3://bucket/*.csv', blocksize=None) </code></pre> <p>And then computing the number of null elements per partition:</p> <pre><code>counts = df.a.isnull().map_partitions(sum).compute() </code></pre> <p>You could then find the filenames</p> <pre><code>from s3fs import S3FileSystem s3 = S3FileSystem() filenames = s3.glob('s3://bucket/*.csv') </code></pre> <p>And compare the two</p> <pre><code>dict(zip(filenames, counts)) </code></pre>
0
2016-08-30T15:58:43Z
[ "python", "dask" ]
Extracting tables using pandas read_html function?
39,232,013
<p>This is an unusual problem. I am trying to extract a table from certain website(link cant be given because of security). The problem is that the site will load the table when accessed through website but when we use <code>inspect element</code> on any values/tables on that table it is not visible. It just show <code>&lt;html&gt;_&lt;/html&gt;</code> with some scripts and links inside. Initially I tried to extract table using <code>beautifulsoup</code> but it was unsuccessful. Then I used pandas <code>pandas.read_html(html)</code> but the site contains more than one table and its output is something like this</p> <pre><code>[ Code Name 0 A John 1 B Terry 2 C Kitty Column 1 Column 2 Column 3 0 1 0.6173661242 8 1 2 0.7232098163 20 2 3 0.9954581943 39 3 4 0.5595425507 18 4 5 0.9644025159 20 5 6 0.3914102544 29 6 7 0.0154642132 49 .... [873 rows x 3 columns], 0\n\t\t\t\t\t\t\t\t\t 0 0 ] </code></pre> <p>Then I tried something like this <code>pandas.read_html(html, match="Column 1")</code> it returns this error</p> <blockquote> <p>ValueError: No tables found matching pattern 'Column 1' </p> </blockquote> <p>any idea how we can use read_html to extract tables?</p>
0
2016-08-30T15:48:33Z
39,232,261
<p>When data scraping off a secure website, the website can be using Java to load the tables so you never see the HTML-styled code. This could be why BeautifulSoup is not returning anything. </p> <p>Does the "scripts and links inside" look like Java? </p> <p>Maybe have a look at <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium?</a></p>
0
2016-08-30T16:01:55Z
[ "python", "html", "pandas", "web-scraping" ]
Smartsheet API failure to recognize number values when creating row objects
39,232,147
<p>I need help adding numbers to a row update using the Smartsheet Python SDK. I am attempting to update/add specific cell values programmatically via a Python script. An example of the code I am using is:</p> <pre><code>import smartsheet smartsheet = smartsheet.Smartsheet(TokenString) row = smartsheet.models.Row() row.to_top = True row.cells.append({ 'column_id': ColumnID, 'value': x }) action = smartsheet.Sheets.add_rows(SheetID, [row]) </code></pre> <p>This seems to work just fine if the <code>'value'</code> I pass is a string. However, when I pass a number it does nothing. I have taken a look at the cell object created (simply printing it, which appears to be a JSON string) it shows <code>"value": null</code>. Again, if I change this to a string the value shows just fine.</p> <p>I have tried this with both integer and float values. Both return null. Any help getting this to work would be very much appreciated.</p>
0
2016-08-30T15:56:11Z
39,257,507
<p>Trying this out myself I experienced the same thing. Only representing the value as a string did it enter into my sheet, otherwise it was a null/blank row. I have reported this as an issue on Github for the <a href="https://github.com/smartsheet-platform/smartsheet-python-sdk/issues/49" rel="nofollow">Python SDK</a>. As a workaround I saw that working with the API directly rather than using the SDK does allow for this function.</p>
1
2016-08-31T19:24:02Z
[ "python", "smartsheet-api" ]
Python speech recognition error converting mp3 file
39,232,150
<p>My first try on audio to text. </p> <pre><code>import speech_recognition as sr r = sr.Recognizer() with sr.AudioFile("/path/to/.mp3") as source: audio = r.record(source) </code></pre> <p>When I execute the above code, the following error occurs,</p> <pre><code>&lt;ipython-input-10-72e982ecb706&gt; in &lt;module&gt;() ----&gt; 1 with sr.AudioFile("/home/yogaraj/Documents/Python workouts/Python audio to text/show_me_the_meaning.mp3") as source: 2 audio = sr.record(source) 3 /usr/lib/python2.7/site-packages/speech_recognition/__init__.pyc in __enter__(self) 197 aiff_file = io.BytesIO(aiff_data) 198 try: --&gt; 199 self.audio_reader = aifc.open(aiff_file, "rb") 200 except aifc.Error: 201 assert False, "Audio file could not be read as WAV, AIFF, or FLAC; check if file is corrupted" /usr/lib64/python2.7/aifc.pyc in open(f, mode) 950 mode = 'rb' 951 if mode in ('r', 'rb'): --&gt; 952 return Aifc_read(f) 953 elif mode in ('w', 'wb'): 954 return Aifc_write(f) /usr/lib64/python2.7/aifc.pyc in __init__(self, f) 345 f = __builtin__.open(f, 'rb') 346 # else, assume it is an open file object already --&gt; 347 self.initfp(f) 348 349 # /usr/lib64/python2.7/aifc.pyc in initfp(self, file) 296 self._soundpos = 0 297 self._file = file --&gt; 298 chunk = Chunk(file) 299 if chunk.getname() != 'FORM': 300 raise Error, 'file does not start with FORM id' /usr/lib64/python2.7/chunk.py in __init__(self, file, align, bigendian, inclheader) 61 self.chunkname = file.read(4) 62 if len(self.chunkname) &lt; 4: ---&gt; 63 raise EOFError 64 try: 65 self.chunksize = struct.unpack(strflag+'L', file.read(4))[0] </code></pre> <p>I don't know what I'm going wrong. Can someone say me what I'm wrong in the above code?</p>
0
2016-08-30T15:56:19Z
39,232,767
<p><code>Speech recognition</code> supports WAV file format. Here is a sample WAV to text program using <code>speech_recognition</code>:</p> <h3>Sample code (Python 3)</h3> <pre><code>import speech_recognition as sr r = sr.Recognizer() with sr.AudioFile("woman1_wb.wav") as source: audio = r.record(source) try: s = r.recognize_google(audio) print("Text: "+s) except Exception as e: print("Exception: "+str(e)) </code></pre> <h3>Output:</h3> <pre><code>Text: to administer medicine to animals is frequency of very difficult matter and yet sometimes it's necessary to do so </code></pre> <p>Used WAV File URL: <a href="http://www-mobile.ecs.soton.ac.uk/hth97r/links/Database/woman1_wb.wav" rel="nofollow">http://www-mobile.ecs.soton.ac.uk/hth97r/links/Database/woman1_wb.wav</a></p>
2
2016-08-30T16:33:52Z
[ "python", "speech-recognition", "speech-to-text" ]
Extending Flask class as main App
39,232,166
<p>I'm learning Flask and am a bit confused about how to structure my code. So I tried to extend Flask main class as follows:</p> <pre><code>from flask import Flask, ... class App(Flask): def __init__(self, import_name, *args, **kwargs): super(App, self).__init__(import_name, *args, **kwargs) </code></pre> <p>Note that I am aware of that this may be a completely wrong approach. <br>So that when I want to start the app I do:</p> <pre><code>app = App(__name__) if __name__ == '__main__': app.run() </code></pre> <p>This way I can order my methods and routes in the class, but the problem is when using self-decorators:</p> <pre><code>@route('/') def home(self, context=None): context = context or dict() return render_template('home.html', **context) </code></pre> <p>Which raises an error as <code>unresolved reference 'route'</code>. I guess this is not the way I should be structuring the app. How should I do it instead or how do I get the error fixed?</p>
1
2016-08-30T15:57:10Z
39,232,991
<p>Doing this doesn't make sense. You would subclass <code>Flask</code> to change its internal behavior, not to define your routes as class methods.</p> <p>Instead, you're looking for <a href="http://flask.pocoo.org/docs/0.11/blueprints/" rel="nofollow">blueprints</a> and the <a href="http://flask.pocoo.org/docs/0.11/patterns/appfactories/" rel="nofollow">app factory pattern</a>. Blueprints divide your views into groups without requiring an app, and the factory creates and sets up the app only when called.</p> <p><code>my_app/users/__init__.py</code></p> <pre><code>from flask import Blueprint bp = Blueprint('users', __name__, url_prefix='/users') </code></pre> <p><code>my_app/users/views.py</code></p> <pre><code>from flask import render_template from my_app.users import bp @bp.route('/') def index(): return render_template('users/index.html') </code></pre> <p><code>my_app/__init__.py</code></p> <pre><code>def create_app(): app = Flask(__name__) # set up the app here # for example, register a blueprint from my_app.users import bp app.register_blueprint(bp) return app </code></pre> <p><code>run.py</code></p> <pre><code>from my_app import create_app app = create_app() </code></pre> <p>Run the dev server with:</p> <pre><code>FLASK_APP=run.py FLASK_DEBUG=True flask run </code></pre> <p>If you need access to the app in a view, use <code>current_app</code>, just like <code>request</code> gives access to the request in the view.</p> <pre><code>from flask import current_app from itsdangerous import URLSafeSerializer @bp.route('/token') def token(): s = URLSafeSerializer(current_app.secret_key) return s.dumps('secret') </code></pre> <hr> <p>If you <em>really</em> want to define routes as methods of a Flask subclass, you'll need to use <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Flask.add_url_rule" rel="nofollow"><code>self.add_url_rule</code></a> in <code>__init__</code> rather than decorating each route locally.</p> <pre><code>class MyFlask(Flask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs): self.add_url_rule('/', view_func=self.index) def index(self): return render_template('index.html') </code></pre> <p>The reason <code>route</code> (and <code>self</code>) won't work is because it's an instance method, but you don't have an instance when you're defining the class.</p>
3
2016-08-30T16:46:32Z
[ "python", "flask" ]
handle errors in Python ArgumentParser
39,232,167
<p>I want to manually handle the situation where <code>parse_args()</code> throws an error in case of a unknown value for an argument. For example: If I have the following python file called <code>script.py</code>:</p> <pre><code>argp = argparse.ArgumentParser(description='example') argp.add_argument('--compiler', choices=['default', 'clang3.4', 'clang3.5']) args = argp.parse_args() </code></pre> <p>and I run the script with the following args <code>python script.py --compiler=foo</code> it throws the following error:</p> <pre><code>error: argument --compiler: invalid choice: 'foo' (choose from 'default', 'clang3.4', 'clang3.5') SystemExit: 2 </code></pre> <p>What do I need to do in order to handle this behaviour myself instead of the script quitting itself? One idea is to subclass <code>argparse.ArgumentParser</code> and override <code>parse_args()</code> or just monkey patch the method but I was wondering if there's a better way that does not require overriding the standard library behaviour?</p>
2
2016-08-30T15:57:11Z
39,233,308
<p>The whole point to defining choices is to make the parser complain about values that are not in the list. But there are some alternatives:</p> <ul> <li><p>omit choices (include them in the help text if you want), and do your own testing after parsing. <code>argparse</code> doesn't have to do everything for you. It's main purpose is to figure out what your user wants.</p></li> <li><p>redefine the <code>parser.error</code> method (via subclassing is best) to redirect the error from <code>sys.exit</code>. But you'll have to parse the error message to distinguish between this error and other ones that the parser might raise.</p></li> <li><p>define a <code>type</code> function that checks for choices, and makes the default substitution.</p></li> </ul> <p>The parsing of the '--compiler' option goes something like this:</p> <ul> <li>grab the string argument after the <code>--compiler</code> flag</li> <li>pass it through the <code>type</code> function. Default is <code>lambda x:x</code>. <code>int</code> converts it to integer, etc. Raise <code>ValueError</code> is value is bad.</li> <li>check the returned value against the <code>choices</code> list (if any)</li> <li>use the <code>action</code> to add the value to the Namespace (default simply stores it).</li> </ul> <p>Error in any of these steps produces an <code>ArgumentError</code> which is trapped by the <code>parser.error</code> method and passed to a <code>parser.exit</code> method.</p> <p>Since the <code>store_action</code> occurs after <code>type</code> and <code>choices</code> checking, a custom action won't bypass their errors.</p> <p>Here's a possible <code>type</code> solution (not tested)</p> <pre><code>def compile_choices(astr): if astr in ['default', 'clang3.4', 'clang3.5']: return astr else: return 'default' # could raise ValueError('bad value') if there are some strings you don't like argp.add_argument('--compiler', type=compile_choices) </code></pre> <p>=================</p> <p>If <code>compile_choices</code> takes other arguments, such as the list of choices or the default, you'll need to wrap in some why that defines those values before parsing.</p> <p>An example accepting a binary string representation:</p> <pre><code>parser.add_argument('--binary', type=lambda x: int(x, base=2), help='integer in binary format', default='1010') </code></pre> <p>or</p> <pre><code>parser.add_argument('--binary', type=functools.partial(int, base=2), default='1010') </code></pre>
2
2016-08-30T17:07:17Z
[ "python", "python-2.7", "python-3.x", "argparse" ]
Is my model underfitting, tensorflow?
39,232,176
<p>My loss first decreased for few epochs but then started increasing and then increased up to a certain point and then stopped moving. I think now it has converged. Now, can we say that my model is underfitting? Because my interpretation is that (slide 93 <a href="http://cs231n.stanford.edu/slides/winter1516_lecture5.pdf" rel="nofollow">link</a>) if my loss is going down and then increasing it means that I have a high learning rate and which after every 2 epochs I'm decaying so after few epochs loss stopped increasing because learning rate is low now, because I'm still decaying my learning rate, now loss should start decreasing again, according to slide 93 because learning rate is low, but it doesn't. Can we say that loss is not decreasing further because my model is underfitting?</p>
0
2016-08-30T15:57:25Z
39,234,296
<p>So, to summarize, the loss on the training data:</p> <ul> <li>first went down</li> <li>then it went up again</li> <li>then it remains at the same level</li> <li>then the learning rate is decayed</li> <li>and the loss doesn't go back down again (still stays the same with decayed learning rate)</li> </ul> <p>To me it sounds like the learning rate was too high initially, and it got stuck in a local minimum afterwards. Decaying the learning rate at that point, once it's already stuck in a local minimum, is not going to help it escape that minimum. Setting the initial learning rate at a lower value is more likely to be beneficial, so that you don't end up in the ''bad'' local minimum to begin with.</p> <p>It is possible that your model is now underfitting, and that making the model more complex (more nodes in hidden layers, for instance) would help. This is not necessarily the case though. </p> <p>Are you using any techniques to avoid overfitting? For example, regularization and/or dropout? If so, it is also possible that your model was initially <em>overfitting</em> (when the loss was going down, before it went back up again). To get a better idea of what's going on, it would be beneficial to plot not only your loss on the training data, but also loss on a validation set. If the loss on your training data drops significantly below the loss on the validation data, you know it's overfitting.</p>
2
2016-08-30T18:06:19Z
[ "python", "machine-learning", "neural-network", "tensorflow", "deep-learning" ]
Emit socket.io message with Python using nodejs as server
39,232,231
<p>I need a bit of help.</p> <p>I'm doing tests to learn how to build a realtime web, so I use node.js with socket.io. All works fun but if I try to publish some message in the channel that is listening node with a different source that isn't node or javascript it crashes.</p> <p>Server side: (node that fails when a external publish is sended)</p> <pre><code>var app = require('express')(); var http = require('http').Server(app); var pub = require('redis').createClient(6379, 'localhost', {detect_buffers: true, return_buffers: false}); var sub = require('redis').createClient(6379, 'localhost', {return_buffers: true}); var io = require('socket.io')(http); var redis = require('socket.io-redis'); io.adapter(redis({pubClient: pub, subClient: sub, host: '127.0.0.1', port: 6379})); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); console.log("something happens: " + msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); </code></pre> <p>You don't need the client-side code for try it, just put this code and run it with node. When it is running, try to publish on the channel with Redis directly and see whats happens.</p> <pre><code>Error: 5 trailing bytes at Object.decode (.../node/node_modules/msgpack-js-v5/msgpack.js:266:47) at Redis.onmessage (.../node/node_modules/socket.io-redis/index.js:93:24) at emitTwo (events.js:87:13) at RedisClient.emit (events.js:172:7) at RedisClient.return_reply (.../node/node_modules/redis/index.js:654:22) at .../node/node_modules/redis/index.js:307:18 at nextTickCallbackWith0Args (node.js:419:9) at process._tickCallback (node.js:348:13) enter code here </code></pre> <p>Somebody understands why this happen? How can I fix it?</p> <p>Thank you!</p> <p>NEW COMMENT: Thanks to robertklep I know that it need to use the same protocol, so I wrote a simple Python script using it, but it fails with the same error.</p> <pre><code>import redis import msgpack text_packed = msgpack.packb('refresh', use_bin_type=True) r = redis.StrictRedis(host='localhost', port=6379, db=0) r.publish('socket.io#/#', text_packed) </code></pre> <p>I also tried this approach, I think Im passing some param wrong:</p> <pre><code>from emitter import Emitter io = Emitter(dict(host='localhost', port=6379)) io.Emit('chat message', "message from python!") # or specificating the room io.To("socket.io#/#").Emit('chat message', "message from python!") </code></pre> <p>In this case, nothing arrives to redis.</p>
0
2016-08-30T15:59:54Z
39,232,668
<p><code>socket.io-redis</code> uses <a href="https://github.com/socketio/socket.io-redis/blob/40c6d284e5e3beff680bc289c393f562192a5328/index.js#L140" rel="nofollow"><code>msgpack</code></a> on top of Redis to pub/sub messages, so you can't just push regular strings to it and expect it to work. The client you're using needs to be talking the same protocol.</p>
0
2016-08-30T16:28:14Z
[ "python", "node.js", "redis", "socket.io", "msgpack" ]
How to get a uuid with python requests
39,232,293
<p>I am attempting to log into a web page using the python requests module but the Post data on the website that I want to log into includes a uuid tag.</p> <pre><code>pass: ******** user: ******** uuid: ******** </code></pre> <p>I have thoroughly searched for any mention of this anywhere in most requests documentation. Is this simply out of the capabilities of the program or is it something that I am overlooking.</p> <p>This is the code I am using.</p> <pre><code>import requests url = 'www.website.com' with requests.Session() as c: c.get(url) values = {'pass': 'passsword', 'user': 'username'} response = c.post(url, data=values) print response </code></pre>
1
2016-08-30T16:04:10Z
39,233,039
<p>You can parse it from the source:</p> <pre><code>In [29]: from bs4 import BeautifulSoup In [30]: import re In [31]: patt = re.compile("document.cplogin.uuid.value=\"(.*?)\"") In [32]: with requests.Session() as s: ....: page = s.get('http://myneu.neu.edu/cp/home/displaylogin').content ....: soup = BeautifulSoup(page, "html.parser") ....: script = soup.find("script", language="javascript1.1") ....: uuid = patt.search(script.text).group(1) ....: In [33]: uuid Out[33]: u'ff3e7ddd-0823-4f44-a003-0e68a9321e08' </code></pre> <p>If you look at the source of the login page, inside the script with the attribute <em>language="javascript1.1"</em>, you can see the uuid:</p> <pre><code>function login() { setQueryAsCookie(); document.cplogin.user.value=document.userid.user.value; document.cplogin.uuid.value="21fbc26a-3a3d-4802-ba4a-39a40aad881c"; document.cplogin.submit(); } </code></pre> <p>So just pass that along with the rest of the form data when you post.</p> <p>The post url also seems to be <em><a href="https://myneu.neu.edu/cp/home/login" rel="nofollow">https://myneu.neu.edu/cp/home/login</a></em>, so:</p> <pre><code>from bs4 import BeautifulSoup import re patt = re.compile("document.cplogin.uuid.value=\"(.*?)\"") data = {"user":"uname", "pass":"passw"} post = "https://myneu.neu.edu/cp/home/login" with requests.Session() as s: page = s.get('http://myneu.neu.edu/cp/home/displaylogin') soup = BeautifulSoup(page.content, "html.parser") script = soup.find("script", language="javascript1.1") uuid = patt.search(script.text).group(1) data["uuid"] = uuid resp = s.post(post, data=data) </code></pre>
2
2016-08-30T16:49:57Z
[ "python", "http", "post", "login", "python-requests" ]
ATLAS on a python virtualenv in Fedora for numpy/scipy/scikit-learn
39,232,482
<p>I am struggeling to let python find and use the installed ATLAS libraries from my distribution when using virtualenv.</p> <p>This is on Fedora 21, atlas, atlas-devel, blas, blas-devel are installed. Outside of a virtualenv, the command <code>python -c 'import numpy; numpy.show_config()'</code> shows that I have ATLAS:</p> <pre><code>atlas_3_10_blas_threads_info: libraries = ['tatlas'] library_dirs = ['/usr/lib64/atlas'] define_macros = [('HAVE_CBLAS', None), ('ATLAS_INFO', '"\\"3.10.1\\""')] language = c include_dirs = ['/usr/include'] lapack_opt_info: libraries = ['tatlas', 'tatlas', 'tatlas'] library_dirs = ['/usr/lib64/atlas'] define_macros = [('ATLAS_INFO', '"\\"3.10.1\\""')] language = f77 include_dirs = ['/usr/include'] blas_opt_info: libraries = ['tatlas'] library_dirs = ['/usr/lib64/atlas'] define_macros = [('HAVE_CBLAS', None), ('ATLAS_INFO', '"\\"3.10.1\\""')] language = c include_dirs = ['/usr/include'] openblas_info: NOT AVAILABLE openblas_lapack_info: NOT AVAILABLE [...] </code></pre> <p>And <code>ls /usr/lib64/atlas/</code> gives:</p> <pre><code>libatlas.a libsatlas.so libsatlas.so.3.10 libtatlas.so.3 libcblas.so libsatlas.so.3 libtatlas.so libtatlas.so.3.10 </code></pre> <p>I also setup an environment variable, so that <code>echo $ATLAS</code> gives</p> <pre><code>/usr/lib64/atlas/libsatlas.so </code></pre> <p>But when I do the following:</p> <pre><code>virtualenv venv source venv/bin/activate pip install --upgrade pip pip install numpy pip install scipy pip install scikit-learn python -c 'import numpy; numpy.show_config()' </code></pre> <p>I get:</p> <pre><code>lapack_opt_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib'] define_macros = [('HAVE_CBLAS', None)] language = c blas_opt_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib'] define_macros = [('HAVE_CBLAS', None)] language = c openblas_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib'] define_macros = [('HAVE_CBLAS', None)] language = c openblas_lapack_info: libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib'] define_macros = [('HAVE_CBLAS', None)] language = c blas_mkl_info: NOT AVAILABLE </code></pre> <p>I would really appreciate help with how to get numpy and scipy simply find and use ATLAS from my distribution in a virtualenv.</p>
1
2016-08-30T16:16:29Z
39,233,754
<p>You need to tell numpy's setup.py where to find your ATLAS libraries.</p> <p>Try creating a <code>.numpy-site.cfg</code> file in your home folder before running <code>pip install</code>. <a href="https://github.com/numpy/numpy/blob/master/site.cfg.example" rel="nofollow">Here's</a> the template for this file. </p> <p>You probably need to add the lines</p> <pre><code>[atlas] library_dirs = /usr/lib64/atlas include_dirs = /usr/include </code></pre> <p>Although, this has required a little bit of trial-and-error in my experience.</p> <p>Using this file in conjunction with <code>pip install</code> seems to work reliably on RHEL and Ubuntu, at least within virtual environments where you don't need <code>sudo</code>.</p> <p>If this fails for one or more of numpy, scipy and scikit-learn, consider installing from source instead, and modify the site.cfg file inside the source dir before running <code>python setup.py install</code>.</p>
1
2016-08-30T17:34:53Z
[ "python", "numpy", "virtualenv", "blas", "atlas" ]
How to seperate a python file to couple files, making a real game with files
39,232,492
<p>I made a little game with python/pygame. It's in one folder and it's 300+ lines. I want to develop this little game. I'm seeing lots of games made by pygame, and I'm seeing they have folders like <code>main.py</code> , <code>classes.py</code> and <code>setup.py</code>.</p> <p>But I only know the python language and a little pygame. How can I do the file things, or how can I learn?</p>
-2
2016-08-30T16:16:57Z
39,237,042
<p>To import a file called <em>script.py</em> from the same directory as your main file:</p> <pre><code>import script </code></pre> <p>To import a file called <em>script.py</em> from a sub directory called <em>app</em>:</p> <pre><code>import sys sys.path.insert('app') import script </code></pre> <p>To import a file called <em>script.py</em> from the parent directory:</p> <pre><code>import sys import os sys.path.insert(0, os.path.abspath('../')) import script </code></pre> <p>To import a file called <em>script.py</em> from a sibling directory called <em>app</em>:</p> <pre><code>import sys import os sys.path.insert(0, os.path.abspath('../app')) import script </code></pre> <p>The methods described above are fine if you need to quickly import a few files, but it is commonly recommended that people use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> when handling larger projects.</p>
1
2016-08-30T21:02:17Z
[ "python", "pygame" ]
needs to find \t in the middle of a string
39,232,555
<p>I have a json file with two variables:</p> <pre><code>\t\t"ROW_ID" : 475895, \t\t"TEXT" : "TITLE:\tCardiology Consult\n\t24 Hour Events:\n\tPatient without any further... </code></pre> <p>I need to find the tabs (<code>\t</code>) in the middle of <code>TEXT</code> (because I cannot load this into python correctly), not the ones at the beginning of the lines, so I can remove them. I am having trouble because there are two tabs at the beginning of the lines, so <code>.\t</code> does not work. Using notepad++. Any ideas?</p>
0
2016-08-30T16:20:49Z
39,238,316
<p>Simple. With a negative lookbehind, you can make sure you're not unnecessarily removing the tabs that come right after newlines.</p> <pre><code>(?&lt;!\n)\t+ </code></pre> <p>If you're worried that <code>\n</code> will match the character <code>n</code> instead of a newline on some regex engines, use <code>\x0A</code> instead.</p> <pre><code>(?&lt;!\x0A)\t+ </code></pre>
0
2016-08-30T22:57:54Z
[ "python", "json", "regex" ]
create 2d array with lists as entries
39,232,625
<p>I want to create a 2d numpy array that contains python lists as entries. The mainprogram will append IDs to each entry. In the end I need to search for the entry with the most appended IDs. I will need these IDs later on and because of this a simple 2d array with integer entries, that just get incremented, won't solve my problem. So my question is: How do I create a 2d numpy array that contains python lists as entries?</p> <pre><code>import cv2 import numpy as np #get image image_rgb = cv2.imread('testpic.png') #grayscale imgae image = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY) #generate evalutatearray (2d array with list entrys) evaluatelist = np.empty(image.shape) ID = 443 evaluatelist[34,78].append(ID) </code></pre>
0
2016-08-30T16:24:28Z
39,244,240
<p>You can try to create an empty numpy array of object type and then assign lists to array entries, you have to adapt your code as such</p> <pre><code>evaluatelist = np.empty(image.shape, dtype=object) for x in xrange(evaluatelist.shape[0]): for y in xrange(evaluatelist.shape[1]): evaluatelist[x,y] = [] </code></pre> <p>That is assuming that the array creation with image.shape works.</p>
0
2016-08-31T08:17:52Z
[ "python", "arrays", "list", "numpy" ]
Why can't I define a class in main()?
39,232,627
<p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p> <pre><code>class graph(object): def __init__(self): self.nodes = [] self.edges = [] self.graphDict = {} def addNodes(self): self.nodes.append(input("Enter the name for a new node: ")) def main(): g = graph() if __name__ == '__main__': main() </code></pre> <p>And in the console:</p> <pre><code>&gt;&gt;&gt; g Traceback (most recent call last): File "&lt;pyshell#29&gt;", line 1, in &lt;module&gt; g NameError: name 'g' is not defined </code></pre> <p>Any ideas how to fix this?</p>
-2
2016-08-30T16:24:33Z
39,232,654
<p>You have defined <code>g</code>. However, you defined it inside your <code>main()</code> function scope. In the console, you are outside this scope, so you can't refer to <code>g</code> anymore.</p>
1
2016-08-30T16:26:57Z
[ "python", "class", "main" ]
Why can't I define a class in main()?
39,232,627
<p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p> <pre><code>class graph(object): def __init__(self): self.nodes = [] self.edges = [] self.graphDict = {} def addNodes(self): self.nodes.append(input("Enter the name for a new node: ")) def main(): g = graph() if __name__ == '__main__': main() </code></pre> <p>And in the console:</p> <pre><code>&gt;&gt;&gt; g Traceback (most recent call last): File "&lt;pyshell#29&gt;", line 1, in &lt;module&gt; g NameError: name 'g' is not defined </code></pre> <p>Any ideas how to fix this?</p>
-2
2016-08-30T16:24:33Z
39,232,657
<p>The variable <code>g</code> is <em>local</em> and exists only inside <code>main()</code>, while you're trying to access it outside <code>main()</code>.</p> <p>The following tutorial explains the difference between local and global variables: <a href="http://www.python-course.eu/global_vs_local_variables.php" rel="nofollow">http://www.python-course.eu/global_vs_local_variables.php</a></p> <p>Note that, despite its name, there is nothing special about <code>main()</code>: it's just a function like any other. Any statement that you type into the console is executed at the global scope, i.e. outside all functions.</p>
4
2016-08-30T16:27:15Z
[ "python", "class", "main" ]
Why can't I define a class in main()?
39,232,627
<p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p> <pre><code>class graph(object): def __init__(self): self.nodes = [] self.edges = [] self.graphDict = {} def addNodes(self): self.nodes.append(input("Enter the name for a new node: ")) def main(): g = graph() if __name__ == '__main__': main() </code></pre> <p>And in the console:</p> <pre><code>&gt;&gt;&gt; g Traceback (most recent call last): File "&lt;pyshell#29&gt;", line 1, in &lt;module&gt; g NameError: name 'g' is not defined </code></pre> <p>Any ideas how to fix this?</p>
-2
2016-08-30T16:24:33Z
39,232,829
<p>A way you can do this is using <a href="https://ipython.org/install.html" rel="nofollow">IPython</a>. <a href="http://ipython.readthedocs.io/en/stable/api/generated/IPython.terminal.embed.html#IPython.terminal.embed.embed" rel="nofollow"><code>IPython.embed(<strong><em>**kwargs</em></strong>)</code></a> will start the terminal from whatever scope you are in.</p> <pre><code>import IPython def main(): g = 'graph()' IPython.embed() main() </code></pre> <pre><code>In [1]: g Out [1]: 'graph()' </code></pre> <p>A slightly more hacky-way, which I could only recommend in development, is updating <a href="https://docs.python.org/3.5/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> with <a href="https://docs.python.org/3.5/library/functions.html#locals" rel="nofollow"><code>locals()</code></a>.</p> <pre><code>def main(): g = 'graph()' globals().update(locals()) main() </code></pre> <pre><code>&gt;&gt;&gt; g 'graph()' </code></pre>
0
2016-08-30T16:37:04Z
[ "python", "class", "main" ]
Loop over multiple columns in dataframe
39,232,632
<p>I have a dataframe from a CSV file that has 61 columns and 1mil rows. 25 of those columns <code>(Flag_1, Flag_2, ..., Flag_25)</code> have <code>True/False</code> as values for each row of the dataframe.</p> <p>What I'm trying to do is loop through each column to determine if there is a True for that entire row within those columns, I just need a minimum of one true. If there is a True then a new column, <code>Flag_All</code> will have a True value for that row, if not, then False.</p> <p>I can use the for loop for a single column like so,</p> <pre><code>for index, x in data2['FLAG_1'].iteritems() : data2['FLAG_ALL'] = data2['FLAG_1'] == True </code></pre> <p>but can't figure out for multiple columns. </p>
2
2016-08-30T16:24:58Z
39,232,739
<p>Please try:</p> <pre><code>data2['FLAG_ALL'] = data2.any(axis=1,bool_only=True).values </code></pre> <p>More info on <strong>any()</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html</a></p>
0
2016-08-30T16:31:53Z
[ "python", "pandas", "for-loop", "dataframe" ]
Loop over multiple columns in dataframe
39,232,632
<p>I have a dataframe from a CSV file that has 61 columns and 1mil rows. 25 of those columns <code>(Flag_1, Flag_2, ..., Flag_25)</code> have <code>True/False</code> as values for each row of the dataframe.</p> <p>What I'm trying to do is loop through each column to determine if there is a True for that entire row within those columns, I just need a minimum of one true. If there is a True then a new column, <code>Flag_All</code> will have a True value for that row, if not, then False.</p> <p>I can use the for loop for a single column like so,</p> <pre><code>for index, x in data2['FLAG_1'].iteritems() : data2['FLAG_ALL'] = data2['FLAG_1'] == True </code></pre> <p>but can't figure out for multiple columns. </p>
2
2016-08-30T16:24:58Z
39,232,823
<p>Given an example dataframe of:</p> <pre><code>df = pd.DataFrame({ 'flag_1': [False, False, True], 'flag_2': [False, False, False], 'flag_3': [True, False, False]}) </code></pre> <p>You can use <code>df.filter</code> to get the appropriate columns (those starting with flag, an underscore and then digits...), then apply <code>any()</code> across the row axis to get your overall boolean column:</p> <pre><code>df['flag_all'] = df.filter(regex='^flag_\d+$').any(axis=1) </code></pre> <p>Which gives you:</p> <pre><code> flag_1 flag_2 flag_3 flag_all 0 False False True True 1 False False False False 2 True False False True </code></pre>
4
2016-08-30T16:36:49Z
[ "python", "pandas", "for-loop", "dataframe" ]
How to call Amazon API gateway with Groovy
39,232,661
<p>I am going to call API gateway from M2M cloud that uses limited version of Groovy inside and I can't use external SDK. So I have checked for the description of the implementation and for some code samples.</p> <ul> <li>I found documentation - <a href="http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html" rel="nofollow">documentation</a></li> <li>And sample on Python - <a href="http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html" rel="nofollow">Python example</a></li> </ul> <p>I have tried to implement <strong>Get</strong> method for pure Groovy, but it doesn't wor, gets me 403 error. It means that my access implementation has mistake.:</p> <pre><code>import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import java.security.InvalidKeyException import java.security.MessageDigest import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.methods.GetMethod import org.apache.commons.httpclient.Header import groovy.json.JsonSlurper import java.text.SimpleDateFormat def method = 'GET' def service = 'ec2' def host = 'ec2.amazonaws.com' def region = 'us-east-1' def endpoint = 'https://ec2.amazonaws.com' def request_parameters = 'Action=DescribeRegions&amp;Version=2013-10-15' def hmac_sha256(byte[] secretKey, String data) { try { Mac mac = Mac.getInstance("HmacSHA256") SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA256") mac.init(secretKeySpec) byte[] digest = mac.doFinal(data.getBytes()) return digest } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key exception while converting to HMac SHA256") } } def hmac_sha256Hex(byte[] secretKey, String data) { def result = hmac_sha256(secretKey, data) return result.encodeHex() } def getSignatureKey(key, dateStamp, regionName, serviceName){ def kDate = hmac_sha256(('AWS4' + key).getBytes(), dateStamp) def kRegion = hmac_sha256(kDate, regionName) def kService = hmac_sha256(kRegion, serviceName) def kSigning = hmac_sha256(kService, 'aws4_request') return kSigning } def getHexDigest(text){ def md = MessageDigest.getInstance("SHA-256") md.update(text.getBytes()) return md.digest().encodeHex() } def access_key = 'Access Key' def secret_key = 'Secret Access Key' def now = new Date() def amzFormat = new SimpleDateFormat( "yyyyMMdd'T'HHmmss'Z'" ) def stampFormat = new SimpleDateFormat( "yyyyMMdd" ) def amzDate = amzFormat.format(now) def dateStamp = stampFormat.format(now) def canonical_uri = '/' def canonical_querystring = request_parameters def canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzDate + '\n' def signed_headers = 'host;x-amz-date' def payload_hash = getHexDigest("") def canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash def algorithm = 'AWS4-HMAC-SHA256' def credential_scope = dateStamp + '/' + region + '/' + service + '/' + 'aws4_request' def hash_canonical_request = getHexDigest(canonical_request) def string_to_sign = algorithm + '\n' + amzDate + '\n' + credential_scope + '\n' + hash_canonical_request def signing_key = getSignatureKey(secret_key, dateStamp, region, service) def signature = hmac_sha256Hex(signing_key, string_to_sign) def authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature def request_url = endpoint + '?' + canonical_querystring def httpClient = new HttpClient() def get = new GetMethod('https://xxxxx.execute-api.us-east-1.amazonaws.com/Method/id000/') get.setRequestHeader(new Header("x-amz-date", amzDate)) get.setRequestHeader(new Header("Authorization", authorization_header)) int statusCode = httpClient.executeMethod(get) if(statusCode &gt;= 200 &amp;&amp; statusCode &lt; 300){ def slurper = new JsonSlurper() def response = slurper.parseText(get.getResponseBodyAsString()) logger.debug response logger.debug response?.Id }else{ logger.debug statusCode } </code></pre> <p>Could anybody point me where I did a mistake?</p>
-1
2016-08-30T16:27:27Z
39,267,020
<p>I have solved this issue. </p> <p>I did the number of mistakes related to host, service, endpoint and request parameter. It is boring to describe each of them so I just add correct script below.</p> <pre><code>import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import java.security.InvalidKeyException import java.security.MessageDigest import org.apache.commons.httpclient.HttpClient import org.apache.commons.httpclient.methods.GetMethod import org.apache.commons.httpclient.Header import groovy.json.JsonSlurper import java.text.SimpleDateFormat def access_key = "Access Key" def secret_key = "Secret Access Key" def method = "GET" def service = "execute-api" def host = "xxxxx.execute-api.us-east-1.amazonaws.com" def region = "us-east-1" def endpoint = "https://xxxxx.execute-api.us-east-1.amazonaws.com/Method/id000/" def request_parameters = "" def now = new Date() def amzFormat = new SimpleDateFormat( "yyyyMMdd'T'HHmmss'Z'" ) def stampFormat = new SimpleDateFormat( "yyyyMMdd" ) def amzDate = amzFormat.format(now) def dateStamp = stampFormat.format(now) def canonical_uri = "/Method/id000/" def canonical_headers = "host:" + host + "\n" + "x-amz-date:" + amzDate + "\n" def signed_headers = "host;x-amz-date" def payload_hash = getHexDigest("") def canonical_request = method + "\n" + canonical_uri + "\n" + request_parameters + "\n" + canonical_headers + "\n" + signed_headers + "\n" + payload_hash def algorithm = "AWS4-HMAC-SHA256" def credential_scope = dateStamp + "/" + region + "/" + service + "/" + "aws4_request" def hash_canonical_request = getHexDigest(canonical_request) def string_to_sign = algorithm + "\n" + amzDate + "\n" + credential_scope + "\n" + hash_canonical_request def signing_key = getSignatureKey(secret_key, dateStamp, region, service) def signature = hmac_sha256Hex(signing_key, string_to_sign) def authorization_header = algorithm + " " + "Credential=" + access_key + "/" + credential_scope + ", " + "SignedHeaders=" + signed_headers + ", " + "Signature=" + signature def httpClient = new HttpClient() def get = new GetMethod(endpoint) get.setRequestHeader(new Header("Content-Type", "application/json")) get.setRequestHeader(new Header("Host", host)) get.setRequestHeader(new Header("x-amz-date", amzDate)) get.setRequestHeader(new Header("Authorization", authorization_header)) def statusCode = httpClient.executeMethod(get) if(statusCode &gt;= 200 &amp;&amp; statusCode &lt; 300){ def slurper = new JsonSlurper() def response = slurper.parseText(get.getResponseBodyAsString()) logger.debug response }else{ logger.debug statusCode } def hmac_sha256(secretKey, data) { Mac mac = Mac.getInstance("HmacSHA256") SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA256") mac.init(secretKeySpec) byte[] digest = mac.doFinal(data.getBytes()) return digest } def hmac_sha256Hex(secretKey, data) { def result = hmac_sha256(secretKey, data) return result.encodeHex() } def getSignatureKey(key, dateStamp, regionName, serviceName){ def kDate = hmac_sha256(("AWS4" + key).getBytes(), dateStamp) def kRegion = hmac_sha256(kDate, regionName) def kService = hmac_sha256(kRegion, serviceName) def kSigning = hmac_sha256(kService, "aws4_request") return kSigning } def getHexDigest(text){ def md = MessageDigest.getInstance("SHA-256") md.update(text.getBytes()) return md.digest().encodeHex() } </code></pre> <p>I hope it will help to somebody to avoid my way and save time with this.</p>
0
2016-09-01T08:57:07Z
[ "python", "amazon-web-services", "groovy", "amazon-api", "amazon-api-gateway" ]
pandas ordering columns misses values
39,232,736
<p>Not sure on the right title for this. But I have a need to take out a column from a dataframe, and show the top five results. The column is a mix of integers and n/a results. As an example I create a basic dataframe:</p> <pre><code>regiona col1 a n/a a 1 a 200 b 208 b 400 b 560 b 600 c 800 c 1120 c 1200 c 1680 d n/a d n/a </code></pre> <p>And so run:</p> <pre><code>import pandas as pd df = pd.read_csv('test_data.csv') </code></pre> <p>I then created a basic function so I could use this on different columns, so constructed:</p> <pre><code>def max_search(indicator): displaced_count = df[df[indicator] != 'n/a'] table = displaced_count.sort_values([indicator], ascending=[False]) return table.head(5) </code></pre> <p>But when I run </p> <pre><code>max_search('col1') </code></pre> <p>It returns:</p> <pre><code> regiona col1 7 c 800 6 b 600 5 b 560 4 b 400 3 b 208 </code></pre> <p>So it misses anything greater than 800. The steps I think the function should be doing is:</p> <ol> <li>Filter out n/a valyes</li> <li>Return the top five values. </li> </ol> <p>However, it is not returning anything over 800? Am I missing something very obvious?</p>
2
2016-08-30T16:31:46Z
39,232,878
<p>Check your dataframe's <code>dtypes</code>, now it is <code>object</code>. So first make sure <code>col1</code>'s datatype is numeric. Use <code>na_values</code> at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>pd.read_csv()</code></a> and your function will work as expected:</p> <pre><code>df = pd.read_csv('test_data.csv', na_values='n/a') # df.dtypes </code></pre>
5
2016-08-30T16:40:34Z
[ "python", "pandas" ]
pandas ordering columns misses values
39,232,736
<p>Not sure on the right title for this. But I have a need to take out a column from a dataframe, and show the top five results. The column is a mix of integers and n/a results. As an example I create a basic dataframe:</p> <pre><code>regiona col1 a n/a a 1 a 200 b 208 b 400 b 560 b 600 c 800 c 1120 c 1200 c 1680 d n/a d n/a </code></pre> <p>And so run:</p> <pre><code>import pandas as pd df = pd.read_csv('test_data.csv') </code></pre> <p>I then created a basic function so I could use this on different columns, so constructed:</p> <pre><code>def max_search(indicator): displaced_count = df[df[indicator] != 'n/a'] table = displaced_count.sort_values([indicator], ascending=[False]) return table.head(5) </code></pre> <p>But when I run </p> <pre><code>max_search('col1') </code></pre> <p>It returns:</p> <pre><code> regiona col1 7 c 800 6 b 600 5 b 560 4 b 400 3 b 208 </code></pre> <p>So it misses anything greater than 800. The steps I think the function should be doing is:</p> <ol> <li>Filter out n/a valyes</li> <li>Return the top five values. </li> </ol> <p>However, it is not returning anything over 800? Am I missing something very obvious?</p>
2
2016-08-30T16:31:46Z
39,232,940
<p>You could also do:</p> <pre><code>df['col1'] = pd.to_numeric(df['col1'], errors='coerce') df.dropna().sort_values(['col1'], ascending=False).head(5) regiona col1 10 c 1680.0 9 c 1200.0 8 c 1120.0 7 c 800.0 6 b 600.0 </code></pre>
3
2016-08-30T16:43:52Z
[ "python", "pandas" ]
Numpy Vectorization of sliding-window operation
39,232,790
<p>I have the following numpy arrays:</p> <pre><code>arr_1 = [[1,2],[3,4],[5,6]] # 3 X 2 arr_2 = [[0.5,0.6],[0.7,0.8],[0.9,1.0],[1.1,1.2],[1.3,1.4]] # 5 X 2 </code></pre> <p><code>arr_1</code> is clearly a <code>3 X 2</code> array, whereas <code>arr_2</code> is a <code>5 X 2</code> array. </p> <p>Now without looping, I want to element-wise multiply arr_1 and arr_2 so that I apply a sliding window technique (window size 3) to arr_2.</p> <pre><code>Example: Multiplication 1: np.multiply(arr_1,arr_2[:3,:]) Multiplication 2: np.multiply(arr_1,arr_2[1:4,:]) Multiplication 3: np.multiply(arr_1,arr_2[2:5,:]) </code></pre> <p>I want to do this in some sort of a matrix multiplication form to make it faster than my current solution which is of the form:</p> <pre><code>for i in (2): np.multiply(arr_1,arr_2[i:i+3,:]) </code></pre> <p>So if the number of rows in arr_2 are large (of the order of tens of thousands), this solution doesn't really scale very well.</p> <p>Any help would be much appreciated.</p>
4
2016-08-30T16:35:09Z
39,232,977
<p>We can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> to create those sliding windowed indices in a vectorized manner. Then, we can simply index into <code>arr_2</code> with those to create a <code>3D</code> array and perform element-wise multiplication with <code>2D</code> array <code>arr_1</code>, which in turn will bring on <code>broadcasting</code> again. </p> <p>So, we would have a vectorized implementation like so -</p> <pre><code>W = arr_1.shape[0] # Window size idx = np.arange(arr_2.shape[0]-W+1)[:,None] + np.arange(W) out = arr_1*arr_2[idx] </code></pre> <p>Runtime test and verify results -</p> <pre><code>In [143]: # Input arrays ...: arr_1 = np.random.rand(3,2) ...: arr_2 = np.random.rand(10000,2) ...: ...: def org_app(arr_1,arr_2): ...: W = arr_1.shape[0] # Window size ...: L = arr_2.shape[0]-W+1 ...: out = np.empty((L,W,arr_1.shape[1])) ...: for i in range(L): ...: out[i] = np.multiply(arr_1,arr_2[i:i+W,:]) ...: return out ...: ...: def vectorized_app(arr_1,arr_2): ...: W = arr_1.shape[0] # Window size ...: idx = np.arange(arr_2.shape[0]-W+1)[:,None] + np.arange(W) ...: return arr_1*arr_2[idx] ...: In [144]: np.allclose(org_app(arr_1,arr_2),vectorized_app(arr_1,arr_2)) Out[144]: True In [145]: %timeit org_app(arr_1,arr_2) 10 loops, best of 3: 47.3 ms per loop In [146]: %timeit vectorized_app(arr_1,arr_2) 1000 loops, best of 3: 1.21 ms per loop </code></pre>
4
2016-08-30T16:45:47Z
[ "python", "arrays", "numpy", "matrix-multiplication", "sliding-window" ]
Numpy Vectorization of sliding-window operation
39,232,790
<p>I have the following numpy arrays:</p> <pre><code>arr_1 = [[1,2],[3,4],[5,6]] # 3 X 2 arr_2 = [[0.5,0.6],[0.7,0.8],[0.9,1.0],[1.1,1.2],[1.3,1.4]] # 5 X 2 </code></pre> <p><code>arr_1</code> is clearly a <code>3 X 2</code> array, whereas <code>arr_2</code> is a <code>5 X 2</code> array. </p> <p>Now without looping, I want to element-wise multiply arr_1 and arr_2 so that I apply a sliding window technique (window size 3) to arr_2.</p> <pre><code>Example: Multiplication 1: np.multiply(arr_1,arr_2[:3,:]) Multiplication 2: np.multiply(arr_1,arr_2[1:4,:]) Multiplication 3: np.multiply(arr_1,arr_2[2:5,:]) </code></pre> <p>I want to do this in some sort of a matrix multiplication form to make it faster than my current solution which is of the form:</p> <pre><code>for i in (2): np.multiply(arr_1,arr_2[i:i+3,:]) </code></pre> <p>So if the number of rows in arr_2 are large (of the order of tens of thousands), this solution doesn't really scale very well.</p> <p>Any help would be much appreciated.</p>
4
2016-08-30T16:35:09Z
39,238,064
<p>This is a nice case to test the speed of <code>as_strided</code> and Divakar's broadcasting.</p> <pre><code>In [281]: %%timeit ...: out=np.empty((L,W,arr1.shape[1])) ...: for i in range(L): ...: out[i]=np.multiply(arr1,arr2[i:i+W,:]) ...: 10 loops, best of 3: 48.9 ms per loop In [282]: %%timeit ...: idx=np.arange(L)[:,None]+np.arange(W) ...: out=arr1*arr2[idx] ...: 100 loops, best of 3: 2.18 ms per loop In [283]: %%timeit ...: arr3=as_strided(arr2, shape=(L,W,2), strides=(16,16,8)) ...: out=arr1*arr3 ...: 1000 loops, best of 3: 805 µs per loop </code></pre> <p><a href="http://stackoverflow.com/questions/39024320/create-numpy-array-without-enumerating-array">Create Numpy array without enumerating array</a> for more of a comparison of these methods.</p>
3
2016-08-30T22:29:38Z
[ "python", "arrays", "numpy", "matrix-multiplication", "sliding-window" ]
Python - How to add the location of each object in the image?
39,232,820
<p>I have tracked more than one objects in the image and now my final step is to add the location of each object in the image here is the <a href="http://i.stack.imgur.com/guyKa.png" rel="nofollow">image</a></p> <p>Another question is when I am printing the x, y, and radius of each object, I found that the locations are printed in a push pop behaviour, for example, if I have 3 Locations of 3 objects:</p> <p>object 1 (1,4)</p> <p>object 2 (7,6)</p> <p>object 3 (5,3)</p> <p>the output is shown like following:</p> <p>1,4</p> <p>7,6</p> <p>5,3 and so on</p> <p>Thus I want to sort each location in an array like this <code>[1,4],[ 7,6],[5,3]</code></p> <p>And I want to print the locations of each object in the image. Any ideas ??</p>
-1
2016-08-30T16:36:43Z
39,254,610
<p>Without seeing all of your code, it's hard to suggest a solution, but it looks like you are at least iterating over your objects. If not, you can put them in a list like so:</p> <pre><code>obj_list = [obj1, obj2, obj3] </code></pre> <p>Then you can add their coordinates to a list like this:</p> <pre><code>obj_coords = [(obj.x, obj.y) for obj in obj_list] </code></pre> <p>Then you can sort the list with python's excellent <code>sorted</code>:</p> <pre><code>obj_coords = sorted(obj_coords, key=lambda x: x[0]) </code></pre> <p>You can also sort by the y value by changing <code>key=lambda x: x[0]</code> to <code>key=lambda x: x[1]</code>.</p> <p><strong><em>EDIT:</em></strong> It would be helpful if you copy-paste all your code into your question so I can test it, See the help section for how to make an <a href="http://stackoverflow.com/help/mcve">MCVE</a>.</p> <p>Anyway, I didn't mean literally <code>[obj1, obj2, obj3]</code> unless those are the variable names you chose. Your code has a line:</p> <pre><code>print int(x), int(y), int(radius) </code></pre> <p>if you create an empty list like this: <code>obj_list = []</code> then add tuples to it by replacing this print statement with:</p> <pre><code>obj_list.append( (int(x), int(y)) ) </code></pre> <p>If you're still having trouble, open a new question with an MVCE. Most people will not help you unless they can copy paste your code to test it out and fix it.</p>
0
2016-08-31T16:24:31Z
[ "python", "python-2.7", "opencv", "computer-vision" ]
Tornado templates setting value field
39,232,936
<p>I have a python array:</p> <pre><code>a=["a","b","c","d","e","f"] </code></pre> <p>I pass this as a value to tornado render:</p> <pre><code> self.render("index.html", a=a) </code></pre> <p>In my html I have the following:</p> <pre><code> &lt;input type="hidden" id="xxx" value=" {% for c in a %} {{c}} {% end %} "/&gt; </code></pre> <p>Which gives me the following messy output:</p> <pre><code>&lt;input type="hidden" id="xxx" value=" a b c d e f "/&gt; </code></pre> <p>I tried to use a {{c.strip()}} but that did the same thing. I also trying to mix in javascript however the javascript didn't execute after rendering to populate the value field. I want the html to be normal that is <code>value="a b c d e f"</code></p> <p>Does anyone know how I can achieve this?</p>
0
2016-08-30T16:43:28Z
39,232,971
<p>Just join the list in the backend itself.</p> <pre><code> self.render("index.html", a=' '.join(a)) </code></pre> <p>And use,</p> <pre><code>&lt;input type="hidden" id="xxx" value="{{ a }}" /&gt; </code></pre> <p>in template</p>
1
2016-08-30T16:45:37Z
[ "python", "html", "tornado" ]