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 |
---|---|---|---|---|---|---|---|---|---|
json2html, python: json data not converted to html | 39,831,894 | <p>I'm trying to format json data to html using json2html.
The json data look like this:</p>
<pre><code>json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "test2.example.com", "username": "user2"}]
</code></pre>
<p>As already reported in post "<a href="http://stackoverflow.com/questions/38633629/json2html-not-a-valid-json-list-python">json2html not a valid json list python</a>", to make the code works, the json parameter must be a dictionary and not a list, so I'm calling it that way:</p>
<pre><code>json_obj_in_html = json2html.convert(json = { "data" : json_obj })
</code></pre>
<p>However it does not format the json data to html only the first level of dictionary { "data" : json_obj }:</p>
<pre><code>print json_obj_in_html
<table border="1"><tr><th>data</th><td>[{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "test2.example.com", "username": "user2"}]</td></tr></table>
</code></pre>
<p>Note that the <strong>online</strong> convert tool provides the right output: <a href="http://json2html.varunmalhotra.xyz/" rel="nofollow">http://json2html.varunmalhotra.xyz/</a></p>
<pre><code><table border="1"><tr><th>data</th><td><ul><table border="1"><tr><th>Agent Status</th><td>status1</td></tr><tr><th>Last backup</th><td></td></tr><tr><th>hostId</th><td>1234567</td></tr><tr><th>hostfqdn</th><td>test1.example.com</td></tr><tr><th>username</th><td>user1</td></tr></table><table border="1"><tr><th>Agent Status</th><td>status2</td></tr><tr><th>Last backup</th><td></td></tr><tr><th>hostId</th><td>2345678</td></tr><tr><th>hostfqdn</th><td>test2.example.com</td></tr><tr><th>username</th><td>user2</td></tr></table></ul></td></tr></table>
</code></pre>
<p>Any help would be very welcome.</p>
| 0 | 2016-10-03T12:39:22Z | 39,855,460 | <p>My list of dictionaries <code>anomaly_list</code> was already in a json format, so trying to convert it using <code>json.dumps(anomaly_list, sort_keys=True)</code> was turning into a string, which was not what I wanted.
I solved the issue by leaving my list of dictionaries as it is and this code now works:</p>
<pre><code>json_obj_in_html = ''
for j in anomalies_list:
json_obj_in_html += json2html.convert(json = j)
</code></pre>
<p>It outputs what I wanted.</p>
<p>@gus42: thanks, your feedback made me understand where the real pb was.</p>
| 0 | 2016-10-04T14:51:29Z | [
"python",
"html",
"json",
"json2html"
]
|
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
</code></pre>
| 1 | 2016-10-03T12:40:56Z | 39,831,969 | <p>It appears as though you are not returning the result of the read() function.</p>
<p>The last line of your read function should be "return a"</p>
<p>And then when you call the read function you would say "a = read()"</p>
| 0 | 2016-10-03T12:43:44Z | [
"python",
"variables"
]
|
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
</code></pre>
| 1 | 2016-10-03T12:40:56Z | 39,831,996 | <p><code>a</code> is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning <code>a</code> from your <code>read()</code> function. Also, the spacing is off in your <code>IsInteger()</code> function.</p>
<pre><code>def IsInteger(b):
try:
b=int(b)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while not IsInteger(a):
a=input("Give a number: ")
return a
c = read()
print(c)
</code></pre>
| 1 | 2016-10-03T12:45:08Z | [
"python",
"variables"
]
|
How do I transfer varibles through functions in Python | 39,831,915 | <p>I am trying to read from keyboard a number and validate it</p>
<p>This is what I have but it doesn't work. </p>
<p>No error but it doesn't <strong>remember</strong> the number I introduced</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
</code></pre>
| 1 | 2016-10-03T12:40:56Z | 39,832,009 | <p>I think this is what you are trying to achieve.</p>
<pre><code>def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
global a
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
</code></pre>
<p>You need to use <code>global</code> expression in order to overwrite the global variable without a need to create <code>return</code> inside the function and typing <code>a = read()</code>. </p>
<p>But I would <strong>highly</strong> recommend u to <strong>use</strong> the <code>return</code> and re-assigned the value of 'a', as someone stated below.</p>
| 1 | 2016-10-03T12:45:44Z | [
"python",
"variables"
]
|
MissingSectionHeaderError: File contains no section headers.(configparser) | 39,831,956 | <p>I'm using configparser in order to read and modify automatically a file conf named 'streamer.conf'.
I'm doing this :</p>
<pre><code>import configparser
config = configparser.ConfigParser()
config.read('C:/Users/../Desktop/streamer.conf')
</code></pre>
<p>And then it breaks apart with this Error message :</p>
<pre><code>MissingSectionHeaderError: File contains no section headers.
file: 'C:/Users/../Desktop/streamer.conf', line: 1
u'input{\n'
</code></pre>
<p>What might be wrong? Any help appreciated.</p>
| 0 | 2016-10-03T12:42:44Z | 39,833,493 | <p>You didn't include <code>streamer.conf</code>, but from the error message, it's not in the right format. <code>configparser</code> is used for parsing "INI" files:</p>
<pre><code>[section1]
setting1 = value
setting2 = value
[section2]
setting3 = value
setting1 = value
</code></pre>
<p>etc.</p>
| 0 | 2016-10-03T14:01:54Z | [
"python",
"python-2.7",
"configuration",
"configuration-files",
"configparser"
]
|
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN between 1 - 1000")
while 1 > userInput > 1000 :
requestInteger("Your PIN is not within 1 - 1000, please try again")
print("Thanks! your new PIN is " + str(userInput))
</code></pre>
<p>thanks for the help guys!</p>
| 0 | 2016-10-03T12:50:48Z | 39,832,196 | <p>You don't assign nothing in the while loop. userInput never gets updated - hence you can't exit the loop</p>
| 1 | 2016-10-03T12:54:53Z | [
"python"
]
|
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN between 1 - 1000")
while 1 > userInput > 1000 :
requestInteger("Your PIN is not within 1 - 1000, please try again")
print("Thanks! your new PIN is " + str(userInput))
</code></pre>
<p>thanks for the help guys!</p>
| 0 | 2016-10-03T12:50:48Z | 39,832,205 | <p>you aren't assigning requestInteger to userInput </p>
<pre><code>while 1 > userInput > 1000 :
userInput =requestInteger("Your PIN is not within 1 - 1000, please try again")
</code></pre>
| 1 | 2016-10-03T12:55:20Z | [
"python"
]
|
User inputted integer using while statement | 39,832,113 | <p>Ok need to understand why my code is not working.
At the moment it's getting stuck in a infinite loop of asking the user for a pin after a wrong pin is inputted.</p>
<p>I believe I'm screwing up the while statement somehow.</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN between 1 - 1000")
while 1 > userInput > 1000 :
requestInteger("Your PIN is not within 1 - 1000, please try again")
print("Thanks! your new PIN is " + str(userInput))
</code></pre>
<p>thanks for the help guys!</p>
| 0 | 2016-10-03T12:50:48Z | 39,832,223 | <p>Try this:</p>
<pre><code>def inputValidator():
userInput = requestInteger("Please input a PIN between 1 - 1000")
while userInput<1 or userInput>1000:
userInput = requestInteger("Your PIN is not within 1 - 1000, please try again")
print("Thanks! your new PIN is " + str(userInput))
</code></pre>
<p>You'll want a new input from your user if <code>userInput</code> is smaller than 1 or bigger than 1000 - and like @Polina F. said - you didn't assign a new value to <code>userInput</code> inside the while loop. This is why it loops for ever. </p>
| 2 | 2016-10-03T12:56:05Z | [
"python"
]
|
Strange behavior when appending dictionary to list | 39,832,125 | <p>I am reading JSON into my script and building a list consisting of dictionaries.</p>
<p>My JSON:</p>
<pre><code>{
"JMF": {
"table1": {
"email": "JMF1@fake.com",
"guests": [
"test1",
"test2"
]
},
"table2": {
"email": "JMF2@fake.com",
"guests": [
"test3"
]
}
},
"JMC": {
"table3": {
"email": "JMC1@fake.com",
"guests": [
"test11"
]
}
},
"JMD": {
"table4": {
"email": "JMD1@fake.com",
"guests": [
"test12"
]
},
"table5": {
"email": "JMD2@fake.com",
"guests": [
"test17"
]
}
}
}
</code></pre>
<p>My code:</p>
<pre><code>def get_json():
userinfo_list = []
with open('guest_users.json') as json_file:
json_file = json.load(json_file)
keys = json_file.keys()
for key in keys:
userinfo = {}
for table_key in json_file[key].keys():
email = json_file[key][table_key]['email']
users_dict = {}
users_list = []
for user in json_file[key][table_key]['guests']:
users_dict['username'] = user
users_dict['password'] = generate_password()
users_list.append(users_dict)
userinfo['company'] = key
userinfo['email'] = email
userinfo['userinfo'] = users_list
userinfo_list.append(userinfo)
print(userinfo)
print(userinfo_list)
</code></pre>
<p>The problem is that the values in <code>userinfo_list</code> get overwritten as soon as my JSON has two sub-keys (<code>table*</code>).</p>
<p>This is the output I get, which doesn't make sense:</p>
<pre><code>{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}
[{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}]
{'userinfo': [{'username': 'test17', 'password': 'A8Jue5'}], 'email': 'JMD2@fake.com', 'company': 'JMD'}
[{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}, {'userinfo': [{'username': 'test17', 'password': 'A8Jue5'}], 'email': 'JMD2@fake.com', 'company': 'JMD'}]
{'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}
[{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}]
{'userinfo': [{'username': 'test2', 'password': 'GagQ59'}, {'username': 'test2', 'password': 'GagQ59'}], 'email': 'JMF1@fake.com', 'company': 'JMF'}
[{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}, {'userinfo': [{'username': 'test2', 'password': 'GagQ59'}, {'username': 'test2', 'password': 'GagQ59'}], 'email': 'JMF1@fake.com', 'company': 'JMF'}]
{'userinfo': [{'username': 'test3', 'password': 'U9gP0j'}], 'email': 'JMF2@fake.com', 'company': 'JMF'}
[{'userinfo': [{'username': 'test11', 'password': '1fEAg0'}], 'email': 'JMC1@fake.com', 'company': 'JMC'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}, {'userinfo': [{'username': 'test12', 'password': '0JSpc0'}], 'email': 'JMD1@fake.com', 'company': 'JMD'}, {'userinfo': [{'username': 'test3', 'password': 'U9gP0j'}], 'email': 'JMF2@fake.com', 'company': 'JMF'}, {'userinfo': [{'username': 'test3', 'password': 'U9gP0j'}], 'email': 'JMF2@fake.com', 'company': 'JMF'}]
</code></pre>
| 0 | 2016-10-03T12:51:28Z | 39,832,231 | <p>You are re-appending the <em>same single dictionary</em> each iteration:</p>
<pre><code>users_dict = {} # only one copy of this dictionary is ever created
users_list = []
for user in json_file[key][table_key]['guests']:
users_dict['username'] = user
users_dict['password'] = generate_password()
users_list.append(users_dict) # appending a reference to users_dict
</code></pre>
<p>Appending does <em>not</em> create a copy, so you get multiple references to the same dictionary, and you'll only see the last change reflected. You make the same mistake with the <code>userinfo</code> dictionary.</p>
<p>Create a new dictionary <em>in</em> the loop:</p>
<pre><code>users_list = []
for user in json_file[key][table_key]['guests']:
users_dict = {}
users_dict['username'] = user
users_dict['password'] = generate_password()
users_list.append(users_dict)
</code></pre>
<p>You can just specify the key-value pairs directly when creating the dictionary:</p>
<pre><code>users_list = []
for user in json_file[key][table_key]['guests']:
users_dict = {
'username': user,
'password': generate_password()
}
users_list.append(users_dict)
</code></pre>
<p>and this can be simplified with a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to:</p>
<pre><code>users_list = [{'username': user, 'password': generate_password()}
for user in json_file[key][table_key]['guests']]
</code></pre>
<p>Note that you don't need to call <code>dict.keys()</code> to loop over a dictionary. You can loop <em>directly</em> over the dictionary with the exact same results. You probably want to loop over <code>.items()</code> instead and avoid having to look up the value for the key each time, and use <code>.values()</code> when you don't actually need the key at all:</p>
<pre><code>userinfo_list = []
for company, db in json_file.items():
for table in db.values():
userinfo = {
'company': company,
'email': table['email'],
'userinfo': [
{'username': user, 'password': generate_password()}
for user in table['guests']]
}
userinfo_list.append(userinfo)
</code></pre>
<p>The creation of dictionaries per table per company can also be replaced by a list comprehension, but at this point sticking to nested <code>for</code> loops is probably going to be easier to comprehend for future readers.</p>
<p>The above now produces:</p>
<pre><code>[{'company': 'JMF',
'email': 'JMF1@fake.com',
'userinfo': [{'password': 'random_password_really', 'username': 'test1'},
{'password': 'random_password_really', 'username': 'test2'}]},
{'company': 'JMF',
'email': 'JMF2@fake.com',
'userinfo': [{'password': 'random_password_really', 'username': 'test3'}]},
{'company': 'JMC',
'email': 'JMC1@fake.com',
'userinfo': [{'password': 'random_password_really', 'username': 'test11'}]},
{'company': 'JMD',
'email': 'JMD1@fake.com',
'userinfo': [{'password': 'random_password_really', 'username': 'test12'}]},
{'company': 'JMD',
'email': 'JMD2@fake.com',
'userinfo': [{'password': 'random_password_really', 'username': 'test17'}]}]
</code></pre>
<p>from your sample data (and my own definition of <code>generate_password()</code>).</p>
| 2 | 2016-10-03T12:56:28Z | [
"python",
"json",
"python-3.x"
]
|
Tensorflow control_dependencies not working with list | 39,832,190 | <p>I have a cost, which depends on two list of variables <code>a</code> and <code>b</code>.<br>
I want to :</p>
<ol>
<li>calculate both gradients of the cost at the current point, </li>
<li>update the loss w.r.t. the first list of variables (<code>a</code>)</li>
<li>update the loss w.r.t. the second list of variable (<code>b</code>).</li>
</ol>
<p>In that order.</p>
<p>To do this I tried something like this: </p>
<p><strong>EDIT:</strong> Following @Yaroslav Bulatov's answer I tried the following:</p>
<pre><code>opt=tf.train.GradientDescentOptimizer(0.001)
grad_cost_wrt_a=opt.compute_gradients(cost,[a])
grad_cost_wrt_b=opt.compute_gradients(cost,[b])
with tf.control_dependencies(grad_cost_wrt_a[0]):
with tf.control_dependencies(grad_cost_wrt_b[0]):
update_wrt_a=opt.apply_gradients(grad_cost_wrt_a)
with tf.control_dependencies([update_wrt_a]):
update_wrt_b=opt.apply_gradients(grad_cost_wrt_b)
</code></pre>
<p>Wondering if this is doing the right thing ? If a and b are list of variables.</p>
<p>To be able to then do:</p>
<pre><code>sess.run([update_wrt_a,update_wrt_b],feed_dict={x: x_input, y: y_input})
</code></pre>
<p>First this does not work I get:
cannot convert a list into a Tensor or Operation but control_dependencies is supposed to recieve a list of tensors...</p>
<p>Then bonus question do I really need all those control_dependencies ?</p>
| 0 | 2016-10-03T12:54:38Z | 39,837,261 | <p>Your <code>grad_cost_wrt_a</code> and <code>grad_cost_wrt_b</code> variables are lists, do something like <code>grad_cost_wrt_a[0], grad_cost_wrt_b[0]</code></p>
| 1 | 2016-10-03T17:33:53Z | [
"python",
"tensorflow",
"deep-learning"
]
|
Testing of existence of a repeated field in a protobuff message | 39,832,547 | <p>I have a google protobuf message:</p>
<pre><code>message Foo {
required int bar = 1;
}
</code></pre>
<p>I know that in order to test the fields of message, we can use:</p>
<pre><code>foo.bar = 1
assert foo.HasField("bar")
</code></pre>
<p>However "HasField" doesn't work for repeated field types.
How to test for existence of field for "repeated type" of fields?</p>
<pre><code>message Foo {
repeated int bar = 1;
}
</code></pre>
| 0 | 2016-10-03T13:13:30Z | 39,963,852 | <p>You could try to test the lenght of the repeated field:</p>
<pre><code>assert len(foo.bar) == 0
</code></pre>
| 0 | 2016-10-10T17:42:12Z | [
"python",
"unit-testing",
"protocol-buffers"
]
|
Repeat for i in list - n number of times | 39,832,566 | <p>After some confusion (probably if not definitely caused by a bad question asking on my part) I am trying to work how to achieve a code to perform the following operation, but n number of times:</p>
<pre><code>def 1_level:
for i in list:
for j in i:
mylist.append(i)
def 2_levels:
for i in list:
for j in i:
for k in j:
mylist.append(k)
def 3_levels:
for i in list:
for j in i:
for k in j:
for l in k:
mylist.append(l)
def 4_levels:
for i in list:
for j in i:
for k in j:
for l in k:
for m in l:
mylist.apend(m)
def 5_levels:
for i in list:
for j in i:
for k in j:
for l in k:
for m in l:
for n in m:
mylist.append(n)
</code></pre>
<p>My thoughts are as below : </p>
<pre><code>def prunelist(n,mylist):
if n > 0: # if n has not been reached
for i in mylist:
templist = [] #create blank list for appended items
for j in i:
templist.append(j) #append items one branch down
mylist = templist #overwrite original list
n -= 1 #reduce n by 1
prunelist(n,mylist) #perform operation again (assuming n >0)
else:
return mylist #when n is exhausted, output list
outputlist = prunelist(n,mylist) #perform operation
</code></pre>
<p>(For a more rambling explanation please see edit!!!)</p>
<p>Cheers </p>
<p>J-P</p>
| 2 | 2016-10-03T13:14:40Z | 39,841,003 | <p>You were almost there with your <code>prunelist</code> function, there are just a few issues:</p>
<ul>
<li>You cannot overwrite a passed list by simply doing <code>mylist = templist</code>. This does modify the <code>mylist</code> variable but not the original variable. You could replace the contents of the original list here, but a better way would be to just return the new list (i.e. <code>templist</code>). This would also fit well with the other recursion case where you return the unmodified <code>mylist</code>.</li>
<li>In every iteration through <code>mylist</code>, you throw away the result from the previous iteration. Move the <code>templist = []</code> initialization outside of the loop, and the <code>return prunelist(n, templist)</code> as well</li>
</ul>
<p>If you do that, your function already works:</p>
<pre><code>def prunelist(n, mylist):
if n > 0:
templist = []
for i in mylist:
for j in i:
templist.append(j)
return prunelist(n - 1, templist)
else:
return mylist
</code></pre>
| 2 | 2016-10-03T21:53:47Z | [
"python",
"python-3.x"
]
|
python lxml: how to get text from a element which has a child element | 39,832,587 | <p>I want to extract sometext from the html code, but the following doesn't r
eturn sometext, instead it return "\n". So how to get sometest?</p>
<pre><code>a=html.fromstring("""
<p class="clearfix">
<i class="xueli"></i>
sometext
</p>
""")
a.find(".//i").getparent().text
</code></pre>
| 1 | 2016-10-03T13:15:55Z | 39,832,753 | <p>Instead of <code>.text</code>, use <code>text_content()</code> method:</p>
<pre><code>In [5]: a.find(".//i").getparent().text_content().strip()
Out[5]: 'sometext'
</code></pre>
<p>Or, you can get to the <em>following text sibling</em> of the <code>i</code> element:</p>
<pre><code>In [6]: a.xpath(".//i/following-sibling::text()")[0].strip()
Out[6]: 'sometext'
</code></pre>
| 1 | 2016-10-03T13:23:57Z | [
"python",
"lxml"
]
|
PyQt: How do I load a ui file from a resource? | 39,832,610 | <p>In general, I load all my ui files via the <code>loadui()</code> method, and this works fine for me. This looks like this:</p>
<pre><code>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
The modules for Qt are imported.
PyQt are a set of Python bindings for Qt.
'''
from PyQt4.QtGui import QDialog
from PyQt4.uic import loadUi
from PyQt4.QtCore import Qt, QFile
from PyQt4 import QtCore
class My_Window(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
UI_PATH = QFile(":/ui_file/test.ui")
UI_PATH.open(QFile.ReadOnly)
self.ui_test = loadUi(UI_PATH, self)
UI_PATH.close()
</code></pre>
<p>Now I try to load the ui file via <code>loaduiType()</code>, but it doesn't work. I tried with this code:</p>
<pre><code>from PyQt4.uic import loadUiType
UI_PATH = QFile(":/ui_file/test.ui")
Ui_Class, _ = loadUiType(UI_PATH)
class Test_Window(QDialog, UiClass):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setupUi(self)
</code></pre>
<p>What is the correct and best why to load the ui file with the <code>loadUiType()</code> method?</p>
| 1 | 2016-10-03T13:16:36Z | 39,835,058 | <p>It's not really much different from what you were already doing:</p>
<pre><code>from PyQt4.QtCore import QFile
from PyQt4.uic import loadUiType
import resources_rc
def loadUiClass(path):
stream = QFile(path)
stream.open(QFile.ReadOnly)
try:
return loadUiType(stream)[0]
finally:
stream.close()
Ui_Class = loadUiClass(':/ui_file/test.ui')
</code></pre>
| 1 | 2016-10-03T15:22:06Z | [
"python",
"qt",
"pyqt",
"pyqt4"
]
|
Meaning of self.__dict__ = self in a class definition | 39,832,721 | <p>I'm trying to understand the following snippet of code:</p>
<pre><code>class Config(dict):
def __init__(self):
self.__dict__ = self
</code></pre>
<p>What is the purpose of the line <code>self.__dict__ = self</code>? I suppose it overrides the default <code>__dict__</code> function with something that simply returns the object itself, but since <code>Config</code> inherits from <code>dict</code> I haven't been able to find any difference with the default behavior.</p>
| 3 | 2016-10-03T13:22:41Z | 39,832,796 | <p>Assigning the dictionary <code>self</code> to <code>__dict__</code> allows attribute access and item access:</p>
<pre><code>>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
</code></pre>
| 3 | 2016-10-03T13:26:39Z | [
"python"
]
|
Meaning of self.__dict__ = self in a class definition | 39,832,721 | <p>I'm trying to understand the following snippet of code:</p>
<pre><code>class Config(dict):
def __init__(self):
self.__dict__ = self
</code></pre>
<p>What is the purpose of the line <code>self.__dict__ = self</code>? I suppose it overrides the default <code>__dict__</code> function with something that simply returns the object itself, but since <code>Config</code> inherits from <code>dict</code> I haven't been able to find any difference with the default behavior.</p>
| 3 | 2016-10-03T13:22:41Z | 39,833,012 | <p>As per <a href="https://docs.python.org/2/library/stdtypes.html#object.__dict__" rel="nofollow">Python Document</a>, <code>object.__dict__</code> is:</p>
<blockquote>
<p>A dictionary or other mapping object used to store an objectâs (writable) attributes.</p>
</blockquote>
<p>Below is the sample example:</p>
<pre><code>>>> class TestClass(object):
... def __init__(self):
... self.a = 5
... self.b = 'xyz'
...
>>> test = TestClass()
>>> test.__dict__
{'a': 5, 'b': 'xyz'}
</code></pre>
| 2 | 2016-10-03T13:36:20Z | [
"python"
]
|
Convert Pandas Dataframe Date Index and Column to Numpy Array | 39,832,735 | <p>How can I convert 1 column and the index of a Pandas dataframe with several columns to a Numpy array with the dates lining up with the correct column value from the dataframe?</p>
<p>There are a few issues here with data type and its driving my nuts trying to get both the index and the column out and into the one array!!</p>
<p>Help would be much appreciated!</p>
| 0 | 2016-10-03T13:23:19Z | 39,832,803 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a>:</p>
<pre><code>start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=5)
df = pd.DataFrame({'a': range(5), 'b':list('ABCDE')}, index=rng)
print (df)
a b
2015-02-24 0 A
2015-02-25 1 B
2015-02-26 2 C
2015-02-27 3 D
2015-02-28 4 E
print (df.values)
[[0 'A']
[1 'B']
[2 'C']
[3 'D']
[4 'E']]
</code></pre>
<p>if need index values also first convert <code>datetime</code> to <code>string</code> values in <code>index</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> for converting <code>index</code> to column:</p>
<pre><code>df.index = df.index.astype(str)
print (df.reset_index().values)
[['2015-02-24' 0 'A']
['2015-02-25' 1 'B']
['2015-02-26' 2 'C']
['2015-02-27' 3 'D']
['2015-02-28' 4 'E']]
</code></pre>
| 1 | 2016-10-03T13:26:59Z | [
"python",
"arrays",
"pandas",
"numpy",
"dataframe"
]
|
Convert Pandas Dataframe Date Index and Column to Numpy Array | 39,832,735 | <p>How can I convert 1 column and the index of a Pandas dataframe with several columns to a Numpy array with the dates lining up with the correct column value from the dataframe?</p>
<p>There are a few issues here with data type and its driving my nuts trying to get both the index and the column out and into the one array!!</p>
<p>Help would be much appreciated!</p>
| 0 | 2016-10-03T13:23:19Z | 39,833,244 | <p>If <code>A</code> is dataframe and <code>col</code> the column:</p>
<p><code>import pandas as pd
output = pd.np.column_stack((A.index.values, A.col.values))</code></p>
| 1 | 2016-10-03T13:47:56Z | [
"python",
"arrays",
"pandas",
"numpy",
"dataframe"
]
|
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<p>How can I get the previous index values list of each item in the shuffled list? </p>
| 3 | 2016-10-03T13:25:10Z | 39,832,824 | <p>If your values are unique, just use the <code>list.index</code> method. For example, you can do this:</p>
<pre><code>import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
start_l = l[:]
random.shuffle(l)
for elem in l:
print(elem, '->', start_l.index(elem))
</code></pre>
<p>Of course, in your example this is trivial - each element is already it's initial index.</p>
<pre><code># gives the same result as above.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(l)
for elem in l:
print(elem, '->', elem)
</code></pre>
<p>In fact, the best method depends strongly on what you want to do. If you have other data, it might be simplest to just shuffle indices, not data. This avoids any problems of duplication etc. Basically you get a permutation list, where each element is the index the position is shifted to. For example, <code>[2, 1, 0]</code> is the permutation for reversing a list.</p>
<pre><code>l = list(random.randint(0, 10) for _ in range(10))
l_idx = list(range(len(l))) # list of indices in l
random.shuffle(l_idx)
for new_idx, old_idx in enumerate(l_idx):
print(l[old_idx], '@', old_idx, '->', new_idx)
</code></pre>
| 2 | 2016-10-03T13:27:52Z | [
"python"
]
|
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<p>How can I get the previous index values list of each item in the shuffled list? </p>
| 3 | 2016-10-03T13:25:10Z | 39,832,854 | <p>You could pair each item with its index using <code>enumerate</code>, then shuffle that.</p>
<pre><code>>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>>> indices
(0, 1, 2, 4, 5, 3)
</code></pre>
<p>One advantage of this approach is that it works regardless of whether <code>l</code> contains duplicates.</p>
| 12 | 2016-10-03T13:28:48Z | [
"python"
]
|
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<p>How can I get the previous index values list of each item in the shuffled list? </p>
| 3 | 2016-10-03T13:25:10Z | 39,832,887 | <p>To keep track of everything using a dictionary, one can do this: </p>
<p>Use <code>enumerate</code> in your dictionary comprehension to have index and value in your iteration, and then assign value as key, and index as value. </p>
<pre><code>import random
l = [5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
d = {v: i for i, v in enumerate(l)}
print(d) # current state
random.shuffle(l)
</code></pre>
<p>The advantage here is that you get <code>O(1)</code> lookup for retrieving your index for whatever value you are looking up. </p>
<p>However, if your list will contain duplicates, <a href="http://stackoverflow.com/a/39832854/1832539">this</a> answer from Kevin should be referred to.</p>
| 1 | 2016-10-03T13:30:32Z | [
"python"
]
|
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<p>How can I get the previous index values list of each item in the shuffled list? </p>
| 3 | 2016-10-03T13:25:10Z | 39,832,896 | <p>Create a copy of the original <code>list</code> and shuffle the copy:</p>
<pre><code>>>> import random
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l_copy = list(l) # <-- Creating copy of the list
>>> random.shuffle(l_copy) # <-- Shuffling the copy
>>> l_copy # <-- Shuffled copy
[8, 7, 1, 3, 6, 5, 9, 2, 0, 4]
>>> l # <-- original list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
</code></pre>
| 1 | 2016-10-03T13:30:52Z | [
"python"
]
|
Getting previous index values of a python list items after shuffling | 39,832,773 | <p>Let's say I have such a python list:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>by using <code>random.shuffle</code>, </p>
<pre><code>>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>
<p>I am having the above list.</p>
<p>How can I get the previous index values list of each item in the shuffled list? </p>
| 3 | 2016-10-03T13:25:10Z | 39,833,394 | <p>A more intuitive alternative to the other answers:</p>
<p>Shuffle a range of indices, and use that to get a shuffled list of the original values.</p>
| 1 | 2016-10-03T13:56:05Z | [
"python"
]
|
python3 12 digits script each digit equal three time beore him? | 39,832,820 | <p>Write a program that displays <strong>12 digits</strong>,</p>
<p>each digit is equal to three times the digit before him.</p>
<p>I tried to code like this </p>
<pre><code>a , b , c = 1 , 1 , 1
print(c)
while c < 12 : # for looping
c = c + 1 # c for counting
b = a+b
y = 3*b
print(c,y)
</code></pre>
<p>can any one help me to correct the result </p>
| 0 | 2016-10-03T13:27:44Z | 39,833,305 | <p>You can use <a href="https://docs.python.org/3/reference/expressions.html#the-power-operator" rel="nofollow">power operator</a> for that:</p>
<pre><code>from itertools import islice
def numbers(x, base=3):
n = 0
while True:
yield x * base ** n
n += 1
for n in islice(numbers(1), 12):
print(n)
</code></pre>
<p>Or if you really like your way of doing that, here's a fixed version of your code:</p>
<pre><code>b, c = 1, 0
while c < 12:
print(c, b)
b *= 3
c += 1
</code></pre>
| 0 | 2016-10-03T13:50:55Z | [
"python",
"python-3.x"
]
|
python3 12 digits script each digit equal three time beore him? | 39,832,820 | <p>Write a program that displays <strong>12 digits</strong>,</p>
<p>each digit is equal to three times the digit before him.</p>
<p>I tried to code like this </p>
<pre><code>a , b , c = 1 , 1 , 1
print(c)
while c < 12 : # for looping
c = c + 1 # c for counting
b = a+b
y = 3*b
print(c,y)
</code></pre>
<p>can any one help me to correct the result </p>
| 0 | 2016-10-03T13:27:44Z | 39,834,337 | <p>You can start with a list where first element is the beginning of the multiples:</p>
<p>-- start with 1 or the number you like</p>
<pre><code>multiples = [1]
for i in range(1, 12):
multiples.append(3 * multiples[i - 1])
print(multiples)
</code></pre>
<p>-- Output : [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]</p>
| 0 | 2016-10-03T14:44:50Z | [
"python",
"python-3.x"
]
|
pip show xml shows Null | 39,832,830 | <p>I am using Python 2.7.12,tried</p>
<pre><code>import xml.etree # successfully imported,
</code></pre>
<p>tried</p>
<pre><code>import lxml.etree # successfully imported.
</code></pre>
<p>when i tried to get the version of xml through </p>
<pre><code>pip show xml #Result is Null
pip show lxml show version 3.4.2
</code></pre>
<p>why it is not showing xml version</p>
| -1 | 2016-10-03T13:28:04Z | 39,832,906 | <p>Because <a href="https://docs.python.org/2/library/xml.html#module-xml" rel="nofollow"><code>xml</code></a> is a built-in package in Python 2.7. Built-in modules and packages are tied to the Python version; they're usually only upgraded whenever you upgrade your Python version.</p>
<p><code>pip version</code> only works with 3rd-party packages that have been installed by <code>pip</code> or compatible tools.</p>
<p>Furthermore it seems that <code>pip</code> doesn't output any diagnostics at all, even when trying to force with <code>-v</code> (verbose) flag; it just exits with exit status 1 when given an invalid package name:</p>
<pre><code>% pip show -v asdfasdfasdfasfd; echo Exit status: $?
Exit status: 1
</code></pre>
| 1 | 2016-10-03T13:31:24Z | [
"python",
"xml",
"python-2.7",
"lxml"
]
|
Django refresh session to obtain any new messages for user | 39,832,988 | <p>I'm trying to do a simple push protocol for <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/messages/" rel="nofollow">django messages</a>. So in my REST call, I have the following snippet:</p>
<pre><code> storage = get_messages(self.request)
res = dict(messages=[dict(level=item.level, message=item.message) for item in storage])
now = monotonic()
while not res.messages and monotonic() - now < 15:
sleep(.5)
res.messages = [dict(level=item.level, message=item.message) for item in storage]
</code></pre>
<p>Naturally, the while loop does nothing because the messages framework simply re-reads the session variable which only "updates" on new requests.</p>
<p>I tried going into the underlying code to see if there was anything about updating the storage on the fly, but there seems to be no code that would do this, at least in the messaging framework. There was this promising undocumented <code>storage.update()</code> method, but it turned out to do something else.</p>
<p>So, is there anything in Django framework that would allow me to poll for any messages changes and report that to the browser when it happens? Or a different method that would achieve the same thing more elegantly?</p>
| 0 | 2016-10-03T13:35:40Z | 39,899,673 | <p>I have managed to come to an acceptable solution with a couple of caveats.
Using existing message stores (either cookie or session) proved to be either impossible (cookies) or much too ridden with internal method calls & setting / deleting internal members (session).</p>
<p>This solution uses a new message store, in my case a database one.</p>
<p>settings.py</p>
<pre><code>MESSAGE_STORAGE = 'your_django_app.messages_store.SessionDBStorage'
</code></pre>
<p>your_django_app/messages_store.py</p>
<pre><code>from django.contrib.messages.storage.session import SessionStorage
from main.models import MessagesStore, models
class SessionDBStorage(SessionStorage):
"""
Stores messages in the database based on session id
"""
def _get(self, *args, **kwargs):
"""
Retrieves a list of messages from the database based on session identifier.
"""
try:
return self.deserialize_messages(
MessagesStore.objects.get(pk=self.request.session.session_key).messages), True
except models.ObjectDoesNotExist:
return [], True
def _store(self, messages, response, *args, **kwargs):
"""
Stores a list of messages to the database.
"""
if messages:
MessagesStore.objects.update_or_create(session_key=self.request.session.session_key,
defaults={'messages': self.serialize_messages(messages)})
else:
MessagesStore.objects.filter(pk=self.request.session.session_key).delete()
return []
</code></pre>
<p>your_django_app/rest.py</p>
<pre><code>def pushed_messages():
from time import sleep, monotonic
# standard get messages code
....
now = monotonic()
while not res.messages and monotonic() - now < 15:
sleep(1)
if hasattr(storage, '_loaded_data'): # one last hack to make storage reload messages
delattr(storage, '_loaded_data')
res.messages = [dict(level=item.level, message=item.message) for item in storage]
</code></pre>
<p>Please note that internally this is still a polling solution (the loop constantly reloads the messages), but it proves the concept and ultimately - works. Any underlying storage / signal mechanism optimisations are beyond the scope of this answer.</p>
| 0 | 2016-10-06T15:11:42Z | [
"python",
"django",
"django-messages"
]
|
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class ExtendedFoo(blackbox.Foo):
def __init__(self, x):
super(ExtendedFoo, self).__init__(x)
</code></pre>
<p>would not work here, since, as mentioned above I need to rely on <code>blackbox.FooMaker</code> instead of <code>Foo</code>'s <code>__init__</code> function.</p>
<p>Any ideas on how to extend the module <code>blackbox</code>?</p>
| 0 | 2016-10-03T13:37:59Z | 39,833,250 | <p>Unless the module does some serious hacking, you can just replace its members. Note that all references and assignment work on the <code>blackbox.</code> names, not local names!</p>
<p>If you want your new class' <code>__init__</code> to be run inside <code>FooMaker</code>, simply inherit and replace <code>Foo</code>.</p>
<pre><code>import blackbox
class ExtendedFoo(blackbox.Foo):
def __init__(self, x):
super(ExtendedFoo, self).__init__(x)
blackbox.Foo = ExtendedFoo
</code></pre>
<p>This way, <code>FooMaker</code> will instantiate classes of <code>ExtendedFoo</code> only.</p>
<p>Alternatively, you can replace <code>FooMaker</code> with your own version.</p>
<pre><code>import blackbox
_bbfoomaker = blackbox.FooMaker # keep reference so we can use it later
def SuperFooMaker(*fooargs, **fookwargs):
new_instance = _bbfoomaker(*fooargs, **fookwargs)
new_instance.whitebox = True # or whatever
blackbox.FooMaker = SuperFooMaker
</code></pre>
<p>The restriction to the second is that if another module does something like <code>from blackbox import FooMaker</code>, your module <em>must</em> be run/imported before. Otherwise, the other module still sees the original factory, similar to how you still have <code>_bbfoomaker</code>.</p>
| -1 | 2016-10-03T13:48:09Z | [
"python",
"python-2.7",
"cython"
]
|
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class ExtendedFoo(blackbox.Foo):
def __init__(self, x):
super(ExtendedFoo, self).__init__(x)
</code></pre>
<p>would not work here, since, as mentioned above I need to rely on <code>blackbox.FooMaker</code> instead of <code>Foo</code>'s <code>__init__</code> function.</p>
<p>Any ideas on how to extend the module <code>blackbox</code>?</p>
| 0 | 2016-10-03T13:37:59Z | 39,839,163 | <p>It turned out that the <code>Foo</code> class had a setter function, so what eventually worked for me was</p>
<pre><code>class ExtendedFoo(blackbox.Foo):
pass
def ExtendedFooMaker(*args):
_efoo = ExtendedFoo()
_efoo.set(FooMaker(*args).get())
return _efoo
</code></pre>
| 0 | 2016-10-03T19:38:32Z | [
"python",
"python-2.7",
"cython"
]
|
Extending a black box python module | 39,833,042 | <p>I have a "blackbox" python module which I would like to extend. The module provides a class <code>class Foo</code> with no <code>__init__</code> function, and a helper function <code>FooMaker</code> which returns objects of type <code>Foo</code>. The usual strategy of extending modules:</p>
<pre><code>class ExtendedFoo(blackbox.Foo):
def __init__(self, x):
super(ExtendedFoo, self).__init__(x)
</code></pre>
<p>would not work here, since, as mentioned above I need to rely on <code>blackbox.FooMaker</code> instead of <code>Foo</code>'s <code>__init__</code> function.</p>
<p>Any ideas on how to extend the module <code>blackbox</code>?</p>
| 0 | 2016-10-03T13:37:59Z | 39,857,805 | <p>This should do the same as your solution but is a bit shorter:</p>
<pre><code>from blackbox import Foo, FooMaker
class ExtendedFoo(Foo):
def __init__(self, *args, **kwargs):
self.set(FooMaker(*args, **kwargs).get())
</code></pre>
| 1 | 2016-10-04T16:52:13Z | [
"python",
"python-2.7",
"cython"
]
|
select data from table where name = list? | 39,833,070 | <p>Let's say I have a table names like this :</p>
<pre><code>cust_id cust_name
1 John
2 Mary
3 Pete
</code></pre>
<p>and I create a list of customers and orders in python like this :</p>
<pre><code>{'Pete','pen','Mary','apple','Pete','pencil','John','shirt','John','watch','Mary','sandal'}
</code></pre>
<p>how do I get the <code>cust_id</code> from the table above where the name is like on the list so that a new table will be like this?</p>
<pre><code>id_order cust_id orders
1 3 pen
2 2 apple
3 3 pencil
4 1 shirt
5 1 watch
6 2 sandal
</code></pre>
<p>so the main point of my question how do i select <code>cust_id</code> in the order of my python customer list? and insert them to a new table of order above?</p>
| -1 | 2016-10-03T13:39:05Z | 39,833,180 | <p>I am assuming all the required columns are already present in your current table say <code>MY_TABLE</code>. Your SQL query should be like:</p>
<pre><code>SELECT id_order, cust_id, orders from MY_TABLE where cust_name IN ('Pete', 'Mary', 'John');
</code></pre>
<p>Columns I am expecting in "MY_TABLE":</p>
<ul>
<li>id_order</li>
<li>cust_id</li>
<li>orders</li>
<li>cust_name</li>
</ul>
| 1 | 2016-10-03T13:44:30Z | [
"python",
"mysql"
]
|
Python 3 - How to return all rows as a dict using csv? | 39,833,308 | <p>Listed below is my code to read rows and return one row based on the key value (a specific column i.e. player). How do I return the rest of records?</p>
<pre><code>with open('Players.csv', 'rt') as f:
reader = csv.DictReader(f)
for row in reader:
key = row.pop('PLAYER') #this is my key column
if key in result:
pass
result[key] = row
print (result) #printd (Player and all attributes)
</code></pre>
| -2 | 2016-10-03T13:51:09Z | 39,833,377 | <p>you can try to look at<code>row.keys()</code> and <code>row.items()</code></p>
| 0 | 2016-10-03T13:55:00Z | [
"python",
"python-3.x",
"csv"
]
|
Return data from struct using Numpy Array | 39,833,373 | <p>I am writing Python C-extensions to a library and wish to return data as an Numpy Array. The library has a function that returns data from a sensor into a C structure. I would like to take the data from that structure and return it as a Numpy Array.</p>
<p>The structure definition in the library:</p>
<pre><code>typedef struct rs_extrinsics
{
float rotation[9]; /* column-major 3x3 rotation matrix */
float translation[3]; /* 3 element translation vector, in meters */
} rs_extrinsics;
</code></pre>
<p>The function prototype:</p>
<pre><code>void rs_get_device_extrinsics(const rs_device * device, rs_stream from_stream, rs_stream to_stream, rs_extrinsics * extrin, rs_error ** error);
</code></pre>
<p>Here is my code that is just trying to return the first value for now:</p>
<pre><code>static PyObject *get_device_extrinsics(PyObject *self, PyObject *args)
{
PyArrayObject *result;
int dimensions = 12;
rs_stream from_stream;
rs_stream to_stream;
rs_extrinsics extrin;
if (!PyArg_ParseTuple(args, "iiffffffffffff", &from_stream, &to_stream, &extrin)) {
return NULL;
}
result = (PyArrayObject *) PyArray_FromDims(1, &dimensions, PyArray_DOUBLE);
if (result == NULL) {
return NULL;
}
rs_get_device_extrinsics(dev, from_stream, to_stream, &extrin, &e);
check_error();
result[0] = extrin.rotation[0];
return PyArray_Return(result);
}
</code></pre>
<p>I get the following error on compile:</p>
<pre><code>error: assigning to 'PyArrayObject' (aka 'struct tagPyArrayObject_fields') from incompatible type 'float'
result[0] = extrin.rotation[0];
^ ~~~~~~~~~~~~~~~~~~
</code></pre>
| 0 | 2016-10-03T13:54:50Z | 39,833,533 | <p>PyArrayObject, apart from data, have multiple fields:</p>
<pre><code>typedef struct PyArrayObject {
PyObject_HEAD
char *data;
int nd;
npy_intp *dimensions;
npy_intp *strides;
PyObject *base;
PyArray_Descr *descr;
int flags;
PyObject *weakreflist;
} PyArrayObject;
</code></pre>
<p>You should get your data field data from your PyArrayObjects. Like this: <code>result->data[index];</code> Also you need to cast your data to proper type indicated by <code>result->descr->type</code> character code. Also dims, you are passing to PyArray constructor should be of type <code>npy_intp *</code>, not int. Type of array in your case should be <code>NPY_DOUBLE</code>.</p>
<p>If you are calling your function from python (are you?), you better just passing list object from Python and use PyList C API to manage float sequence. </p>
<pre><code>PyObject*list_of_floats;
PyArg_ParseTuple(args, "iiO", &from_stream, &to_stream, &list_of_floats);
</code></pre>
| 0 | 2016-10-03T14:03:50Z | [
"python",
"c",
"arrays",
"numpy",
"python-c-extension"
]
|
Dataframe Nested Loop - set_value variable inputs | 39,833,405 | <p>Hoping someone may be able to point me in the right direction as I am new to Python. </p>
<p>I am doing a small project to get to grips with data analysis in Python using some football data. I have two dataframes, one with player information and another with match information (match_df). The match_df has 22 columns with a player ID for each player in the match. I would like to swap the player_ID data in the match_df for the player's skill rating. I have written a function to look up a player and a date and return the rating (find_player_skill). I want to apply this to every relevant column in the dataframe but can't work out how to use the apply function because the arguments depend on the dataframe row. Therefore I think the easiest way is to use set_value on each element of the dataframe as below.</p>
<p>The problem is that I haven't managed to get this to execute (although I haven't tried running for hours on end). I assume there is a way to do the same thing in a reasonable time with different code or a souped up version. I have tried running the code on a small sample (3 rows) which was quick and then 1000 rows which didn't complete in 30 mins or so.</p>
<pre><code>#change player ID's to skill data, currently runs very slowly
for i in range(len(match_df['match_date'])):
match_date = match_df['match_date'].iloc[i]
match_index = match_df.iloc[i].name
for pl_lab in ['h1','h2','h3','h4','h5','h6','h7','h8','h9','h10', 'h11',\
'a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11']:
player_ID = match_df[pl_lab].iloc[i]
player_skill = find_player_skill(player_ID, match_date)
match_df.set_value(match_index,pl_lab,player_skill)
</code></pre>
<p>Any suggestions much appreciated.</p>
<p>EDIT: It is also worth saying that I thought about debugging the code and downloaded Pycharm for this but some of the earlier code that I wrote seemed to run very slowly (I wrote everything in iPython initially)</p>
| 1 | 2016-10-03T13:56:38Z | 39,834,000 | <p>here is a manipulation you can do, assuming df is the dataframe of match where columns 0 to 2 is the player ID: </p>
<pre><code>df = pd.DataFrame([['c' , 'a', 'b'], ['b', 'c', 'a']])
df
Out[70]:
0 1 2
0 c a b
1 b c a
df_player = pd.DataFrame([['a', 100], ['b', 230], ['c', 200]],columns=['ID', 'skill']).set_index('ID')
skill
ID
a 100
b 230
c 200
dic = df_player.to_dict()['skill']
df.apply(lambda x: [dic[n] if n in dic.keys() else n for n in x], axis=1)
Out[69]:
0 1 2
0 200 100 230
1 230 200 100
</code></pre>
| 0 | 2016-10-03T14:26:38Z | [
"python",
"pandas",
"dataframe"
]
|
Alternatively replace chars in the string with the corresponding index | 39,833,473 | <p>How to replace the alternative characters in the string with the corresponding index without iterating? For example:</p>
<pre><code>'abcdefghijklmnopqrstuvwxyz'
</code></pre>
<p>should be returned as:</p>
<pre><code>'a1c3e5g7i9k11m13o15q17s19u21w23y25'
</code></pre>
<p>I have the below code to achieve this. <em>But is there a way to skip the loop or, more pythonic way to achieve this</em>:</p>
<pre><code>string = 'abcdefghijklmnopqrstuvwxyz'
new_string = ''
for i, c in enumerate(string):
if i % 2:
new_string += str(i)
else:
new_string += c
</code></pre>
<p>where <code>new_string</code> hold my required value</p>
| 1 | 2016-10-03T14:00:42Z | 39,833,537 | <p>You could use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>, and re-join the characters with <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>; the latter avoids repeated (slow) string concatenation):</p>
<pre><code>newstring = ''.join([str(i) if i % 2 else l for i, l in enumerate(string)])
</code></pre>
<p>Note that you can't evade iteration here. Even if you defined a large list of pre-stringified odd numbers here (<code>odds = [str(i) for i in range(1, 1000, 2)]</code>) then re-use that to use slice assignment on a list <code>string_list[1::2] = odds[:len(string) // 2]</code> Python has to iterate under the hood to re-assign the indices. That's the nature of working with an arbitrary-length sequence.</p>
| 2 | 2016-10-03T14:03:59Z | [
"python",
"string",
"list-comprehension"
]
|
How to add an initial/default value using Django Filters? | 39,833,494 | <p>How can I add an initial/default value when using <a href="https://github.com/carltongibson/django-filter" rel="nofollow">Django Filters</a>?</p>
<p>For example, something like this <code>initial=False</code></p>
<pre><code>class UserFilter(django_filters.FilterSet):
archive = django_filters.BooleanFilter(initial=False)
class Meta:
model = User
fields = ['archive']
</code></pre>
<p>I've tired to override the <code>__init__</code> but this does not appear to work.</p>
| 1 | 2016-10-03T14:02:04Z | 39,833,570 | <p>You can try overriding the <code>__init__</code> method of <code>UserFilter</code>:</p>
<pre><code>def __init__(self, *args, **kwargs):
super(UserFilter, self).__init__(*args, **kwargs)
self.form.initial['archive'] = False
</code></pre>
| 1 | 2016-10-03T14:05:36Z | [
"python",
"django"
]
|
Use python script in robot framework | 39,833,518 | <p>Please help to understand.</p>
<p>I have script (SplitModule.py) :</p>
<pre><code>from robot.api.deco import keyword
@keyword('Split Function')
def splitfunction(string):
print "atata"
new_list = string.split(",")
return new_list
</code></pre>
<p>And robot framework script test.txt :</p>
<pre><code>*** Settings ***
Library DiffLibrary
Library String
Library OperatingSystem
Library Collections
Library SplitModule.py
*** Test Cases ***
Example of calling a python keyword that calls a robot keyword
Split Function ${services}
</code></pre>
<p>But I have a problem with function, there is out :</p>
<blockquote>
<p>============================================================================== Robot
============================================================================== Robot.Check Services
============================================================================== Example of calling a python keyword that calls a robot keyword<br>
| FAIL | No keyword with name 'Split Function ${services}' found.
------------------------------------------------------------------------------ Robot.Check Services<br>
| FAIL | 1 critical test, 0 passed, 1 failed 1 test total, 0 passed, 1
failed
============================================================================== Robot<br>
| FAIL | 1 critical test, 0 passed, 1 failed 1 test total, 0 passed, 1
failed
============================================================================== Output: /opt/robot/logs/output.xml Log: /opt/robot/logs/log.html
Report: /opt/robot/logs/report.html</p>
</blockquote>
<p>What's the problem? thanks</p>
| -1 | 2016-10-03T14:03:16Z | 39,836,092 | <p>Read what the error message is telling you:</p>
<blockquote>
<p>No keyword with name 'Split Function ${services}' found. </p>
</blockquote>
<p>It thinks the test is trying to call the keyword <code>Split Function ${services}</code>. You don't have a keyword with that name. What you <em>do</em> have is a keyword named <code>Split Function</code> which takes an argument. Therefore, you need to use the proper syntax for passing the argument to the keyword. </p>
<p>In other words, you need two or more spaces between the keyword and the argument:</p>
<pre><code>Split Function ${services} # need at least two spaces before $
</code></pre>
| 0 | 2016-10-03T16:20:07Z | [
"python",
"robotframework"
]
|
How to save the edited .csv file in python | 39,833,520 | <p>I have sensor readings stored in csv files and now I am adding some more values to these files. How can I save these files in new locations in csv format for future use. </p>
| 0 | 2016-10-03T14:03:18Z | 39,833,594 | <p>Take a look at this guide: <a href="http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/" rel="nofollow">http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/</a></p>
<p>Basically the <a href="https://docs.python.org/3.3/library/csv.html" rel="nofollow">csv module</a> does what you need:</p>
<pre><code>import csv
</code></pre>
| 0 | 2016-10-03T14:06:41Z | [
"python",
"csv"
]
|
Django test discovery fails | 39,833,731 | <p>I have a bunch of apps, all are inside a <code>apps</code> folder.
I'm adding some tests to my project.
It works well, the models / templates / static discovery works super well.
Now I would like to add some tests to my projects, so I created a <code>tests.py</code> file inside my app. When I want to run the test (<code>manage.py test</code>) it does not work. I have to specify the name of the app to make it works.
I tried with django-nose and I have to same output. I figure out it's because my apps are nested inside a folder but every other django discovery works.</p>
<pre><code>ttn_org
âââ apps
â  âââ app1
â  â  âââ __init__.py
â  â  âââ forms.py
â  â  âââ urls.py
â  â  âââ views.py
â  âââ app2
â  â  âââ __init__.py
â  â  âââ forms.py
â  â  âââ tests.py <- does not work
â  â  âââ urls.py
â  â  âââ views.py
âââ app3
â  âââ __init__.py
â  âââ tests.py <- does work
â  âââ forms.py
â  âââ urls.py
â  âââ views.py
âââ manage.py
âââ requirements.txt
âââ project
âââ __init__.py
âââ celery.py
âââ settings.py
âââ urls.py
âââ wsgi.py
</code></pre>
<p>I have <code>sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))</code> to add make the apps folder usable</p>
| 0 | 2016-10-03T14:13:29Z | 39,848,161 | <p>I installed <code>django-nose</code> and run it with the option <code>--where apps</code></p>
| 0 | 2016-10-04T08:58:52Z | [
"python",
"django",
"testing",
"discover"
]
|
pass several parameters in Django rest Framework | 39,833,747 | <p>I am new with <code>Django</code> and <code>Django rest framework</code>, I try to create several routes to get the data from the database.</p>
<p>Right now in my <code>urls.py</code> file I have this</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cpuProjects'),
</code></pre>
<p>this return this </p>
<pre><code>"cpuProjects": "http://127.0.0.1:8000/cpuProjects/"
</code></pre>
<p>and I have the possibility to do this
<code>http://127.0.0.1:8000/cpuProjects/</code> => return all project
<code>http://127.0.0.1:8000/cpuProjects/ad</code> => return a particular project.</p>
<p>In my view.py I have this</p>
<pre><code>class cpuProjectsViewSet(viewsets.ViewSet):
serializer_class = serializers.cpuProjectsSerializer
# lookup_field = 'project_name'
lookup_url_kwarg = 'project_name'
def list(self, request):
all_rows = connect_database()
serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
return Response(serializer.data)
def retrieve(self, request, project_name=None):
try:
opc = {'name_proj' : project_name }
all_rows = connect_database(opc)
except KeyError:
return Response(status=status.HTTP_404_NOT_FOUND)
except ValueError:
return Response(status=status.HTTP_400_BAD_REQUEST)
serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
return Response(serializer.data)
</code></pre>
<p>Now I want that my Url accepted something like that</p>
<p><code>http://127.0.0.1:8000/cpuProjects/ad/comments</code>
<code>http://127.0.0.1:8000/cpuProjects/ad/ussing</code>
<code>http://127.0.0.1:8000/cpuProjects/ad/process</code></p>
<p>For this I add this new url</p>
<pre><code>router.register(r'cpuProjects/([a-zA-Z0-9]+)$', cpuProjectsViewSet, base_name='cpuProjects'),
</code></pre>
<p>but now when I try this </p>
<pre><code>http://127.0.0.1:8000/cpuProjects/ad/ussing
</code></pre>
<p>I obtain "page no found"</p>
<p>I understood that this URL have to call to retrieve function to get the parameters, so, why this error?</p>
<p>This URL don't do the same process like </p>
<pre><code>http://127.0.0.1:8000/cpuProjects/ad
</code></pre>
<p>Thanks in advance!</p>
| 1 | 2016-10-03T14:14:20Z | 39,833,934 | <p>The routers framework isn't meant to be used with several parameters .. you can manually do it with primary keys (in the regular expressions).</p>
| 0 | 2016-10-03T14:23:20Z | [
"python",
"django",
"django-rest-framework"
]
|
pass several parameters in Django rest Framework | 39,833,747 | <p>I am new with <code>Django</code> and <code>Django rest framework</code>, I try to create several routes to get the data from the database.</p>
<p>Right now in my <code>urls.py</code> file I have this</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cpuProjects'),
</code></pre>
<p>this return this </p>
<pre><code>"cpuProjects": "http://127.0.0.1:8000/cpuProjects/"
</code></pre>
<p>and I have the possibility to do this
<code>http://127.0.0.1:8000/cpuProjects/</code> => return all project
<code>http://127.0.0.1:8000/cpuProjects/ad</code> => return a particular project.</p>
<p>In my view.py I have this</p>
<pre><code>class cpuProjectsViewSet(viewsets.ViewSet):
serializer_class = serializers.cpuProjectsSerializer
# lookup_field = 'project_name'
lookup_url_kwarg = 'project_name'
def list(self, request):
all_rows = connect_database()
serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
return Response(serializer.data)
def retrieve(self, request, project_name=None):
try:
opc = {'name_proj' : project_name }
all_rows = connect_database(opc)
except KeyError:
return Response(status=status.HTTP_404_NOT_FOUND)
except ValueError:
return Response(status=status.HTTP_400_BAD_REQUEST)
serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True)
return Response(serializer.data)
</code></pre>
<p>Now I want that my Url accepted something like that</p>
<p><code>http://127.0.0.1:8000/cpuProjects/ad/comments</code>
<code>http://127.0.0.1:8000/cpuProjects/ad/ussing</code>
<code>http://127.0.0.1:8000/cpuProjects/ad/process</code></p>
<p>For this I add this new url</p>
<pre><code>router.register(r'cpuProjects/([a-zA-Z0-9]+)$', cpuProjectsViewSet, base_name='cpuProjects'),
</code></pre>
<p>but now when I try this </p>
<pre><code>http://127.0.0.1:8000/cpuProjects/ad/ussing
</code></pre>
<p>I obtain "page no found"</p>
<p>I understood that this URL have to call to retrieve function to get the parameters, so, why this error?</p>
<p>This URL don't do the same process like </p>
<pre><code>http://127.0.0.1:8000/cpuProjects/ad
</code></pre>
<p>Thanks in advance!</p>
| 1 | 2016-10-03T14:14:20Z | 39,863,393 | <p>This is somewhat similar to what we did in our earlier <a href="http://stackoverflow.com/questions/39729388/using-django-rest-framework-to-return-info-by-name/39736838#39736838">Q&A</a></p>
<pre><code>from rest_framework.decorators import detail_route, list_route
@detail_route(url_path='(?P<slug>[\w-]+)/(?P<what>[\w-]+)')
def get_by_name(self, request, pk=None,slug=None, what=None):
print(slug, what)
</code></pre>
<p>Similarly you can do the same for a <code>list_route</code></p>
| 1 | 2016-10-04T23:47:03Z | [
"python",
"django",
"django-rest-framework"
]
|
Python Gtk3 create cell of treeview with a color field | 39,833,792 | <p>I want to fill a cell of a treeview with a color field and searching for a good method to do this.</p>
<p>Here is what I have tried already:</p>
<pre><code>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk, GdkPixbuf
window = Gtk.Window()
window.set_default_size(300, 100)
window.connect("delete-event", Gtk.main_quit)
window.set_title("CellRendererPixbuf in GTK3")
box = Gtk.HBox()
window.add(box)
liststore = Gtk.ListStore(GdkPixbuf.Pixbuf)
pix = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 10, 10)
liststore.append([pix])
treeview = Gtk.TreeView(model=liststore)
renderer_pixbuf = Gtk.CellRendererPixbuf().new()
column_pixbuf = Gtk.TreeViewColumn("Color", renderer_pixbuf, stock_id=0)
treeview.append_column(column_pixbuf)
box.pack_start(treeview, True, True, 0)
window.show_all()
Gtk.main()
</code></pre>
| 0 | 2016-10-03T14:16:32Z | 39,835,802 | <p><strong>Solution</strong></p>
<p>Finally I got it working now:</p>
<pre><code>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GdkPixbuf
window = Gtk.Window()
window.set_default_size(300, 100)
window.connect("delete-event", Gtk.main_quit)
window.set_title("CellRendererPixbuf in GTK3")
box = Gtk.HBox()
window.add(box)
# creat liststore
liststore = Gtk.ListStore(str, GdkPixbuf.Pixbuf)
pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 32, 16)
pixbuf.fill(0xff0000)
liststore.append(["Green", pixbuf])
pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 32, 16)
pixbuf.fill(0x00ff00)
liststore.append(["Blue", pixbuf])
pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 32, 16)
pixbuf.fill(0x000000)
liststore.append(["Black", pixbuf])
# create treeview
treeview = Gtk.TreeView(model=liststore)
# create text column
renderer_text = Gtk.CellRendererText()
column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0)
treeview.append_column(column_text)
# create pixbuf column
renderer_pixbuf = Gtk.CellRendererPixbuf().new()
column_pixbuf = Gtk.TreeViewColumn("Color", renderer_pixbuf, pixbuf=1)
treeview.append_column(column_pixbuf)
# pack
box.pack_start(treeview, True, True, 0)
window.show_all()
Gtk.main()
</code></pre>
| 0 | 2016-10-03T16:03:03Z | [
"python",
"gtk3"
]
|
QSpacerItem crashes pyQT when instantiated twice | 39,833,793 | <p>I've been hunting a nasty crash-upon-exit bug in my pyQt Application <a href="https://github.com/chipmuenk/pyfda" rel="nofollow">https://github.com/chipmuenk/pyfda</a> for more than a year now and have just found it by chance: The following code snippet</p>
<pre><code> self.cmbResponseType = QtGui.QComboBox(self)
self.cmbFilterType = QtGui.QComboBox(self)
self.cmbDesignMethod = QtGui.QComboBox(self)
spacer = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Fixed)
layHFilWdg = QtGui.QHBoxLayout() # container for filter subwidgets
layHFilWdg.addWidget(self.cmbResponseType)
layHFilWdg.addItem(spacer)
layHFilWdg.addWidget(self.cmbFilterType)
layHFilWdg.addItem(spacer)
layHFilWdg.addWidget(self.cmbDesignMethod)
</code></pre>
<p>places three combo boxes in a horizontal layout box with variable spacing between them.</p>
<p>The bug disappears (no more crash upon exit) when I comment out one of the two <code>layHFilWdg.addItem(spacer)</code> instructions. I'm using python 2.7 ... 3.5 and pyQt 4.8.</p>
<p>I've got lot of tabbed widgets (and had a lot of other bugs as well) in the application and had worked in a design flow that somehow suppressed the bug for too long, that's why it took me so long. That the crash only happens when a matplotlib canvas has been instantiated in a completely unrelated subwidget is just another weirdness that made me bark up the wrong tree for a long time ... </p>
<p>Has anybody got an idea where the problem lies with the code above?</p>
| 1 | 2016-10-03T14:16:38Z | 39,836,017 | <p>This looks like a typical case of the Python garbage-collector deleting objects in an order that Qt is not expecting. It's possible that adding a spacer multiple times to the same layout may result in Qt trying to delete it twice, or delete it when it's no longer there. With the obvious solution being simply: don't do that.</p>
<p>So either create a new spacer each time:</p>
<pre><code> def spacer():
return QtGui.QSpacerItem(
1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
...
layHFilWdg.addItem(spacer())
</code></pre>
<p>or just use the layout's <code>addStretch()</code> method:</p>
<pre><code> layHFilWdg.addWidget(self.cmbResponseType)
layHFilWdg.addStretch()
</code></pre>
| 1 | 2016-10-03T16:16:33Z | [
"python",
"user-interface",
"crash",
"pyqt"
]
|
OpenCV NoneType object has no attribute shape | 39,833,796 | <p>Hello I'm working on Raspberry Pi with OpenCV. I want to try a tutorial which is ball tracking in link
<a href="http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/</a></p>
<p>But when I compile it, i get an error: 'NoneType' object has no attribute 'shape'.</p>
<p>What should I do?</p>
| -2 | 2016-10-03T14:16:43Z | 39,834,344 | <p>It means that somewhere a function which should return a image just returned None and therefore has no shape attribute. Try
"print img"
to check if your image is None or an actual numpy object.</p>
| 0 | 2016-10-03T14:45:10Z | [
"python",
"opencv",
"raspberry-pi2"
]
|
how do I prevent my list items from being broken up into individual strings when writing to CSV? | 39,833,801 | <p>When writing to my CSV my list item gets broken up into individual strings even though I am using the append function. I think the problem is in how I am using <em>writerow</em>, but I'm not quite sure.</p>
<p>This is my code.</p>
<pre><code>twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
input_path = 'doc_list.csv'
output_path = 'doc_tweets.csv'
docs_array = []
with open(input_path, 'r') as doc_file:
docs = csv.reader(doc_file)
for row in docs:
docs_array.append(row)
with open(output_path, 'w') as tweets_file:
writer = csv.writer(tweets_file, quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for name in docs_array:
tweet_list = []
user_timeline = twitter.get_user_timeline(screen_name=name, count=100, include_retweets=False)
for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow(li)
del tweet_list[:]
del docs_array[:]
</code></pre>
<p>An example of what is in the list before it's iterated for writerow is</p>
<blockquote>
<p>, '@etritabaugh gorgeous',</p>
</blockquote>
<p>After being passed through writer.writerow(li) it becomes</p>
<blockquote>
<p>@,e,t,r,i,t,a,b,a,u,g,h, ,g,o,r,g,e,o,u,s</p>
</blockquote>
| 0 | 2016-10-03T14:16:53Z | 39,833,890 | <p><code>writerow</code> expects an <em>iterable</em>, and once it gets a string, each character in the string gets <em>splitted</em> as separate columns.</p>
<p>To write the entire list as a single row in to the csv, you won't need the second <em>for</em> loop:</p>
<pre><code>for tweet in user_timeline:
tweet_list.append(tweet['text'])
writer.writerow(tweet_list)
</code></pre>
<p>If instead, you want to write each item in the list as a <em>separate</em> row, then use a list literal which will prevent the string from being used as the row:</p>
<pre><code>for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow([li])
# ^ ^
</code></pre>
| 0 | 2016-10-03T14:21:37Z | [
"python",
"csv",
"twitter",
"twython"
]
|
How to count values in a list Python 3 | 39,833,902 | <p>I have code like this:</p>
<pre><code>winners = [red, blue, yellow]
player_1_guesses = [red, green, orange]
player_2_guesses = [red, blue, orange]
player_3_guess = [red, green, yellow]
</code></pre>
<p>I'd like to count how many times each value in <code>winners</code> appears across the three <code>player_x_guesses</code> lists. So I would expect to see something like:</p>
<pre><code>totals = {'red': 3, 'blue': 1, 'yellow': 1}
</code></pre>
<p>I'm not really sure what this kind of data analysis (?) is called or even what to google to achieve what I want. </p>
<p>Thanks for any help.</p>
| 0 | 2016-10-03T14:22:13Z | 39,833,975 | <p>Try doing this:</p>
<pre><code>all_guesses = player_1_guess + player_2_guess + player_3_guess
dct = {i:all_guesses.count(i) for i in winners}
</code></pre>
<p>output:</p>
<pre><code>{'blue': 1, 'yellow': 1, 'red': 3}
</code></pre>
<p>Using <code>collections</code>:</p>
<pre><code>from collections import Counter
dct = Counter(word for word in all_guesses if word in winners)
</code></pre>
| 5 | 2016-10-03T14:25:35Z | [
"python",
"list",
"dictionary",
"counting"
]
|
How to count values in a list Python 3 | 39,833,902 | <p>I have code like this:</p>
<pre><code>winners = [red, blue, yellow]
player_1_guesses = [red, green, orange]
player_2_guesses = [red, blue, orange]
player_3_guess = [red, green, yellow]
</code></pre>
<p>I'd like to count how many times each value in <code>winners</code> appears across the three <code>player_x_guesses</code> lists. So I would expect to see something like:</p>
<pre><code>totals = {'red': 3, 'blue': 1, 'yellow': 1}
</code></pre>
<p>I'm not really sure what this kind of data analysis (?) is called or even what to google to achieve what I want. </p>
<p>Thanks for any help.</p>
| 0 | 2016-10-03T14:22:13Z | 39,834,552 | <p>Not sure if I'm breaking the rules here, but my approach was to search for
"python compare string arrays" and I got this: <a href="http://stackoverflow.com/questions/2783969/compare-string-with-all-values-in-array">Compare string with all values in array</a></p>
<p>You have one list/array of strings that you want to compare with three other lists/arrays.</p>
<p>Assuming you want to know how many players guessed the correct colour and in the right position. In other words player_1_guesses = [green, red, orange] would not count as a correct guess for red because it's not in the first position, for your example.</p>
<p>In my head, the logic of your code would go like this (this isn't python code by the way!):</p>
<ol>
<li>get winners[0], which is 'red'</li>
<li><p>check winners[0] against values in player_n_guesses[0] and record the outcome in a variable called red (e.g. if player_n_guesses[0]==winners[0]:red +=1)</p></li>
<li><p>use nested for loops to go through everything, then make your totals list using the format method.</p></li>
</ol>
<p>I expect there's a more efficient way that directly compares matrices - try searching for 'string matrix comparison python' or something like that.</p>
| 0 | 2016-10-03T14:56:34Z | [
"python",
"list",
"dictionary",
"counting"
]
|
How to describe scopes in EBNF? | 39,833,913 | <p>I'm trying to write a parser for Cisco IOS and ASA configurations, using Grako and Python. I'm trying to figure out how to represent 'scoped' keywords in EBNF - for example, the 'description' keyword must appear inside an <code>interface</code> scope, but there are multiple options for <code>interface</code> and they are all optional (and the order can change between devices, I believe):</p>
<pre><code>interface Vlan1435
nameif untrust
description the outside interface for customer X
bridge-group 1
security-level 0
</code></pre>
<p>The nearest I have found to an example is in a Perl application called Farly that uses the perl Parse::Recdescent module, which appears to be similar to Grako.</p>
<p>From there I have this type of recursive definition:</p>
<pre><code>@@eol_comments :: /!([^\n]*?)\n/
@@whitespace :: /[\t ]+/
start
=
file_input $
;
file_input
=
{NEWLINE | asa_line}
;
asa_line
=
'names' NEWLINE
| interface NEWLINE
;
interface
=
'interface' string NEWLINE interface_options
;
interface_options
=
if_name | sec_level | if_addr | if_bridgegroup | NEWLINE
;
if_bridgegroup
=
'bridge-group' digit NEWLINE interface_options
;
if_name
=
'nameif' string NEWLINE interface_options
;
sec_level
=
'security-level' digit NEWLINE interface_options
;
</code></pre>
<p>but it produces a strange nested AST, and it doesn't "reset" to detect the second interface or anything else in the configuration that follows.</p>
<p>How are these kind of scopes normally defined in EBNF?
(is there a useful tutorial for this type of thing, too? My google-fu did not turn up anything for Grako or parsers generally)</p>
| 0 | 2016-10-03T14:22:30Z | 39,852,149 | <p>A trick I use in these situations is to use repetition even if the options can appear only once:</p>
<pre><code>interface_options
=
{ @+:(if_name | sec_level | if_addr | if_bridgegroup) NEWLINE}*
;
</code></pre>
<p>If necessary, you can use a semantic action to validate that options are not repeated.</p>
| 1 | 2016-10-04T12:18:55Z | [
"python",
"ebnf",
"cisco-ios",
"grako",
"ciscoconfparse"
]
|
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
</code></pre>
<p>What I'm trying to do, is check to see if there is already a dictionary with the ID from the input in the list, and if there is, add the Balance from the input.
Is there any readable pythonic way to do this?</p>
| 0 | 2016-10-03T14:22:59Z | 39,833,999 | <p>What I'm hearing here is "how do I get an item from a list, given that I know some unique key value about it?". How much are you committed to keeping the current data structure? I'm inclined to dispense with the list entirely and use a dict-of-dicts.</p>
<pre><code>d = {
123: {'Balance': 45, 'Comments': None}
456: {'Balance': 78, 'Comments': None}
}
</code></pre>
<p>now checking if an id exists is just <code>if some_id in d:</code> and adding to the balance is <code>d[some_id]["Balance"] += some_amount</code>.</p>
| 0 | 2016-10-03T14:26:37Z | [
"python",
"list",
"dictionary",
"nested"
]
|
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
</code></pre>
<p>What I'm trying to do, is check to see if there is already a dictionary with the ID from the input in the list, and if there is, add the Balance from the input.
Is there any readable pythonic way to do this?</p>
| 0 | 2016-10-03T14:22:59Z | 39,834,023 | <pre><code>data = [{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
any( inputData == item['ID'] for item in data )
inputData = 123
True
</code></pre>
| 0 | 2016-10-03T14:28:05Z | [
"python",
"list",
"dictionary",
"nested"
]
|
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
</code></pre>
<p>What I'm trying to do, is check to see if there is already a dictionary with the ID from the input in the list, and if there is, add the Balance from the input.
Is there any readable pythonic way to do this?</p>
| 0 | 2016-10-03T14:22:59Z | 39,834,026 | <p>Iterate over the list, check that whether there is match with the <code>ID</code>, if yes, add the value to the existing value of <code>BALANCE</code> of that dict. Below is the sample code:</p>
<pre><code>>>> my_dict_list = [{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
>>>
>>> new_id = int(raw_input())
123
>>> for dict_obj in my_dict_list:
... if new_id == dict_obj['ID']:
... dict_obj['Balance'] += float(raw_input())
...
34
>>> my_dict_list
[{'Balance': 79.0, 'ID': 123, 'Comments': None}, {'Balance': 78, 'ID': 456, 'Comments': None}]
# Value updated for "ID" 123
</code></pre>
| 0 | 2016-10-03T14:28:13Z | [
"python",
"list",
"dictionary",
"nested"
]
|
Add items in nested dictionaries based on ID number in python | 39,833,927 | <p>I have dictionaries nested in a list. The dictionaries are set up as follows:</p>
<p><code>{'ID': 123, 'Balance': 45, 'Comments': None}</code></p>
<p>I have multiple of these dictionaries in a list, so the list looks like this:</p>
<pre><code>[{'ID': 123, 'Balance': 45, 'Comments': None}, {'ID': 456, 'Balance': 78, 'Comments': None}]
</code></pre>
<p>What I'm trying to do, is check to see if there is already a dictionary with the ID from the input in the list, and if there is, add the Balance from the input.
Is there any readable pythonic way to do this?</p>
| 0 | 2016-10-03T14:22:59Z | 39,834,676 | <pre><code>accounts = [
{'ID': 123, 'Balance': 45, 'Comments': None},
{'ID': 456, 'Balance': 78, 'Comments': None},
]
def update_balance(account_id, amount):
account = next((a for a in accounts if a['ID'] == account_id), None)
if account:
account['Balance'] += amount
return account
account = int(input('Account ID: '))
amount = float(input('Amount: '))
update_balance(account, amount)
</code></pre>
| 0 | 2016-10-03T15:03:01Z | [
"python",
"list",
"dictionary",
"nested"
]
|
How does the automatic Ansible documentation work? | 39,834,013 | <p>So this is my situation:
I am writing Ansible playbooks and roles in a huge project directory. Currently my documentation is stored in .md files. But I want to use Ansible's documentation mechanism, so I looked into the sphinx documentation system. It seems pretty neat to me, so I installed it and got into the mechanisms.</p>
<p>But what I cant figure out: How does Ansible include the documentation that is located in the python modules into the sphinx documentation?<br>
I am sorry to be not able to be more specific, but currently I am just scratching the surface I assume.</p>
<p>So here is what I want to achieve:</p>
<ul>
<li>I have the typical <code>roles</code> directory</li>
<li>In it there are several roles</li>
<li>The files are mainly .yaml or .yml files</li>
<li>I at least want to include documentation from one file within these role directories</li>
<li>Ideally I want to pull documentation from several files within the directory</li>
</ul>
<p>If too much is unclear please tell me and I will try to improve the question as I can't figure out for hours how to achieve this or even how to ask precisely.</p>
<p><strong>Thanks in advance for every comment and answer!</strong></p>
| 1 | 2016-10-03T14:27:24Z | 39,835,639 | <p>Auto doc is only for Ansible modules, not playbooks.<br>
If you want to document your playbooks, you are on your own.<br>
There is a small project on github: <a href="https://github.com/starboarder2001/ansible-docgen" rel="nofollow">ansible-docgen</a> â it fetches a list of tasks into MD files and adds a couple of headers.<br>
You can achive comparable result by calling <code>ansible-playbook --list-tasks myplaybook.yml</code></p>
<p>In my personal opinion, reading playbooks with comments is very convenient.</p>
| 0 | 2016-10-03T15:54:20Z | [
"python",
"documentation",
"ansible",
"yaml",
"python-sphinx"
]
|
Insert dictionary into SQLlite3 | 39,834,047 | <p>I want to insert data from a dictionary into a sqlite table, I am using slqalchemy to do that, the keys in the dictionary and the column names are the same, and I want to insert the values into the same column name in the table. So this is my code:</p>
<pre><code>#This is the class where I create a table from with sqlalchemy, and I want to
#insert my data into.
#I didn't write the __init__ for simplicity
class Sizecurve(Base):
__tablename__ = 'sizecurve'
XS = Column(String(5))
S = Column(String(5))
M = Column(String(5))
L = Column(String(5))
XL = Column(String(5))
XXL = Column(String(5))
o = Mapping() #This creates an object which is actually a dictionary
for eachitem in myitems:
# Here I populate the dictionary with keys from another list
# This gives me a dictionary looking like this: o={'S':None, 'M':None, 'L':None}
o[eachitem] = None
for eachsize in mysizes:
# Here I assign values to each key of the dictionary, if a value exists if not just None
# product_row is a class and size and stock are its attributes
if(product_row.size in o):
o[product_row.size] = product_row.stock
# I put the final object into a list
simplelist.append(o)
</code></pre>
<p>Now I want to put each the values from the dictionaries saved in simplelist into the right column in the sizecurve table. But I am stuck I don't know how to do that? So for example I have an object like this:</p>
<pre><code>o= {'S':4, 'M':2, 'L':1}
</code></pre>
<p>And I want to see for the row for column S value 4, column M value 2 etc.</p>
| 0 | 2016-10-03T14:28:59Z | 39,837,714 | <p>Yes, it's possible (though aren't you missing primary keys/foreign keys on this table?).</p>
<pre><code>session.add(Sizecurve(**o))
session.commit()
</code></pre>
<p>That should insert the row.</p>
<p><a href="http://docs.sqlalchemy.org/en/latest/core/tutorial.html#executing-multiple-statements" rel="nofollow">http://docs.sqlalchemy.org/en/latest/core/tutorial.html#executing-multiple-statements</a></p>
<p>EDIT: On second read it seems like you are trying to insert all those values into one column? If so, I would make use of pickle. </p>
<p><a href="https://docs.python.org/3.5/library/pickle.html" rel="nofollow">https://docs.python.org/3.5/library/pickle.html</a></p>
<p>If performance is an issue (pickle is pretty fast, but if your doing 10000 reads per second it'll be the bottleneck), you should either redesign the table or use a database like PostgreSQL that supports JSON objects.</p>
| 0 | 2016-10-03T18:02:45Z | [
"python",
"sqlite",
"dictionary",
"sqlalchemy"
]
|
Insert dictionary into SQLlite3 | 39,834,047 | <p>I want to insert data from a dictionary into a sqlite table, I am using slqalchemy to do that, the keys in the dictionary and the column names are the same, and I want to insert the values into the same column name in the table. So this is my code:</p>
<pre><code>#This is the class where I create a table from with sqlalchemy, and I want to
#insert my data into.
#I didn't write the __init__ for simplicity
class Sizecurve(Base):
__tablename__ = 'sizecurve'
XS = Column(String(5))
S = Column(String(5))
M = Column(String(5))
L = Column(String(5))
XL = Column(String(5))
XXL = Column(String(5))
o = Mapping() #This creates an object which is actually a dictionary
for eachitem in myitems:
# Here I populate the dictionary with keys from another list
# This gives me a dictionary looking like this: o={'S':None, 'M':None, 'L':None}
o[eachitem] = None
for eachsize in mysizes:
# Here I assign values to each key of the dictionary, if a value exists if not just None
# product_row is a class and size and stock are its attributes
if(product_row.size in o):
o[product_row.size] = product_row.stock
# I put the final object into a list
simplelist.append(o)
</code></pre>
<p>Now I want to put each the values from the dictionaries saved in simplelist into the right column in the sizecurve table. But I am stuck I don't know how to do that? So for example I have an object like this:</p>
<pre><code>o= {'S':4, 'M':2, 'L':1}
</code></pre>
<p>And I want to see for the row for column S value 4, column M value 2 etc.</p>
| 0 | 2016-10-03T14:28:59Z | 39,855,876 | <p>I have found this answer to a similar question, though this is about reading the data from a json file, so now I am working on understanding the code and also changing my data type to json so that I can insert them in the right place.
<a href="http://stackoverflow.com/questions/8811783/convert-json-to-sqlite-in-python-how-to-map-json-keys-to-database-columns-prop">Convert JSON to SQLite in Python - How to map json keys to database columns properly?</a></p>
| -1 | 2016-10-04T15:09:34Z | [
"python",
"sqlite",
"dictionary",
"sqlalchemy"
]
|
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
print(raw_input(fourthQuestion))
elif secondQuestion == "no":
print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
print(raw_input(seventhQuestion))
elif fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
elif fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
elif sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
elif seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:33:22Z | 39,834,335 | <p>Indeed your program can't go further than the second question,</p>
<pre><code>if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
</code></pre>
<p>whether I answer yes or no to the first question, the code will go in one of those two cases, and therefore can't go to the rest of your program.</p>
<p>You have to write your program thinking of all the possible scenarios and how to reach them:</p>
<pre><code>if firstQuestion == "yes":
#The user answered "yes" to the first question
if secondQuestion == "yes":
#The user answered "yes" to the first question and "yes" to the second
elif secondQuestion == "no":
#The user answered "yes" to the first question and "no" to the second
elif firstQuestion == "no":
#The user answered "no" to the first question
#etc...
</code></pre>
<p>by continuing this graph to all levels, you have all the scenarios of your game covered</p>
| 0 | 2016-10-03T14:44:47Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
]
|
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
print(raw_input(fourthQuestion))
elif secondQuestion == "no":
print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
print(raw_input(seventhQuestion))
elif fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
elif fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
elif sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
elif seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:33:22Z | 39,834,361 | <p>First you ask for the input on the first question. This puts the answer into the firstQuestion variable. Then you go into the if-section. There you ask for the raw_input for another question and then you tell the program to print that value. At that point one the elif's has been succesfull and the others are skipped. </p>
<p>What you should do for the desired result is to create a seperate if-group for each new question that should be asked or create a while-loop.</p>
<p>For example:</p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
secondQuestion = raw_input(secondQuestion)
elif firstQuestion == "no":
thirdQuestion = raw_input(thirdQuestion)
if secondQuestion == "yes":
fourthQuestion = raw_input(fourthQuestion)
elif secondQuestion == "no":
fifthQuestion = raw_input(fifthQuestion)
if thirdQuestion == "no":
sixthQuestion = raw_input(sixthQuestion)
elif thirdQuestion == "yes":
seventhQuestion = raw_input(seventhQuestion)
if fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
if fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
if sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
if seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:46:05Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
]
|
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
print(raw_input(fourthQuestion))
elif secondQuestion == "no":
print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
print(raw_input(seventhQuestion))
elif fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
elif fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
elif sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
elif seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:33:22Z | 39,834,453 | <p>Can you provide the input you used?</p>
<p>It isn't needed though, as I think improving the structure of this program would help answer your question.</p>
<p>For instance, notice how you write:</p>
<pre><code>firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
</code></pre>
<p>Since you assigned the "raw_input..." to "firstQuestion", "firstQuestion" no longer holds the question but the answer to the question. There is a lack of consistency between these lines. It would make more sense to do something like:</p>
<pre><code>firstQuestion = "Is it an even number? "
secondQuestion = "Is it less than or equal to 4? "
#put your other questions here
firstAnswer = raw_input(firstQuestion)
if firstAnswer == "yes":
...
</code></pre>
<p>By changing your program in a way such as this, the logic and resulting behavior will be more clear.</p>
| 0 | 2016-10-03T14:50:30Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
]
|
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
print(raw_input(fourthQuestion))
elif secondQuestion == "no":
print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
print(raw_input(seventhQuestion))
elif fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
elif fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
elif sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
elif seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:33:22Z | 39,834,491 | <p>Consider that your program doesn't scale well at all for larger numbers: if you have to guess a number between 1 and 1000, you're going to have to write a lot of code.</p>
<p>Instead, consider looping through all the ranges that you might get:</p>
<pre><code>lower_limit = 1
upper_limit = 100
while lower_limit < upper_limit:
middle = int(0.5 * (lower_limit + upper_limit))
check = raw_input("Larger than " + str(middle) + "? ")
if check.lower().startswith("y"): # Accept anything that starts with a Y as "yes"
lower_limit = middle + 1
else:
upper_limit = middle
print(lower_limit)
</code></pre>
| 6 | 2016-10-03T14:52:42Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
]
|
guessing numbers from 1 to 8 | 39,834,132 | <p>My program needs to guess the user's number (from 1 to 8) by only asking 3 questions. It prints the first two questions correctly but then when I press enter for the third question, it just prints the last input I did.
How to make all inputs (yes or no) lower case? </p>
<pre><code># Simple Expert System
#firstQuestion = prstr(firstQuestion.lower())
print("Think of a number between 1 and 8.")
firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "
if firstQuestion == "yes":
print(raw_input(secondQuestion))
elif firstQuestion == "no":
print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
print(raw_input(fourthQuestion))
elif secondQuestion == "no":
print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
print(raw_input(seventhQuestion))
elif fourthQuestion == "yes":
print("Your number is 2")
elif fourthQuestion == "no":
print("Your number is 4")
elif fifthQuestion == "yes":
print("Your number is 8")
elif fifthQuestion == "no":
print("Your number is 6")
elif sixthQuestion == "yes":
print("Your number is 7")
elif sixthQuestion == "no":
print("Your number is 5")
elif seventhQuestion == "yes":
print("Your number is 1")
elif seventhQuestion == "no":
print("Your number is 3")
</code></pre>
| 0 | 2016-10-03T14:33:22Z | 39,834,530 | <p>What you've got there doesn't actually use the input from any of the questions except the first. For example:</p>
<pre><code>secondQuestion = "Is it less than or equal to 4? "
# other stuff
elif secondQuestion == "yes": # will never be true
</code></pre>
<p>Calling <code>raw_input(secondQuestion)</code> doesn't change the value of <code>secondQuestion</code>, it just returns the input. Which in your case means printing it a second time.</p>
<p>Also, your <code>elif</code>s mean that it will only check until the first one comes out true - so if you answered <code>'yes'</code> to the first question, it prints and requests input for the second question, and stops there.</p>
<p>Something that would be more like what you want:</p>
<pre><code>questions = []
questions.append("Is it an even number? ")
questions.append("Is it less than or equal to 4? ")
questions.append("Is it less than or equal to 3? ")
questions.append("Is it less than 3? ")
questions.append("Is it greater than 6? ")
questions.append("Is it greater than 5? ")
questions.append("Is it less than 2? ")
answers = [raw_input(q) for q in questions]
# Make sure to validate input
while True:
if answers[0] == 'yes':
is_even = True
break
elif answers[0] == 'no':
is_even = False
break
else:
answers[0] = raw_input("Yes or no, please. ")
# Now repeat that pattern with later questions
while True:
if answers[1] == 'yes':
maximum = 4
break
elif answers[1] == 'no':
minimum = 5
break
else:
answers[1] = raw_input("Yes or no, please. ")
# Continue collecting data like this for all questions,
# Then use it at the end to get an answer
</code></pre>
<p>There's definitely a more efficient way to do it - no reason to hardcode all the questions, for example, it's just a binary search - but this is closer to what you had written than that.</p>
| 0 | 2016-10-03T14:55:05Z | [
"python",
"python-2.7",
"python-3.x",
"if-statement"
]
|
convert python operations to numpy | 39,834,321 | <p>I wrote a basic code which accepts two point coordinates, derives the eqaution of the line passing through it and of the perpendicular, then outputs two points which are the edges of the same perpendicular line. My aim is to do something like what is shown in the pictures of <a href="http://gis.stackexchange.com/questions/50108/elevation-profile-10-km-each-side-of-a-line">this answer</a>, but without all those third-party packages, and without a GIS.</p>
<p>Now, talking about performance, I think my code could greatly benefit of the <code>numpy</code> package, especially in view of using this calculations in a loop with lots (even millions) of pair of point coordinates. Since I didn't use <code>numpy</code> so much, can anyone:</p>
<ol>
<li>(confirm that adapting the code to use <code>numpy</code> would enhance the performance)</li>
<li>suggest of should I adapt the code (e.g. some good hint to start)?</li>
</ol>
<p>Here is the code, hope someone would find it useful (<code>matplotlib</code> is there just to visualize the result).</p>
<pre><code>import matplotlib.pyplot as plt
# calculate y from X coord, slope and intercept
def calculate_y(x, m, q):
y = m * x + q
return y
# the two point coordinates
point_A = [5,7] # First considered point
point_B = [4,10] # Second considered point
# calculate the slope between the point pair
m = (point_A[1] - point_B[1]) / (point_A[0] - point_B[0])
# calculate slope and intercept of the perpendicular (using the second original point)
m_perp = -(1/m)
q_perp = point_B[1] - m_perp * point_B[0]
##print "Perpendicular Line is y = {m}x + {q}".format(m=m_perp,q=q_perp)
# calculate corods of the perpendicular line
distance_factor = 1 #distance from central point
min_X = point_B[0] - distance_factor # left-side X
min_Y = calculate_y(min_X, m_perp, q_perp) # left-side Y
max_X = point_B[0] + distance_factor # right-side X
max_Y = calculate_y(max_X, m_perp, q_perp) # right-side Y
perp_A = (min_X, min_Y)
perp_B = (max_X, max_Y)
x_coord, y_coord = zip(*[point_A, point_B])
x_perp_coord, y_perp_coord = zip(*[perp_A, perp_B])
plt.scatter(x_coord, y_coord)
plt.scatter(x_perp_coord, y_perp_coord)
plt.show()
</code></pre>
| 1 | 2016-10-03T14:43:55Z | 39,841,573 | <p>1) Yes, numpy would increase the performance a lot. Instead of doing a loop in python, you have it in C using the vectorization of numpy.</p>
<p>2) ideas:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# get random coords
npts = 10
distance_factor = 0.05
points = (np.sort(np.random.random(2*npts)).reshape((npts,2)) \
+ np.random.random((npts,2))/npts).T
points_x = points[0] # vector of the chain of x coords
points_y = points[1] # vector of the chain of y coords
plt.plot(points_x, points_y, 'k-o')
plt.gca().set_aspect('equal')
points_x_center = (points_x[1:] + points_x[:-1])*0.5
points_y_center = (points_y[1:] + points_y[:-1])*0.5
plt.plot(points_x_center, points_y_center, 'bo')
ang = np.arctan2(np.diff(points_y), np.diff(points_x)) + np.pi*0.5
min_X = points_x_center + distance_factor*np.cos(ang)
min_Y = points_y_center + distance_factor*np.sin(ang)
max_X = points_x_center - distance_factor*np.cos(ang)
max_Y = points_y_center - distance_factor*np.sin(ang)
plt.plot(np.vstack((min_X,max_X)), np.vstack((min_Y,max_Y)), 'r-')
plt.plot(np.vstack((min_X,max_X)).T, np.vstack((min_Y,max_Y)).T, 'r-', lw=2)
</code></pre>
| 1 | 2016-10-03T22:44:15Z | [
"python",
"python-2.7",
"numpy",
"coordinates"
]
|
scipy.signal.spectrogram output not as expected | 39,834,345 | <p>I am using <code>scipy.signal.spectrogram()</code> for analysing a dataset containing values for a current. My input to the function is as follows:</p>
<pre><code>f, t, Sxx = signal.spectrogram(y, fs)
</code></pre>
<p>(for plotting in subplot 3 (from the top) I use <code>plt.pcolormesh(t, f, Sxx)</code>)</p>
<p>Where <code>y</code> is a list of 10002 values, containing the y values for the green graph in the first plot (from the top). <code>fs = 1/T</code> where <code>T = x[1]-x[0]</code> where <code>x</code> is the list of x values (time) belonging to the y-values (current).</p>
<p>My problem is that</p>
<pre><code>t[-1]-t[0] != x[-1]-x[0]
</code></pre>
<p>Meaning: I want to compare plot 3 with the green graph in plot 1, and when these two do not range over the same time-span, the spectrogram becomes useless. You can see from the picture that <code>total_length_x > total_length_t</code></p>
<p><a href="http://i.stack.imgur.com/HCI6k.png" rel="nofollow"><img src="http://i.stack.imgur.com/HCI6k.png" alt="enter image description here"></a></p>
<p>Why is this so? And what can I do to make the spectrum range over the same time-span as my original data?</p>
| 0 | 2016-10-03T14:45:16Z | 39,877,490 | <p>I wrote some code to explain my comments above about the sizes of the data:</p>
<pre><code>#!/usr/bin/env python
import numpy as np
import scipy.signal
from scipy.signal import spectrogram
WINDOW_LEN = 256
OVERLAP_LEN = WINDOW_LEN / 8
DATA_LEN = 10002
DURATION = 2.0001997
fs = (DATA_LEN - 1) / DURATION
eps = 1/(fs * 1000.0)
y = np.random.rand(DATA_LEN)
x = np.arange(0, DURATION + 1/fs, 1/fs)
f, t, Sxx = spectrogram(y, fs=fs, nperseg=WINDOW_LEN)
T = np.zeros( int(1 + np.floor((len(y) - WINDOW_LEN) / (WINDOW_LEN - OVERLAP_LEN))) )
T[0] = x[WINDOW_LEN / 2]
T[1:] = [x[WINDOW_LEN / 2 + (n + 1) * (WINDOW_LEN - OVERLAP_LEN)] for n in np.arange(0,len(T) - 1)]
if all(t - T < eps):
print (t - T)
print "All are fine"
print x[-1] - x[0]
print t[-1] - t[0]
print T[-1] - T[0]
else:
print t
print T
print "Wrong estimates"
</code></pre>
| 0 | 2016-10-05T15:00:14Z | [
"python",
"scipy",
"signal-processing",
"fft",
"spectrogram"
]
|
Flask-restful app fails when authentication is enabled | 39,834,436 | <p>I'm getting this error whenever I try and enable authentication using flask_httpauth for my flask_restful project:</p>
<pre><code>AttributeError: 'function' object has no attribute 'as_view'
</code></pre>
<p>Here's a very basic example:
apicontroller.py:</p>
<pre><code>from flask_restful import Resource, Api
from flasktest import api, app
from flask_httpauth import HTTPTokenAuth
auth = HTTPTokenAuth()
@auth.login_required
class ApiController(Resource):
def get(self):
return True
api.add_resource(ApiController, '/api/apicontroller')
</code></pre>
<p><strong>init</strong>.py:</p>
<pre><code>from flask import render_template
from flask import Flask, request, render_template, session, flash, redirect, url_for, jsonify
from flask_restful import Resource, Api, reqparse, fields
from flask_httpauth import HTTPTokenAuth
app = Flask(__name__)
api = Api(app)
import flasktest.apicontroller
</code></pre>
<p>Whenever I decorate the controller class with <code>@auth.login_required</code>, it fails with the mentioned error. How can I fix this?</p>
| 0 | 2016-10-03T14:49:49Z | 39,834,643 | <p>I believe that you cannot not apply decorators to class.</p>
<p>To solve that:</p>
<pre><code>from flask_restful import Resource, Api
from flasktest import api, app
from flask_httpauth import HTTPTokenAuth
auth = HTTPTokenAuth()
class ApiController(Resource):
decorators = [auth.login_required]
def get(self):
return True
api.add_resource(ApiController, '/api/apicontroller')
</code></pre>
| 2 | 2016-10-03T15:01:00Z | [
"python",
"flask-restful",
"flask-httpauth"
]
|
Updating matplotlib plot during code execution | 39,834,523 | <p>I have found that the latest update to python/matplotlib has broken a crucial feature, namely, the ability to regularly update or "refresh" a matplotlib plot during code execution. Below is a minimally (non-)working example.</p>
<pre><code>import numpy as np
from matplotlib.pyplot import *
from time import sleep
x = np.array([0])
y = np.array([0])
figure()
for i in range(51):
gca().cla()
plot(x,y)
xlim([0,50])
ylim([0,2500])
draw()
show(block = False)
x = np.append(x,[x[-1]+1])
y = np.append(y,[x[-1]**2])
sleep(0.01)
</code></pre>
<p>If I run this program using Python 3.4.3 and matplotlib 1.4.3, I can see the plot continually update, and the curve grows as the program runs. However, using Python 3.5.1 with matplotlib 1.5.3, the matplotlib window opens but does not show the plot. Instead, it continually shows the window is "not responding" and only presents the final plot when the code finishes executing.</p>
<p>What can I do about this? Is there some way to achieve the functionality that I want using the latest release?</p>
<p>Note: I'm running this from the default IDLE environment if that makes a difference.</p>
| 3 | 2016-10-03T14:54:40Z | 39,839,489 | <p>That is interesting. I'm used to draw interactive plots a little bit differently: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from time import sleep
x = np.array([0])
y = np.array([0])
plt.ion()
fig = plt.figure()
ax=fig.add_subplot(111)
ax.set_xlim([0,50])
ax.set_ylim([0,2500])
line, = ax.plot(x,y)
plt.show()
for i in range(51):
x = np.append(x,[x[-1]+1])
y = np.append(y,[x[-1]**2])
line.set_data(x,y)
plt.draw()
sleep(0.01)
</code></pre>
<p>Can you (or anyone) check if this shows the same problems in Matplotlib 1.5?</p>
| 0 | 2016-10-03T20:00:59Z | [
"python",
"matplotlib",
"plot"
]
|
Function for Iteration over tuples | 39,834,536 | <p>I have the following problem:
I want to iterate over a given list and return the minimum of the sum of all possible cartesian products:</p>
<pre><code>from itertools import product
z = ((1, 2),(2, 3))
def zmin(tup):
return min(sum(a*a for a in s) for s in product(tup))
zmin(z) --> ERROR MESSAGE
</code></pre>
<p>The correct answer should be like that:</p>
<pre><code>1*1 + 2*2 = 5
1*1 + 3*3 = 10
2*2 + 2*2 = 8
2*2 + 3*3 = 13
</code></pre>
<p>So that the return value of zmin(z) = 5</p>
<p>Do you know what am i doing wrong?
Also is there an efficient way with bumpy or something similar?</p>
| 0 | 2016-10-03T14:55:38Z | 39,836,330 | <p>I found an soloution myself:
I added <code>*args</code> for return value:</p>
<pre><code>def zmin(tup):
return min(sum(a*a for a in s) for s in product(*tup))
</code></pre>
| 0 | 2016-10-03T16:35:29Z | [
"python",
"tuples",
"itertools"
]
|
Appending a Path to a Path | 39,834,556 | <p>Is it possible to append a <code>pathlib.Path</code> generator or, combine two <code>Path</code>s?</p>
<pre><code>from pathlib import Path
paths = Path('folder_with_pdfs').glob('**/*.pdf')
paths.append(Path('folder_with_xlss').glob('**/*.xls'))
</code></pre>
<p>With this attempt you'll get:</p>
<pre><code>AttributeError: 'generator' object has no attribute 'append'
</code></pre>
| 0 | 2016-10-03T14:56:44Z | 39,834,727 | <p>That's because <a href="https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob" rel="nofollow"><code>Path.glob</code></a> returns a <code>generator</code>, i.e an object that returns values when <code>next</code> is called which has absolutely no idea what <code>append</code>ing is.</p>
<p>You have two options here, if you require a list wrap the paths in a <code>list</code> call:</p>
<pre><code>paths = list(Path('folder_with_pdfs').glob('**/*.pdf'))
paths.append(list(Path('folder_with_xlss').glob('**/*.xls')))
</code></pre>
<p><sub>(Even though <code>extend</code> is probably what you're after here.)</sub></p>
<p>this of course defeats the purpose of the generator. </p>
<p>So, I'd suggest using something like <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> and creating a generator that will combine them and yield from them one at a time:</p>
<pre><code>from itertools import chain
p1 = Path('folder_with_pdfs').glob('**/*.pdf')
p2 = Path('folder_with_xlss').glob('**/*.xls')
paths = chain(p1, p2)
</code></pre>
<p>Then iterating over <code>paths</code> as required while keeping the memory footprint down.</p>
| 1 | 2016-10-03T15:05:36Z | [
"python",
"python-3.x",
"pathlib"
]
|
TypeError: coercing to Unicode: need string or buffer, int found ( Str method doesn't work ) | 39,834,604 | <p>i am trying to conclude the unfinished module, but i'm having major problem which i can't find fix for, Also note, that i am doing this in Python2. Full code is <a href="https://github.com/GTB3NW/SteamTradingServices/blob/master/Exchange/exchange.py" rel="nofollow">here</a>.</p>
<p>When the code was executed, the first problem i got was in line 69:</p>
<p>Full Log:</p>
<pre><code>>>> main()
INFO:Exchange.exchange:Exchange Service is starting
INFO:pika.adapters.base_connection:Connecting to 127.0.0.1:5672
INFO:pika.adapters.blocking_connection:Created channel=1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click-6.6-py2.7.egg/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click-6.6-py2.7.egg/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click-6.6-py2.7.egg/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click-6.6-py2.7.egg/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Exchange/exchange.py", line 38, in main
Exchange(rmqhost, redishost, redisport, redisdb, status, publishresult).consume()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Exchange/exchange.py", line 69, in __init__
log.debug("Connecting to redis on " + self.redishost + ":" + self.redisport + " db: " + self.redisdb)
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre>
<p>So i tried converting it to unicode string:</p>
<pre><code> log.debug("Connecting to redis on " + str(self.redishost) + ":" + str(self.redisport) + " db: " + str(self.redisdb))
</code></pre>
<p>But it gave me the same error on the same line:</p>
<pre><code> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Exchange/exchange.py", line 69, in __init__
log.debug("Connecting to redis on " + str(self.redishost) + ":" + str(self.redisport) + " db: " + str(self.redisdb))
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre>
<p>I also tried another way of converting string, but same error: </p>
<pre><code> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Exchange/exchange.py", line 69, in __init__
log.debug("Connecting to redis on %s: %s db: %s",
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre>
<hr>
<p>What may the problem be? Even when i tried to covert it to the string it gave me the same error unfortunately... Do i need to import something from <code>__futre__</code> that would help the problem?</p>
| 1 | 2016-10-03T14:59:26Z | 39,835,744 | <p>The <em>coercing</em> error happens when trying so do an operation with a unicode and something which cannot be automatically converted to unicode.</p>
<p>For example:</p>
<pre><code>>>> u'something' + 11
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre>
<p>On the other hand, with <code>unicode</code> and <code>str</code> it will work - <code>str</code> will coerce to <code>unicode</code> before applying the operation:</p>
<pre><code>>>> u'something' + 'else'
u'somethingelse'
</code></pre>
<p>In the example, there are strings and variables (of unknown type), so it has to be that at least one of the variables was <code>unicode</code> and one an <code>int</code>, hence the <em>"coercing to Unicode"</em> error.</p>
<h2>General Solution</h2>
<p>Any of these will work:</p>
<pre><code>>>> u'aaaa ' + str(9) + ':' + str(15)
u'aaaa 9:15'
>>> u'aaaa %s: %s' % (9, 15)
u'aaaa 9: 15'
>>> u'aaaa {}: {}'.format(9, 15)
u'aaaa 9: 15'
</code></pre>
<h2>Logging Solution</h2>
<p>The proper way to format logs would be:</p>
<pre><code>log.debug("Connecting to redis on %s: %s db: %s",
self.redishost,
self.redisport,
self.redisdb)
</code></pre>
<p>I.e. you do not format the string - you let the logger do that.</p>
<p>That way, you avoid formatting the strings if the log level is disabled.</p>
<p>It also looks much better.</p>
| 2 | 2016-10-03T15:59:47Z | [
"python",
"python-2.7",
"unicode"
]
|
Ansible VM:TypeError: __init__() takes at least 3 arguments (2 given) | 39,834,641 | <p>I'm learning about virtual machine and others, I'm trying to configure a VM(with Ansible and DigitalOcean API V2)that needs a file.py to the full correct configuration of this machine (according to the book that I'm studying), but when I try use the command <strong>python do_api_v1.py</strong> the output says:</p>
<blockquote>
<p>**Traceback (most recent call last):</p>
<p>File "do_api_v1.py", line 12, in
do = DoManager(token) TypeError: <strong>init</strong>() takes at least 3 arguments (2 given)
**</p>
</blockquote>
<p>the file do_api_v1.py it is like: </p>
<pre><code>"""
dependencias:
sudo pip install dopy pyopenssl ndg-httpsclient pyasn1
"""
import os
from dopy.manager import DoManager
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
api_version = os.getenv("DO_API_VERSION")
api_token=os.getenv("DO_API_
do = DoManager(None, 'api_token', 'api_version')
keys = do.all_ssh_keys()
print "ssh key nametid"
for key in keys:
print "%s\t%d" % (key["name"], key["id"])
print "Image name\tid"
imgs = do.all_images()
for img in imgs:
if img["slug"] == "ubuntu-14-04-x64":
print "%s\t%d" % (img["name"], img["id"])
print "Region name\tid"
regions = do.all_regions()
for region in regions:
if region["slug"] == "nyc2":
print "%s\t%d" % (region["slug"], region["id"])
print "Size name\tid"
sizes = do.sizes()
for size in sizes:
if size["slug"] == "512mb":
print "%s\t%d" % (size["slug"], size["id"])
</code></pre>
| 0 | 2016-10-03T15:00:54Z | 39,834,764 | <p>You are not passing enough arguments to <a href="https://github.com/Wiredcraft/dopy/blob/8b7bcbc85ef27ec4ae2fb46eae9bac827c4c3df0/dopy/manager.py#L47" rel="nofollow"><code>DoManager</code></a> as the error message says. You need to pass an obligatory <code>client_id</code> as the first argument, and an <code>api_key</code> as the second.</p>
| 0 | 2016-10-03T15:07:32Z | [
"python",
"virtual-machine",
"ansible"
]
|
Ansible VM:TypeError: __init__() takes at least 3 arguments (2 given) | 39,834,641 | <p>I'm learning about virtual machine and others, I'm trying to configure a VM(with Ansible and DigitalOcean API V2)that needs a file.py to the full correct configuration of this machine (according to the book that I'm studying), but when I try use the command <strong>python do_api_v1.py</strong> the output says:</p>
<blockquote>
<p>**Traceback (most recent call last):</p>
<p>File "do_api_v1.py", line 12, in
do = DoManager(token) TypeError: <strong>init</strong>() takes at least 3 arguments (2 given)
**</p>
</blockquote>
<p>the file do_api_v1.py it is like: </p>
<pre><code>"""
dependencias:
sudo pip install dopy pyopenssl ndg-httpsclient pyasn1
"""
import os
from dopy.manager import DoManager
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
api_version = os.getenv("DO_API_VERSION")
api_token=os.getenv("DO_API_
do = DoManager(None, 'api_token', 'api_version')
keys = do.all_ssh_keys()
print "ssh key nametid"
for key in keys:
print "%s\t%d" % (key["name"], key["id"])
print "Image name\tid"
imgs = do.all_images()
for img in imgs:
if img["slug"] == "ubuntu-14-04-x64":
print "%s\t%d" % (img["name"], img["id"])
print "Region name\tid"
regions = do.all_regions()
for region in regions:
if region["slug"] == "nyc2":
print "%s\t%d" % (region["slug"], region["id"])
print "Size name\tid"
sizes = do.sizes()
for size in sizes:
if size["slug"] == "512mb":
print "%s\t%d" % (size["slug"], size["id"])
</code></pre>
| 0 | 2016-10-03T15:00:54Z | 39,834,767 | <p>DoManager requires more arguments. </p>
<p>From the <a href="https://pypi.python.org/pypi/dopy" rel="nofollow">docs</a>:</p>
<p>For V1 of the API:</p>
<pre><code># export DO_CLIENT_ID='client_id'
# export DO_API_KEY='long_api_key'
>>> from dopy.manager import DoManager
>>> do = DoManager('client_id', 'long_api_key')
</code></pre>
<p>And for V2:</p>
<pre><code># export DO_API_VERSION='2'
# export DO_API_TOKEN='api_token'
>>> from dopy.manager import DoManager
>>> do = DoManager(None, 'api_token', api_version=2)
</code></pre>
<p>Both versions require you to supply an API key, but V2 doesn't need the client ID anymore. </p>
| 0 | 2016-10-03T15:07:40Z | [
"python",
"virtual-machine",
"ansible"
]
|
Using Django outside of view.py | 39,834,690 | <p>I have a twisted based script running that is managing IO, monitoring serial inputs, writing logs etc. It uses Twisted to run events every minute and every hour as well as interrupt on serial traffic.</p>
<p>Can Django be used to provide an interface for this, for example taking live values and display them using </p>
<pre><code>#python code generating value1 and value2
def displayValues(request):
context = {
'value1':value1,
'value2':value2
}
return render(request, 'interface.html', context)
</code></pre>
<p>The obvious issue is that this python file doesn't live in the Django file setup and so the URL call wouldn't know where to look or how to call the displayValues function. </p>
<p>An additional feature I might look to is to write the IO values in to a mysql database through Django as it is already setup.</p>
<p>I understand Django from a simple databases application point of view but this is not something I've come across online and I might be moving outside of the scope of Django.</p>
<p>I've seen this but it is more to do with using the Model outside of the standard setup. <a href="http://stackoverflow.com/questions/2180415/using-django-database-layer-outside-of-django">Using Django database layer outside of Django?</a></p>
<p>Is this possible?</p>
<p>Thanks! </p>
| -1 | 2016-10-03T15:03:31Z | 39,834,798 | <p>Why do you need Django for such a simple use case?
For simple Http requests you can you the included Python tool:</p>
<p><a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow">https://docs.python.org/2/library/simplehttpserver.html</a></p>
| 0 | 2016-10-03T15:09:45Z | [
"python",
"django",
"twisted"
]
|
Flask can't redirect me to home page, it just gives me the html code as response | 39,834,722 | <p>I'm building a login with flask and flask-login, and the authentication works perfectly. When a user is authenticated, he should be automatically redirected to the home page (which is unavailable for a not-logged user). The issue is that <code>flask.redirect</code> function just returns me the html code of the home page instead of redirecting to that page. I see the html code in the response object inside the browser console. How can I solve?
Here it is the relevant code:</p>
<pre><code>@app.route('/home')
@flask_login.login_required
def home():
return render_template('home.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if(request.method == 'GET'):
return render_template('login.html')
email = request.form['email']
passwd = request.form['passwd']
data = getUsersData()
for key in data:
if(email == data[key]['email'] and passwd == data[key]['pass']):
user = User()
user.id = email
flask_login.login_user(user, remember=True)
next = request.args.get('next')
if(next):
return redirect(next)
else:
return redirect(url_for('home'))
abort(401) # if inside the for, it can't find valid username and password
</code></pre>
<p>I would like that when the authentication succeeded, the browser redirects me to <code>localhost:10000/home</code> </p>
<p>EDIT:
<a href="http://i.stack.imgur.com/FkRXB.png" rel="nofollow">The terminal log with both GET and POST request to <code>/home</code></a></p>
<p>EDIT 2:
<a href="http://i.stack.imgur.com/CwIB3.png" rel="nofollow">The response object</a></p>
| 0 | 2016-10-03T15:05:15Z | 39,860,813 | <p>If I look at your screen copy, you have something like this:</p>
<pre><code>"POST /login HTTP/1.1" 302 -
"POST /home HTTP/1.1" 200 -
</code></pre>
<p><em>note:</em> you can have exit code 302 or 307, which is approximately the same: a redirection.</p>
<p>So, the redirection from <code>/login</code> to <code>/home</code> works. No error here.</p>
<p>You said:</p>
<blockquote>
<p>The issue is that <code>flask.redirect</code> function just returns me the HTML code of the home page instead of redirecting to that page.</p>
</blockquote>
<p>But this is exactly what you implement here:</p>
<pre><code>@app.route('/home')
@flask_login.login_required
def home():
return render_template('home.html')
</code></pre>
<p>So, I think there is an ambiguity: what do you call "home page"? Is it the page of the <code>/home</code> route, or an "index.html" page which can be the page of the "/" route?</p>
| 0 | 2016-10-04T20:01:13Z | [
"python",
"flask"
]
|
Read lines from text as a list in Python | 39,834,839 | <p>I am read data from text file. Every line of my data have the following structure </p>
<pre><code>(110, 'Math', 1, 5)
(110, 'Sports', 1, 5)
(110, 'Geography', 4, 10)
(112, 'History', 1, 9)
....
</code></pre>
<p>and when I am reading the data from the file it is parsed as a string. So for all the lines I parse the data in a list of strings. However I want to create a list of lists with the 4 different elements (intengers and strings). How can I read the file elementwise and not parse it as string?</p>
<p>My code for read the file is the following:</p>
<pre><code>data1 = [line.strip() for line in open("data.txt", 'r')]
</code></pre>
| 1 | 2016-10-03T15:11:34Z | 39,834,931 | <p>Assuming that the format is always as you described (i.e. corresponds to the Python tuple syntax), this is easily done with <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval"><code>ast.literal_eval()</code></a>:</p>
<pre><code>>>> ast.literal_eval("(110, 'Math', 1, 5)")
(110, 'Math', 1, 5)
</code></pre>
<p>So, the full code is:</p>
<pre><code>import ast
with open('data.txt') as fp:
data = [ast.literal_eval(line) for line in fp]
</code></pre>
| 5 | 2016-10-03T15:16:30Z | [
"python"
]
|
Read lines from text as a list in Python | 39,834,839 | <p>I am read data from text file. Every line of my data have the following structure </p>
<pre><code>(110, 'Math', 1, 5)
(110, 'Sports', 1, 5)
(110, 'Geography', 4, 10)
(112, 'History', 1, 9)
....
</code></pre>
<p>and when I am reading the data from the file it is parsed as a string. So for all the lines I parse the data in a list of strings. However I want to create a list of lists with the 4 different elements (intengers and strings). How can I read the file elementwise and not parse it as string?</p>
<p>My code for read the file is the following:</p>
<pre><code>data1 = [line.strip() for line in open("data.txt", 'r')]
</code></pre>
| 1 | 2016-10-03T15:11:34Z | 39,834,937 | <p>Do as follow :</p>
<pre><code>data1 = [line.strip(')').strip('(').split() for line in open("data.txt", 'r')]
</code></pre>
| 1 | 2016-10-03T15:16:43Z | [
"python"
]
|
Python .pyd equivalent on linux | 39,834,856 | <p>I have some c++ code that is working as a python module using boost.
It is actually a plugin of another c++ python module.</p>
<p>On windows, I have to link against a <code>libavg.pyd</code> file of this library.</p>
<p>On linux I tried linking against <code>libavg.so</code>, but when doing that, dlopen fails with undefined references to functions that should be defined in <code>libavg.pyd</code>.</p>
<p>What is the equivalent of linking to a .pyd file on linux?</p>
| 0 | 2016-10-03T15:12:33Z | 39,835,809 | <p>On linux .pyd equivalent is .so files.</p>
<p>I'm not know about Boost::Python specifics, but you can try to use script like this:</p>
<pre><code>from distutils.core import setup, Extension
module = Extension('ModuleName', sources=['yourmodule.cpp'], language="c++")
setup(name="ModuleName",
version='1.0',
description='My package',
ext_modules=[module])
</code></pre>
<p>And after this just import your built module with .so-extension.</p>
| 1 | 2016-10-03T16:03:23Z | [
"python",
"c++",
"linux",
"python-2.7"
]
|
Sublime Text: Add character in column position | 39,834,861 | <p>I have a Python file with a few hundred lines of code. The longest line is 146 characters. How would I put <code>#</code> in column 200 down the whole file within Sublime Text? Preferably with one or two Sublime Text commands?</p>
<p><code>1 200</code></p>
<p><code>print("Hello world!") #</code> </p>
| -2 | 2016-10-03T15:12:35Z | 39,835,077 | <p>You can try something like this. Note that this writes to a new file: let me know if you want me to modify so that it overwrites the existing file:</p>
<pre><code>data = []
with open('data.txt', 'r') as f:
data = [line[:-1] + ' ' * (200 - len(line)) + '#\n' for line in f]
with open('new_data.txt', 'w') as f:
f.writelines(data)
</code></pre>
<p>Note that this will have just append the "#" at the end of the line (regardless of column number) if the line length >= 200.</p>
| 1 | 2016-10-03T15:23:17Z | [
"python",
"comments",
"sublimetext2",
"sublimetext3"
]
|
Sublime Text: Add character in column position | 39,834,861 | <p>I have a Python file with a few hundred lines of code. The longest line is 146 characters. How would I put <code>#</code> in column 200 down the whole file within Sublime Text? Preferably with one or two Sublime Text commands?</p>
<p><code>1 200</code></p>
<p><code>print("Hello world!") #</code> </p>
| -2 | 2016-10-03T15:12:35Z | 39,835,417 | <p>Here's a possible solution:</p>
<pre><code>N = 200
output = [l.rstrip() for l in f]
output = ["{0}#{1}".format(
l[:len(l[:N])] + ' ' * (N - len(l[:N])), l[N:]) for l in output]
print("\n".join(output))
</code></pre>
<p>Or written differently:</p>
<pre><code>N = 200
output = []
for l in f:
l = l.rstrip()
l1 = len(l[:N])
output.append("{0}#{1}".format(l[:l1] + ' ' * (N - l1), l[N:]))
print("\n".join(output))
</code></pre>
| 0 | 2016-10-03T15:41:54Z | [
"python",
"comments",
"sublimetext2",
"sublimetext3"
]
|
Running twisted reactor in iPython | 39,834,949 | <p>I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.</p>
<p><a href="http://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython">How to start twisted's reactor from ipython</a> asked basically the same thing but the first solution no longer works with current ipython/twisted, while the second is also unusable (thread raises multiple errors).</p>
<p><a href="https://gist.github.com/kived/8721434" rel="nofollow">https://gist.github.com/kived/8721434</a> has something called TPython which purports to do this, but running that seems to work except clients never connect to the server (while running the same clients works in the python shell).</p>
<p>Do I <em>have</em> to use Conch Manhole, or is there a way to get iPython to play nice (probably with _threadedselect).</p>
<p>For reference, I'm asking using ipython 5.0.0, python 2.7.12, twisted 16.4.1</p>
| 0 | 2016-10-03T15:17:16Z | 39,841,749 | <p>While this doesn't answer the question I thought I had, it does answer (sort of) the question I posted. Embedding ipython works in the sense that you get access to business objects with the reactor running.</p>
<pre><code>from twisted.internet import reactor
from twisted.internet.endpoints import serverFromString
from myfactory import MyFactory
class MyClass(object):
def __init__(self, **kwargs):
super(MyClass, self).__init__(**kwargs)
server = serverFromString(reactor, 'tcp:12345')
server.list(MyFactory(self))
def interact():
import IPython
IPython.embed()
reactor.callInThread(interact)
if __name__ == "__main__":
myclass = MyClass()
reactor.run()
</code></pre>
<p>Call the above with <code>python myclass.py</code> or similar.</p>
| 0 | 2016-10-03T23:04:46Z | [
"python",
"ipython",
"twisted"
]
|
Running twisted reactor in iPython | 39,834,949 | <p>I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.</p>
<p><a href="http://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython">How to start twisted's reactor from ipython</a> asked basically the same thing but the first solution no longer works with current ipython/twisted, while the second is also unusable (thread raises multiple errors).</p>
<p><a href="https://gist.github.com/kived/8721434" rel="nofollow">https://gist.github.com/kived/8721434</a> has something called TPython which purports to do this, but running that seems to work except clients never connect to the server (while running the same clients works in the python shell).</p>
<p>Do I <em>have</em> to use Conch Manhole, or is there a way to get iPython to play nice (probably with _threadedselect).</p>
<p>For reference, I'm asking using ipython 5.0.0, python 2.7.12, twisted 16.4.1</p>
| 0 | 2016-10-03T15:17:16Z | 39,843,043 | <p>Async code in general can be troublesome to run in a live interpreter. It's best just to run an async script in the background and do your iPython stuff in a separate interpreter. You can intercommunicate using files or TCP. If this went over your head, that's because it's not always simple and it might be best to avoid the hassle of possible.</p>
<p>However, you'll be happy to know there is an awesome project called <code>crochet</code> for using Twisted in non-async applications. It truly is one of my favorite modules and I'm shocked that it's not more widely used (you can change that ;D though). The <code>crochet</code> module has a <code>run_in_reactor</code> decorator that runs a Twisted reactor in a separate thread managed by <code>crochet</code> itself. Here is a quick class example that executes requests to a Star Wars RESTFul API, then stores the JSON response in a list.</p>
<pre><code>from __future__ import print_function
import json
from twisted.internet import defer, task
from twisted.web.client import getPage
from crochet import run_in_reactor, setup as setup_crochet
setup_crochet()
class StarWarsPeople(object):
people_id = [_id for _id in range(1, 89)]
people = []
@run_in_reactor
def requestPeople(self):
"""
Request Star Wars JSON data from the SWAPI site.
This occurs in a Twisted reactor in a separate thread.
"""
for _id in self.people_id:
url = 'http://swapi.co/api/people/{0}'.format(_id).encode('utf-8')
d = getPage(url)
d.addCallback(self.appendJSON)
def appendJSON(self, response):
"""
A callback which will take the response from the getPage() request,
convert it to JSON, then append it to self.people, which can be
accessed outside of the crochet thread.
"""
response_json = json.loads(response.decode('utf-8'))
#print(response_json) # uncomment if you want to see output
self.people.append(response_json)
</code></pre>
<p>Save this in a file (example: <code>swapi.py</code>), open iPython, import the newly created module, then run a quick test like so:</p>
<pre><code>from swapi import StarWarsPeople
testing = StarWarsPeople()
testing.requestPeople()
from time import sleep
for x in range(5):
print(len(testing.people))
sleep(2)
</code></pre>
<p>As you can see it runs in the background and stuff can still occur in the main thread. You can continue using the iPython interpreter as you usually do. You can even have a manhole running in the background for some cool hacking too!</p>
<h1>References</h1>
<ul>
<li><a href="https://crochet.readthedocs.io/en/1.5.0/introduction.html#crochet-use-twisted-anywhere" rel="nofollow">https://crochet.readthedocs.io/en/1.5.0/introduction.html#crochet-use-twisted-anywhere</a></li>
</ul>
| 0 | 2016-10-04T01:52:00Z | [
"python",
"ipython",
"twisted"
]
|
Adding row to dataframe | 39,834,999 | <p>Suppose I am trying add rows to a dataframe with 40 columns. Ordinarily it would be something like this:</p>
<pre><code>df = pandas.DataFrame(columns = 'row1', 'row2', ... ,'row40'))
df.loc[0] = [value1, value2, ..., value40]
</code></pre>
<p>(don't take the dots literally)</p>
<p>However let's say value1 to value10 are in list1 (i.e. list1 = [value1, value2, ..., value10]), and all the remaining values are individual elements.</p>
<p>I tried: </p>
<pre><code>df.loc[0] = [list1, value11, value12, ..., value40]
</code></pre>
<p>but it doesn't work, because Python interprets the entire list as one element. So it's the wrong dimension. How can I rewrite the code to make it work?</p>
| 1 | 2016-10-03T15:19:35Z | 39,835,057 | <p>I think you need:</p>
<pre><code>df.loc[0] = list1 + [value11, value12, ..., value40]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame(columns = ['row1', 'row2','row3', 'row4','row5', 'row6','row40'])
list1 = ['a','b','c']
df.loc[0] = list1 + ['d','e','f', 'g']
print (df)
row1 row2 row3 row4 row5 row6 row40
0 a b c d e f g
</code></pre>
| 2 | 2016-10-03T15:22:06Z | [
"python",
"list",
"pandas",
"append",
"multiple-columns"
]
|
IOError: [Errno socket error] using BeautifulSoup | 39,835,010 | <p>I am trying to get the data from US Census website using beautiful soup with Python 2.7. This is the code that I use:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = "https://www.census.gov/quickfacts/table/PST045215/01"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
</code></pre>
<p>However, this is the error I got:</p>
<pre><code>IOError Traceback (most recent call last)
<ipython-input-5-47941f5ea96a> in <module>()
59
60 url = "https://www.census.gov/quickfacts/table/PST045215/01"
---> 61 html = urllib.urlopen(url).read()
62 soup = BeautifulSoup(html)
63
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.pyc in urlopen(url, data, proxies, context)
85 opener = _urlopener
86 if data is None:
---> 87 return opener.open(url)
88 else:
89 return opener.open(url, data)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.pyc in open(self, fullurl, data)
211 try:
212 if data is None:
--> 213 return getattr(self, name)(url)
214 else:
215 return getattr(self, name)(url, data)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.pyc in open_https(self, url, data)
441 if realhost: h.putheader('Host', realhost)
442 for args in self.addheaders: h.putheader(*args)
--> 443 h.endheaders(data)
444 errcode, errmsg, headers = h.getreply()
445 fp = h.getfile()
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.pyc in endheaders(self, message_body)
1051 else:
1052 raise CannotSendHeader()
-> 1053 self._send_output(message_body)
1054
1055 def request(self, method, url, body=None, headers={}):
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.pyc in _send_output(self, message_body)
895 msg += message_body
896 message_body = None
--> 897 self.send(msg)
898 if message_body is not None:
899 #message_body was not a string (i.e. it is a file) and
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.pyc in send(self, data)
857 if self.sock is None:
858 if self.auto_open:
--> 859 self.connect()
860 else:
861 raise NotConnected()
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.pyc in connect(self)
1276
1277 self.sock = self._context.wrap_socket(self.sock,
-> 1278 server_hostname=server_hostname)
1279
1280 __all__.append("HTTPSConnection")
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.pyc in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
351 suppress_ragged_eofs=suppress_ragged_eofs,
352 server_hostname=server_hostname,
--> 353 _context=self)
354
355 def set_npn_protocols(self, npn_protocols):
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.pyc in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context)
599 # non-blocking
600 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 601 self.do_handshake()
602
603 except (OSError, ValueError):
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.pyc in do_handshake(self, block)
828 if timeout == 0.0 and block:
829 self.settimeout(None)
--> 830 self._sslobj.do_handshake()
831 finally:
832 self.settimeout(timeout)
IOError: [Errno socket error] [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)
</code></pre>
<p>I have looked from two Stack Overflow sources such as <a href="http://stackoverflow.com/questions/30918761/sslv3-alert-handshake-failure-with-urllib2">this</a> and <a href="http://stackoverflow.com/questions/33394517/html-link-parsing-using-beautifulsoup">this</a> for solutions but they do not solve the issue.</p>
| 1 | 2016-10-03T15:19:59Z | 39,835,375 | <p>One workaround to this problem would be to switch to <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = "https://www.census.gov/quickfacts/table/PST045215/01"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
print(soup.title.get_text())
</code></pre>
<p>Prints:</p>
<pre><code>Alabama QuickFacts from the US Census Bureau
</code></pre>
<p>Note that this might need <a href="http://stackoverflow.com/a/34473533/771848"><code>requests\[security\]</code> package</a> to be installed as well:</p>
<pre><code>pip install requests[security]
</code></pre>
| 2 | 2016-10-03T15:39:49Z | [
"python",
"beautifulsoup"
]
|
Pandas random sample with remove | 39,835,021 | <p>I'm aware of <code>DataFrame.sample()</code>, but how can I do this and also remove the sample from the dataset? (<em>Note: AFAIK this has nothing to do with sampling with replacement</em>)</p>
<p>For example here is <strong>the essence</strong> of what I want to achieve, this does not actually work:</p>
<pre><code>len(df) # 1000
df_subset = df.sample(300)
len(df_subset) # 300
df = df.remove(df_subset)
len(df) # 700
</code></pre>
| 2 | 2016-10-03T15:20:13Z | 39,835,095 | <p>If your index is unique</p>
<pre><code>df = df.drop(df_subset.index)
</code></pre>
<hr>
<p><strong><em>example</em></strong></p>
<pre><code>df = pd.DataFrame(np.arange(10).reshape(-1, 2))
</code></pre>
<hr>
<p><strong><em>sample</em></strong></p>
<pre><code>df_subset = df.sample(2)
df_subset
</code></pre>
<p><a href="http://i.stack.imgur.com/9iD0E.png" rel="nofollow"><img src="http://i.stack.imgur.com/9iD0E.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>drop</em></strong></p>
<pre><code>df.drop(df_subset.index)
</code></pre>
<p><a href="http://i.stack.imgur.com/4TU49.png" rel="nofollow"><img src="http://i.stack.imgur.com/4TU49.png" alt="enter image description here"></a></p>
| 2 | 2016-10-03T15:24:00Z | [
"python",
"pandas"
]
|
Pandas random sample with remove | 39,835,021 | <p>I'm aware of <code>DataFrame.sample()</code>, but how can I do this and also remove the sample from the dataset? (<em>Note: AFAIK this has nothing to do with sampling with replacement</em>)</p>
<p>For example here is <strong>the essence</strong> of what I want to achieve, this does not actually work:</p>
<pre><code>len(df) # 1000
df_subset = df.sample(300)
len(df_subset) # 300
df = df.remove(df_subset)
len(df) # 700
</code></pre>
| 2 | 2016-10-03T15:20:13Z | 39,835,133 | <p>pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">random sample</a> : </p>
<pre><code>train=df.sample(frac=0.8,random_state=200)
test=df.drop(train.index)
</code></pre>
| 1 | 2016-10-03T15:26:00Z | [
"python",
"pandas"
]
|
Find linear part and slope in curve | 39,835,069 | <p>For a device that monitors the mass change in function of time, we would like to calculate the slope of the linear part of the data.</p>
<p>The example shown below is produced by reading a dataframe produced by the device.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
#Find DataFrame
df = pd.read_table("raw_data.csv", sep =";", skiprows = 11, decimal = ",")
# Plot figures
plt.figure()
plt.plot(df["Time(s)"], df["Mass(g)"], label = "Raw Data")
plt.axvspan(2, 17, color="b", alpha=0.2)
plt.xlabel("Time (s)")
plt.ylabel("Mass (g)")
plt.legend(loc=0)
plt.axis([0, None, 0, None])
plt.show()
</code></pre>
<p><img src="http://i.stack.imgur.com/fJZXs.png" alt="Example curve"></p>
<p>Is it possible to fit the linear part in this curve (roughly the highlighted part) and calculate the slope of it?</p>
| 1 | 2016-10-03T15:22:52Z | 39,835,435 | <p>Use <strong>numpy.polyfit()</strong> :</p>
<pre><code>df_sampled = df[:max_value] #select the points you want to keep
m, p = numpy.polyfit(df_sampled.index, df_sampled, deg=1)
</code></pre>
<p>The function returns the <strong>slope</strong> and the <strong>intercept</strong> of your linear regression.</p>
| 1 | 2016-10-03T15:42:50Z | [
"python",
"pandas",
"plot",
"dataframe"
]
|
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is_avilable:
choice_b_1()
return
else:
choice_c()
while 1:
run()
</code></pre></li>
<li><p>But the code to decide if choice_a_is_avilable is quite long, and condition should bind to method. I change the code to make it more clear.</p>
<pre><code>def run():
if(choice_a()):
return
elif(choice_b()):
return
else(choice_c()):
return
def choice_b():
if choice_b_is_avilable:
if(choice_b_1()):
return True
elif(choice_b_2)
return True
return False
</code></pre></li>
<li><p>When more and more choice comes into my code, it become more and more confusing and ugly, I considered using <code>Exception</code>:</p>
<pre><code>class GetChoiceException(Exception):
"""docstring for GetChoiceException"""
def __init__(self, *args):
super(GetChoiceException, self).__init__(*args)
def run():
try:
choice_a()
choice_b()
choice_c()
except GetChoiceException:
pass
def choice_a():
if choice_a_is_avilable:
some_function()
raise GetChoiceException()
</code></pre></li>
</ol>
<p>Is it a kind of abuse of <code>Exception</code>?</p>
<p>What is the write way to make choices in Python?</p>
| 2 | 2016-10-03T15:28:32Z | 39,835,314 | <p>If your <code>choice_</code> functions are returning <code>True</code> if successful, <code>False</code> if unsuccessful, then you can try each in turn until one is successful with simply:</p>
<pre><code>choice_a() or choice_b() or choice_c()
</code></pre>
<p>Because <code>or</code> is short-circuited, the expression will finish as soon as it finds an operand that returns true.</p>
<p>Or, if it seems more elegant, you could write that like this:</p>
<pre><code>any(x() for x in (choice_a, choice_b, choice_c))
</code></pre>
<p><code>any</code> is also short-circuited to stop as soon as it finds an operand that is true.</p>
<p>This would also allow you to maintain a list of function choices that are part of this operation, and use it like this:</p>
<pre><code>choices = [choice_a, choice_b, choice_c]
...
any(x() for x in choices)
</code></pre>
| 0 | 2016-10-03T15:36:29Z | [
"python"
]
|
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is_avilable:
choice_b_1()
return
else:
choice_c()
while 1:
run()
</code></pre></li>
<li><p>But the code to decide if choice_a_is_avilable is quite long, and condition should bind to method. I change the code to make it more clear.</p>
<pre><code>def run():
if(choice_a()):
return
elif(choice_b()):
return
else(choice_c()):
return
def choice_b():
if choice_b_is_avilable:
if(choice_b_1()):
return True
elif(choice_b_2)
return True
return False
</code></pre></li>
<li><p>When more and more choice comes into my code, it become more and more confusing and ugly, I considered using <code>Exception</code>:</p>
<pre><code>class GetChoiceException(Exception):
"""docstring for GetChoiceException"""
def __init__(self, *args):
super(GetChoiceException, self).__init__(*args)
def run():
try:
choice_a()
choice_b()
choice_c()
except GetChoiceException:
pass
def choice_a():
if choice_a_is_avilable:
some_function()
raise GetChoiceException()
</code></pre></li>
</ol>
<p>Is it a kind of abuse of <code>Exception</code>?</p>
<p>What is the write way to make choices in Python?</p>
| 2 | 2016-10-03T15:28:32Z | 39,835,316 | <p>There is nothing "wrong" in your exception method if this is what you want to do. To me it looks a bit static, though. </p>
<p>Not exactly knowing your problem, one alternative to consider is having a list of available function calls if it helps. You can store functions, classes and pretty much anything you want in lists. You can then pick one by random or by choice and execute that. </p>
<pre><code>from random import choice
def foo():
print "foo"
def bar():
print "bar"
options = [foo,bar]
x = choice(options)
x()
</code></pre>
<p>would execute either foo() or bar(). You can then add or remove functions by modifying the contents of options list. If you just want to execute the first in list, you would call</p>
<pre><code>options[0]()
</code></pre>
<p>Hope this helps. </p>
<p>Hannu</p>
| 0 | 2016-10-03T15:36:37Z | [
"python"
]
|
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is_avilable:
choice_b_1()
return
else:
choice_c()
while 1:
run()
</code></pre></li>
<li><p>But the code to decide if choice_a_is_avilable is quite long, and condition should bind to method. I change the code to make it more clear.</p>
<pre><code>def run():
if(choice_a()):
return
elif(choice_b()):
return
else(choice_c()):
return
def choice_b():
if choice_b_is_avilable:
if(choice_b_1()):
return True
elif(choice_b_2)
return True
return False
</code></pre></li>
<li><p>When more and more choice comes into my code, it become more and more confusing and ugly, I considered using <code>Exception</code>:</p>
<pre><code>class GetChoiceException(Exception):
"""docstring for GetChoiceException"""
def __init__(self, *args):
super(GetChoiceException, self).__init__(*args)
def run():
try:
choice_a()
choice_b()
choice_c()
except GetChoiceException:
pass
def choice_a():
if choice_a_is_avilable:
some_function()
raise GetChoiceException()
</code></pre></li>
</ol>
<p>Is it a kind of abuse of <code>Exception</code>?</p>
<p>What is the write way to make choices in Python?</p>
| 2 | 2016-10-03T15:28:32Z | 39,835,343 | <p>Would this work:</p>
<pre><code>choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
</code></pre>
| 0 | 2016-10-03T15:38:19Z | [
"python"
]
|
What is the right way to switch between many choices in Python | 39,835,176 | <p>I want to write something like a AI in Python:</p>
<ol>
<li><p>My first code is like this:</p>
<pre><code>def run()
if choice_a_is_avilable:
choice_a()
return
elif choice_b_is_avilable:
if choice_b_1_is_avilable:
choice_b_1()
return
elif choice_b_2_is_avilable:
choice_b_1()
return
else:
choice_c()
while 1:
run()
</code></pre></li>
<li><p>But the code to decide if choice_a_is_avilable is quite long, and condition should bind to method. I change the code to make it more clear.</p>
<pre><code>def run():
if(choice_a()):
return
elif(choice_b()):
return
else(choice_c()):
return
def choice_b():
if choice_b_is_avilable:
if(choice_b_1()):
return True
elif(choice_b_2)
return True
return False
</code></pre></li>
<li><p>When more and more choice comes into my code, it become more and more confusing and ugly, I considered using <code>Exception</code>:</p>
<pre><code>class GetChoiceException(Exception):
"""docstring for GetChoiceException"""
def __init__(self, *args):
super(GetChoiceException, self).__init__(*args)
def run():
try:
choice_a()
choice_b()
choice_c()
except GetChoiceException:
pass
def choice_a():
if choice_a_is_avilable:
some_function()
raise GetChoiceException()
</code></pre></li>
</ol>
<p>Is it a kind of abuse of <code>Exception</code>?</p>
<p>What is the write way to make choices in Python?</p>
| 2 | 2016-10-03T15:28:32Z | 39,838,131 | <p>I'm a big fan of table-driven programs.</p>
<pre><code>ctrl_table = [
[choice_a_test, choice_a_func],
[choice_b_test, choice_b_func],
[choice_c_test, choice_c_func]]
for test, func in ctrl_table:
if test():
func()
break
</code></pre>
| 0 | 2016-10-03T18:28:50Z | [
"python"
]
|
python/psychopy: for loop to split image names | 39,835,238 | <p>I have a list of images and I want to split their names at the '=' symbol.</p>
<p>e.g. from:</p>
<pre><code>'set_one-C:\Users\Documents\stim\01=aa.png'
</code></pre>
<p>to </p>
<pre><code>'aa.png'
</code></pre>
<p>I have tried to create a 'for loop' to run through each item in the list and split the names in turn. Despite no error in the console, the names don't appear to be split.</p>
<p>Here is my code and loop:</p>
<pre><code>imgList1 = glob.glob(os.path.join('C:\Users\Documents\stim','*.png'))
set_one = [visual.ImageStim(win, img, name='set_one-' + img) for img in imgList1[:8]]
set_two = [visual.ImageStim(win, img, name='set_two-' + img) for img in imgList1[8:16]]
sets = [set_one, set_two]
a1 = sets[0][0]
a2 = sets[0][1]
a3 = sets[0][2]
a4 = sets[0][3]
a5 = sets[0][4]
a6 = sets[0][5]
a7 = sets[0][6]
a8 = sets[0][7]
list = [a1,a2,a3,a4,a5,a6,a7,a8]
print a1
for item in list:
item = item.name.split('=')[1]
print a1
>>ImageStim(autoLog=True, color=array([ 1., 1., 1.]), colorSpace='rgb', contrast=1.0, depth=0, flipHoriz=False, flipVert=False, image=str(...), interpolate=False, mask=None, maskParams=None, name=str(...), opacity=1.0, ori=0.0, pos=array([ 0., 0.]), size=array([ 18.36534845, 11.47834278]), texRes=128, units='deg', win=Window(...))
>>ImageStim(autoLog=True, color=array([ 1., 1., 1.]), colorSpace='rgb', contrast=1.0, depth=0, flipHoriz=False, flipVert=False, image=str(...), interpolate=False, mask=None, maskParams=None, name=str(...), opacity=1.0, ori=0.0, pos=array([ 0., 0.]), size=array([ 18.36534845, 11.47834278]), texRes=128, units='deg', win=Window(...))
</code></pre>
<p>I know I could simply split them individually like this:</p>
<pre><code>a1 = a1.name.split('=')[1]
a2 = a2.name.split('=')[1] etc..
print a1
>>aa.png
</code></pre>
<p>But I do need to automate this due to the amount of splitting that I need to do. I'm unsure as to why the for loop does not split the names of each image from the list.</p>
<p>Thanks,
Steve</p>
| 0 | 2016-10-03T15:31:55Z | 39,835,533 | <pre><code>item = item.name.split('=')[1]
</code></pre>
<p>This doesn't work.... You want this instead:</p>
<pre><code>new_list = []
for item in list:
new_list.append(item.name.split('=')[1])
print(new_list)
</code></pre>
<p>Since you aren't changing your <code>list</code> in the for loop. You are only changing the item, but you aren't editing it in the list, if that make sense.</p>
<p>Another way around this is the following:</p>
<pre><code>for i, item in enumerate(list):
list[i] = item.name.split('=')[1]
</code></pre>
<p>Edit:</p>
<p>Seeing how you want to keep the references to a1,a2,...,a8 for whatever reason... here's why you can't do it with what we have right now. Strings are immutable objects, once you change it you are making a new object, of course you can reassign it back to your variable but that's not the point. If you want to keep reference then you should use a dictionary where the keys are your variable names and the value is well the value. </p>
<pre><code>list_of_var = ['a1','a2','a3'] # and so on
list = [a1,a2,a3,a4,a5,a6,a7,a8]
new_dict = {key: value.name.split("=")[1] for value, key in zip(list,list_of_var)}
#call it like new_dict["a1"]
</code></pre>
<p>But at the end of the day if you are dead set on a1 calls with out dictionary, the only way you can do it, is what you have at the end of your question.</p>
| 1 | 2016-10-03T15:47:55Z | [
"python",
"psychopy"
]
|
Python, QT and matplotlib scatter plots with blitting | 39,835,300 | <p>I am trying to animate a scatter plot (it needs to be a scatter plot as I want to vary the circle sizes). I have gotten the matplotlib documentation tutorial <a href="http://matplotlib.org/examples/animation/rain.html" rel="nofollow">matplotlib documentation tutorial </a> to work in my PyQT application, but would like to introduce blitting into the equation as my application will likely run on slower machines where the animation may not be as smooth.</p>
<p>I have had a look at many examples of animations with blitting, but none ever use a scatter plot (they use plot or lines) and so I am really struggling to figure out how to initialise the animation (the bits that don't get re-rendered every time) and the ones that do. I have tried quite a few things, and seem to be getting nowhere (and I am sure they would cause more confusion than help!). I assume that I have missed something fairly fundamental. Has anyone done this before? Could anyone help me out splitting the figure into the parts that need to be initiated and the ones that get updates?</p>
<p>The code below works, but does not blit. Appending </p>
<pre><code>blit=True
</code></pre>
<p>to the end of the animation call yields the following error:</p>
<pre><code>RuntimeError: The animation function must return a sequence of Artist objects.
</code></pre>
<p>Any help would be great.</p>
<p>Regards </p>
<p>FP</p>
<pre><code>import numpy as np
from PyQt4 import QtGui, uic
import sys
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupAnim()
self.show()
def setupAnim(self):
self.fig = plt.figure(figsize=(7, 7))
self.ax = self.fig.add_axes([0, 0, 1, 1], frameon=False)
self.ax.set_xlim(0, 1), self.ax.set_xticks([])
self.ax.set_ylim(0, 1), self.ax.set_yticks([])
# Create rain data
self.n_drops = 50
self.rain_drops = np.zeros(self.n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
# Initialize the raindrops in random positions and with
# random growth rates.
self.rain_drops['position'] = np.random.uniform(0, 1, (self.n_drops, 2))
self.rain_drops['growth'] = np.random.uniform(50, 200, self.n_drops)
# Construct the scatter which we will update during animation
# as the raindrops develop.
self.scat = self.ax.scatter(self.rain_drops['position'][:, 0], self.rain_drops['position'][:, 1],
s=self.rain_drops['size'], lw=0.5, edgecolors=self.rain_drops['color'],
facecolors='none')
self.animation = FuncAnimation(self.fig, self.update, interval=10)
plt.show()
def update(self, frame_number):
# Get an index which we can use to re-spawn the oldest raindrop.
self.current_index = frame_number % self.n_drops
# Make all colors more transparent as time progresses.
self.rain_drops['color'][:, 3] -= 1.0/len(self.rain_drops)
self.rain_drops['color'][:, 3] = np.clip(self.rain_drops['color'][:, 3], 0, 1)
# Make all circles bigger.
self.rain_drops['size'] += self.rain_drops['growth']
# Pick a new position for oldest rain drop, resetting its size,
# color and growth factor.
self.rain_drops['position'][self.current_index] = np.random.uniform(0, 1, 2)
self.rain_drops['size'][self.current_index] = 5
self.rain_drops['color'][self.current_index] = (0, 0, 0, 1)
self.rain_drops['growth'][self.current_index] = np.random.uniform(50, 200)
# Update the scatter collection, with the new colors, sizes and positions.
self.scat.set_edgecolors(self.rain_drops['color'])
self.scat.set_sizes(self.rain_drops['size'])
self.scat.set_offsets(self.rain_drops['position'])
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
</code></pre>
| 1 | 2016-10-03T15:35:44Z | 39,902,728 | <p>You need to add <code>return self.scat,</code> at the end of the <code>update</code> method if you want to use <code>FuncAnimation</code> with <code>blit=True</code>. See also this nice <a href="http://stackoverflow.com/a/9416663/4481445">StackOverflow post</a> that presents an example of a scatter plot animation with matplotlib using blit.</p>
<p>As a side-note, if you wish to embed a mpl figure in a Qt application, it is better to avoid using the pyplot interface and to use instead the Object Oriented API of mpl as suggested in the <a href="http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html" rel="nofollow">matplotlib documentation</a>.</p>
<p>This could be achieved, for example, as below, where <code>mplWidget</code> can be embedded as any other Qt widget in your main application. Note that I renamed the <code>update</code> method to <code>update_plot</code> to avoid conflict with the already existing method of the <code>FigureCanvasQTAgg</code> class.</p>
<pre><code>import numpy as np
from PyQt4 import QtGui
import sys
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
class mplWidget(FigureCanvasQTAgg):
def __init__(self):
super(mplWidget, self).__init__(mpl.figure.Figure(figsize=(7, 7)))
self.setupAnim()
self.show()
def setupAnim(self):
ax = self.figure.add_axes([0, 0, 1, 1], frameon=False)
ax.axis([0, 1, 0, 1])
ax.axis('off')
# Create rain data
self.n_drops = 50
self.rain_drops = np.zeros(self.n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)
])
# Initialize the raindrops in random positions and with
# random growth rates.
self.rain_drops['position'] = np.random.uniform(0, 1, (self.n_drops, 2))
self.rain_drops['growth'] = np.random.uniform(50, 200, self.n_drops)
# Construct the scatter which we will update during animation
# as the raindrops develop.
self.scat = ax.scatter(self.rain_drops['position'][:, 0],
self.rain_drops['position'][:, 1],
s=self.rain_drops['size'],
lw=0.5, facecolors='none',
edgecolors=self.rain_drops['color'])
self.animation = FuncAnimation(self.figure, self.update_plot,
interval=10, blit=True)
def update_plot(self, frame_number):
# Get an index which we can use to re-spawn the oldest raindrop.
indx = frame_number % self.n_drops
# Make all colors more transparent as time progresses.
self.rain_drops['color'][:, 3] -= 1./len(self.rain_drops)
self.rain_drops['color'][:, 3] = np.clip(self.rain_drops['color'][:, 3], 0, 1)
# Make all circles bigger.
self.rain_drops['size'] += self.rain_drops['growth']
# Pick a new position for oldest rain drop, resetting its size,
# color and growth factor.
self.rain_drops['position'][indx] = np.random.uniform(0, 1, 2)
self.rain_drops['size'][indx] = 5
self.rain_drops['color'][indx] = (0, 0, 0, 1)
self.rain_drops['growth'][indx] = np.random.uniform(50, 200)
# Update the scatter collection, with the new colors,
# sizes and positions.
self.scat.set_edgecolors(self.rain_drops['color'])
self.scat.set_sizes(self.rain_drops['size'])
self.scat.set_offsets(self.rain_drops['position'])
return self.scat,
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = mplWidget()
sys.exit(app.exec_())
</code></pre>
| 1 | 2016-10-06T17:58:49Z | [
"python",
"qt",
"matplotlib",
"scatter-plot",
"blit"
]
|
How do I find an Index of a header in a csv file in Python? | 39,835,362 | <p>My program list the headers of a CSV file to a user and asks him to pick an x and an y to plot. It works fine, but I don't want the user to type out the header string. I would rather find the index of each of the header and ask him to type a number instead. My csv file looks as follows:</p>
<pre><code>time(s),speed(m/s),alt_a(m),....
25,62,10
45,70,20
30,50,30
</code></pre>
<p>Currently, the user has to type out for x, speed(m/s) I would rather the data shows up something like this and have the user just type 2.</p>
<pre><code>1.time(s),2.speed(m/s),3.alt_a(m)
</code></pre>
<p>I looked a lot during the past two days and I can't seem to find any information of how would I even begin to do this.</p>
<pre><code>import pandas as pd
df = pd.DataFrame.from_csv('data.csv',index_col=False)
while True:
print (list(df))
print ('Select X-Axis')
xaxis = input()
print ('Select Y-Axis')
yaxis = input()
break
df.plot(x= xaxis, y= yaxis1)
</code></pre>
| 0 | 2016-10-03T15:39:14Z | 39,835,457 | <p>You can get the header with <code>df.columns</code>,</p>
<pre><code>print(", ".join(["{0}.{1}".format(i,x) for i,x in enumerate(df.columns)]))
x_index = input("index of the x series:")
x_header = df.columns[x_index]
y_index = input("index of the y series:")
y_header = df.columns[y_index]
df.plot(x= x_header , y= y_header )
</code></pre>
<p>the first line creates a list of the headers in the format you specified <code>1.time(s),2.speed(m/s),3.alt_a(m)</code> and prints it.</p>
<p><code>"{0}.{1}".format(i,x)</code> creates a string in the format "i.x" where i is a counter and x is an element of the headers</p>
<p>The second line asks an input to the user, which would be the index <code>0,1,2..</code> in accordance to the previous list.</p>
<p>In the third line, <code>df.columns[x_index]</code> is the header that the user chose.</p>
| 0 | 2016-10-03T15:44:05Z | [
"python"
]
|
Trying to calculate distance between points from a .txt file | 39,835,405 | <p>I am trying to figure out how to calculate the length of a line segment using coordinates that are in a text file:</p>
<blockquote>
<p>X,Y format (x,y,x,y,x,y,etc...)</p>
<p>4.5,10.0,4.5,5.7,5.5,2.5,6.5,0.3,6.8,0.0,1.0,1.0,3.5,3.5,2,5,6.0,2.0</p>
</blockquote>
<p>This is what I have so far:</p>
<blockquote>
<p>Python</p>
</blockquote>
<pre><code> # -*- coding: cp1252 -*-
#Starter code for GIS301 Lab 2
#GIS301Lab2Starter.py
import math
#-----------------------------------------------------------
#Procedure for reading a coordinate text file
#in x1,y1,x2,y2,⦠xn,yn format
#and resulting in a list as type float
#open file to read
file = open(r'C:\Users\Tristan\Desktop\USB_Backup_10-4-16\2016-2017\Fall2016\SpatialDataStructures\Labs\Lab2\points.txt','r')
#read file to string
coordString = file.read()
#Split coordString into list elements
coordList = coordString.split(',')
#convert from string to float type
for index, item in enumerate(coordList):
coordList[index] = float(coordList[index])
file.close
#-----------------------------------------------------------
print (coordList)
#add more code here
numPoints = len(coordList)/2
print("Number of Points")
print (numPoints)
x = [float(r) for r in coordList[0::2]]
y = [float(r) for r in coordList[1::2]]
xy = list(zip(x,y))
# pre-define distance and add subsequent distances
dist = 0
for r in coordList(len(xy)-1):
dist += ( (xy[r][0]-xy[r+1][0])**2 + (xy[r][1]-xy[r+1][1])**2 )**0.5
print (dist)
#for r in coordList(len(xy)-1):
# dist += ( (xy[r][0]-xy[r+1][0])**2 + (xy[r][1]-xy[r+1][1])**2 )**0.5
</code></pre>
<blockquote>
<p>When I run it in PyhthonWin:</p>
</blockquote>
<pre><code> Traceback (most recent call last):
File "C:\Users\Tristan\Desktop\USB_Backup_10-4-16\2016-2017\Fall2016\SpatialDataStructures\Labs\Lab2\GOERSLab2.py", line 39, in <module>
for r in coordList(len(xy)-1):
TypeError: 'list' object is not callable
</code></pre>
<p>The equation for calculating distance between two points is:
<a href="http://i.stack.imgur.com/vOcu0.png" rel="nofollow">http://i.stack.imgur.com/vOcu0.png</a></p>
<p>Then I need to add them all up!</p>
| 1 | 2016-10-03T15:41:18Z | 39,836,218 | <p>From what you have provided I do not see the need to over complicate this. Assuming you can properly import your text-file data, and split it, you could do this: </p>
<pre><code>points = ['4.5','10.0','4.5','5.7','5.5','2.5','6.5','0.3','6.8','0.0','1.0','1.0','3.5','3.5','2','5','6.0','2.0']
x = [float(r) for r in points[0::2]]
y = [float(r) for r in points[1::2]]
# put x/y coordinates in tuples
xy = list(zip(x,y))
# pre-define distance and add subsequent distances
dist = 0
for r in xrange(len(xy)-1):
dist += ( (xy[r][0]-xy[r+1][0])**2 + (xy[r][1]-xy[r+1][1])**2 )**0.5
</code></pre>
<p>I think something along these lines will work well (you don't even need to put the coordinates in tuples, really). Is this along the lines of what you needed?</p>
| 0 | 2016-10-03T16:27:56Z | [
"python",
"loops",
"for-loop",
"coordinates",
"gis"
]
|
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
[4,6], [5,6]]
</code></pre>
<p>The lists (and sublists) are of various, random lengths. </p>
| -2 | 2016-10-03T15:42:31Z | 39,835,612 | <p>You can do the following</p>
<pre><code>>>> from itertools import chain
>>> a=[[1,2,3],[4,5],[6]]
>>> b=[]
>>> for index, item in enumerate(a):
... b.extend([[i, j] for i in item for j in chain.from_iterable(a[index+1:])])
>>> b
[[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6],
[4, 6],
[5, 6]]
</code></pre>
| 1 | 2016-10-03T15:52:42Z | [
"python"
]
|
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
[4,6], [5,6]]
</code></pre>
<p>The lists (and sublists) are of various, random lengths. </p>
| -2 | 2016-10-03T15:42:31Z | 39,835,618 | <pre><code>from itertools import chain, product, combinations
sublists = [[1, 2, 3], [4, 5], [6]]
pairs = chain.from_iterable(
product(*sublist_pair) for sublist_pair in combinations(sublists, 2)
)
for x, y in pairs:
print(x, y)
</code></pre>
| 1 | 2016-10-03T15:53:28Z | [
"python"
]
|
Get all pairs from elements in sublists | 39,835,426 | <p>I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: </p>
<pre><code>a=[[1,2,3],[4,5],[6]]
</code></pre>
<p>The result should be: </p>
<pre><code>result=[[1,4], [1,5], [1,6],
[2,4], [2,5], [2,6],
[3,4], [3,5], [3,6],
[4,6], [5,6]]
</code></pre>
<p>The lists (and sublists) are of various, random lengths. </p>
| -2 | 2016-10-03T15:42:31Z | 39,835,733 | <pre><code># create an empty set to store unique sublist elements
initSet = set()
# combine all sublist elements
for sublist in a:
tempSet = set(sublist)
initSet = intiSet.union(tempSet)
initSet = list(initSet)
# find all possible non-repeating combinations
for _element in initSet:
combinations = list()
for i in range(1, len(initSet) - 1):
combinations.append([_element, initSet[i]]
initSet.pop(0)
#result stored in combinations
</code></pre>
| 0 | 2016-10-03T15:59:22Z | [
"python"
]
|
combine SQLAlchemy Core and ORM get problems | 39,835,530 | <p>How do I combine the two component of SQLAlchemy -- Core (SQL Expression) and ORM ?
I have some table that using ORM mapper and others just Table object, and I want <strong>one connection and one transaction for the two</strong>. </p>
<p>I have following two examples but run into problems (result is not consistent to my queries that interleaving two access styles).
One using autocommit session, another using default session.</p>
<hr>
<pre><code>session_autocommit=Session(bind=db,autocommit=True)
def f():
with session_autocommit.begin() as trans:
# ORM
x=session_autocommit.query(Mytable).filter(Mytable.id==1).first()
# sql expression by SQLAlchemy Core
session_autocommit.execute(mytable.update().where(mytable.c.id==1)\
.values(note=None))
# update via ORM
x.note='a'
f() # ok two update appear in log.
f() # ! only one update as below
x.note == 'a'
# the second run of f() returns False but should be True.
</code></pre>
<p>the log of second run of f() says it only one update (note=None) , the second update is missed?</p>
<pre><code>INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
INFO sqlalchemy.engine.base.Engine SELECT mytable.id AS mytable_id, mytable.note AS mytable_note
FROM mytable
WHERE mytable.id = %(id_1)s
LIMIT %(param_1)s
INFO sqlalchemy.engine.base.Engine {'param_1': 1, 'id_1': 1}
INFO sqlalchemy.engine.base.Engine UPDATE mytable SET note=%(note)s WHERE mytable.id = %(id_1)s
INFO sqlalchemy.engine.base.Engine {'id_1': 1, 'note': None}
INFO sqlalchemy.engine.base.Engine COMMIT
</code></pre>
<hr>
<p><strong>UPDATE</strong> The second problem is solved.<br>
Thanks @univerio 's comment, I need to <code>flush</code> it first for right ordering of executions. Since I am using two independent mechanism of SQLAlchemy.</p>
<pre><code>session=Session(bind=db,autocommit=False)
# default session must rely commit to control transaction.
session.commit()
x=session.query(Mytable).filter(Mytable.id==1).first()
x.note='a'
session.execute(mytable.update().where(mytable.c.id==1)\
.values(note=None))
session.commit()
x.note=='a'
# the test return True but should be None.
</code></pre>
<p>the log says the different order of two updates ?</p>
<pre><code>INFO sqlalchemy.engine.base.Engine COMMIT
INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
INFO sqlalchemy.engine.base.Engine SELECT mytable.id AS mytable_id, mytable.note AS mytable_note
FROM mytable
WHERE mytable.id = %(id_1)s
LIMIT %(param_1)s
INFO sqlalchemy.engine.base.Engine {'id_1': 1, 'param_1': 1}
INFO sqlalchemy.engine.base.Engine UPDATE mytable SET note=%(note)s WHERE mytable.id = %(id_1)s
INFO sqlalchemy.engine.base.Engine {'note': None, 'id_1': 1}
INFO sqlalchemy.engine.base.Engine SELECT mytable.id AS mytable_id
FROM mytable
WHERE mytable.id = %(param_1)s
INFO sqlalchemy.engine.base.Engine {'param_1': 1}
INFO sqlalchemy.engine.base.Engine UPDATE mytable SET note=%(note)s WHERE mytable.id = %(mytable_id)s
INFO sqlalchemy.engine.base.Engine {'note': 'a', 'mytable_id': 1}
INFO sqlalchemy.engine.base.Engine COMMIT
</code></pre>
| 0 | 2016-10-03T15:47:44Z | 39,843,661 | <p>After reading more about <code>session</code>, I have answer about it. </p>
<hr>
<p><code>session</code> has its working mechanisms, one is <code>unit of work</code> --</p>
<blockquote>
<p>"All changes to objects maintained by a Session are tracked - before
the database is queried again or before the current transaction is
committed, it flushes all pending changes to the database. This is
known as the Unit of Work pattern."
<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/session_basics.html</a></p>
</blockquote>
<ul>
<li><p>The first problem is because of <code>unit of work</code> so that SQLAlchemy will track what is changed and smartly do only what's really needed. The result is only one update is needed. </p></li>
<li><p>The second problem is solved by manual <code>session.flush()</code> the ORM update to get the right ordering of executions. Since I am using two independent mechanism of SQLAlchemy and it seems that <code>unit of work</code> doesn't also apply to raw SQL expression. </p></li>
</ul>
| 0 | 2016-10-04T03:24:33Z | [
"python",
"sql",
"orm",
"sqlalchemy",
"relational-database"
]
|
Python multiplying all even numbers in a list | 39,835,536 | <p>I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?</p>
<pre><code>def evens_product(xs):
product = 2
for i in xs:
if i%2 == 0:
product *= i
return product
else:
return (1)
</code></pre>
<p>Edit: Chepner's solution worked thank you to everyone who helped</p>
| 0 | 2016-10-03T15:48:16Z | 39,835,582 | <p>This will be your answer:</p>
<pre><code>def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product
</code></pre>
<p>There is no need to <code>return</code> <code>1</code> since the product is already assigned <code>1</code>.
Since you has the <code>return</code> inside the <code>for</code> loop it was returning the value after identifying the first even number. Hope it helped.</p>
| -1 | 2016-10-03T15:50:54Z | [
"python",
"list",
"numbers",
"multiplying"
]
|
Python multiplying all even numbers in a list | 39,835,536 | <p>I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?</p>
<pre><code>def evens_product(xs):
product = 2
for i in xs:
if i%2 == 0:
product *= i
return product
else:
return (1)
</code></pre>
<p>Edit: Chepner's solution worked thank you to everyone who helped</p>
| 0 | 2016-10-03T15:48:16Z | 39,835,649 | <p>You need to initialize <code>product = 1</code>, for two reasons. One, simply put, you'll get the wrong answer. <code>evens_product([4])</code> should return 4, not 8.
Two, it saves you from having to treat a list with no even numbers as a special case. If there are no even numbers, you never change the value of <code>product</code> and return it unchanged.</p>
<pre><code>def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product
</code></pre>
| 3 | 2016-10-03T15:54:49Z | [
"python",
"list",
"numbers",
"multiplying"
]
|
how to remove gibberish that exhibits no pattern using python nltk? | 39,835,546 | <p>I am writing a code to clean the urls and extract just the underlying text.</p>
<pre><code> train_str = train_df.to_string()
letters_only = re.sub("[^a-zA-Z]", " ", train_str)
words = letters_only.lower().split()
stops = set(stopwords.words("english"))
stops.update(['url','https','http','com'])
meaningful_words = [w for w in words if not w in stops]
long_words = [w for w in meaningful_words if len(w) > 3]
</code></pre>
<p>Using the above code i am able to extract just the words after removing the punctuations, stopwords, etc. But i am unable to remove the words that are gibberish in nature. These are some of the many words that i get after cleaning the urls.</p>
<pre><code>['uact', 'ahukewim', 'asvpoahuhxbqkhdtibveqfggtmam', 'fchrisalbon','afqjcnhil', 'ukai', 'khnaantjejdfrhpeza']
</code></pre>
<p>There is no particular pattern in their occurrence or in the letters to use regex or other functions. Could anyone suggest any ways in which these words could be removed?
Thanks!</p>
| 1 | 2016-10-03T15:48:50Z | 39,836,090 | <p>create an empty list. Loop through all the words in the current list. use <code>words.words()</code> from the corpera to check if it is a real world. Append all the "non-junk words" to that new list. Use that new list for whatever you'd like.</p>
<pre><code>from nltk.corpus import words
test = ['uact', 'ahukewim', 'asvpoahuhxbqkhdtibveqfggtmam', 'fchrisalbon',\
'afqjcnhil', 'ukai', 'khnaantjejdfrhpeza', 'this', 'is' , 'a' , 'word']
final = []
for x in test:
if x in words.words():
final.append(x)
print(final)
</code></pre>
<p>output: </p>
<pre><code>['this', 'is', 'a', 'word']
</code></pre>
| 0 | 2016-10-03T16:19:57Z | [
"python",
"python-3.x",
"nltk"
]
|
Convert the key of a dictionary into a string | 39,835,555 | <p>I think that the problem of my code is that each time the loop in iterating on a new variable, the previous variable is not deleted. So I end up with plot that contains all the previous data coming from the previous iterations.
What I may need is a function to clear up the memory at the end of each loop...
The reason while I originally asked this question, was that I run the same loop over and over and I end up having to many data on my plot (since it seems like the data are not clear at the end of each iteration). </p>
<pre><code>dicohist = {
'couts-formels': dftotal.total_cout_formels,
'couts_direct': dftotal.cout_total,
'perte-de-prod': dftotal.snt_prix
}
for key in dicohist:
histo = Series.hist(dicohist[key],bins=50)
histo.set_xlabel("cout en euros")
histo.set_ylabel("nombre de sujets")
histo.set_title(key)
fig = histo.get_figure()
fig.savefig('/Users/Salim/Desktop/plot/%s.png'%(key))
</code></pre>
| -3 | 2016-10-03T15:49:30Z | 39,837,360 | <p>I added a pyplot function : plt.close() at the end of my loop which solved the problem</p>
| 0 | 2016-10-03T17:41:06Z | [
"python",
"string",
"dictionary"
]
|
Solving a second-order boundary value equation on a non-uniform mesh | 39,835,627 | <p>I have an equation of the form </p>
<p><code>y'' + a(x) y' + b(x) y = f(x)
y(0) = y(1) = 1</code></p>
<p>where <code>x</code> is non-uniformly spaced. </p>
<p>How can I solve this type of second-order boundary value problem in python? </p>
| 0 | 2016-10-03T15:53:55Z | 39,840,646 | <p>Are you searching for the family of functions [ y<sub>x</sub><code>(t)</code> ] where <code>t</code> is the variable on which you derive <code>y</code>?</p>
<p>Are your boundary conditions true for all x?</p>
<p>You might want to look at <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html</a></p>
| 0 | 2016-10-03T21:24:40Z | [
"python",
"numpy",
"scipy",
"numerical-methods",
"differential-equations"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.