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
sequence |
---|---|---|---|---|---|---|---|---|---|
How to get mean of rows selected with another column's values in pandas | 40,074,739 | <p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p>
<p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p>
<p>What I originally tried was:</p>
<pre><code> import pandas as pd
import numpy as np
import os
dataFrame = pd.read_csv("test.csv")
for date in dataFrame["Dates"]:
if date == "Oct-16":
print(date)##Just checking
print(dataFrame["Score 1"].mean())
</code></pre>
<p>But my results are the mean for the whole column <code>Score 1</code></p>
<p>Another thing I tried was manually telling it which indices to calculate the mean for:</p>
<pre><code>dataFrame["Score 1"].iloc[0:2].mean()
</code></pre>
<p>But ideally I would like to find a way to do it if <code>Dates == "Oct-16"</code>.</p>
| 2 | 2016-10-16T19:51:29Z | 40,074,796 | <p>Iterating through the rows doesn't take advantage of Pandas' strengths. If you want to do something with a column based on values of another column, you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>.loc[]</code></a>:</p>
<pre><code>dataFrame.loc[dataFrame['Dates'] == 'Oct-16', 'Score 1']
</code></pre>
<p>The first part of <code>.loc[]</code> selects the rows you want, using your specified criteria (<code>dataFrame['Dates'] == 'Oct-16'</code>). The second part specifies the column you want (<code>Score 1</code>). Then if you want to get the mean, you can just put <code>.mean()</code> on the end:</p>
<pre><code>dataFrame.loc[dataFrame['Dates'] == 'Oct-16', 'Score 1'].mean()
</code></pre>
| 3 | 2016-10-16T19:57:53Z | [
"python",
"pandas",
"numpy"
] |
How to get mean of rows selected with another column's values in pandas | 40,074,739 | <p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p>
<p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p>
<p>What I originally tried was:</p>
<pre><code> import pandas as pd
import numpy as np
import os
dataFrame = pd.read_csv("test.csv")
for date in dataFrame["Dates"]:
if date == "Oct-16":
print(date)##Just checking
print(dataFrame["Score 1"].mean())
</code></pre>
<p>But my results are the mean for the whole column <code>Score 1</code></p>
<p>Another thing I tried was manually telling it which indices to calculate the mean for:</p>
<pre><code>dataFrame["Score 1"].iloc[0:2].mean()
</code></pre>
<p>But ideally I would like to find a way to do it if <code>Dates == "Oct-16"</code>.</p>
| 2 | 2016-10-16T19:51:29Z | 40,074,798 | <pre><code>import pandas as pd
import numpy as np
import os
dataFrame = pd.read_csv("test.csv")
dates = dataFrame["Dates"]
score1s = dataFrame["Score 1"]
result = []
for i in range(0,len(dates)):
if dates[i] == "Oct-16":
result.append(score1s[i])
print(result.mean())
</code></pre>
| 0 | 2016-10-16T19:58:09Z | [
"python",
"pandas",
"numpy"
] |
How to get mean of rows selected with another column's values in pandas | 40,074,739 | <p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p>
<p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p>
<p>What I originally tried was:</p>
<pre><code> import pandas as pd
import numpy as np
import os
dataFrame = pd.read_csv("test.csv")
for date in dataFrame["Dates"]:
if date == "Oct-16":
print(date)##Just checking
print(dataFrame["Score 1"].mean())
</code></pre>
<p>But my results are the mean for the whole column <code>Score 1</code></p>
<p>Another thing I tried was manually telling it which indices to calculate the mean for:</p>
<pre><code>dataFrame["Score 1"].iloc[0:2].mean()
</code></pre>
<p>But ideally I would like to find a way to do it if <code>Dates == "Oct-16"</code>.</p>
| 2 | 2016-10-16T19:51:29Z | 40,075,040 | <p>How about the mean for all dates</p>
<pre><code>dataframe.groupby('Dates').['Score 1'].mean()
</code></pre>
| 1 | 2016-10-16T20:20:08Z | [
"python",
"pandas",
"numpy"
] |
Adding new values to empty nested lists | 40,074,768 | <p>This is related to <a href="http://stackoverflow.com/questions/6339235/how-to-append-to-the-end-of-an-empty-list">How to append to the end of an empty list?</a>, but I don't have enough reputation yet to comment there, so I posted a new question here.</p>
<p>I need to append terms onto an empty list of lists. I start with:</p>
<pre><code>Talks[eachFilename][TermVectors]=
[['paragraph','1','text'],
['paragraph','2','text'],
['paragraph','3','text']]
</code></pre>
<p>I want to end with </p>
<pre><code>Talks[eachFilename][SomeTermsRemoved]=
[['paragraph','text'],
['paragraph','2'],
['paragraph']]
</code></pre>
<p><code>Talks[eachFilename][SomeTermsRemoved]</code> starts empty. I can't specify that I want: </p>
<pre><code>Talks[eachFilename][SomeTermsRemoved][0][0]='paragraph'
Talks[eachFilename][SomeTermsRemoved][0][1]='text'
Talks[eachFilename][SomeTermsRemoved][1][0]='paragraph'
</code></pre>
<p>etc... (IndexError: list index out of range). If I force populate the string and then try to change it, I get a strings are immutable error.</p>
<p>So, how do I specify that I want <code>Talks[eachFilename][SomeTermsRemoved][0]</code> to be <code>['paragraph','text']</code>, and <code>Talks[eachFilename][SomeTermsRemoved][1]</code> to be <code>['paragraph','2']</code> etc?</p>
<p><code>.append</code> works, but only generates a single long column, not a set of lists.</p>
<p>To be more specific, I have a number of lists that are initialized inside a dict</p>
<pre><code>Talks = {}
Talks[eachFilename]= {}
Talks[eachFilename]['StartingText']=[]
Talks[eachFilename]['TermVectors']=[]
Talks[eachFilename]['TermVectorsNoStops']=[]
</code></pre>
<p><code>eachFilename</code> gets populated from a list of text files, e.g.:</p>
<pre><code>Talks[eachFilename]=['filename1','filename2']
</code></pre>
<p><code>StartingText</code> has several long lines of text (individual paragraphs)</p>
<pre><code>Talks[filename1][StartingText]=['This is paragraph one','paragraph two']
</code></pre>
<p>TermVectors are populated by the NLTK package with a list of terms, still grouped in the original paragraphs:</p>
<pre><code>Talks[filename1][TermVectors]=
[['This','is','paragraph','one'],
['paragraph','two']]
</code></pre>
<p>I want to further manipulate the <code>TermVectors</code>, but keep the original paragraph list structure. This creates a list with 1 term per line:</p>
<pre><code>for eachFilename in Talks:
for eachTerm in range( 0, len( Talks[eachFilename]['TermVectors'] ) ):
for term in Talks[eachFilename]['TermVectors'][ eachTerm ]:
if unicode(term) not in stop_words:
Talks[eachFilename]['TermVectorsNoStops'].append( term )
</code></pre>
<p>Result (I lose my paragraph structure):</p>
<pre><code>Talks[filename1][TermVectorsNoStops]=
[['This'],
['is'],
['paragraph'],
['one'],
['paragraph'],
['two']]
</code></pre>
| 0 | 2016-10-16T19:54:49Z | 40,074,911 | <p>The errors you are reporting (strings immutable?) don't make any sense unless your list is actually not empty but already populated with strings. In any event, if you start with an empty list, then the simplest way to populate it is by appending:</p>
<pre><code>>>> talks = {}
>>> talks['each_file_name'] = {}
>>> talks['each_file_name']['terms_removed'] = []
>>> talks['each_file_name']['terms_removed'].append(['paragraph','text'])
>>> talks['each_file_name']['terms_removed'].append(['paragraph','2'])
>>> talks['each_file_name']['terms_removed'].append(['paragraph'])
>>> talks
{'each_file_name': {'terms_removed': [['paragraph', 'text'], ['paragraph', '2'], ['paragraph']]}}
>>> from pprint import pprint
>>> pprint(talks)
{'each_file_name': {'terms_removed': [['paragraph', 'text'],
['paragraph', '2'],
['paragraph']]}}
</code></pre>
<p>If you have an empty list and try to assign to it by using indexing, it will throw an error:</p>
<pre><code>>>> empty_list = []
>>> empty_list[0] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
</code></pre>
<p>As an aside, code like this:</p>
<pre><code>for eachFilename in Talks:
for eachTerm in range( 0, len( Talks[eachFilename]['TermVectors'] ) ):
for term in Talks[eachFilename]['TermVectors'][ eachTerm ]:
if unicode(term) not in stop_words:
Talks[eachFilename]['TermVectorsNoStops'].append( term )
</code></pre>
<p>Is very far from proper Python style. Don't use <em>camelCase</em>, use <em>snake_case</em>. Don't capitalize variables. Also, in your mid-level for-loop, you use <code>for eachTerm in range(0, len(Talks[eachFilename]['TermVectors']</code>, but <code>eachTerm</code> is an <code>int</code>, so it makes more sense to use the standard <code>i</code> <code>j</code> or <code>k</code>. Even <code>idx</code>.</p>
<p>Anyway, there is no reason why that code should be turning this:</p>
<pre><code>Talks[filename1][TermVectors] =
[['This','is','paragraph','one'],
['paragraph','two']]
</code></pre>
<p>Into this:</p>
<pre><code>Talks[filename1][TermVectors] =
[['This'],
['is'],
['paragraph'],
['one'],
['paragraph'],
['two']]
</code></pre>
<p>Here is a reproducible example (I've made this for you, BUT YOU SHOULD DO THIS YOURSELF BEFORE POSTING A QUESTION):</p>
<pre><code>>>> pprint(talks)
{'file1': {'no_stops': [],
'term_vectors': [['This', 'is', 'paragraph', 'one'],
['paragraph', 'two']]},
'file2': {'no_stops': [],
'term_vectors': [['This', 'is', 'paragraph', 'three'],
['paragraph', 'four']]}}
>>> for file in talks:
... for i in range(len(talks[file]['term_vectors'])):
... for term in talks[file]['term_vectors'][i]:
... if term not in stop_words:
... talks[file]['no_stops'].append(term)
...
>>> pprint(file)
'file2'
>>> pprint(talks)
{'file1': {'no_stops': ['This', 'paragraph', 'one', 'paragraph'],
'term_vectors': [['This', 'is', 'paragraph', 'one'],
['paragraph', 'two']]},
'file2': {'no_stops': ['This', 'paragraph', 'paragraph', 'four'],
'term_vectors': [['This', 'is', 'paragraph', 'three'],
['paragraph', 'four']]}}
>>>
</code></pre>
<p>The more pythonic approach would be something like the following:</p>
<pre><code>>>> pprint(talks)
{'file1': {'no_stops': [],
'term_vectors': [['This', 'is', 'paragraph', 'one'],
['paragraph', 'two']]},
'file2': {'no_stops': [],
'term_vectors': [['This', 'is', 'paragraph', 'three'],
['paragraph', 'four']]}}
>>> for file in talks.values():
... file['no_stops'] = [[term for term in sub if term not in stop_words] for sub in file['term_vectors']]
...
>>> pprint(talks)
{'file1': {'no_stops': [['This', 'paragraph', 'one'], ['paragraph']],
'term_vectors': [['This', 'is', 'paragraph', 'one'],
['paragraph', 'two']]},
'file2': {'no_stops': [['This', 'paragraph'], ['paragraph', 'four']],
'term_vectors': [['This', 'is', 'paragraph', 'three'],
['paragraph', 'four']]}}
>>>
</code></pre>
| 0 | 2016-10-16T20:07:20Z | [
"python",
"list",
"assign"
] |
Adding new values to empty nested lists | 40,074,768 | <p>This is related to <a href="http://stackoverflow.com/questions/6339235/how-to-append-to-the-end-of-an-empty-list">How to append to the end of an empty list?</a>, but I don't have enough reputation yet to comment there, so I posted a new question here.</p>
<p>I need to append terms onto an empty list of lists. I start with:</p>
<pre><code>Talks[eachFilename][TermVectors]=
[['paragraph','1','text'],
['paragraph','2','text'],
['paragraph','3','text']]
</code></pre>
<p>I want to end with </p>
<pre><code>Talks[eachFilename][SomeTermsRemoved]=
[['paragraph','text'],
['paragraph','2'],
['paragraph']]
</code></pre>
<p><code>Talks[eachFilename][SomeTermsRemoved]</code> starts empty. I can't specify that I want: </p>
<pre><code>Talks[eachFilename][SomeTermsRemoved][0][0]='paragraph'
Talks[eachFilename][SomeTermsRemoved][0][1]='text'
Talks[eachFilename][SomeTermsRemoved][1][0]='paragraph'
</code></pre>
<p>etc... (IndexError: list index out of range). If I force populate the string and then try to change it, I get a strings are immutable error.</p>
<p>So, how do I specify that I want <code>Talks[eachFilename][SomeTermsRemoved][0]</code> to be <code>['paragraph','text']</code>, and <code>Talks[eachFilename][SomeTermsRemoved][1]</code> to be <code>['paragraph','2']</code> etc?</p>
<p><code>.append</code> works, but only generates a single long column, not a set of lists.</p>
<p>To be more specific, I have a number of lists that are initialized inside a dict</p>
<pre><code>Talks = {}
Talks[eachFilename]= {}
Talks[eachFilename]['StartingText']=[]
Talks[eachFilename]['TermVectors']=[]
Talks[eachFilename]['TermVectorsNoStops']=[]
</code></pre>
<p><code>eachFilename</code> gets populated from a list of text files, e.g.:</p>
<pre><code>Talks[eachFilename]=['filename1','filename2']
</code></pre>
<p><code>StartingText</code> has several long lines of text (individual paragraphs)</p>
<pre><code>Talks[filename1][StartingText]=['This is paragraph one','paragraph two']
</code></pre>
<p>TermVectors are populated by the NLTK package with a list of terms, still grouped in the original paragraphs:</p>
<pre><code>Talks[filename1][TermVectors]=
[['This','is','paragraph','one'],
['paragraph','two']]
</code></pre>
<p>I want to further manipulate the <code>TermVectors</code>, but keep the original paragraph list structure. This creates a list with 1 term per line:</p>
<pre><code>for eachFilename in Talks:
for eachTerm in range( 0, len( Talks[eachFilename]['TermVectors'] ) ):
for term in Talks[eachFilename]['TermVectors'][ eachTerm ]:
if unicode(term) not in stop_words:
Talks[eachFilename]['TermVectorsNoStops'].append( term )
</code></pre>
<p>Result (I lose my paragraph structure):</p>
<pre><code>Talks[filename1][TermVectorsNoStops]=
[['This'],
['is'],
['paragraph'],
['one'],
['paragraph'],
['two']]
</code></pre>
| 0 | 2016-10-16T19:54:49Z | 40,075,068 | <p>Some continued experimentation, along with the comments got me moving towards a solution. Rather than appending each individual term, which generates a single long list, I accumulated the terms into a list and then appended each list, as follows:</p>
<pre><code>for eachFilename in Talks:
for eachTerm in range( 0, len( Talks[eachFilename]['TermVectors'] ) ):
term_list = [ ]
for term in Talks[eachFilename]['TermVectors'][ eachTerm ]:
if unicode(term) not in stop_words:
term_list.append(term)
Talks[eachFilename]['TermVectorsNoStops'].append( term )
</code></pre>
<p>Thanks everyone!</p>
| 0 | 2016-10-16T20:24:07Z | [
"python",
"list",
"assign"
] |
Syntax error in python2 script using ldap module | 40,074,769 | <p>Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting the syntax error:</p>
<pre><code> File "UserGroupModify.py", line 66
attrs = {}
^
SyntaxError: invalid syntax
~/Scripts/Termination-Script$ python2 UserGroupModify.py
File "UserGroupModify.py", line 69
ldif = modlist.addModlist(attrs)
^
SyntaxError: invalid syntax
</code></pre>
<p>The code currently looks like the following (including previous things I had tried all with syntax errors of their own when I tried to use them). Getting it to log in and search for the user was easy enough, but modifying the user is where I am having a hard time. The current code is uncommented and is from an example I found online.</p>
<pre><code>#!/usr/bin/env python2
import ldap
import getpass
import ldap.modlist as modlist
## first you must open a connection to the server
try:
#Ignore self signed certs
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
username = raw_input("LDAP Login: ")
passwd = getpass.getpass()
userlook = raw_input("User to lookup: ")
l = ldap.initialize("ldaps://ldap.example.com:636/")
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("uid="+username+",ou=people,dc=example,dc=com", ""+passwd+"")
except ldap.LDAPError, e:
print(e)
# The dn of our existing entry/object
dn = "ou=People,dc=example,dc=com"
searchScope = ldap.SCOPE_SUBTREE
searchAttribute = ["uid"]
#retrieveAttributes = ["ou=Group"]
retrieveAttributes = ["ou"]
#searchFilter = "uid=*"
searchFilter = "(uid="+userlook+")"
#mod_attrs = [(ldap.MOD_REPLACE, 'ou', 'former-people' )]
attrs = {}
attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
try:
#ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
print(result_data)
# Some place-holders for old and new values
#old={'Group':'l.result(ldap_result_id, 0)'}
#new={'Group':'uid="+userlook+",ou=former-people,dc=example,dc=com'}
#newsetting = {'description':'I could easily forgive his pride, if he had not mortified mine.'}
#print(old)
#print(new)
# Convert place-holders for modify-operation using modlist-module
#ldif = modlist.modifyModlist(old,new)
# Do the actual modification
#l.modify_s(dn,ldif)
#l.modify_s('uid="+userlook+,ou=People,dc=example,dc=com', mod_attrs)
#l.modify_s('uid="+userlook+",ou=People', mod_attrs)
#moved up due to SyntaxError
#attrs = {}
#attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
except ldap.LDAPError, e:
print(e)
</code></pre>
<p>Any direction pointing on what's causing the error would be greatly appreciated. Thanks</p>
| 0 | 2016-10-16T19:54:52Z | 40,074,895 | <p>It's a syntax error to have try without except. Because there's a whole lot of unindented code before the except, Python doesn't see it as part of the try. Make sure everything between try and except is indented.</p>
| 0 | 2016-10-16T20:06:38Z | [
"python",
"python-2.7"
] |
Syntax error in python2 script using ldap module | 40,074,769 | <p>Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting the syntax error:</p>
<pre><code> File "UserGroupModify.py", line 66
attrs = {}
^
SyntaxError: invalid syntax
~/Scripts/Termination-Script$ python2 UserGroupModify.py
File "UserGroupModify.py", line 69
ldif = modlist.addModlist(attrs)
^
SyntaxError: invalid syntax
</code></pre>
<p>The code currently looks like the following (including previous things I had tried all with syntax errors of their own when I tried to use them). Getting it to log in and search for the user was easy enough, but modifying the user is where I am having a hard time. The current code is uncommented and is from an example I found online.</p>
<pre><code>#!/usr/bin/env python2
import ldap
import getpass
import ldap.modlist as modlist
## first you must open a connection to the server
try:
#Ignore self signed certs
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
username = raw_input("LDAP Login: ")
passwd = getpass.getpass()
userlook = raw_input("User to lookup: ")
l = ldap.initialize("ldaps://ldap.example.com:636/")
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("uid="+username+",ou=people,dc=example,dc=com", ""+passwd+"")
except ldap.LDAPError, e:
print(e)
# The dn of our existing entry/object
dn = "ou=People,dc=example,dc=com"
searchScope = ldap.SCOPE_SUBTREE
searchAttribute = ["uid"]
#retrieveAttributes = ["ou=Group"]
retrieveAttributes = ["ou"]
#searchFilter = "uid=*"
searchFilter = "(uid="+userlook+")"
#mod_attrs = [(ldap.MOD_REPLACE, 'ou', 'former-people' )]
attrs = {}
attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
try:
#ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
print(result_data)
# Some place-holders for old and new values
#old={'Group':'l.result(ldap_result_id, 0)'}
#new={'Group':'uid="+userlook+",ou=former-people,dc=example,dc=com'}
#newsetting = {'description':'I could easily forgive his pride, if he had not mortified mine.'}
#print(old)
#print(new)
# Convert place-holders for modify-operation using modlist-module
#ldif = modlist.modifyModlist(old,new)
# Do the actual modification
#l.modify_s(dn,ldif)
#l.modify_s('uid="+userlook+,ou=People,dc=example,dc=com', mod_attrs)
#l.modify_s('uid="+userlook+",ou=People', mod_attrs)
#moved up due to SyntaxError
#attrs = {}
#attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
except ldap.LDAPError, e:
print(e)
</code></pre>
<p>Any direction pointing on what's causing the error would be greatly appreciated. Thanks</p>
| 0 | 2016-10-16T19:54:52Z | 40,074,909 | <p>You haven't ended your <code>try</code> block by the time you reach this line</p>
<pre><code>ldif = modlist.addModlist(attrs)
</code></pre>
<p>since the accompanying <code>except</code> is below. However, you reduced the indentation level and this is causing the syntax error since things in the same block should have the same indentation.</p>
| 0 | 2016-10-16T20:07:11Z | [
"python",
"python-2.7"
] |
Python system libraries leak into virtual environment | 40,074,820 | <p>While working on a new python project and trying to learn my way through virtual environments, I've stumbled twice with the following problem:</p>
<ul>
<li>I create my virtual environment called venv. Running <code>pip freeze</code> shows nothing. </li>
<li>I install my dependencies using pip install dependency. the venv library starts to populate, as confirmed by pip freeze. </li>
<li>After a couple of days, I go back to my project, and after activating the virtual environment via <code>source venv/bin/activate</code>, when running pip freeze I see the whole list of libraries installed in the system python distribution (I'm using Mac Os 10.9.5), instead of the small subset I wanted to keep inside my virtual environment. </li>
</ul>
<p>I'm sure I must be doing something wrong in between, but I have no idea how could this happen. Any ideas? </p>
<hr>
<p>Update:
after looking at <a href="http://stackoverflow.com/a/33366748/3294665">this</a> answer, I realized the that when running <code>pip freeze</code>, the <code>pip</code> command that's being invoked is the one at <code>/usr/local/bin/pip</code> instead of the one inside my virtual environment. So the virtual environment is fine, but I wonder what changes in the path might be causing this, and how to prevent them to happen again (my PYTHONPATH variable is not set).</p>
| 0 | 2016-10-16T20:01:09Z | 40,077,668 | <p>I realized that my problem arose when moving my virtual environment folder around the system. The fix was to modify the <code>activate</code> and <code>pip</code> scripts located inside the <code>venv/bin</code> folder to point to the new venv location, as suggested by <a href="http://stackoverflow.com/a/16683703/3294665">this</a> answer. Now my pip freeze is showing the right files.</p>
| 0 | 2016-10-17T02:28:56Z | [
"python",
"osx",
"pip",
"virtualenv"
] |
If a string contains a suffix from a list, how do I strip that specific suffix from the string? | 40,074,825 | <p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p>
<pre><code>b = ["food", "stuffing", "hobbitses"]
y = ["ing", "es", "s", "ly"]
def stemming():
for i in range(len(b)):
if b[i].endswith(tuple(y)):
b[i] = b[i] - #???
print b
</code></pre>
| -1 | 2016-10-16T20:01:19Z | 40,074,891 | <p>I'd recommend separating out the stem removal into its own function, and then using a list comprehension or a separate function for the whole list. Here's one way of doing it</p>
<pre><code>def remove_stems(word, stems):
for stem in stems:
if word.endswith(stem):
return word[:-len(stem)]
else:
return word
b_without_stems = [remove_stem(word, stems) for word in b]
</code></pre>
| 0 | 2016-10-16T20:06:10Z | [
"python",
"string",
"python-2.7",
"stemming"
] |
If a string contains a suffix from a list, how do I strip that specific suffix from the string? | 40,074,825 | <p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p>
<pre><code>b = ["food", "stuffing", "hobbitses"]
y = ["ing", "es", "s", "ly"]
def stemming():
for i in range(len(b)):
if b[i].endswith(tuple(y)):
b[i] = b[i] - #???
print b
</code></pre>
| -1 | 2016-10-16T20:01:19Z | 40,074,914 | <p>You need to know which ending has been found, so you need to check them one at a time instead of trying to check them all at once. Once you have found an ending, you can chop it off using a slice.</p>
<pre><code>def stemming():
for i, word in enumerate(b):
for suffix in y:
if word.endswith(suffix):
b[i] = word[:-len(suffix)]
break
</code></pre>
<p>A better approach would use a regular expression:</p>
<pre><code>import re
suffix = re.compile("(%s)$" % "|".join(y))
def stemming():
for i, word in enumerate(b):
b[i] = suffix.sub("", word)
</code></pre>
<p>Then you can easily do the stemming using a list comprehension:</p>
<pre><code>b = [suffix.sub("", w) for w in b]
</code></pre>
| 0 | 2016-10-16T20:07:38Z | [
"python",
"string",
"python-2.7",
"stemming"
] |
If a string contains a suffix from a list, how do I strip that specific suffix from the string? | 40,074,825 | <p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p>
<pre><code>b = ["food", "stuffing", "hobbitses"]
y = ["ing", "es", "s", "ly"]
def stemming():
for i in range(len(b)):
if b[i].endswith(tuple(y)):
b[i] = b[i] - #???
print b
</code></pre>
| -1 | 2016-10-16T20:01:19Z | 40,074,997 | <p>assuming you want to strip the first suffix found this will do it</p>
<pre><code>def stemming(strings, endings):
for i, string in enumerate(strings):
for ending in endings:
if string.endswith(ending):
strings[i] = string[:-len(ending)]
continue
</code></pre>
| 0 | 2016-10-16T20:15:28Z | [
"python",
"string",
"python-2.7",
"stemming"
] |
How to use sublime 3 jinja2 highlighter | 40,074,856 | <p>I have a problem with jinja2 highlighter in sublime 3.All the files associated with .html
extensions don't recognize jinja templates blocks..I searched the web but the only solution I found is to make a .jinja.html custom extension..anyone got any idea how to solve this?..This is the plugin I installed <a href="https://packagecontrol.io/packages/Jinja2" rel="nofollow">https://packagecontrol.io/packages/Jinja2</a></p>
| 0 | 2016-10-16T20:03:26Z | 40,080,168 | <p>You need to add <code>.j2</code> to your file extension:</p>
<p><code>mysupertemplate.html.j2</code></p>
<p>Have a look at the <a href="https://github.com/kudago/jinja2-tmbundle/blob/master/Syntaxes/HTML%20(Jinja2).tmLanguage" rel="nofollow">syntax file</a> (under <code>fileTypes</code>)</p>
<p>Matt</p>
| 0 | 2016-10-17T06:55:30Z | [
"python",
"sublimetext3",
"jinja2",
"syntax-highlighting",
"sublime-text-plugin"
] |
Looping and saving multiple inputs | 40,074,874 | <p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p>
<p>For Example: </p>
<pre><code>course_count = False
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
#ELSE END LOOP
else:
course_count = True
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")
</code></pre>
<p>The problem is it will always print out only one inputted course, hour and grade. How would I save more than one answer using only accumulative strings? </p>
<p>The output I'm looking to make is:</p>
<pre><code># Please Enter the Course Code (or done if finished): COMP 10001
# How many credit hours was COMP 10001? 5
# What grade did you earn in COMP 10001? 75
# Please Enter the Course Code (or done if finished): COMP 20002
# How many credit hours was COMP 10001? 8
# What grade did you earn in COMP 10001? 95
# Please Enter the Course Code (or done if finished): done
# Course: COMP 10001 Weight: 5 Grade: 75%
# Course: COMP 20002 Weight: 8 Grade: 95%
</code></pre>
<p>It's for a school practice problem and were not allowed to use lists, arrays or dictionaries if that makes sense</p>
| 1 | 2016-10-16T20:04:35Z | 40,074,927 | <p>See if you can relate this simplified example to your code. To get the output you describe, you need to <em>store</em> the output text somehow and access it later:</p>
<pre><code>output_lines = []
for i in range(10):
input_string = input("Enter some input")
output_lines.append(input_string)
for output_line in output_lines:
print(output_line)
</code></pre>
<p>From the comments, using only string "accumulation" (warning: quadratically bad):</p>
<pre><code>output_text
for i in range(10):
input_string = input("Enter some input")
output_text = output_text + '\n' + input_string
print(output_text)
</code></pre>
<p>Note that the preferred way to build up a long string <em>is</em> to append to a list and use <code>'separator'.join(list_of_strings)</code> or print one-by-one as above.</p>
| 1 | 2016-10-16T20:08:38Z | [
"python"
] |
Looping and saving multiple inputs | 40,074,874 | <p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p>
<p>For Example: </p>
<pre><code>course_count = False
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
#ELSE END LOOP
else:
course_count = True
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")
</code></pre>
<p>The problem is it will always print out only one inputted course, hour and grade. How would I save more than one answer using only accumulative strings? </p>
<p>The output I'm looking to make is:</p>
<pre><code># Please Enter the Course Code (or done if finished): COMP 10001
# How many credit hours was COMP 10001? 5
# What grade did you earn in COMP 10001? 75
# Please Enter the Course Code (or done if finished): COMP 20002
# How many credit hours was COMP 10001? 8
# What grade did you earn in COMP 10001? 95
# Please Enter the Course Code (or done if finished): done
# Course: COMP 10001 Weight: 5 Grade: 75%
# Course: COMP 20002 Weight: 8 Grade: 95%
</code></pre>
<p>It's for a school practice problem and were not allowed to use lists, arrays or dictionaries if that makes sense</p>
| 1 | 2016-10-16T20:04:35Z | 40,074,964 | <p>You may find it useful to keep your information in a <code>dictionary</code> structure where the key is stored as the course code. Then it is as simple as iterating over each course saved in your dictionary to get the details.</p>
<p><strong>Example:</strong> </p>
<pre><code>course_count = False
course_info = {}
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
course_info[course_code] = {};
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
course_info[course_code]['hours'] = course_hours;
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
course_info[course_code]['grade'] = course_grade
#ELSE END LOOP
else:
course_count = True
For course_code in course_info :
course_hours = course_info[course_code]['hours']
course_grade = course_info[course_code]['grade']
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")
</code></pre>
| 1 | 2016-10-16T20:11:58Z | [
"python"
] |
Looping and saving multiple inputs | 40,074,874 | <p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p>
<p>For Example: </p>
<pre><code>course_count = False
#LOOP through Inputs
while not course_count:
#GET course code
course_code = input( "Please Enter the Course Code (or done if finished): " )
#IF course code is not equal to done (convert to lowercase)
if course_code.lower() != "done":
#GET course hours
course_hours = int( input( "How many credit hours was " + course_code + "? " ) )
#GET grade earned
course_grade = float( input( "What grade did you earn in " + course_code + "? " ) )
#ELSE END LOOP
else:
course_count = True
print("Course: " + course_code + " Weight: " + str( course_hours ) + " hours " + "Grade: " + str( course_grade ) + "%")
</code></pre>
<p>The problem is it will always print out only one inputted course, hour and grade. How would I save more than one answer using only accumulative strings? </p>
<p>The output I'm looking to make is:</p>
<pre><code># Please Enter the Course Code (or done if finished): COMP 10001
# How many credit hours was COMP 10001? 5
# What grade did you earn in COMP 10001? 75
# Please Enter the Course Code (or done if finished): COMP 20002
# How many credit hours was COMP 10001? 8
# What grade did you earn in COMP 10001? 95
# Please Enter the Course Code (or done if finished): done
# Course: COMP 10001 Weight: 5 Grade: 75%
# Course: COMP 20002 Weight: 8 Grade: 95%
</code></pre>
<p>It's for a school practice problem and were not allowed to use lists, arrays or dictionaries if that makes sense</p>
| 1 | 2016-10-16T20:04:35Z | 40,075,095 | <p>Use an output string <code>output_string</code></p>
<p>Add each new line to the output string</p>
<pre><code>...
output_string += "Course: {} Weight: {} hours Grade: {}\n".format(course_code, course_hours, course_grade"
#ELSE END LOOP
...
</code></pre>
<p>This accumulates the information into a string, using standard string formatting to insert the data from each pass through the loop.</p>
<p>At the end of the program, print the output string.</p>
<p>As others have noted, this is a pretty silly way of storing data, since accessing it, except to print out, will be difficult. Lists/dictionaries would be a lot better. </p>
| 0 | 2016-10-16T20:26:43Z | [
"python"
] |
Interpolating a variable with regular grid to a location not on the regular grid with Python scipy interpolate.interpn value error | 40,074,882 | <p>I have a variable from a netcdf file it is a function of time, height, lon, and lat of regular gridded data: U[time,height,lon,lat]. I want to interpolate this variable to a defined location of lon_new,lat_new that is not on the regular grid (it is in between grid points). I want to be able to have the variable U[0,0,lon_new,lat_new] in terms of the single interpolated location. </p>
<p>I read up on the scipy interpolation functions and think that scipy.interpolate.interpn is the function that I want to use. I attempted to do a simple example of this function but keep getting an error. </p>
<pre><code>x_points = [1,2,3,4] #lets call this list of lons on the grid
y_points = [1,2,3,4] #lets call this list of lats on the grid
#Get the lon,lat pairs
point_pairs=[]
for i in x_points:
for j in y_points:
points = [i,j]
point_pairs.append(points)
print point_pairs
print np.shape(point_pairs)
[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]]
(16L, 2L)
xi = (2.5,2.5) #point in between grid points that I am interested in getting the interpolated value
xi=np.array(xi)
print xi
print np.shape(xi)
[ 2.5 2.5]
(2L,)
values = np.ones(16) #array of values at every grid point Let's say I loop over every grid point and get the value at each one
print values
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
interpolated_value = interpolate.interpn(point_pairs, values, xi, method='linear')
ValueError: There are 16 point arrays, but values has 1 dimensions
</code></pre>
| 0 | 2016-10-16T20:05:20Z | 40,075,119 | <p>You can use any appropriate multivariate interpolation function from <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow">scipy</a>. With corrections below your example produces proper result.</p>
<pre><code># -*- coding: utf-8 -*-
import numpy as np
from scipy import interpolate
x_points = np.array([1, 2, 3, 4])
y_points = np.array([1, 2, 3, 4])
values = np.ones((4, 4)) # 2 dimensional array
xi = np.array([2.5, 2.5])
interpolated_value = interpolate.interpn((x_points, y_points), values, xi, method='linear')
print(interpolated_value)
</code></pre>
| 1 | 2016-10-16T20:29:44Z | [
"python",
"scipy",
"interpolation"
] |
How to filter the list by selecting for unique combinations of characters in the elements (Python)? | 40,074,884 | <p>I have the the following pairs stored in the following list</p>
<pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]]
</code></pre>
<p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p>
<pre><code> In sample[1]
C C
G A
C T
G C
</code></pre>
<p>Look a the corresponding elements in both sub-lists, CC, GA, CT, GC.</p>
<p>Here, there are more than two types of pairs (CC), (GA), (CT) and (GC). So this pairwise comparison cannot occur. </p>
<p>Every comparison can have only 2 combinations out of (AA, GG,CC,TT, AT,TA,AC,CA,AG,GA,GC,CG,GT,TG,CT,TC) ... basically all possible combinations of ACGT where order matters.</p>
<p>In the above example, more than 2 such combinations are found.</p>
<p>However, </p>
<pre><code> In sample[0]
C A
G T
C A
G T
</code></pre>
<p>There are only 2 unique combinations: CA and GT</p>
<p>Thus, the only pairs, that remain are:</p>
<pre><code>output = [[CGCG,ATAT],[ATAT,TATA]]
</code></pre>
<p>I would prefer if the code was in traditional for-loop format and not comprehensions</p>
<p>This is a small part of the question listed <a href="http://stackoverflow.com/questions/40066439/how-to-calculate-frequency-of-elements-for-pairwise-comparisons-of-lists-in-pyth/40073665?noredirect=1#comment67421103_40073665">here</a>. This portion of the question is re-asked, as the answer provided earlier provided incorrect output.</p>
| 1 | 2016-10-16T20:05:25Z | 40,075,027 | <p>The core of this task is extracting the pairs from your sublists and counting the number of unique pairs. Assuming your samples actually contain strings, you can use <code>zip(*sub_list)</code> to get the pairs. Then you can use <code>set()</code> to remove duplicate entries.</p>
<pre><code>sample = [['CGCG','ATAT'],['CGCG','CATC'],['ATAT','CATC']]
def filter(sub_list, n_pairs):
pairs = zip(*sub_list)
return len(set(pairs)) == n_pairs
</code></pre>
<p>Then you can use a for loop or a list comprehension to apply this function to your main list.</p>
<pre><code>new_sample = [sub_list for sub_list in sample if filter(sub_list, 2)]
</code></pre>
<p>...or as a for loop...</p>
<pre><code>new_sample = []
for sub_list in sample:
if filter(sub_list, 2):
new_sample.append(sub_list)
</code></pre>
| 1 | 2016-10-16T20:19:01Z | [
"python",
"list",
"unique",
"combinations"
] |
How to filter the list by selecting for unique combinations of characters in the elements (Python)? | 40,074,884 | <p>I have the the following pairs stored in the following list</p>
<pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]]
</code></pre>
<p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p>
<pre><code> In sample[1]
C C
G A
C T
G C
</code></pre>
<p>Look a the corresponding elements in both sub-lists, CC, GA, CT, GC.</p>
<p>Here, there are more than two types of pairs (CC), (GA), (CT) and (GC). So this pairwise comparison cannot occur. </p>
<p>Every comparison can have only 2 combinations out of (AA, GG,CC,TT, AT,TA,AC,CA,AG,GA,GC,CG,GT,TG,CT,TC) ... basically all possible combinations of ACGT where order matters.</p>
<p>In the above example, more than 2 such combinations are found.</p>
<p>However, </p>
<pre><code> In sample[0]
C A
G T
C A
G T
</code></pre>
<p>There are only 2 unique combinations: CA and GT</p>
<p>Thus, the only pairs, that remain are:</p>
<pre><code>output = [[CGCG,ATAT],[ATAT,TATA]]
</code></pre>
<p>I would prefer if the code was in traditional for-loop format and not comprehensions</p>
<p>This is a small part of the question listed <a href="http://stackoverflow.com/questions/40066439/how-to-calculate-frequency-of-elements-for-pairwise-comparisons-of-lists-in-pyth/40073665?noredirect=1#comment67421103_40073665">here</a>. This portion of the question is re-asked, as the answer provided earlier provided incorrect output.</p>
| 1 | 2016-10-16T20:05:25Z | 40,075,034 | <pre><code>sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,CATC]]
result = []
for s in sample:
first = s[0]
second = s[1]
combinations = []
for i in range(0,len(first)):
comb = [first[i],second[i]]
if comb not in combinations:
combinations.append(comb)
if len(combinations) == 2:
result.append(s)
print result
</code></pre>
| 1 | 2016-10-16T20:19:27Z | [
"python",
"list",
"unique",
"combinations"
] |
How to filter the list by selecting for unique combinations of characters in the elements (Python)? | 40,074,884 | <p>I have the the following pairs stored in the following list</p>
<pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]]
</code></pre>
<p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p>
<pre><code> In sample[1]
C C
G A
C T
G C
</code></pre>
<p>Look a the corresponding elements in both sub-lists, CC, GA, CT, GC.</p>
<p>Here, there are more than two types of pairs (CC), (GA), (CT) and (GC). So this pairwise comparison cannot occur. </p>
<p>Every comparison can have only 2 combinations out of (AA, GG,CC,TT, AT,TA,AC,CA,AG,GA,GC,CG,GT,TG,CT,TC) ... basically all possible combinations of ACGT where order matters.</p>
<p>In the above example, more than 2 such combinations are found.</p>
<p>However, </p>
<pre><code> In sample[0]
C A
G T
C A
G T
</code></pre>
<p>There are only 2 unique combinations: CA and GT</p>
<p>Thus, the only pairs, that remain are:</p>
<pre><code>output = [[CGCG,ATAT],[ATAT,TATA]]
</code></pre>
<p>I would prefer if the code was in traditional for-loop format and not comprehensions</p>
<p>This is a small part of the question listed <a href="http://stackoverflow.com/questions/40066439/how-to-calculate-frequency-of-elements-for-pairwise-comparisons-of-lists-in-pyth/40073665?noredirect=1#comment67421103_40073665">here</a>. This portion of the question is re-asked, as the answer provided earlier provided incorrect output.</p>
| 1 | 2016-10-16T20:05:25Z | 40,075,035 | <pre><code>def filter_sample(sample):
filtered_sample = []
for s1, s2 in sample:
pairs = {pair for pair in zip(s1, s2)}
if len(pairs) <= 2:
filtered_sample.append([s1, s2])
return filtered_sample
</code></pre>
<p>Running this</p>
<pre><code>sample = [["CGCG","ATAT"],["CGCG","CATC"],["ATAT","TATA"]]
filter_sample(sample)
</code></pre>
<p>Returns this</p>
<pre><code>[['CGCG', 'ATAT'], ['ATAT', 'TATA']]
</code></pre>
| 2 | 2016-10-16T20:19:31Z | [
"python",
"list",
"unique",
"combinations"
] |
Read list of lists of tuples in Python from file | 40,074,923 | <p>I'd like to read and write a list of lists of tuples from and to files.</p>
<pre><code>g_faces = [[(3,2)(3,5)],[(2,4)(1,3)(1,3)],[(1,2),(3,4),(6,7)]]
</code></pre>
<p>I used</p>
<ul>
<li><code>pickle.dump(g_faces, fp)</code></li>
<li><code>pickle.load(fp)</code></li>
</ul>
<p>But the file is not human readable. Is there an easy way to do it?</p>
| 0 | 2016-10-16T20:08:16Z | 40,074,961 | <p>Try the json module.</p>
<pre><code>import json
g_faces = [[(3,2), (3,5)],[(2,4), (1,3), (1,3)],[(1,2), (3,4), (6,7)]]
json.dump(g_faces, open('test.json', 'w'))
g_faces = json.load(open('test.json'))
# cast back to tuples
g_faces = [[tuple(l) for l in L] for L in g_faces]
</code></pre>
| 0 | 2016-10-16T20:11:32Z | [
"python",
"serialization",
"pickle"
] |
Numerology with certain rules | 40,074,994 | <p><strong>The challenge is to :</strong>
Create a function name_numerology(name) which takes input and turns this input into single digit value and then returns it.</p>
<p><strong>The rules are:</strong></p>
<ul>
<li>function must ignore all kind of characters that are not in the list
of letters above, treat them as something that matches value 0</li>
<li>function must be able to handle the case where input is not string</li>
<li>function must do it's job despite that input might consist of both<br>
lower or upper case letters </li>
<li>if sum of letters is too big (over 10), then the sum the digits
of the sum until the value is number between 0 and 10. Ex: total
is 99 => 9 + 9 => 18 => 1 + 8 = 9. 9 is valid</li>
</ul>
<p>Can't figure out the rest. I am stuck, help please.</p>
<pre><code>letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
numbers = '12345678912345678912345678'
def name_numerology(name):
if isinstance(name, str):
name = str(name)
name = name.upper()
summed = 0
for i in name:
if i not in letters:
i = 0
else:
a = letters.index(i)
summed += int(numbers[a])
ha, hu = divmod(summed, 10)
return ha+hu
else:
return 'Please enter a name'
</code></pre>
| -1 | 2016-10-16T20:15:04Z | 40,075,142 | <p>I think the purpose is that you start adding digits only after you have processed all input characters:</p>
<pre><code>letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
numbers = '12345678912345678912345678'
def name_numerology(name):
if not isinstance(name, str):
return 'Please enter a name'
summed = 0
for c in name.upper():
a = letters.find(c)
if a > -1:
summed += int(numbers[a])
while summed > 9:
temp = summed
summed = 0
while temp > 0:
temp, digit = divmod(temp, 10)
summed += digit
return summed
result = name_numerology('JackTheRipper')
print(result)
</code></pre>
| 0 | 2016-10-16T20:33:15Z | [
"python",
"python-3.x"
] |
python - read email from postfix in python on linux | 40,075,029 | <p>I'm very new to postfix and python. I've setup postfix on Ubuntu and have configured the <code>main.cf</code> with <code>mailbox_command = /home/someuser/test.py</code></p>
<p>test.py:</p>
<pre><code>#!/usr/bin/python
import sys, MySQLdb
email_input = sys.stdin
db = MySQLdb.connect(host="localhost",
user="user",
passwd="password",
db="test")
cur = db.cursor()
sql = "insert into postfix (value) values (%s)"
cur.execute(sql, (email_input,))
db.commit()
db.close()
</code></pre>
<p>I was expecting the content of the email to be inserted into the field but instead I ended up with <code><open file '<stdin>', mode 'r' at 0x7f018b3b40c0></code></p>
<p>How do I get the raw email string from what seems to be that memory address?</p>
| 0 | 2016-10-16T20:19:13Z | 40,075,084 | <p><code>sys.stdin</code> is an object of type <code>TextIOWrapper</code> and <code>cur.execute</code> is expecting a string. You need to instruct <code>sys.stdin</code> to read input and return the string representing it. Use either <code>readline</code> or <code>readlines</code> depending on what you're trying to do.</p>
<pre><code>cur.execute(sql, (sys.stdin.readlines(),))
</code></pre>
| 1 | 2016-10-16T20:25:32Z | [
"python",
"linux",
"postfix"
] |
Replace values in pandas Series with dictionary | 40,075,106 | <p>I want to replace values in a pandas <code>Series</code> using a dictionary. I'm following @DSM's <a href="http://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict">accepted answer</a> like so:</p>
<pre><code>s = Series(['abc', 'abe', 'abg'])
d = {'b': 'B'}
s.replace(d)
</code></pre>
<p>But this has no affect:</p>
<pre><code>0 abc
1 abe
2 abg
dtype: object
</code></pre>
<p>The <a href="http://nipy.bic.berkeley.edu/nightly/pandas/doc/generated/pandas.Series.replace.html" rel="nofollow">documentation</a> explains the required format of the dict for <code>DataFrames</code> (i.e. nested dicts with top level keys corresponding to column names) but I can't see anything specific for <code>Series</code>.</p>
| 2 | 2016-10-16T20:28:05Z | 40,075,212 | <p>You can do it using <code>regex=True</code> parameter:</p>
<pre><code>In [37]: s.replace(d, regex=True)
Out[37]:
0 aBc
1 aBe
2 aBg
dtype: object
</code></pre>
<p>As you have already <a href="http://stackoverflow.com/questions/40075106/replace-values-in-pandas-series-with-dictionary/40075212#comment67423617_40075106">found out yourself</a> - it's a RegEx replacement and it won't work as you expected:</p>
<pre><code>In [36]: s.replace(d)
Out[36]:
0 abc
1 abe
2 abg
dtype: object
</code></pre>
<p>this is working as expected:</p>
<pre><code>In [38]: s.replace({'abc':'ABC'})
Out[38]:
0 ABC
1 abe
2 abg
dtype: object
</code></pre>
| 1 | 2016-10-16T20:41:06Z | [
"python",
"pandas",
"dictionary",
"replace"
] |
Determine mean value of âdataâ where the highest number of CONTINUOUS cond=True | 40,075,164 | <p>I have a pandas Dataframe with a 'data' and 'cond'(-ition) column. I need the mean value (of the data column) of the rows with the highest number of CONTINUOUS True objects in 'cond'. </p>
<pre><code> Example DataFrame:
cond data
0 True 0.20
1 False 0.30
2 True 0.90
3 True 1.20
4 True 2.30
5 False 0.75
6 True 0.80
Result = 1.466, which is the mean value of row-indexes 2:4 with 3 True
</code></pre>
<p>I was not able to find a âvectorizedâ solution with a groupby or pivot method. So I wrote a func that loops the rows. Unfortunately this takes about an hour for 1 Million lines, which is way to long. Unfortunately, the @jit decoration does not reduce the duration measurably. </p>
<p>The data I want to analyze is from a monitoring project over one year and I have every 3 hours a DataFrame with one Million rows. Thus, about 3000 such files. </p>
<p>An efficient solution would be very important. I am also very grateful for a solution in numpy. </p>
| 3 | 2016-10-16T20:36:09Z | 40,075,274 | <p>Here's a NumPy based approach -</p>
<pre><code># Extract the relevant cond column as a 1D NumPy array and pad with False at
# either ends, as later on we would try to find the start (rising edge)
# and stop (falling edge) for each interval of True values
arr = np.concatenate(([False],df.cond.values,[False]))
# Determine the rising and falling edges as start and stop
start = np.nonzero(arr[1:] > arr[:-1])[0]
stop = np.nonzero(arr[1:] < arr[:-1])[0]
# Get the interval lengths and determine the largest interval ID
maxID = (stop - start).argmax()
# With maxID get max interval range and thus get mean on the second col
out = df.data.iloc[start[maxID]:stop[maxID]].mean()
</code></pre>
<p><strong>Runtime test</strong></p>
<p>Approaches as functions -</p>
<pre><code>def pandas_based(df): # @ayhan's soln
res = df['data'].groupby((df['cond'] != df['cond'].shift()).\
cumsum()).agg(['count', 'mean'])
return res[res['count'] == res['count'].max()]
def numpy_based(df):
arr = np.concatenate(([False],df.cond.values,[False]))
start = np.nonzero(arr[1:] > arr[:-1])[0]
stop = np.nonzero(arr[1:] < arr[:-1])[0]
maxID = (stop - start).argmax()
return df.data.iloc[start[maxID]:stop[maxID]].mean()
</code></pre>
<p>Timings -</p>
<pre><code>In [208]: # Setup dataframe
...: N = 1000 # Datasize
...: df = pd.DataFrame(np.random.rand(N),columns=['data'])
...: df['cond'] = np.random.rand(N)>0.3 # To have 70% True values
...:
In [209]: %timeit pandas_based(df)
100 loops, best of 3: 2.61 ms per loop
In [210]: %timeit numpy_based(df)
1000 loops, best of 3: 215 µs per loop
In [211]: # Setup dataframe
...: N = 10000 # Datasize
...: df = pd.DataFrame(np.random.rand(N),columns=['data'])
...: df['cond'] = np.random.rand(N)>0.3 # To have 70% True values
...:
In [212]: %timeit pandas_based(df)
100 loops, best of 3: 4.12 ms per loop
In [213]: %timeit numpy_based(df)
1000 loops, best of 3: 331 µs per loop
</code></pre>
| 1 | 2016-10-16T20:47:01Z | [
"python",
"performance",
"pandas",
"numpy"
] |
Determine mean value of âdataâ where the highest number of CONTINUOUS cond=True | 40,075,164 | <p>I have a pandas Dataframe with a 'data' and 'cond'(-ition) column. I need the mean value (of the data column) of the rows with the highest number of CONTINUOUS True objects in 'cond'. </p>
<pre><code> Example DataFrame:
cond data
0 True 0.20
1 False 0.30
2 True 0.90
3 True 1.20
4 True 2.30
5 False 0.75
6 True 0.80
Result = 1.466, which is the mean value of row-indexes 2:4 with 3 True
</code></pre>
<p>I was not able to find a âvectorizedâ solution with a groupby or pivot method. So I wrote a func that loops the rows. Unfortunately this takes about an hour for 1 Million lines, which is way to long. Unfortunately, the @jit decoration does not reduce the duration measurably. </p>
<p>The data I want to analyze is from a monitoring project over one year and I have every 3 hours a DataFrame with one Million rows. Thus, about 3000 such files. </p>
<p>An efficient solution would be very important. I am also very grateful for a solution in numpy. </p>
| 3 | 2016-10-16T20:36:09Z | 40,075,307 | <p>Using the approach from <a href="http://stackoverflow.com/questions/29142487/calculating-the-number-of-specific-consecutive-equal-values-in-a-vectorized-way">Calculating the number of specific consecutive equal values in a vectorized way in pandas</a>:</p>
<pre><code>df['data'].groupby((df['cond'] != df['cond'].shift()).cumsum()).agg(['count', 'mean'])[lambda x: x['count']==x['count'].max()]
Out:
count mean
cond
3 3 1.466667
</code></pre>
<p>Indexing by a callable requires 0.18.0, for earlier versions, you can do:</p>
<pre><code>res = df['data'].groupby((df['cond'] != df['cond'].shift()).cumsum()).agg(['count', 'mean'])
res[res['count'] == res['count'].max()]
Out:
count mean
cond
3 3 1.466667
</code></pre>
<p>How it works:</p>
<p>The first part, <code>df['cond'] != df['cond'].shift()</code> returns a boolean array:</p>
<pre><code>df['cond'] != df['cond'].shift()
Out:
0 True
1 True
2 True
3 False
4 False
5 True
6 True
Name: cond, dtype: bool
</code></pre>
<p>So the value is False whenever the row is the same as the above. That means that if you take the cumulative sum, these rows (consecutive ones) will have the same number:</p>
<pre><code>(df['cond'] != df['cond'].shift()).cumsum()
Out:
0 1
1 2
2 3
3 3
4 3
5 4
6 5
Name: cond, dtype: int32
</code></pre>
<p>Since groupby accepts any Series to group on (it is not necessary to pass a column, you can pass an arbitrary list), this can be used to group the results. <code>.agg(['count', 'mean']</code> part just gives the respective counts and means for each group and at the end it selects the one with the highest count.</p>
<p>Note that this would group consecutive False's together, too. If you want to only consider consecutive True's, you can change the grouping Series to:</p>
<pre><code>((df['cond'] != df['cond'].shift()) | (df['cond'] != True)).cumsum()
</code></pre>
<p>Since we want False's when the condition is True, the condition became 'not equal to the row below <em>OR</em> not True'. So the original line would change to:</p>
<pre><code>df['data'].groupby(((df['cond'] != df['cond'].shift()) | (df['cond'] != True)).cumsum()).agg(['count', 'mean'])[lambda x: x['count']==x['count'].max()]
</code></pre>
| 2 | 2016-10-16T20:50:23Z | [
"python",
"performance",
"pandas",
"numpy"
] |
Django admin dashboard, not able to "select all" records | 40,075,189 | <p>I have a weird issue were I am not able to "select all" records for any model in my Django admin dashboard.</p>
<p><a href="https://i.stack.imgur.com/HQH57.png" rel="nofollow"><img src="https://i.stack.imgur.com/HQH57.png" alt="Django admin, not able to "select all""></a></p>
<p><strong>This is using Django 1.10.1</strong></p>
<p>It is a small issue, but I still rather have it solved. Appreciate any help!</p>
| 0 | 2016-10-16T20:38:45Z | 40,077,667 | <p>I think you'll need to run </p>
<pre><code>python manage.py collectstatic
</code></pre>
<p>so your js will function on the page.</p>
| 0 | 2016-10-17T02:28:46Z | [
"python",
"django"
] |
GMPY2 Not installing, mpir.h not found | 40,075,271 | <p>I am trying to install gmpy2 on my Anaconda Python 3.5 distribution using pip. I was able to install other modules such as primefac perfectly. When I try to install gmpy2 this is what I get:</p>
<pre><code>(C:\Program Files\Anaconda3) C:\WINDOWS\system32>pip install gmpy2
Collecting gmpy2
Using cached gmpy2-2.0.8.zip
Building wheels for collected packages: gmpy2
Running setup.py bdist_wheel for gmpy2 ... error
Complete output from command "C:\Program Files\Anaconda3\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\HADIKH~1\\AppData\\Local\\Temp\\pip-build-hd7b270n\\gmpy2\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\HADIKH~1\AppData\Local\Temp\tmplefsjn80pip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_ext
building 'gmpy2' extension
creating build
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
creating build\temp.win-amd64-3.5\Release\src
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMPIR -DWITHMPFR -DWITHMPC "-IC:\Program Files\Anaconda3\include" "-IC:\Program Files\Anaconda3\include" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /Tcsrc\gmpy2.c /Fobuild\temp.win-amd64-3.5\Release\src\gmpy2.obj
gmpy2.c
c:\users\hadi khan\appdata\local\temp\pip-build-hd7b270n\gmpy2\src\gmpy.h(104): fatal error C1083: Cannot open include file: 'mpir.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for gmpy2
</code></pre>
<p>I have noticed that whenever I try installing gmpy2 on a computer I always get some sort of error and it is a different one every time. Can someone please tell me how to fix this.</p>
<p>Thanks.</p>
| 0 | 2016-10-16T20:46:52Z | 40,076,291 | <p>I maintain <code>gmpy2</code> and unfortunately I have not been able to build Windows binaries for Python 3.5 and later. <code>gmpy2</code> relies on either the MPIR or GMP libraries, and the MPFR and MPC libraries. There are detailed instructions included in the source distribution but they are not trivial to build on Windows. It is probably impossible(*) to build MPIR, MPFR, and MPC via pip. I would use the pre-compiled binaries available from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>(*) I'm sure it is possible with enough effort but I haven't done it.</p>
| 1 | 2016-10-16T22:43:13Z | [
"python",
"install"
] |
Selenium on Elementary OS not working with Firefox | 40,075,329 | <p>I've got a problem with Selenium on my system. For some reason, it wont launch a Firefox browser window. </p>
<p>Here are the steps that I have gone though.</p>
<ul>
<li>Downloaded Selenium via pip</li>
<li>Downloaded the Marionette (gecko) driver</li>
<li>Added the directory of the downloaded file to my PATH.</li>
</ul>
<p>I am still receiving the below error though.</p>
<pre><code>/usr/bin/python2.7 /home/keva161/PycharmProjects/selenium_test.py
Traceback (most recent call last):
File "/home/keva161/PycharmProjects/selenium_test.py", line 21, in <module>
driver = webdriver.Firefox(capabilities=caps)
File "/home/keva161/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __init__
self.service.start()
File "/home/keva161/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x7f9bcde911d0>> ignored
</code></pre>
<p>The script the I am trying to run is:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"
driver = webdriver.Firefox(capabilities=caps)
driver = webdriver.Firefox()
driver.get('http://saucelabs.com/test/guinea-pig')
driver.quit()
</code></pre>
<p>I am using the latest version of Firefox.</p>
| 1 | 2016-10-16T20:52:10Z | 40,092,191 | <p>PyCharm ignores your PYTHONPATH, instead it builds it based on your project configuration(s), so you need to teach it where it can find <code>gecko</code>. You can do that in either of these 2 ways:</p>
<ul>
<li>configure your interpreter path to include the gecko's dir, see <a href="https://www.jetbrains.com/help/pycharm/2016.1/project-interpreters.html#paths" rel="nofollow">Interpreter paths</a></li>
<li>add the gecko's dir as content or source root (see <a href="https://www.jetbrains.com/help/pycharm/2016.1/content-root.html" rel="nofollow">Content Root</a>) and select the respective check box (<code>Add content roots to PYTHONPATH</code> or <code>Add source roots to PYTHONPATH</code>) in the project's run configuration, see <a href="https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-python.html" rel="nofollow">Run/Debug Configuration: Python</a>.</li>
</ul>
| 0 | 2016-10-17T17:18:42Z | [
"python",
"selenium",
"firefox",
"pycharm",
"elementary"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,454 | <pre><code>input = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
firsts = []
lasts = []
for i in input:
s = i.split(',')
firsts.append(s[0].strip(' '))
lasts.append(s[1].strip(' '))
result = [lasts,firsts]
print result
</code></pre>
<p>result:-</p>
<pre><code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]
</code></pre>
| -1 | 2016-10-16T21:03:31Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,455 | <p>first split & strip items to get name/first name couples, then recombine to get proper arrangement, using listcomps</p>
<pre><code>l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [[y.strip() for y in x.split(",")] for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]
</code></pre>
<p>result:</p>
<pre><code>[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
</code></pre>
<p>EDIT: we don't even need the <code>strip</code> part if it's guaranteed that the separation is <code>", "</code>, because <code>split</code> accepts a multichar string argument. In that case it's even simpler:</p>
<pre><code>l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [x.split(", ") for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]
</code></pre>
| 1 | 2016-10-16T21:03:38Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,579 | <p>This also works:</p>
<pre><code>people = ["Gerber, Len", "Fox, Kate", "Dunn, Bob", "Walsh, Jack"]
def lastfirst(the_list):
name = []
lastname = []
for i in the_list:
lastname.append(i.split(",")[0])
name.append(i.split(", ")[1])
firstlast = [name, lastname]
print (firstlast)
lastfirst(people)
</code></pre>
<p>Made a few corrections, this route is longer but maybe more beginner friendly, at least I would find it so. I realize the output depends on the input being given in correct form as was observed.</p>
| 0 | 2016-10-16T21:16:45Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,682 | <p>Keep it simple and take advantage of list comprehension!</p>
<pre><code>def lastfirst(l):
return [[x.split(',')[1].strip() for x in l], [x.split(',')[0].strip() for x in l]]
print lastfirst(['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'])
</code></pre>
<p>It will print</p>
<pre><code>[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
</code></pre>
| 0 | 2016-10-16T21:28:22Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,698 | <p>In Repl</p>
<pre><code>>>> l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
>>> print [[x.split(',')[1].strip() for x in l], [x.split(',')[0].strip() for x in l]]
[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
</code></pre>
| 0 | 2016-10-16T21:30:22Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,786 | <p>Take advantage of <code>zip</code></p>
<pre><code>>>> a = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
>>> b = [i.split(', ') for i in a]
list(zip(*b))
[('Gerber', 'Fox', 'Dunn'), ('Len', 'Kate', 'Bob')]
</code></pre>
<p>This returns a list of tuples, but if you truly want a list you can use <code>map</code></p>
<pre><code>>>> list(map(list, (zip(*b))))
[['Gerber', 'Fox', 'Dunn'], ['Len', ' Kate', 'Bob']]
</code></pre>
<p>if you want to reverse the list just used the inbuilt <code>reversed</code> function</p>
| 1 | 2016-10-16T21:39:33Z | [
"python"
] |
String splitting within a list | 40,075,389 | <p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input:
<code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p>
<p>Then the function should return a list containing two lists of first names and last names, like this:
<code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code></p>
<p>I'm not sure why this is causing me so many problems and I've tried so many different ways of figuring it out, but I just can't get it. Any help is appreciated. :)</p>
| 1 | 2016-10-16T20:56:33Z | 40,075,832 | <p>Taking Jean-Francois's proposal one step further (BTW, he was right by not giving this answer)</p>
<ol>
<li>Flip name and surname in first step</li>
</ol>
<p><code>c = [[y.strip() for y in x.split(",")][::-1] for x in l]</code></p>
<p>The result is</p>
<pre><code>In [14]: c
Out[14]: [['Len', 'Gerber'], ['Kate', 'Fox'], ['Bob', 'Dunn']]
</code></pre>
<ol start="2">
<li>Re-arrange lists - asterick "unpacks" <em>c</em> as 3 consecutive lists of <em>[name, surname]</em> , and <em>zip</em> reshuffles 3 lists of length 2 into 2 lists of length 3</li>
</ol>
<p><code>result = zip(*c)</code></p>
<p>This is more advanced approach that you may find useful in the future</p>
| 1 | 2016-10-16T21:46:47Z | [
"python"
] |
CountVectorizer: transform method returns multidimensional array on a single text line | 40,075,497 | <p>Firstly, I fit it on the corpus of sms:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
clf = CountVectorizer()
X_desc = clf.fit_transform(X).toarray()
</code></pre>
<p>Seems to works fine:</p>
<pre><code>X.shape = (5574,)
X_desc.shape = (5574, 8713)
</code></pre>
<p>But then I applied transform method to the textline, as we know, it should have (, 8713) shape as a result, but what we see:</p>
<pre><code>str2 = 'Have you visited the last lecture on physics?'
print len(str2), clf.transform(str2).toarray().shape
</code></pre>
<blockquote>
<p>52 (52, 8713)</p>
</blockquote>
<p>What is going on here? One more thing - all numbers are zeros</p>
| 0 | 2016-10-16T21:07:33Z | 40,077,817 | <p>You always need to pass an array or vector to <code>transform</code>; if you just want to transform a single element, you need to pass a singleton array, and then extract its contents:</p>
<pre><code>clf.transform([str1])[0]
</code></pre>
<p>Incidentally the reason that you are getting a 2-dimensional array as output is that the a string is actually stored as a list of characters, and so the vectoriser is treating your string as an array, where each character is being considered as a single document.</p>
| 3 | 2016-10-17T02:53:15Z | [
"python",
"python-2.7",
"text",
"scikit-learn",
"sklearn-pandas"
] |
Python program asks for input twice, doesn't return value the first time | 40,075,530 | <p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br>
How do I fix this?</p>
<pre><code>import random
MIN = 1
MAX = 6
def main():
userValue = 0
compValue = 0
again = get_response()
while again == 'y':
userRoll, compRoll = rollDice()
userValue += userRoll
compValue += compRoll
if userValue > 21:
print("User's points: ", userValue)
print("Computer's points: ", compValue)
print("Computer wins")
else:
print('Points: ', userValue, sep='')
again = get_response()
if again == 'n':
print("User's points: ", userValue)
print("Computer's points: ", compValue)
if userValue > compValue:
print('User wins')
elif userValue == compValue:
print('Tie Game!')
else:
print('Computer wins')
def rollDice():
userRoll = random.randint(MIN, MAX)
compRoll = random.randint(MIN, MAX)
return userRoll, compRoll
def get_response():
answer = input('Do you want to roll? ')
if answer != 'y' or answer != 'n':
print("Invalid response. Please enter 'y' or 'n'.")
answer = input('Do you want to roll? ')
main()
</code></pre>
| -2 | 2016-10-16T21:11:31Z | 40,075,549 | <p><code>answer != 'y' or answer != 'n':</code> is always true; <code>or</code> should be <code>and</code>.</p>
| 2 | 2016-10-16T21:13:31Z | [
"python"
] |
Python program asks for input twice, doesn't return value the first time | 40,075,530 | <p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br>
How do I fix this?</p>
<pre><code>import random
MIN = 1
MAX = 6
def main():
userValue = 0
compValue = 0
again = get_response()
while again == 'y':
userRoll, compRoll = rollDice()
userValue += userRoll
compValue += compRoll
if userValue > 21:
print("User's points: ", userValue)
print("Computer's points: ", compValue)
print("Computer wins")
else:
print('Points: ', userValue, sep='')
again = get_response()
if again == 'n':
print("User's points: ", userValue)
print("Computer's points: ", compValue)
if userValue > compValue:
print('User wins')
elif userValue == compValue:
print('Tie Game!')
else:
print('Computer wins')
def rollDice():
userRoll = random.randint(MIN, MAX)
compRoll = random.randint(MIN, MAX)
return userRoll, compRoll
def get_response():
answer = input('Do you want to roll? ')
if answer != 'y' or answer != 'n':
print("Invalid response. Please enter 'y' or 'n'.")
answer = input('Do you want to roll? ')
main()
</code></pre>
| -2 | 2016-10-16T21:11:31Z | 40,075,571 | <p>It should be <code>answer != 'y' and answer != 'n':</code></p>
| 0 | 2016-10-16T21:16:05Z | [
"python"
] |
Python program asks for input twice, doesn't return value the first time | 40,075,530 | <p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br>
How do I fix this?</p>
<pre><code>import random
MIN = 1
MAX = 6
def main():
userValue = 0
compValue = 0
again = get_response()
while again == 'y':
userRoll, compRoll = rollDice()
userValue += userRoll
compValue += compRoll
if userValue > 21:
print("User's points: ", userValue)
print("Computer's points: ", compValue)
print("Computer wins")
else:
print('Points: ', userValue, sep='')
again = get_response()
if again == 'n':
print("User's points: ", userValue)
print("Computer's points: ", compValue)
if userValue > compValue:
print('User wins')
elif userValue == compValue:
print('Tie Game!')
else:
print('Computer wins')
def rollDice():
userRoll = random.randint(MIN, MAX)
compRoll = random.randint(MIN, MAX)
return userRoll, compRoll
def get_response():
answer = input('Do you want to roll? ')
if answer != 'y' or answer != 'n':
print("Invalid response. Please enter 'y' or 'n'.")
answer = input('Do you want to roll? ')
main()
</code></pre>
| -2 | 2016-10-16T21:11:31Z | 40,075,609 | <p>You're logically thinking that <em>"answer is not y OR n"</em>, but in code that is </p>
<pre><code>not (answer == 'y' or answer == 'n')
</code></pre>
<p>Apply DeMorgans' rule you get</p>
<pre><code>answer != 'y' and answer != 'n'
</code></pre>
<p>Perhaps you should restructure using <code>in</code>. </p>
<p>You'll also want to <code>return answer</code></p>
<pre><code>def get_response():
while True:
answer = input('Do you want to roll? ')
if answer not in {'y', 'n'}:
print("Invalid response. Please enter 'y' or 'n'.")
else:
return answer
</code></pre>
| 0 | 2016-10-16T21:19:08Z | [
"python"
] |
Python Code works in IDLE but not in VS Code | 40,075,578 | <p>I'm currently starting to learn Python and chose Al Sweigart's "Automate the Boring Stuff with Python" to help me with my first steps. As I really like the look and feel of Visual Studio Code I tried to switch after the first part of the book. </p>
<p>The following code is from the online material and should therefore be correct. Unfortunately it works fine in IDLE but not in VS Code.</p>
<pre><code>def isPhoneNumber(text):
if len(text) != 12:
return False # not phone number-sized
for i in range(0, 3):
if not text[i].isdecimal():
return False # not an area code
if text[3] != '-':
return False # does not have first hyphen
for i in range(4, 7):
if not text[i].isdecimal():
return False # does not have first 3 digits
if text[7] != '-':
return False # does not have second hyphen
for i in range(8, 12):
if not text[i].isdecimal():
return False # does not have last 4 digits
return True # "text" is a phone number!
print('415-555-4242 is a phone number:')
print(isPhoneNumber('415-555-4242'))
print('Moshi moshi is a phone number:')
print(isPhoneNumber('Moshi moshi'))
</code></pre>
<p>I get the following error:</p>
<pre><code> 415-555-4242 is a phone number:
Traceback (most recent call last):
File "/Users/.../isPhoneNumber.py", line 20, in <module>
print(isPhoneNumber('415-555-4242'))
File "/Users/.../isPhoneNumber.py", line 5, in isPhoneNumber
if not text[i].isdecimal(): AttributeError: 'str' object has no attribute 'isdecimal'
</code></pre>
<p>I'd be happy about your suggestions to make it work. I already installed the Python Extension and installed suggested stuff with pip3.</p>
<p>Thanks in advance.</p>
| 1 | 2016-10-16T21:16:45Z | 40,075,717 | <p>Only Unicode strings have isdecimal(), so you'd have to mark it as such. </p>
<p>To convert a string to a unicode string in python, you can do this:</p>
<pre><code>s = "Hello!"
u = unicode(s, "utf-8")
</code></pre>
<p>In your question you can just change <code>print(isPhoneNumber('415-555-4242'))</code> to <code>print(isPhoneNumber(u'415-555-4242'))</code> and <code>print(isPhoneNumber('Moshi moshi'))</code> to <code>print(isPhoneNumber(u'Moshi moshi'))</code> </p>
<blockquote>
<p>u'string' in python determines that the string is a unicode string</p>
</blockquote>
| 1 | 2016-10-16T21:32:04Z | [
"python",
"vscode"
] |
Containerization pattern best practice | 40,075,618 | <p>I am dockerizing a Python webapp using the <a href="https://hub.docker.com/r/tiangolo/uwsgi-nginx" rel="nofollow">https://hub.docker.com/r/tiangolo/uwsgi-nginx</a> image, which uses supervisor to control the uWSGI instance.</p>
<p>My app actually requires an additional supervisor-mediated process to run (LibreOffice headless, with which I generate documents through the <code>appy</code> module), and I'm wondering what is the proper pattern to implement it.</p>
<p>The way I see it, I could extend the above image with the extra supervisor config for my needs (along with all the necessary OS-level install steps), but this would be in contradiction with the general principle of running the least amount of distinct processes in a given container. However, since my Python app is designed to talk with LibreOffice only locally, I'm not sure how I could achieve it with a more containerized approach. Thanks for any help or suggestion.</p>
| 0 | 2016-10-16T21:20:09Z | 40,075,742 | <p>You've already blown the "one process per container" -- just add another process. It's not a hard rule, or even one that everybody agrees with.</p>
<p>Extend away, or better yet author your own custom container. That way you own it, you understand it, and it's optimized for your purpose.</p>
| 1 | 2016-10-16T21:34:20Z | [
"python",
"nginx",
"docker",
"uwsgi",
"supervisord"
] |
Containerization pattern best practice | 40,075,618 | <p>I am dockerizing a Python webapp using the <a href="https://hub.docker.com/r/tiangolo/uwsgi-nginx" rel="nofollow">https://hub.docker.com/r/tiangolo/uwsgi-nginx</a> image, which uses supervisor to control the uWSGI instance.</p>
<p>My app actually requires an additional supervisor-mediated process to run (LibreOffice headless, with which I generate documents through the <code>appy</code> module), and I'm wondering what is the proper pattern to implement it.</p>
<p>The way I see it, I could extend the above image with the extra supervisor config for my needs (along with all the necessary OS-level install steps), but this would be in contradiction with the general principle of running the least amount of distinct processes in a given container. However, since my Python app is designed to talk with LibreOffice only locally, I'm not sure how I could achieve it with a more containerized approach. Thanks for any help or suggestion.</p>
| 0 | 2016-10-16T21:20:09Z | 40,084,170 | <p>The recommendation for one-process-per-container is sound - Docker only monitors the process it starts when the container runs, so if you have multiple processes they're not watched by Docker. It's also a better design - you have lightweight, focused containers with single responsibilities, and you can manage them independently.</p>
<p><a href="http://stackoverflow.com/users/2105103/user2105103">user2105103</a> is right though, the image you're using already loses that benefit because it runs Python and Nginx, and you could extend it with LibreOffice headless and package your whole app without changing code.</p>
<p>If you move to a more "best practice" approach, you'd have a distributed app running across three containers in a Docker network:</p>
<ul>
<li><code>nginx</code> - web proxy, this is the public entry point to the app. Nginx can do routing, caching, SSL termination, rate limiting etc. </li>
<li><code>app</code> - your Python app, only visible inside the Docker network. Receives requests from <code>nginx</code> and uses <code>libreoffice</code> for document manipulation;</li>
<li><code>libreoffice</code> - running in headless mode with the API exposed, but only available within the Docker network.</li>
</ul>
<p>You'd need code changes for this, bringing in something like <a href="https://pypi.python.org/pypi/pyoo" rel="nofollow">PyOO</a> to use the LibreOffice API remotely from the app container.</p>
| 2 | 2016-10-17T10:36:20Z | [
"python",
"nginx",
"docker",
"uwsgi",
"supervisord"
] |
GAE (Python) Best practice: Load config from JSON file or Datastore? | 40,075,640 | <p>I wrote a platform in GAE Python with a Datastore database (using NDB). My platform allows for a theme to be chosen by the user. Before <em>every</em> page load, I load in a JSON file (using <code>urllib.urlopen(FILEPATH).read()</code>). Should I instead save the JSON to the Datastore and load it through NDB instead?</p>
<p>Here's an example of my JSON config file. These can range in size but not by much. They're generally very small.</p>
<pre><code>{
"TITLE": "Test Theme",
"VERSION": "1.0",
"AUTHOR": "ThePloki",
"DESCRIPTION": "A test theme for my platform",
"FONTS": ["Arial", "Times New Roman"],
"TOOLBAR": [
{"left":[
{"template":"logo"}
]},
{"center":[
{"template":"breadcrumbs"}
]},
{"right":[
{"template":"link", "url":"account", "msg":"Account"},
{"template":"link", "url":"logout", "msg":"Log Out"}
]}
],
"NAV_LEFT": true,
"SHOW_PAGE_TITLE": false
}
</code></pre>
<p>I don't currently notice any delays, but I'm working locally. During production would the <code>urllib.urlopen().read()</code> cause problems if there is high traffic?</p>
| 0 | 2016-10-16T21:22:53Z | 40,075,677 | <p>Do you expect the configuration to change without the application code being re-deployed? That is the scenario where it would make sense to store the configuration in the Datastore.</p>
<p>If the changing the configuration involves re-deploying the code anyway, a local file is probably fine - you might even consider making it a Python file rather than JSON, so that it'd simply be a matter of importing it rather than messing around with file handles.</p>
| 0 | 2016-10-16T21:27:59Z | [
"python",
"json",
"google-app-engine",
"gae-datastore",
"urllib"
] |
Using Python 2.7 and RawInput how do I load code into a string variable then convert to all uppercase? | 40,075,689 | <p>I need to convert a file into a string using raw input then convert the characters to uppercase? How do I do this?</p>
| -2 | 2016-10-16T21:29:26Z | 40,075,914 | <p>To convert a string <code>s</code> to uppercase: <code>s.upper()</code>.</p>
<p>You use raw input like this: </p>
<pre><code>name = raw_input("What is your name? ")
print "Hello, %s." % name
</code></pre>
| 0 | 2016-10-16T21:58:27Z | [
"python"
] |
Python: Use specific parts of a string (that looks like a list) | 40,075,696 | <p>I have a text file (file.txt):</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])
</code></pre>
<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>
<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>
<p>Note: text file is obviously not a list, even though it looks like it.</p>
<pre><code>myFile = open("file.txt", "r")
while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:
...
myFile.close()
</code></pre>
<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>
<p>Thank you.</p>
| 1 | 2016-10-16T21:30:12Z | 40,075,816 | <p>First, parse the couples using a regular expression which extracts them all.</p>
<p>Then use the nice <code>itertools.groupby</code> to gather the values using keys as the <code>a,b,c...</code> letter (first item of the regex tuple).</p>
<p>Finally, create tuples with variable, sum of values as integer</p>
<pre><code>import re,itertools
with open("file.txt", "r") as myFile:
r = re.compile("(\w+):(-?\d+)")
for l in myFile:
tuples = r.findall(l)
sums = []
for variable,values in itertools.groupby(tuples,lambda t: t[0]):
sums.append((variable,sum(int(x[1]) for x in values)))
print(l,sums)
</code></pre>
<p>output:</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10]) [('a', 15), ('b', 50), ('c', 20)]
(B->[e:120,g:50]) [('e', 120), ('g', 50)]
(C->[a:5,f:20]) [('a', 5), ('f', 20)]
</code></pre>
<p>If you want the total sum for all lines, small changes. First accumulate all tuples in a list (source line is not important), then apply <code>groupby</code> on the sorted list (or grouping won't work properly)</p>
<pre><code>import re,itertools
with open("file.txt", "r") as myFile:
r = re.compile("(\w+):(-?\d+)")
tuples = []
for l in myFile:
tuples += r.findall(l)
sums = []
for variable,values in itertools.groupby(sorted(tuples),lambda t: t[0]):
sums.append((variable,sum(int(x[1]) for x in values)))
print(sums)
</code></pre>
<p>result:</p>
<pre><code>[('a', 20), ('b', 50), ('c', 20), ('e', 120), ('f', 20), ('g', 50)]
</code></pre>
| 0 | 2016-10-16T21:43:52Z | [
"python",
"string",
"file",
"python-3.x"
] |
Python: Use specific parts of a string (that looks like a list) | 40,075,696 | <p>I have a text file (file.txt):</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])
</code></pre>
<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>
<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>
<p>Note: text file is obviously not a list, even though it looks like it.</p>
<pre><code>myFile = open("file.txt", "r")
while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:
...
myFile.close()
</code></pre>
<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>
<p>Thank you.</p>
| 1 | 2016-10-16T21:30:12Z | 40,075,848 | <pre><code>def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
myFile = open("file.txt", "r")
content = myFile.read()
totalValue = 0
all_colon_indexes = find(content,':')
for i in range(0,len(content)):
if content[i]==':':
if content[i-1]=='a': #THIS IS WHERE YOU SPECIFY 'a' or 'b' or 'c', etc
value=''
index = i+1
while True:
if content[index].isdigit()==True:
value=value+content[index]
index=index+1
else:
break
_value = int(value)
totalValue = totalValue + _value
print totalValue
</code></pre>
<p>result:</p>
<pre><code>20
</code></pre>
| 0 | 2016-10-16T21:49:27Z | [
"python",
"string",
"file",
"python-3.x"
] |
Python: Use specific parts of a string (that looks like a list) | 40,075,696 | <p>I have a text file (file.txt):</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])
</code></pre>
<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>
<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>
<p>Note: text file is obviously not a list, even though it looks like it.</p>
<pre><code>myFile = open("file.txt", "r")
while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:
...
myFile.close()
</code></pre>
<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>
<p>Thank you.</p>
| 1 | 2016-10-16T21:30:12Z | 40,075,872 | <p>Parse the file using regular expressions:</p>
<ul>
<li><code>\w</code> stands for a word character</li>
<li><code>\d</code> stands for a digit</li>
<li><code>+</code> specifies that you want to match one or more of the preceding match groups</li>
<li><code>?</code> specifies that you want to match zero or one of the preceding match groups (to account for a minus character)</li>
<li>parentheses specify that what is matched inside them should be extracted as a group of characters so we have two groups (one for the letter, one for the number)</li>
</ul>
<p>Then use a <code>defaultdict</code> to hold the name -> sum mapping. A <code>defaultdict</code> is like an ordinary <code>dict</code>, but when the key is missing, it creates it with a default value obtained by calling the callable you supplied when creating it. In this case this is <code>int</code> which returns <code>0</code> when called.</p>
<pre><code>import re
from collections import defaultdict
value_pattern = re.compile("(\w+):(-?\d+)")
totals = defaultdict(int)
with open("file.txt", "r") as myFile:
for line in myFile.readlines():
values = value_pattern.findall(line)
for name, value in values:
totals[name] += int(value)
print(totals.items())
totals.clear()
</code></pre>
<p>This gives</p>
<pre><code>dict_items([('c', 20), ('a', 15), ('b', 50)])
dict_items([('g', 50), ('e', 120)])
dict_items([('f', 20), ('a', 5)])
</code></pre>
<p>when run on your file.</p>
| 0 | 2016-10-16T21:52:44Z | [
"python",
"string",
"file",
"python-3.x"
] |
Python: Use specific parts of a string (that looks like a list) | 40,075,696 | <p>I have a text file (file.txt):</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])
</code></pre>
<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>
<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>
<p>Note: text file is obviously not a list, even though it looks like it.</p>
<pre><code>myFile = open("file.txt", "r")
while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:
...
myFile.close()
</code></pre>
<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>
<p>Thank you.</p>
| 1 | 2016-10-16T21:30:12Z | 40,075,874 | <p>If I may suggest a somehow more compact solution that sums up every "key" in the text file and outputs a dictionary:</p>
<pre><code>import re
from collections import defaultdict
with open('a.txt') as f:
lines = f.read()
tups = re.findall(r'(\w+):(\d+)', lines)
print(tups)
# tups is a list of tuples in the form (key, value), ie [('a': '5'), ...]
sums = defaultdict(int)
for tup in tups:
sums[tup[0]] += int(tup[1])
print(sums)
</code></pre>
<p>Will output:</p>
<pre><code>[('a', '5'), ('a', '5'), ('a', '5'), ('b', '50'), ('c', '10'), ('c', '10'), ('e', '120'), ('g', '50'), ('a', '5'), ('f', '20')]
defaultdict(<class 'int'>, {'f': 20, 'b': 50, 'e': 120, 'a': 20, 'c': 20, 'g': 50})
</code></pre>
<p>And more specifically:</p>
<pre><code>print(sums['a'])
>> 20
print(sums['b'])
>> 50
</code></pre>
| 0 | 2016-10-16T21:53:10Z | [
"python",
"string",
"file",
"python-3.x"
] |
Python: Use specific parts of a string (that looks like a list) | 40,075,696 | <p>I have a text file (file.txt):</p>
<pre><code>(A->[a:5,a:5,a:5,b:50,c:10,c:10])
(B->[e:120,g:50])
(C->[a:5,f:20])
</code></pre>
<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>
<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>
<p>Note: text file is obviously not a list, even though it looks like it.</p>
<pre><code>myFile = open("file.txt", "r")
while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:
...
myFile.close()
</code></pre>
<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>
<p>Thank you.</p>
| 1 | 2016-10-16T21:30:12Z | 40,075,933 | <p>No intention on stepping on Jean-Francois's toes :-) - I would suggest using <em>Counter</em> for count.</p>
<pre><code>import collections
with open("file.txt", "r") as myFile:
r = re.compile("(\w+):(-?\d+)")
res = collections.Counter()
for l in myFile:
for key, cnt in r.findall(l):
res.update({key: int(cnt)})
</code></pre>
<p>result: <code>res</code> is now:</p>
<pre><code>Counter({'e': 120, 'b': 50, 'g': 50, 'c': 20, 'f': 20, 'a': 20})
</code></pre>
<p>you can access it like a dictionary: ex:</p>
<pre><code>res["a"] => 20
</code></pre>
| 0 | 2016-10-16T22:00:52Z | [
"python",
"string",
"file",
"python-3.x"
] |
Retrieveing files form URL in Python returns blank | 40,075,703 | <p>I'm working on a chess related project for which I have to download a very large quantity of files from <a href="http://chesstempo.com" rel="nofollow">ChessTempo</a>. </p>
<p>When running the following code:</p>
<pre><code>import urllib.request
url = "http://chesstempo.com/requests/download_game_pgn.php?gameids="
for i in range (3,500):
urllib.request.urlretrieve(url + str(i),'Games/Game ' + str(i) + ".pgn")
print("Downloaded file nº " + str(i))
</code></pre>
<p>I get the expected list of 500~ files but they are all blank except the second and third files, which have the correct data in them.</p>
<p>When I open the URLs by hand, it all works perfectly. What am I missing?</p>
| 0 | 2016-10-16T21:31:05Z | 40,088,708 | <p>In fact, I can only download files 2 & 3, all others are empty...</p>
<p>Were you logged in while accessing those files "manually"? (Which I assume to be using a web browser).</p>
<p>If so, FYI an http request does not only consist of the URL, lots of other information is transfered. So if you are not getting the same information, you are almost certainly not making the same request.</p>
<p>In chrome you can see the requests you make within a page.</p>
<p>From <em>Developer Tools</em> go to <em>Network</em> > <em>Select a name form the list</em> > <em>Request Headers</em> (<a href="https://i.stack.imgur.com/GORS4.png" rel="nofollow">See picture</a>)</p>
<p>The most probable thing that you may be looking for are the <em>cookies</em></p>
<p>Hope it helps.</p>
| 1 | 2016-10-17T14:11:59Z | [
"python",
"urllib"
] |
Bayesian Correlation with PyMC3 | 40,075,725 | <p>I'm trying to convert this <a href="http://www.philippsinger.info/?p=581" rel="nofollow">example of Bayesian correlation for PyMC2</a> to PyMC3, but get completely different results. Most importantly, the mean of the multivariate Normal distribution quickly goes to zero, whereas it should be around 400 (as it is for PyMC2). Consequently, the estimated correlation quickly goes towards 1, which is wrong as well.</p>
<p>The full code is available in this <a href="http://nbviewer.jupyter.org/github/psinger/notebooks/blob/master/bayesian_correlation_pymc.ipynb" rel="nofollow">notebook for PyMC2</a> and in this <a href="http://nbviewer.jupyter.org/github/sebp/bayesian-correlation/blob/master/bayesian_correlation_pymc3.ipynb" rel="nofollow">notebook for PyMC3</a>.</p>
<p>The relevant code for PyMC2 is</p>
<pre><code>def analyze(data):
# priors might be adapted here to be less flat
mu = pymc.Normal('mu', 0, 0.000001, size=2)
sigma = pymc.Uniform('sigma', 0, 1000, size=2)
rho = pymc.Uniform('r', -1, 1)
@pymc.deterministic
def precision(sigma=sigma,rho=rho):
ss1 = float(sigma[0] * sigma[0])
ss2 = float(sigma[1] * sigma[1])
rss = float(rho * sigma[0] * sigma[1])
return np.linalg.inv(np.mat([[ss1, rss], [rss, ss2]]))
mult_n = pymc.MvNormal('mult_n', mu=mu, tau=precision, value=data.T, observed=True)
model = pymc.MCMC(locals())
model.sample(50000,25000)
</code></pre>
<p>My port of the above code to PyMC3 is as follows:</p>
<pre><code>def precision(sigma, rho):
C = T.alloc(rho, 2, 2)
C = T.fill_diagonal(C, 1.)
S = T.diag(sigma)
return T.nlinalg.matrix_inverse(T.nlinalg.matrix_dot(S, C, S))
def analyze(data):
with pm.Model() as model:
# priors might be adapted here to be less flat
mu = pm.Normal('mu', mu=0., sd=0.000001, shape=2, testval=np.mean(data, axis=1))
sigma = pm.Uniform('sigma', lower=1e-6, upper=1000., shape=2, testval=np.std(data, axis=1))
rho = pm.Uniform('r', lower=-1., upper=1., testval=0)
prec = pm.Deterministic('prec', precision(sigma, rho))
mult_n = pm.MvNormal('mult_n', mu=mu, tau=prec, observed=data.T)
return model
model = analyze(data)
with model:
trace = pm.sample(50000, tune=25000, step=pm.Metropolis())
</code></pre>
<p>The PyMC3 version runs, but clearly does not return the expected result. Any help would be highly appreciated.</p>
| 1 | 2016-10-16T21:32:52Z | 40,076,826 | <p>The call signature of pymc.Normal is </p>
<pre><code>In [125]: pymc.Normal?
Init signature: pymc.Normal(self, *args, **kwds)
Docstring:
N = Normal(name, mu, tau, value=None, observed=False, size=1, trace=True, rseed=True, doc=None, verbose=-1, debug=False)
</code></pre>
<p>Notice that the third positional argument of <code>pymc.Normal</code> is <code>tau</code>, not the standard deviation, <code>sd</code>.</p>
<p>Therefore, since the <code>pymc</code> code uses </p>
<pre><code>mu = Normal('mu', 0, 0.000001, size=2)
</code></pre>
<p>The corresponding <code>pymc3</code> code should use</p>
<pre><code>mu = pm.Normal('mu', mu=0., tau=0.000001, shape=2, ...)
</code></pre>
<p>or</p>
<pre><code>mu = pm.Normal('mu', mu=0., sd=math.sqrt(1/0.000001), shape=2, ...)
</code></pre>
<p>since <code>tau = 1/sigma**2</code>.</p>
<hr>
<p>With this one change, your pymc3 code produces (something like)</p>
<p><a href="https://i.stack.imgur.com/7OpTW.png" rel="nofollow"><img src="https://i.stack.imgur.com/7OpTW.png" alt="enter image description here"></a></p>
| 1 | 2016-10-17T00:03:58Z | [
"python",
"correlation",
"bayesian",
"pymc",
"pymc3"
] |
TypeError: 'HtmlResponse' object is not iterable | 40,075,760 | <p>I'm new to python, but trying to get my head around it in order to use Scrapy for work.</p>
<p>I'm currently following this tutorial:
<a href="http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html" rel="nofollow">http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html</a></p>
<p>I've having trouble with this part (from the tutorial): </p>
<pre><code>def parse(self, response):
for sel in response.xpath('//ul/li'):
title = sel.xpath('a/text()').extract()
link = sel.xpath('a/@href').extract()
desc = sel.xpath('text()').extract()
print title, link, desc
</code></pre>
<p>The problem I'm having is with the <code>for sel in response.xpath('//ul/li'):</code> part. I understand that line to essentially narrow down what is crawled to anything that matches the xpath <code>//ul/li</code>.</p>
<p>However, in my implementation, I can't narrow down the page to one singular section. I tried to get around this by selecting the entire HTML, see my attempt below:</p>
<pre><code> def parse(self, response):
for sel in response.xpath('//html'):
title = sel.xpath('//h1/text()').extract()
author = sel.xpath('//head/meta[@name="author"]/@content').extract()
mediumlink = sel.xpath('//head/link[@rel="author"]/@href').extract()
print title, author, mediumlink
</code></pre>
<p>The xpaths work both in a Chrome plugin I use, and using <code>response.xpath('//title').extract()</code> in <code>scrapy shell</code></p>
<p>I've tried changing the line to this:</p>
<p><code>for sel in response.xpath('//html'):</code> and <code>for sel in response.xpath('html'):</code></p>
<p>But each time I get this:</p>
<pre><code>2016-10-16 14:33:43 [scrapy] ERROR: Spider error processing <GET https://medium.com/swlh/how-our-app-went-from-20-000-day-to-2-day-in-revenue-d6892a2801bf#.smmwwqxlf> (referer: None)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 587, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/Users/Matthew/Sites/crawl/tutorial/tutorial/spiders/medium_Spider.py", line 11, in parse
for sel in response:
TypeError: 'HtmlResponse' object is not iterable
</code></pre>
<p>Could somebody give me some pointers on how best to resolve this? Go easy on me, my skills are not so hot. Thanks!</p>
| 0 | 2016-10-16T21:36:17Z | 40,083,781 | <p>As the error message states</p>
<pre><code> for sel in response:
</code></pre>
<p>You try to iterate through the <code>response</code> object in your <code>medium_Spider.py</code> file at <strong>line 11</strong>.</p>
<p>However <code>response</code> is an <code>HtmlResponse</code> not an <em>iterable</em> which you could use in a <code>for</code> loop --> you are missing some method call on <code>response</code>. Try to do the loops as you have written in your question:</p>
<pre><code>for sel in response.xpath('//html'):
</code></pre>
<p>Where <code>.xpath('//html')</code> returns an iterable which you can use in the <code>for</code> loop.</p>
| 1 | 2016-10-17T10:17:51Z | [
"python",
"xpath",
"scrapy",
"scrapy-spider"
] |
Luhns Algorithm | 40,075,829 | <p>Hey I am doing Luhn's algorithm for an assignment for school.</p>
<p>A few outputs are coming out the correct way; however, some are not. </p>
<p><code>0004222222222222</code> is giving me a total of <code>44</code>, </p>
<p>and</p>
<p><code>0378282246310005</code> is giving me a total of <code>48</code>, </p>
<p>for a few examples.</p>
<p>I know my code isn't the cleanest as I am a novice but if anyone can identify where I'm getting my error I'd really appreciate</p>
<p>Here is my code: </p>
<pre><code>cardNumber = input( "What is your card number? ")
digit = len(cardNumber)
value = 0
total = 0
while ( len( cardNumber ) == 16 and digit > 0):
# HANDLE even digit positions
if ( digit % 2 == 0 ):
value = ( int( cardNumber[digit - 1]) * 2 )
if( value > 9 ):
double = str( value )
value = int( double[:1] ) + int( double[-1] )
total = total + value
value = 0
digit = digit - 1
else:
total = total + value
value = 0
digit = digit - 1
# HANDLE odd digit positions
elif ( digit % 2 != 0):
total = total + int( cardNumber[digit - 1] )
digit = digit - 1
</code></pre>
| 3 | 2016-10-16T21:46:30Z | 40,076,095 | <p>You almost got it right. Only that the last digit (or first from behind) should be considered as odd for your 16 digit card. So you should set:</p>
<pre><code>digit = len(cardNumber) - 1
</code></pre>
<p>And then your <em>while</em> condition should stop at <code>>= 0</code> (zeroth item inclusive); note that the <code>len( cardNumber ) == 16</code> is redundant as the length of the card is constant:</p>
<pre><code>while digit >= 0:
</code></pre>
<p>And finally your indexing of the creditcard number will no longer need a minus 1:</p>
<pre><code>value = int(cardNumber[digit]) * 2
...
...
total = total + int(cardNumber[digit])
</code></pre>
| 2 | 2016-10-16T22:19:44Z | [
"python",
"luhn"
] |
Luhns Algorithm | 40,075,829 | <p>Hey I am doing Luhn's algorithm for an assignment for school.</p>
<p>A few outputs are coming out the correct way; however, some are not. </p>
<p><code>0004222222222222</code> is giving me a total of <code>44</code>, </p>
<p>and</p>
<p><code>0378282246310005</code> is giving me a total of <code>48</code>, </p>
<p>for a few examples.</p>
<p>I know my code isn't the cleanest as I am a novice but if anyone can identify where I'm getting my error I'd really appreciate</p>
<p>Here is my code: </p>
<pre><code>cardNumber = input( "What is your card number? ")
digit = len(cardNumber)
value = 0
total = 0
while ( len( cardNumber ) == 16 and digit > 0):
# HANDLE even digit positions
if ( digit % 2 == 0 ):
value = ( int( cardNumber[digit - 1]) * 2 )
if( value > 9 ):
double = str( value )
value = int( double[:1] ) + int( double[-1] )
total = total + value
value = 0
digit = digit - 1
else:
total = total + value
value = 0
digit = digit - 1
# HANDLE odd digit positions
elif ( digit % 2 != 0):
total = total + int( cardNumber[digit - 1] )
digit = digit - 1
</code></pre>
| 3 | 2016-10-16T21:46:30Z | 40,076,387 | <p>So your code is mostly correct, the only issue is that you haven't properly defined what should be considered an "odd" and an "even" number. As you read the number from the end, "odd and even" are also relative from the end, so :</p>
<ul>
<li>odd numbers start from the <em>last one</em>, and then every other one </li>
<li>even numbers start from the <em>last but one</em>, and then every other one </li>
</ul>
<p>Example : 1234 is EOEO, 12345 is OEOEO (O means odd , E means even)</p>
<p>Here the fixed code (I only modified three lines, see comments):</p>
<pre><code>digit = len(cardNumber)
value = 0
total = 0
while digit > 0: # I removed the length condition
# HANDLE even digit positions
if ( (len(cardNumber)+1-digit) % 2 == 0 ): # <- modification here
value = ( int( cardNumber[digit - 1]) * 2 )
if( value > 9 ):
double = str( value )
value = int( double[:1] ) + int( double[-1] )
total = total + value
digit = digit - 1
else:
total = total + value
digit = digit - 1
# HANDLE odd digit positions
elif ( (len(cardNumber)+1-digit) % 2 != 0): # <- modification here
value=int( cardNumber[digit - 1] )
total = total + int( cardNumber[digit - 1] )
digit = digit - 1
return total
</code></pre>
<p>Some tests :</p>
<pre><code>In : '0378282246310005' -> Out : 60
In : '00378282246310005' -> Out : 60
In : '0004222222222222' -> Out : 40
</code></pre>
| 0 | 2016-10-16T22:57:11Z | [
"python",
"luhn"
] |
Unable to access modified value of imported variable | 40,075,860 | <p>I am new to python and have some problem understanding the scope here.</p>
<p>I have a python module A with three global variables :</p>
<pre><code>XYZ = "val1"
ABC = {"k1" : "v1", "k2" : "v2"}
PQR = 1
class Cls_A() :
def sm_fn_A(self) :
global XYZ
global ABC
global PQR
XYZ = "val2"
ABC["k1"] = "z1"
ABC["k3"] = "v3"
PQR += 1
</code></pre>
<p>And another module B :</p>
<pre><code>from A import Cls_A, XYZ, ABC, PQR
class Cls_B():
def sm_fn_B(self) :
Cls_A().sm_fn_A()
print XYZ
print ABC
print PQR
Cls_B().sm_fn_B()
</code></pre>
<p>This gives me the following output :</p>
<pre><code>val1
{'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}
1
</code></pre>
<p>Since these are all global variables, why do I not get updated values of all the global variables printed ? </p>
| 0 | 2016-10-16T21:51:40Z | 40,076,268 | <h1>Explanation</h1>
<p>Three global variables are defined in module <code>A</code>, in this code:</p>
<pre><code>XYZ = "val1"
ABC = {"k1" : "v1", "k2" : "v2"}
PQR = 1
</code></pre>
<p>Then new global variables <code>XYZ</code>, <code>ABC</code>, <code>PQR</code> are defined in module <code>B</code>, in this code:</p>
<pre><code>from A import Cls_A, XYZ, ABC, PQR
</code></pre>
<p>This line of code creates new variables, just as if the following was written:</p>
<pre><code>import A
XYZ = A.XYZ
ABC = A.ABC
PQR = A.PQR
</code></pre>
<p>It is important to understand that <code>A.XYZ</code> and <code>B.XYZ</code> are two variables which point to the same object. They are not the same variable.</p>
<p>Then a new object is assigned to <code>A.XYZ</code>:</p>
<pre><code> XYZ = "val2"
</code></pre>
<p>This modified <code>A.XYZ</code>, but did not modify <code>B.XYZ</code>. The two used to be two variables which pointed to the same object, but now <code>A.XYZ</code> points to a different object.</p>
<p>On the other hand, <code>A.ABC</code> is not assiciated with a different object. Instead, the object itself is modified. When the object is modified, both <code>A.ABC</code> and <code>B.ABC</code> still point to the same object:</p>
<pre><code> ABC["k1"] = "z1"
ABC["k3"] = "v3"
</code></pre>
<p>The third case is also not a case of object modification, but rather reassignment:</p>
<pre><code> PQR += 1
</code></pre>
<p>The value was incremented. That created a new object and than thet new object was assigned to <code>A.PQR</code>. <code>B.PQR</code> is unchanged. This is equivalent to:</p>
<pre><code> PQR = PQR + 1
</code></pre>
<p>A thing which may not be obvious is that both strings and integers are <em>immutable</em> objects in Python (there is no way to change number to <code>2</code> to become <code>3</code> - one can only assign a different int object to a variable, not change the existing one). Because of that, there is actually no way to change <code>A.XYZ</code> in a way that affects <code>B.XYZ</code>.</p>
<h2>The dictionary could behave the same way</h2>
<p>The reason why with the dictionary it <em>"worked"</em> is that the object was modified. If a new dictioanry was assigned to <code>A.ABC</code>, that would not work. E.g.</p>
<pre><code> ABC = {'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}
</code></pre>
<p>Now it would not affect <code>B.ABC</code>, because the object in <code>A.ABC</code> was not changed. Another object was assigned to <code>A.ABC</code> instead.</p>
<h1>Not related to modules</h1>
<p>The same behaviour can be seen without any modules:</p>
<pre><code>A_XYZ = "val1"
A_ABC = {"k1" : "v1", "k2" : "v2"}
A_PQR = 1
B_XYZ = A_XYZ
B_ABC = A_ABC
B_PQR = A_PQR
A_XYZ = "val2"
A_ABC["k1"] = "z1"
A_ABC["k3"] = "v3"
A_PQR += 1
print B_XYZ
print B_ABC
print B_PQR
</code></pre>
<p>Prints:</p>
<pre><code>val1
{'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}
1
</code></pre>
<h1>Solution</h1>
<p>Well, don't keep reference to the temporary object. Use the variable which has the correct value.</p>
<p>For example, in module <code>B</code>:</p>
<pre><code>import A
class Cls_B():
def sm_fn_B(self) :
A.Cls_A().sm_fn_A()
print A.XYZ
print A.ABC
print A.PQR
Cls_B().sm_fn_B()
</code></pre>
<p>Now there is actually no <code>B.XYZ</code> variable, which could be wrong. <code>A.XYZ</code> is always used.</p>
| 1 | 2016-10-16T22:39:59Z | [
"python",
"python-2.7",
"import",
"scope",
"global-variables"
] |
Get input from user at command line and use that input to feed variables into Python script | 40,075,894 | <p>I have a script named <code>GetStats.py</code>. </p>
<p>At a high level, the <code>GetStats.py</code> script does the following:</p>
<p>1) makes a connection to an external database
2) retrieves some data from this database
3) writes the data retrieved in step 2 to a csv file</p>
<p>Importantly, the <code>GetStats.py</code> script references a configuration (.cfg) file, which includes (among many other details), the IP address and server details of the specific database to which to connect.</p>
<p>The <code>GetStats.py</code> script requires that the user pass the following parameters on the command line:</p>
<p>a) the number of days of data to retrieve (i.e. the look back period)
b) the granularity of the data (which is either hourly or daily)
c) whether to include a limited set of data (which takes about 30 minutes to run) or the full set of data (which takes about 1 hour and 15 minutes to run)</p>
<p>I also have a batch file that I use to run everything. The batch file looks as follows:</p>
<pre><code>GetStats.py Client_A.cfg 30 -d -full
GetStats.py Client_B.cfg 30 -d -full
GetStats.py Client_C.cfg 30 -d -full
GetStats.py Client_D.cfg 30 -d -full
GetStats.py Client_E.cfg 30 -d -full
... and so on up to Client_M
</code></pre>
<p>As we can see from the batch file above, the GetStats.py script is called and it runs against Client_A through Client_E for a period of 30 days, with daily granularity and returns the full set of data.</p>
<p>The problem is that if I want to change any of these parameters (e.g. change the number of days in the look back period, the data granularity and/or the set of data to return), I need to edit the batch file directly, and that process can take several minutes. </p>
<p>I'd like to streamline the process such that the user is prompted for the following <strong>only once</strong> at the command line once the batch file is run:</p>
<p>"Please enter the number of days to look back: "</p>
<p>"Please enter the granularity of the data: "</p>
<p>"Please enter the data set to return: "</p>
<p>I've given some thought as to how to incorporate these three parameters <strong>directly</strong> into the GetStats.py script. </p>
<p>But, I think I will run into a problem because the batch file will run the GetStats.py script and then prompt the user for the 3 parameters above <strong>each time</strong> the GetStats.py script is called (which is currently 13 times). </p>
<p>I don't want the user to have to enter "30", "-d" and "-full" a total of 13 times. I'd like the user to enter "30", "-d" and "-full" <strong>only once</strong>.</p>
<p>Does anyone have any ideas how I can prompt the user for the above-mentioned 3 parameters <strong>only once</strong> after the batch file is run?</p>
<p>Thanks!</p>
| -2 | 2016-10-16T21:55:35Z | 40,076,855 | <p>Consider sourcing your <em>GetStats.py</em> as a module in a different .py script that receives user input via <code>input()</code> (or <code>raw_input()</code> in Python 2). In this way, you do no need a batch file or entering parameters via command line which is not a user-friendly interface. Plus, you can loop through all client types for a DRY-er approach using <code>string.ascii_uppercase</code>. Below is setup:</p>
<p><strong>GetStats.py</strong> </p>
<p><em>(wrap entire script in a defined module receiving the params previously sent via command line, no longer the <code>sys.argv[]</code> collection)</em></p>
<pre><code>def processData(clienttype, lookbackdaysparam, granularityparam, datasettypeparam):
#...script...
</code></pre>
<p><strong>UserInput.py</strong> </p>
<p><em>(place in same directory as GetStats.py; consider controlling for numeric/string values)</em></p>
<pre><code>import GetStats
from string import ascii_uppercase
lookbackdays = ''; granularity = ''; datasettype = ''
# LOOP RUNS INFINITELY PROMPTING INPUT UNTIL USER FILLS OUT EACH ONE:
while True:
if lookbackdays == '':
lookbackdays = input("Please enter the number of days to look back: ")
elif granularity == '':
granularity = input("Please enter the granularity of the data: ")
elif datasettype == '':
datasettype = input("Please enter the data set to return: ")
else:
break
# LOOPS THROUGH LETTERS A-M
for c in ascii_uppercase[0:13]:
GetStats.processData('Client_'+c+'.cfg', lookbackdays, granularity, datasettype)
print("Successfully processed data!")
</code></pre>
<hr>
<p><strong>Tkinter</strong> GUI</p>
<p>Even better, consider an actual GUI interface using the <a href="https://docs.python.org/2/library/tkinter.html" rel="nofollow">tkinter</a> module (pre-installed in Python 3):</p>
<pre><code>import GetStats
from tkinter import *
from tkinter import ttk
from string import ascii_uppercase
class GUIapp():
def __init__(self):
self.root = Tk()
self.buildControls()
self.root.mainloop()
def buildControls(self):
self.root.wm_title("Get Stats Menu")
self.guiframe = Frame(self.root, width=2500, height=500, bd=1, relief=FLAT)
self.guiframe.pack(padx=5, pady=5)
# IMAGE
self.photo = PhotoImage(file="Stats.png")
self.imglbl = Label(self.guiframe, image=self.photo)
self.imglbl.photo = self.photo
self.imglbl.grid(row=0, sticky=W, padx=5, pady=5)
self.imglbl = Label(self.guiframe, text="Enter parameters for data request",
font=("Arial", 12)).\
grid(row=0, column=1, sticky=W, padx=5, pady=5)
# PERIOD DAYS
self.periodDayslbl = Label(self.guiframe, text="Please enter the number of days to look back: ",
font=("Arial", 10)).grid(row=1, sticky=W, padx=5, pady=5)
self.periodDaysvar = StringVar()
self.periodDaystxt = Entry(self.guiframe, textvariable=self.periodDaysvar,
relief=SOLID, font=("Arial", 10), width=34).\
grid(row=1, column=1, sticky=W, padx=5, pady=5)
# DATA GRANULARITY
self.granularitylbl = Label(self.guiframe, text="Please enter the granularity of the data: ",
font=("Arial", 10)).grid(row=2, sticky=W, padx=5, pady=5)
self.granularityvar = StringVar()
self.granularitytxt = Entry(self.guiframe, textvariable=self.granularityvar,
relief=SOLID, font=("Arial", 10), width=34).\
grid(row=2, column=1, sticky=W, padx=5, pady=5)
# DATASET TO RETURN
self.datasetTypelbl = Label(self.guiframe, text="Please enter the data set to return: ",
font=("Arial", 10)).grid(row=3, sticky=W, padx=5, pady=5)
self.datasetTypevar = StringVar()
self.datasetTypetxt = Entry(self.guiframe, textvariable=self.datasetTypevar, relief=SOLID,
font=("Arial", 10), width=34).\
grid(row=3, column=1, sticky=W, padx=5, pady=5)
# PROCESS BUTTON
self.btnoutput = Button(self.guiframe, text="PROCESS",
font=("Arial", 10), width=25, command=self.processData).\
grid(row=4, column=1, sticky=W, padx=10, pady=5)
def processData(self):
if self.periodDaysvar.get() != '' and self.granularityvar.get() != '' and self.datasetTypevar.get() != '':
for c in ascii_uppercase[0:13]:
GetStats.processData('Client_'+c+'cfg', self.periodDaysvar.get(),
self.granularityvar.get(), self.datasetTypevar.get())
messagebox.showinfo("SUCCESFUL OUTPUT", "Successfully processed data!")
else:
messagebox.showerror("MISSING FIELD", "Please enter all fields to process request.")
if __name__ == "__main__":
GUIapp()
</code></pre>
<p><strong>GUI</strong> Menu <em>(image is a small pic named Stats.png in same directory as script)</em></p>
<p><a href="https://i.stack.imgur.com/g8PSL.png" rel="nofollow"><img src="https://i.stack.imgur.com/g8PSL.png" alt="GUI Menu"></a></p>
<p>Message Boxes <em>(called on Process button click)</em></p>
<p><a href="https://i.stack.imgur.com/qnoxe.png" rel="nofollow"><img src="https://i.stack.imgur.com/qnoxe.png" alt="GUI Success Message"></a>
<a href="https://i.stack.imgur.com/vFUc3.png" rel="nofollow"><img src="https://i.stack.imgur.com/vFUc3.png" alt="GUI Error Message"></a></p>
| 0 | 2016-10-17T00:08:42Z | [
"python",
"batch-file"
] |
How to transform a slice of dataframe into a new data frame | 40,075,924 | <p>I'm new to python and I'm confused sometimes with some operations
I have a dataframe called <code>ro</code> and I also have filtered this dataframe using a specific column <code>PN 3D</code> for a specific value <code>921</code> and I assigned the results into a new data frame called <code>headlamp</code> by using the following code:</p>
<pre><code> headlamp = ro[ro['PN 3D']=="921"]
</code></pre>
<p>Does my headlamp is also a <strong>dataframe</strong> or is just a <strong>slice</strong>?
The reason I'm asking this is because I'm getting some strange warnings and results later on my script.</p>
<p>Such as, I create a new column called <code>word</code> and I assigned to <code>headlamp</code></p>
<pre><code> headlamp['word'] = ""
</code></pre>
<p>I got the following warning:</p>
<pre><code> A value is trying to be set on a copy of a slice from a DataFrame
</code></pre>
<p>After that I used the following script to assign the results to <code>headlamp['word']</code></p>
<pre><code> i = 0
for row in headlamp['Comment'].astype(list):
headlamp['word'][i] = Counter(str(row).split())
i+=1
print headlamp['word']
</code></pre>
<p>The same warning appeared and it has impacted on my results, because when I used the <code>headlamp.tail()</code>, The last rows of <code>headlamp['word']</code> were empty.</p>
<p>Does anyone has an idea what is the problem and how to fix?</p>
<p>Any help will be highly appreciated</p>
| 1 | 2016-10-16T21:59:33Z | 40,076,219 | <p>Use <code>.loc</code></p>
<pre><code>headlamp = ro.loc[ro['PN 3D']=="921"]
</code></pre>
<hr>
<p>As for the rest and your comments... I'm very confused. But this is my best guess</p>
<p><strong><em>setup</em></strong> </p>
<pre><code>import pandas as pd
from string import ascii_lowercase
chars = ascii_lowercase + ' '
probs = [0.03] * 26 + [.22]
headlamp = pd.DataFrame(np.random.choice(list(chars), (10, 100), p=probs)).sum(1).to_frame('comment')
headlamp
</code></pre>
<p><a href="https://i.stack.imgur.com/AHJnt.png" rel="nofollow"><img src="https://i.stack.imgur.com/AHJnt.png" alt="enter image description here"></a></p>
<pre><code>headlamp['word'] = headlamp.comment.str.split().apply(lambda x: pd.value_counts(x).to_dict())
headlamp
</code></pre>
<p><a href="https://i.stack.imgur.com/6ySKH.png" rel="nofollow"><img src="https://i.stack.imgur.com/6ySKH.png" alt="enter image description here"></a></p>
| 1 | 2016-10-16T22:32:59Z | [
"python",
"pandas",
"dataframe",
"slice"
] |
Compiling f90 function that returns array using f2py | 40,075,932 | <p>I have a subroutine that calculates a large array and writes it to a file. I'm trying to transform that into a function that returns that array. However, I'm getting a very weird error which seems to be connected to the fact that I am returning an array. When I try to return a float (as a test) it works perfectly fine.</p>
<p>Here's the MWE, which I call from python with <code>mwe('dir', 'postpfile', 150, 90.)</code>:</p>
<pre><code>FUNCTION mwe(dir, postpfile, nz, z_scale)
IMPLICIT NONE
INTEGER :: nz
REAL(KIND=8) :: z_scale
CHARACTER(len=100) :: postpfile
CHARACTER(len=100) :: dir
REAL(kind=8) :: mwe
print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale
mwe = 4.5d0
END FUNCTION mwe
</code></pre>
<p>This works well and prints, as expected:</p>
<pre><code> dir dir
postpfile postpfile
nz 150
Lz 90.000000000000000
</code></pre>
<p>However, if I define the function as an array:</p>
<pre><code>FUNCTION mwe(dir, postpfile, nz, z_scale)
IMPLICIT NONE
INTEGER :: nz
REAL(KIND=8) :: z_scale
CHARACTER(len=100) :: postpfile
CHARACTER(len=100) :: dir
REAL(KIND=8),DIMENSION (2,23) :: mwe
print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale
mwe = 4.5d0
END FUNCTION mwe
</code></pre>
<p>Then it prints this:</p>
<pre><code> dir postpfile
postpfile ��:����������k�� 2����V@(����H���;�!��v
nz 0
Segmentation fault (core dumped)
</code></pre>
<p>I am running f2py version 2, NumPy 1.11.1 and Python 3.5.1.</p>
<p><strong>EDIT</strong></p>
<p>I'm compiling with <code>f2py -c -m fmwe fmwe.f90</code>, and calling the function with <code>mwe('dir', 'postpfile', 150, 90.)</code>.</p>
| 0 | 2016-10-16T22:00:46Z | 40,097,112 | <p><em>I think the problem is coming from somewhere from lack of the explicit interface. (not sure may be someone else can point out what is the problem more precisely.)</em></p>
<p>Even though, I am not sure about my explanation, I have 2 working cases. <strong>Changing your function into a subroutine</strong> or <strong>putting your function inside a module</strong> (which generates the explicit interface by itself) solves the issue you mentioned. </p>
<p>Below script still can be called like <code>my_sub('dir', 'postpfile', 150, 90.)</code> from python.</p>
<pre><code>subroutine my_sub(mwe, dir, postpfile, nz, z_scale)
implicit none
integer,intent(in) :: nz
real(KIND=8),intent(in) :: z_scale
chracter(len=100),intent(in) :: postpfile
character(len=100), intent(in) :: dir
real(KIND=8), intent(out) :: mwe(2,23)
print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale
mwe = 4.5d0
end subroutine my_sub
</code></pre>
<p>If you use the function within a module, you need to make the call from python a little differently; <code>test('dir', 'postpfile', 150, 90.)</code>.</p>
<pre><code>module test
contains
function mwe(dir, postpfile, nz, z_scale)
implicit none
integer :: nz
real(KIND=8) :: z_scale
chracter :: postpfile
character(len=100) :: dir
real(KIND=8) :: mwe(2,23)
print*,'dir ', dir
print*,'postpfile ', postpfile
print*,'nz ', nz
print*,'Lz ', z_scale
mwe = 4.5d0
end function mwe
end module test
</code></pre>
<p><em>I did not try, but it will probably work with proper Fortran <code>interface</code> including your function.(assuming existence of the explicit interface is the key)</em></p>
<p>I hope that someone will complete/correct my answer. </p>
| 0 | 2016-10-17T23:16:31Z | [
"python",
"arrays",
"fortran",
"f2py"
] |
Python 2.7 reading a new line in CSV and store it as variable | 40,075,967 | <p>I am using the code below to read the last line of my csv. file which
is constantly updated and is working great. I am receiving the last line
and it is consisted of 11 values which are comma separated. It goes like:</p>
<p>10/16/16, -1, false, 4:00:00 PM, 4585 , .......etc</p>
<p>Now I want to take the values from column 6 and 9 for example and store them
as two separate variables and later use them as a conditions. Is there simple way to add just few lines to the existing code to achieve this or i have to write a new code?</p>
<pre><code>import time, os
#Set the filename and open the file
filename = 'Test.csv'
file = open(filename,'r')
#Find the size of the file and move to the end
st_results = os.stat(filename)
st_size = st_results[6]
file.seek(st_size)
while 1:`enter code here`
where = file.tell()
line = file.readline()
if not line:
time.sleep(0.5)`enter code here`
file.seek(where)
else:
print line, # already has newline
</code></pre>
| 1 | 2016-10-16T22:03:56Z | 40,076,247 | <p>You certainly can just add a few line in there to get what you want. I would delim each line by comma using <code>line.split(',')</code>. This will return an array like this <code>['10/16/16', '-1', 'false', '4:00:00 PM', '4585' ]</code>. Then you can simply save the array at index 6 ~ 9 for your convenience and use it later in the code. </p>
<p>Ex)</p>
<pre><code>while 1:`enter code here`
where = file.tell()
line = file.readline()
if not line:
time.sleep(0.5)`enter code here`
file.seek(where)
else:
arr_line = line.split(',')
var6 = arr_line[6]
var7 = arr_line[7]
var8 = arr_line[8]
var9 = arr_line[9]
# other code ...
print line
</code></pre>
| 0 | 2016-10-16T22:37:24Z | [
"python",
"csv"
] |
Accessing Variable in Keras Callback | 40,076,021 | <p>So I've a CNN implemented. I have made custom callbacks that are confirmed working but I have an issue.</p>
<p>This is a sample output.
Example of iteration 5 (batch-size of 10,000 for simplicity)</p>
<pre><code>50000/60000 [========================>.....] - ETA: 10s ('new lr:', 0.01)
('accuracy:', 0.70)
</code></pre>
<p>I have 2 callbacks (tested to work as shown in the output):
(1) Changes the learning rate at each iteration. (2) Prints the accuracy at each iteration.</p>
<p>I have an external script that determines the learning rate by taking in the accuracy. </p>
<p><strong>Question:</strong>
How to make the accuracy at each iteration available so that an external script can access it? In essence an accessible variable at each iteration. I'm able to access it only once the process is over with <code>AccuracyCallback.accuracy</code></p>
<p><strong>Problem</strong>
I can pass a changing learning rate. But how do I get the accuracy once this has been passed in a form of an accessible variable at each iteration?</p>
<p><strong>Example</strong>
My external script determines the learning rate at iteration 1: 0.01. How do I get the accuracy as an accessible variable in my external script at iteration 1 instead of a print statement?</p>
| 0 | 2016-10-16T22:11:12Z | 40,087,960 | <p>You can <a href="https://keras.io/callbacks/#create-a-callback" rel="nofollow">create your own callback</a></p>
<pre><code>class AccCallback(keras.callbacks.Callback):
def on_batch_end(self, batch, logs={}):
accuracy = logs.get('acc')
# pass accuracy to your 'external' script and set new lr here
</code></pre>
<p>In order for <code>logs.get('acc')</code> to work, you have to tell Keras to monitor it:</p>
<pre><code>model.compile(optimizer='...', loss='...', metrics=['accuracy'])
</code></pre>
<p>Lastly, note that the type of <code>accuracy</code> is <code>ndarray</code> here. Should it cause you any issue, I suggest wrapping it: <code>float(accuracy)</code>.</p>
| 0 | 2016-10-17T13:38:56Z | [
"python",
"keras"
] |
Passing request (user) to a class based view | 40,076,046 | <p>As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on.</p>
<p>However, I would like to make this chart dynamic and would like it to change based on who is seeing it. </p>
<p>How can one pass a request (to get the user from) to a class based view?</p>
<p>Below is my non-working implementation (working with dummy data but no request being passed):</p>
<p><strong>View:</strong></p>
<pre><code>class LineChartJSONView(BaseLineChartView, request):
user = request.user
def get_labels(self):
labels = []
items = Item.objects.filter(user = user)
for i in items:
labels.add(i.name)
return labels
def get_data(self):
prices = []
items = Item.objects.filter(user = user)
for i in items:
prices.add(i.price)
return prices
line_chart = TemplateView.as_view(template_name='dashboard/test_chart.html')
line_chart_json = LineChartJSONView.as_view()
</code></pre>
<p><strong>URL:</strong></p>
<pre><code>url(r'^chart_data/$', LineChartJSONView.as_view(), name='line_chart_json'),
url(r'^chart/$', views.ViewBaseChart, name='basic_chart'),
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code>{% load staticfiles %}
<html>
<head>
<title>test chart</title>
</head>
<body>
<canvas id = "myChart" width="500" height="200"></canvas>
<!-- jQuery 2.2.3 -->
<script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script>
<!-- Bootstrap 3.3.6 -->
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<!-- ChartJS 1.0.1 -->
<script src="{% static 'plugins/chartjs/Chart.min.js' %}"></script>
<!-- FastClick -->
<script src="{% static 'plugins/fastclick/fastclick.js' %}"></script>
<!-- AdminLTE App -->
<script src="{% static 'dist/js/app.min.js' %}"></script>
<!-- AdminLTE for demo purposes -->
<script src="{% static 'dist/js/demo.js' %}"></script>
<!-- page script -->
<script type="text/javascript">
$.get('{% url "line_chart_json" %}', function(data)
{
var ctx =
$("#myChart").get(0).getContext("2d");
new Chart(ctx).Line(data);
});
</script>
</body>
</html>
</code></pre>
<p><strong>View (for static above - non classbasedview):</strong></p>
<pre><code>def ViewBaseChart(request):
context = {}
template = "dashboard/test_chart.html"
return render(request,template,context)
</code></pre>
<p>I am not sure I am using the class based view concept correctly here however, have found this to be the only way to implement charts thus far.</p>
| 0 | 2016-10-16T22:13:32Z | 40,076,715 | <p>Your class definition is incorrect. A CBV shouldn't inherit from HttpRequest (and I am not even sure if that's what you mean by <code>request</code>)
. The correct definition is</p>
<pre><code>class LineChartJSONView(BaseLineChartView):
</code></pre>
<p>This assumes of course that <code>BaseLineChartView</code> has been defined correctly. The following line should also be removed since it defines a global user and secondly because there isn't a request object there!</p>
<pre><code>user = request.user
</code></pre>
<p>Now to get hold of a user instance, you need to override the get, post methods.</p>
<pre><code>def get(self, request):
user = request.user
</code></pre>
| 1 | 2016-10-16T23:44:39Z | [
"python",
"django",
"django-views",
"django-class-based-views"
] |
Passing request (user) to a class based view | 40,076,046 | <p>As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on.</p>
<p>However, I would like to make this chart dynamic and would like it to change based on who is seeing it. </p>
<p>How can one pass a request (to get the user from) to a class based view?</p>
<p>Below is my non-working implementation (working with dummy data but no request being passed):</p>
<p><strong>View:</strong></p>
<pre><code>class LineChartJSONView(BaseLineChartView, request):
user = request.user
def get_labels(self):
labels = []
items = Item.objects.filter(user = user)
for i in items:
labels.add(i.name)
return labels
def get_data(self):
prices = []
items = Item.objects.filter(user = user)
for i in items:
prices.add(i.price)
return prices
line_chart = TemplateView.as_view(template_name='dashboard/test_chart.html')
line_chart_json = LineChartJSONView.as_view()
</code></pre>
<p><strong>URL:</strong></p>
<pre><code>url(r'^chart_data/$', LineChartJSONView.as_view(), name='line_chart_json'),
url(r'^chart/$', views.ViewBaseChart, name='basic_chart'),
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code>{% load staticfiles %}
<html>
<head>
<title>test chart</title>
</head>
<body>
<canvas id = "myChart" width="500" height="200"></canvas>
<!-- jQuery 2.2.3 -->
<script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script>
<!-- Bootstrap 3.3.6 -->
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<!-- ChartJS 1.0.1 -->
<script src="{% static 'plugins/chartjs/Chart.min.js' %}"></script>
<!-- FastClick -->
<script src="{% static 'plugins/fastclick/fastclick.js' %}"></script>
<!-- AdminLTE App -->
<script src="{% static 'dist/js/app.min.js' %}"></script>
<!-- AdminLTE for demo purposes -->
<script src="{% static 'dist/js/demo.js' %}"></script>
<!-- page script -->
<script type="text/javascript">
$.get('{% url "line_chart_json" %}', function(data)
{
var ctx =
$("#myChart").get(0).getContext("2d");
new Chart(ctx).Line(data);
});
</script>
</body>
</html>
</code></pre>
<p><strong>View (for static above - non classbasedview):</strong></p>
<pre><code>def ViewBaseChart(request):
context = {}
template = "dashboard/test_chart.html"
return render(request,template,context)
</code></pre>
<p>I am not sure I am using the class based view concept correctly here however, have found this to be the only way to implement charts thus far.</p>
| 0 | 2016-10-16T22:13:32Z | 40,079,588 | <p>You do not need to pass <code>request</code> to class based views, it is already there for you if you inherit them from Django's generic views. Generic class based views have methods for handling requests (GET, POST, etc). </p>
<p>For example:</p>
<pre><code>class LineChartJSONView(generic.View):
def get(self, request, *args, **kwargs):
"""Handle GET request and return response"""
def post(self, request, *args, **kwargs):
"""Handle POST request and return response"""
</code></pre>
<p>Read about Django's generic class based views. They are full of ready to use functionalities. Here is the link to the doc <a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/" rel="nofollow" title="Class based views">Django class based views introduction</a></p>
| 1 | 2016-10-17T06:14:55Z | [
"python",
"django",
"django-views",
"django-class-based-views"
] |
Getting Django PROD ready best practice on Heroku | 40,076,092 | <p>I have recently run into some problems flipping off Debug mode on my Heroku instance of Django (filled from the Heroku Django template).</p>
<p>I have begun diving through the specific Heroku logs. However, was wondering if anyone has already made a checklist for things one should do after turning off Debug mode on Heroku (allowed hosts, email services etc)?</p>
| -2 | 2016-10-16T22:19:18Z | 40,123,144 | <p>Not specific to Heroku, but I've made the following checklist. You may want to checkout <a href="http://djangodeployment.com/2016/10/18/checklist-for-django-settings-on-deployment/" rel="nofollow">the original list</a>, which expands on static files and links the settings to the Django documentation.</p>
<ul>
<li><strong>Databases.</strong> Set DATABASES to your production database.</li>
<li><strong>Allowed hosts.</strong> Set ALLOWED_HOSTS to the list of domain names to be served by this Django installation. It should be the same list as that listed in nginxâs server_name or in apacheâs ServerName and ServerAlias.</li>
<li><strong>Static files.</strong> Set STATIC_ROOT to the directory where the static files should be stored, and STATIC_URL to the URL where they will be found (commonly /static/). Donât forget to run collectstatic.</li>
<li><strong>Media files.</strong> Same thing as static files, but also make sure that the user Django is running as has permission to write to MEDIA_ROOT.</li>
<li><strong>Email.</strong> Regardless whether your project uses email or not, it is very important to set this up so that it can send you information about internal server errors. So you need to use EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_USE_TLS, DEFAULT_FROM_EMAIL, and SERVER_EMAIL. Also set up ADMINS and MANAGERS.</li>
<li><strong>Miscellaneous.</strong> Other settings you probably need to set different from development are SECRET_KEY, LOGGING, CACHES. Finally, set DEBUG to False.</li>
</ul>
| 1 | 2016-10-19T05:46:32Z | [
"python",
"django",
"debugging",
"heroku"
] |
Annotate graph using data from Array | 40,076,093 | <p>I have a matplotlib graph that I have created using data from arrays. I want to annotate this graph at certain points. The x axis is populated with dates (14/06/12, 15/06/12) etc.. The y axis is price (6500, 6624) etc... I would like to annotate at point: for example (x,y) (14/06/12, 6500). This is my code so far:</p>
<pre><code>Date = ["14/06/12", "15/06/12"]
Open = [6500, 6544]
High = [5434, 5234]
Low = [5342, 5325]
Close = [4523, 2342]
ohlc = []
i = 0
while i < 2:
Prices = Date[i], Open[i], High[i], low[i], Close[i]
ohlc.append(Prices)
i += 1
candlestick_ohlc(ax, ohlc, width=0.8, colorup='g', colordown='r')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.annotate('Here!', xy=(Date[1], Price[1]))
plt.show()
</code></pre>
<p>This is the current graph and I want the annotation on it where i put it:
<a href="http://imgur.com/a/mv945" rel="nofollow">http://imgur.com/a/mv945</a></p>
| 0 | 2016-10-16T22:19:24Z | 40,076,234 | <p>Here's a quick example using the matplotlib.pyplot text command to add text to a plot at a specified location:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.figure()
x = np.arange(-5, 5, 0.1)
plt.plot(x, np.cos(x))
plt.text(x=-4, y=0.5, s="Cosine", fontsize=20)
plt.show()
</code></pre>
<p>There are lots of additional formatting options available for text (alignment, font, etc.). Full documentation is available here:</p>
<p><a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text</a></p>
| 0 | 2016-10-16T22:35:17Z | [
"python",
"matplotlib"
] |
Removing duplicate mpatches from a list | 40,076,108 | <p>I startet to work with buttons in my plots (<code>from matplotlib.widgets import Button</code>). By pressing the buttons different plots will show up. For that reason my legends do change. I handle this by putting the mpatches in a list:</p>
<pre><code>red_patch = mpatches.Patch(color='red', label='Numerical average')
handlelist.append(red_patch)
ax.legend(handles=handlelist, numpoints=1)
</code></pre>
<p>Now if I press the same button twice, the red_patch will also be displayed twice. Because of that I want to delete duplicates but this won't work. So far I tried:</p>
<pre><code>list(set(handelist))
</code></pre>
<p>and also:</p>
<pre><code>if red_patch not in handelist:
handlelist.append(red_patch)
</code></pre>
<p>But both won't work and I don't understand why. Hope you have an idea :) </p>
| 0 | 2016-10-16T22:21:22Z | 40,076,185 | <p>The problem is that:</p>
<pre><code>red_patch = mpatches.Patch(color='red', label='Numerical average')
</code></pre>
<p>creates an instance of <code>red_patch</code> every time. The <code>__eq__</code> operator seems to be unimplemented for this particular type, so the <code>set</code> only compares references of the object, which are not equal.</p>
<p>I would suggest the following code instead:</p>
<pre><code># declare as ordered dict (so order of creation matters), not list
import collections
handlelist = collections.OrderedDict()
color = 'red'
label = 'Numerical average'
if (color,label) not in handlelist:
handlelist[(color,label)] = mpatches.Patch(color=color, label=label)
# pass the values of the dict as list (legend expects a list)
ax.legend(handles=list(handlelist.values()), numpoints=1)
</code></pre>
<p>The key of your dictionary is the couple <code>(color,label)</code> and when you call the <code>legend</code> method you only get one <code>red_patch</code>, because if the entry already exists, no extra <code>Patch</code> will be created.</p>
<p>Of course, you have to do the same in other parts of your code where you update <code>handlelist</code>. A shared method would be handy:</p>
<pre><code>def create_patch(color,label):
if (color,label) not in handlelist:
handlelist[(color,label)] = mpatches.Patch(color=color, label=label)
</code></pre>
<p>EDIT: if you have only 1 patch total, you could do even simpler:</p>
<pre><code>p = mpatches.Patch(color='red', label='Numerical average')
ax.legend([p], numpoints=1)
</code></pre>
| 1 | 2016-10-16T22:29:35Z | [
"python",
"matplotlib"
] |
Python IRC Bot, distinguish from channel messages and private messages | 40,076,143 | <p>I'm coding a simple IRC bot in Python. Actually, It can connect to a specific channel, read messages and send response, but it can't distinguish between channel messages and private messages. </p>
<p><strong>Example</strong>:<br>
John, connected to the same channel, send a private message to the Bot's chat, like "!say hello";
Bot have to send "hello" to the same private chat, only to John.<br>
Instead, when bot read "!say hello" in channel's board, have to send "hello" to the channel.</p>
<p><strong>My code:</strong> </p>
<pre><code>ircmsg = connection.ircsock.recv(2048)
ircmsg_clean = ircmsg.strip(str.encode('\n\r'))
if ircmsg.find(str.encode("!say")) != -1:
try:
parts = ircmsg_clean.split()
content = parts[4]
connection.sendMsg(channel, content)
except IndexError:
connection.sendMsg(channel, "Invalid syntax")
</code></pre>
<p><strong>Connection file:</strong></p>
<pre><code>def sendmsg(channel, msg):
ircsock.send(str.encode("PRIVMSG " + channel +" :" + msg + "\n"))
</code></pre>
<p>I know how to send a message to a specific user:</p>
<pre><code>def sendPrivateMsg(username, msg):
ircsock.send(str.encode("PRIVMSG " + username + " :" + msg + "\n"))
</code></pre>
<p>But have to know from where the message came, channel or user, and send appropriate response.</p>
<p>Sorry for my bad english.</p>
| 1 | 2016-10-16T22:25:06Z | 40,110,181 | <p>The source of the message is included in the protocol message, now you are just not using it. </p>
<p>In the part where you do this</p>
<pre><code>parts = ircmsg_clean.split()
</code></pre>
<p>you get it in to the list <code>parts</code>.</p>
<p>If I remember correctly, and understand the RFQ right, the irc message you receive from the server looks something like this:</p>
<blockquote>
<p>:[email protected] PRIVMSG BotName :Are you receiving this message ?</p>
</blockquote>
<p>so splitting that would result in this:</p>
<pre><code>[':[email protected]', 'PRIVMSG', 'BotName', ':Are', 'you', 'receiving', 'this', 'message', '?']
</code></pre>
<p>The sender of the message is that the first element <code>parts</code>, so <code>parts[0]</code>. You would need to strip away the extra ':'.</p>
<p>The target of the message is at <code>parts[2]</code>, and that can be your name or the channel name, and you then need to compare the target to your own name to know if it is a message to you or to a channel.</p>
<p>If that is true, you can then do something like this:</p>
<pre><code>source = parts[0].strip(':')
content = ' '.join(parts[3:]).strip(':')
connection.sendMsg(source, content)
</code></pre>
<p>Notice that the actual content of the message is also splitted, so you need to rejoin that into a string if you are doing it like that. If you are hitting that <code>IndexError</code> it means that you received a message that had only one word, since the first word is at index 3, not 4.</p>
| 1 | 2016-10-18T13:53:22Z | [
"python",
"networking",
"bots",
"irc",
"channel"
] |
Rectangle collision in pygame? (Bumping rectangles into each other) | 40,076,160 | <p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop?
My code:</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Squarey")
done = False
is_red = True
x = 30
y = 30
x2 = 100
y2 = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_red = not is_red
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_w]: y2 -= 3
if pressed[pygame.K_s]: y2 += 3
if pressed[pygame.K_a]: x2 -= 3
if pressed[pygame.K_d]: x2 += 3
if y < 0:
y += 3
if x > 943:
x -= 3
if y > 743:
y -= 3
if x < 0:
x += 3
if y2 < 0:
y2 += 3
if x2 > 943:
x2 -= 3
if y2 > 743:
y2 -= 3
if x2 < 0:
x2 += 3
screen.fill((0, 0, 0))
if is_red: color = (252, 117, 80)
else: color = (168, 3, 253)
if is_red: color2 = (0, 175, 0)
else: color2 = (255, 255, 0)
rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
rect2 = pygame.draw.rect(screen, color2, pygame.Rect(x2, y2, 60, 60))
pygame.display.flip()
clock.tick(60)
pygame.quit()
</code></pre>
| 0 | 2016-10-16T22:26:46Z | 40,076,469 | <p>To check for collisions, try something like this:</p>
<pre><code>def doRectsOverlap(rect1, rect2):
for a, b in [(rect1, rect2), (rect2, rect1)]:
# Check if a's corners are inside b
if ((isPointInsideRect(a.left, a.top, b)) or
(isPointInsideRect(a.left, a.bottom, b)) or
(isPointInsideRect(a.right, a.top, b)) or
(isPointInsideRect(a.right, a.bottom, b))):
return True
return False
def isPointInsideRect(x, y, rect):
if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
return True
else:
return False
</code></pre>
<p>Then, while moving them, you can call</p>
<pre><code>if doRectsOverlap(rect1, rect2):
x -= 3
y -= 3
rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
</code></pre>
<p>Or something like that.</p>
| 0 | 2016-10-16T23:07:34Z | [
"python",
"pygame",
"collision",
"rectangles"
] |
Rectangle collision in pygame? (Bumping rectangles into each other) | 40,076,160 | <p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop?
My code:</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Squarey")
done = False
is_red = True
x = 30
y = 30
x2 = 100
y2 = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_red = not is_red
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_w]: y2 -= 3
if pressed[pygame.K_s]: y2 += 3
if pressed[pygame.K_a]: x2 -= 3
if pressed[pygame.K_d]: x2 += 3
if y < 0:
y += 3
if x > 943:
x -= 3
if y > 743:
y -= 3
if x < 0:
x += 3
if y2 < 0:
y2 += 3
if x2 > 943:
x2 -= 3
if y2 > 743:
y2 -= 3
if x2 < 0:
x2 += 3
screen.fill((0, 0, 0))
if is_red: color = (252, 117, 80)
else: color = (168, 3, 253)
if is_red: color2 = (0, 175, 0)
else: color2 = (255, 255, 0)
rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
rect2 = pygame.draw.rect(screen, color2, pygame.Rect(x2, y2, 60, 60))
pygame.display.flip()
clock.tick(60)
pygame.quit()
</code></pre>
| 0 | 2016-10-16T22:26:46Z | 40,077,464 | <p>Use <a href="http://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect" rel="nofollow">pygame.Rect.colliderect</a></p>
<pre><code>if rect1.colliderect(rect2):
print("Collision !!")
</code></pre>
<hr>
<p>BTW: you can create <code>rect1</code> (and <code>rect2</code>) only once - before main loop - and then you can use <code>rect1.x</code> and <code>rect1.y</code> instead of <code>x</code>, <code>y</code>. And you can use <code>pygame.draw.rect(screen, color, rect1)</code> without creating new Rect all the time.</p>
<p>Rect is usefull</p>
<pre><code> # create
rect1 = pygame.Rect(30, 30, 60, 60)
# move
rect1.x += 3
# check colision with bottom of the screen
if rect1.bottom > screen.get_rect().bottom:
# center on the screen
rect1.center = screen.get_rect().center
</code></pre>
| 0 | 2016-10-17T01:54:01Z | [
"python",
"pygame",
"collision",
"rectangles"
] |
How to remove data from DataFrame permanently | 40,076,176 | <p>After reading CSV data file with:</p>
<pre><code>import pandas as pd
df = pd.read_csv('data.csv')
print df.shape
</code></pre>
<p>I get DataFrame 99 rows (indexes) long:</p>
<pre><code>(99, 2)
</code></pre>
<p>To cleanup DataFrame I go ahead and apply dropna() method which reduces it to 33 rows:</p>
<pre><code>df = df.dropna()
print df.shape
</code></pre>
<p>which prints:</p>
<pre><code>(33, 2)
</code></pre>
<p>Now when I iterate the columns it prints out all 99 rows like they weren't dropped:</p>
<pre><code>for index, value in df['column1'].iteritems():
print index
</code></pre>
<p>which gives me this:</p>
<pre><code>0
1
2
.
.
.
97
98
99
</code></pre>
<p>It appears the <code>dropna()</code> simply made the data "hidden". That hidden data returns back when I iterate DataFrame. How to assure the dropped data is removed from DataFrame instead just getting hidden?</p>
| 2 | 2016-10-16T22:28:45Z | 40,076,307 | <p>You're being confused by the fact that the row labels have been preserved so the last row label is still <code>99</code>.</p>
<p>Example:</p>
<pre><code>In [2]:
df = pd.DataFrame({'a':[0,1,np.NaN, np.NaN, 4]})
df
Out[2]:
a
0 0
1 1
2 NaN
3 NaN
4 4
</code></pre>
<p>After calling <code>dropna</code> the index row labels are preserved:</p>
<pre><code>In [3]:
df = df.dropna()
df
Out[3]:
a
0 0
1 1
4 4
</code></pre>
<p>If you want to reset so that they are contiguous then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index(drop=True)</code></a> to assign a new index:</p>
<pre><code>In [4]:
df = df.reset_index(drop=True)
df
Out[4]:
a
0 0
1 1
2 4
</code></pre>
| 3 | 2016-10-16T22:45:12Z | [
"python",
"pandas",
"dataframe"
] |
Finding and printing a specific Pattern in a given string | 40,076,198 | <p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p>
<p>My string looks like this (Amino acid sequence) :-</p>
<pre><code> MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
</code></pre>
<p>The pattern I want to find is </p>
<pre><code> KXXXXXX(K\R)XR
</code></pre>
<p>Please note that Letters between K and K\R are not fixed. However, there is only letter between K\R and R. So, in the given string my pattern is like this and exist between letter no. 54 to 65 (if I counted correctly) based on "smallest pattern" search :-</p>
<pre><code> KYMLSVDNLKLR
</code></pre>
<p>Previously, I was using C if-else condition to break this given string and printed out word count (not fully successful).</p>
<pre><code> printf(%c, word[i]);
if ((word [i] == 'K' || word [i] == 'R' )) && word [i+2] == 'R') {
printf("\n");
printf("%d\n",i);
}
</code></pre>
<p>I agree It dint capture everything. If anyone can help me help me solving this problem, that would be great.</p>
| -2 | 2016-10-16T22:30:53Z | 40,076,255 | <p>Regardless of the language, this looks a task suitable for regular expressions.</p>
<p>Here is an example of how you could do the regex in python. If you want the index where the match starts, you can do:</p>
<pre><code>m = re.search(r'K(?:[A-JL-Z]+?|K)[KR][A-Z]R', s)
print m.start() # prints index
print m.group() # prints matching string
</code></pre>
<p>Or as @bunji points out, you an use <code>finditer</code> as well:</p>
<pre><code>for m in re.finditer(r'K(?:[A-JL-Z]+?|K)[KR][A-Z]R', s):
print m.start() # prints index
print m.group() # prints matching string
</code></pre>
| 0 | 2016-10-16T22:38:17Z | [
"python",
"perl"
] |
Finding and printing a specific Pattern in a given string | 40,076,198 | <p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p>
<p>My string looks like this (Amino acid sequence) :-</p>
<pre><code> MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
</code></pre>
<p>The pattern I want to find is </p>
<pre><code> KXXXXXX(K\R)XR
</code></pre>
<p>Please note that Letters between K and K\R are not fixed. However, there is only letter between K\R and R. So, in the given string my pattern is like this and exist between letter no. 54 to 65 (if I counted correctly) based on "smallest pattern" search :-</p>
<pre><code> KYMLSVDNLKLR
</code></pre>
<p>Previously, I was using C if-else condition to break this given string and printed out word count (not fully successful).</p>
<pre><code> printf(%c, word[i]);
if ((word [i] == 'K' || word [i] == 'R' )) && word [i+2] == 'R') {
printf("\n");
printf("%d\n",i);
}
</code></pre>
<p>I agree It dint capture everything. If anyone can help me help me solving this problem, that would be great.</p>
| -2 | 2016-10-16T22:30:53Z | 40,076,542 | <p>You say you want the match to be non-greedy, but that doesn't make sense. I think you are trying to find the minimal match. If so, that's very hard to do. This is the regex match you need:</p>
<pre><code>/
K
(?: (?: [^KR] | R(?!.R) )+
| .
)
[KR]
.
R
/sx
</code></pre>
<hr>
<p>However, it wouldn't surprise me if there's a bug. The only sure way to find a minimal match is to find all possible matches.</p>
<pre><code>my $match;
while (/(?= ( K.+[KR].R ) )/sxg) {
if (!defined($match) || length($1) > length($match)) {
$match = $1;
}
}
</code></pre>
<p>But this will be far slower, especially for long strings.</p>
| 0 | 2016-10-16T23:17:23Z | [
"python",
"perl"
] |
Finding and printing a specific Pattern in a given string | 40,076,198 | <p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p>
<p>My string looks like this (Amino acid sequence) :-</p>
<pre><code> MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
</code></pre>
<p>The pattern I want to find is </p>
<pre><code> KXXXXXX(K\R)XR
</code></pre>
<p>Please note that Letters between K and K\R are not fixed. However, there is only letter between K\R and R. So, in the given string my pattern is like this and exist between letter no. 54 to 65 (if I counted correctly) based on "smallest pattern" search :-</p>
<pre><code> KYMLSVDNLKLR
</code></pre>
<p>Previously, I was using C if-else condition to break this given string and printed out word count (not fully successful).</p>
<pre><code> printf(%c, word[i]);
if ((word [i] == 'K' || word [i] == 'R' )) && word [i+2] == 'R') {
printf("\n");
printf("%d\n",i);
}
</code></pre>
<p>I agree It dint capture everything. If anyone can help me help me solving this problem, that would be great.</p>
| -2 | 2016-10-16T22:30:53Z | 40,077,287 | <p>Only did it this way because I hate back tracking in my regular expressions. But I do find its usually faster if I perform the most restrictive part of the match first. Which in this case is made simpler by reversing the input and the search pattern. This should stop at the first (shortest) possible match; rather than finding the longest match, then hunting down the shortest. </p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
my $pattern = "MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL";
my $reverse = reverse $pattern;
my $length = length $reverse;
if( $reverse =~ /(R.[KR][^K]+K)/ ) {
my $match = $1;
$match = reverse $match;
my $start_p = $length-$+[0];
my $end_p = $length-$-[0]-1;
my $where = $start_p + length $match;
print "FOUND ...\n";
print "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\n";
print $pattern."\n";
printf "%${where}s\n", $match;
print "Found pattern '$match' starting at position '$start_p' and ending at position '$end_p'\n";
# test it
if( $pattern =~ /$match/ ) {
if( $start_p == $-[0] && $end_p == $+[0]-1 ) {
print "Test successful, match found in original pattern.\n";
} else {
print "Test failed, you screwed something up!\n";
}
} else {
print "Hmmm, pattern '$match' wasn't found in '$pattern'?\n";
}
} else {
print "Dang, no match was found!\n";
}
</code></pre>
<p>I'm not certain if the elimination of back-tracking here would outweigh the performance hit of the reversing. I guess it would depend greatly on the sizes of both the input string and the length of what could possibly match.</p>
<pre><code>$> perl ./search.pl
FOUND ...
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
KYMLSVDNLKLR
Found pattern 'KYMLSVDNLKLR' starting at position '53' and ending at position '64'
Test successful, match found in original pattern.
</code></pre>
<p>I apologize to those that don't understand why I started at zero.</p>
<p>And a bit more real world example - which will find interwoven matches.</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
# NOTE THE INPUT WAS MODIFIED FROM OP
my $input = "MKTSGNQDEILVIRKKRKRRGWKLTINNIRGRIMRGRKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFALKGR";
my $rstart = length $input;
my( $match, $start, $end ) = rsearch( $input, "R.[KR].+?K" );
while( $match ) {
print "Found matching pattern '$match' starting at offset '$start' and ending at offset $end\n";
$input = substr $input, 0, $end;
( $match, $start, $end ) = rsearch( $input, "R.[KR].+?K" );
}
exit(0);
sub rsearch {
my( $input, $pattern ) = @_;
my $reverse = reverse $input;
if( $reverse =~ /($pattern)/ ) {
my $length = length $reverse;
$match = reverse $1;
$start = $length-$+[0];
$end = $length-$-[0]-1;
return( $match, $start, $end );
}
return( undef );
}
perl ./search.pl
Found matching pattern 'KHIFALKGR' starting at offset '85' and ending at offset 93
Found matching pattern 'KYMLSVDNLKLR' starting at offset '64' and ending at offset 75
Found matching pattern 'KLTINNIRGRIMRGR' starting at offset '22' and ending at offset 36
Found matching pattern 'KLTINNIRGR' starting at offset '22' and ending at offset 31
Found matching pattern 'KRKRR' starting at offset '15' and ending at offset 19
Found matching pattern 'KKRKR' starting at offset '14' and ending at offset 18
Found matching pattern 'KTSGNQDEILVIRKKR' starting at offset '1' and ending at offset 16
</code></pre>
| -1 | 2016-10-17T01:27:01Z | [
"python",
"perl"
] |
How to calculate counts and frequencies for pairs in list of lists? | 40,076,241 | <p>Bases refers to A,T,G and C</p>
<pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']]
# Note on fragility of data: Each element can only be made up only 2 of the 4 bases.
# [['CGG' ==> Only C and G,'ATT' ==> Only A and T],['GCGC'==> Only C and G,'TAAA' ==> Only T and A]]
# Elements like "ATGG" are not present in the data as the have more than 3 different types of bases
</code></pre>
<p>Consider the first pair : ['CGG','ATT']</p>
<ol>
<li><p>Calculate frequency of each base in the pairs separately:</p>
<p>CGG => (C = 1/3, G = 2/3)
ATT => (A = 1/3, T = 2/3)</p></li>
<li><p>Calculate frequency of occurrence of combination of bases in the pairs. Here, the combinations are 'CA' and 'GT' (Notice, order of the base matters. It is not 'CA','AC','GT' and 'TG'. Just only 'CA' and 'GT'). </p>
<p>Pairs => (CA = 1/3, GT = 2/3) </p></li>
<li><p>Calculate float(a) = (freq of Pairs) - ((freq of C in CGG) * (freq of A in ATT))</p>
<p>Eg in CA pairs, float (a) = (freq of CA pairs) - ((freq of C in CGG) * (freq of A in ATT))</p>
<p>Output a = (1/3) - ((1/3) * (1/3)) = 0.222222</p></li>
</ol>
<p>Calculating "a" for any one combination (either CA pair or GT pair)</p>
<p>NOTE: If the pair is AAAC and CCCA, the freq of C would it be 1/4, i.e. it is the frequency of the base over one of the pairs</p>
<ol start="4">
<li><p>Calculate b
float (b) = (float(a)^2)/ (freq of C in CGG) * (freq G in CGG) * (freq A in ATT) * (freq of T in ATT)</p>
<pre><code>Output b = 1
</code></pre></li>
</ol>
<p>Do this for the entire list</p>
<pre><code> Final Output a = [0.2222, - 0.125]
b = [1, 0.3333]
</code></pre>
<p>This code has been adapted from <a href="http://stackoverflow.com/questions/40066439/how-to-calculate-frequency-of-elements-for-pairwise-comparisons-of-lists-in-pyth?noredirect=1#comment67422112_40066439">this answer</a>. Please note that there are subtle differences in the two questions and they are NOT the same, in the approach to the problem. </p>
<p>However, I am unable to get this code to run. I get the following error:
for pair, count in i:
TypeError: 'int' object is not iterable</p>
<pre><code>#Count individual bases.
sample4 = [['CGG','ATT'],['GCGC','TAAA']]
base_counter = Counter()
for i in enumerate(sample4):
for pair, count in i:
base_counter[pair[0]] += count
base_counter[pair[1]] += count
print base_counter
# Get the total for each base.
total_count = sum(base_counter.values())
# Convert counts to frequencies.
base_freq = {}
for base, count in base_counter.items():
base_freq[base] = count / total_count
# Not sure how to write a code to count the number of pairs (Step 2)
# Let's say the counts have been stored in pair_counts
# Examine a pair from the two unique pairs to calculate float_a.
for i in enumerate(sample4):
float(a) = (pair_count[pair] / sum(pair_count.values())) - (base_freq[pair[0]] * base_freq[pair[1]])
# Step 7!
for i in enumerate(sample4):
float_b = float_a / float(base_freq[0][0] * base_freq[0][1] * base_freq[1][0] * base_freq[1][1])
</code></pre>
| 0 | 2016-10-16T22:36:35Z | 40,076,570 | <p>You are not really using <code>Counter</code> any different than a plain <code>dict</code>. Try something like the following approach:</p>
<pre><code>>>> sample = [['CGG','ATT'],['GCGC','TAAA']]
>>> from collections import Counter
>>> base_counts = [[Counter(base) for base in sub] for sub in sample]
>>> base_counts
[[Counter({'G': 2, 'C': 1}), Counter({'T': 2, 'A': 1})], [Counter({'G': 2, 'C': 2}), Counter({'A': 3, 'T': 1})]]
</code></pre>
<p>Now you can continue with a functional approach using nested comprehensions to transform your data*:</p>
<pre><code>>>> base_freqs = [[{k_v[0]:k_v[1]/len(bases[i]) for i,k_v in enumerate(count.items())} for count in counts]
... for counts, bases in zip(base_counts, sample)]
>>>
>>> base_freqs
[[{'G': 0.6666666666666666, 'C': 0.3333333333333333}, {'A': 0.3333333333333333, 'T': 0.6666666666666666}], [{'G': 0.5, 'C': 0.5}, {'A': 0.75, 'T': 0.25}]]
>>>
</code></pre>
<p>*Note, some people do not like big, nested comprehensions like that. I think it's fine as long as you are sticking to functional constructs and not mutating data structures inside your comprehensions. I actually find it very expressive. Others disagree vehemently. You can always unfold that code into nested for-loops.</p>
<p>Anyway, you can then work the same thing with the pairs. First:</p>
<pre><code>>>> pairs = [list(zip(*bases)) for bases in sample]
>>> pairs
[[('C', 'A'), ('G', 'T'), ('G', 'T')], [('G', 'T'), ('C', 'A'), ('G', 'A'), ('C', 'A')]]
>>> pair_counts = [Counter(base_pair) for base_pair in pairs]
>>> pair_counts
[Counter({('G', 'T'): 2, ('C', 'A'): 1}), Counter({('C', 'A'): 2, ('G', 'T'): 1, ('G', 'A'): 1})]
>>>
</code></pre>
<p>Now, here it is easier to not use comprehensions so we don't have to calculate <code>total</code> more than once:</p>
<pre><code>>>> pair_freq = []
>>> for count in pair_counts:
... total = sum(count.values())
... pair_freq.append({k:c/total for k,c in count.items()})
...
>>> pair_freq
[{('C', 'A'): 0.3333333333333333, ('G', 'T'): 0.6666666666666666}, {('G', 'T'): 0.25, ('C', 'A'): 0.5, ('G', 'A'): 0.25}]
>>>
</code></pre>
| 0 | 2016-10-16T23:20:53Z | [
"python",
"list",
"dictionary",
"count"
] |
DRF auth_token: "non_field_errors": [ "Unable to log in with provided credentials." | 40,076,254 | <p>Both JWT packages written for Django gave me issues with poor documentation, so I try DRF-auth_token package. This is a good example I followed, <a href="http://stackoverflow.com/questions/14838128/django-rest-framework-token-authentication">Django Rest Framework Token Authentication</a>. You should in theory be able to go to </p>
<p><code>localhost:8000/api-token-auth/</code></p>
<p>urls.py:</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework.authtoken import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls', namespace='api')),
url(r'^orders/', include('orders.urls', namespace='orders')),
url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'),
]
</code></pre>
<p>Getting a token for users is not working so I have rewritten it myself to make it work:</p>
<pre><code>@api_view(['POST'])
def customer_login(request):
"""
Try to login a customer (food orderer)
"""
data = request.data
try:
username = data['username']
password = data['password']
except:
return Response(status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(username=username, password=password)
except:
return Response(status=status.HTTP_401_UNAUTHORIZED)
try:
user_token = user.auth_token.key
except:
user_token = Token.objects.create(user=user)
data = {'token': user_token}
return Response(data=data, status=status.HTTP_200_OK)
</code></pre>
<p>My version works:</p>
<pre><code>http://localhost:8000/api/login/customer-login/
{"username": "[email protected]", "password": "wombat"}
-->
{
"token": "292192b101153b7ced74dd52deb6b3df22ef2c74"
}
</code></pre>
<p>The DRF auth_token does not work:</p>
<pre><code>http://localhost:8000/api-token-auth/
{"username": "[email protected]", "password": "wombat"}
-->
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
</code></pre>
<p>settings.py</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# third party:
'django_extensions',
'rest_framework',
'rest_framework.authtoken',
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
</code></pre>
<p>It seems set up correctly. Every user in my DB has a token. Each user is <code>is_authenticated</code> and <code>is_active</code> in DB. Super users can get their token:</p>
<pre><code>localhost:8000/api-token-auth/
{"username": "mysuperuser", "password": "superuserpassword"}
-->
{
"token": "9297ff1f44dbc6caea67bea534f6f7590d2161b0"
}
</code></pre>
<p>for some reason, only super user can get a token:</p>
<pre><code>localhost:8000/api-token-auth/
{"username": "regularguy", "password": "password"}
-->
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
</code></pre>
<p>Why can't my users log in and get their token? Thank you</p>
| 0 | 2016-10-16T22:38:14Z | 40,077,820 | <p>I went ahead and did this from the <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">drf token auth docs</a> and didn't run into any problems with superusers, staffusers, or normal users. Maybe take a look at my code and see if you can find some difference. <a href="https://github.com/awwester/so40076254drftoken" rel="nofollow">https://github.com/awwester/so40076254drftoken</a></p>
<p>Also try following the steps of the official docs instead of that SO answer and see if that fixes the problem - it's possible something changed.</p>
<p>Here were the general steps I took:</p>
<ul>
<li>install django, drf</li>
<li>put 'rest_framework' and 'rest_framework.authtoken' in INSTALLED_APPS</li>
<li>add 'TokenAuthentication' in my rest_framework settings</li>
<li>run migrate</li>
<li>create tokens for users (I just did this in urls.py)</li>
<li>create the url for token</li>
<li>POST <a href="http://localhost:8000/token/" rel="nofollow">http://localhost:8000/token/</a> {"username": "...", "password": "..."}</li>
</ul>
<p>If you have the code public anywhere I'd be glad to take a further look and see what I find.</p>
| 1 | 2016-10-17T02:53:57Z | [
"python",
"django",
"django-rest-framework",
"django-rest-auth",
"django-1.10"
] |
Kivy changing color of a custom button on press | 40,076,274 | <p>Goes without saying that I am new to kivy, trying to write a simple GUI with triangular buttons (and I want them to be decent, not just images that are still a square canvas that be clicked off the triangular part). So I found this great code that makes a triangle and gets the clickable area. </p>
<p>Basically I just want it to change colors when pressed (and revert back when unpressed) and I'm too newbish to get that to work. </p>
<pre class="lang-py prettyprint-override"><code>import kivy
from kivy.uix.behaviors.button import ButtonBehavior
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
from kivy.vector import Vector
from kivy.lang import Builder
Builder.load_string('''
<TriangleButton>:
id: trianglething
# example for doing a triangle
# this will automatically recalculate pX from pos/size
#p1: 0, 0
#p2: self.width, 0
#p3: self.width / 2, self.height
# If you use a Widget instead of Scatter as base class, you need that:
p1: self.pos
p2: self.right, self.y
p3: self.center_x, self.top
# draw something
canvas:
Color:
rgba: self.triangle_down_color
Triangle:
points: self.p1 + self.p2 + self.p3
''')
def point_inside_polygon(x, y, poly):
'''Taken from http://www.ariel.com.au/a/python-point-int-poly.html
'''
n = len(poly)
inside = False
p1x = poly[0]
p1y = poly[1]
for i in range(0, n + 2, 2):
p2x = poly[i % n]
p2y = poly[(i + 1) % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
class TriangleButton(ButtonBehavior, Widget):
triangle_down_color = ListProperty([1,1,1,1])
p1 = ListProperty([0, 0])
p2 = ListProperty([0, 0])
p3 = ListProperty([0, 0])
def changecolor(self, *args):
print "color"
self.ids.trianglething.canvas.triangle_down_color = (1,0,1,1)
def collide_point(self, x, y):
x, y = self.to_local(x, y)
return point_inside_polygon(x, y,
self.p1 + self.p2 + self.p3)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(TriangleButton(on_press=TriangleButton.changecolor,size_hint=(None,None)))
</code></pre>
<p>I'm thinking I just have this line wrong:</p>
<pre class="lang-py prettyprint-override"><code>self.ids.trianglething.canvas.triangle_down_color = (1,0,1,1)
</code></pre>
<p>but heck I don't really know. Any help would be appreciated</p>
| 3 | 2016-10-16T22:40:30Z | 40,076,499 | <p>You are already in the widget, go directly for it, not through <code>ids</code>. <code>Ids</code> are for property <code>id</code> set in the children of a widget in kv language e.g. if your TriangleButton had a child <code>Image</code> with an <code>id: myimage</code>, you'd get it with this:</p>
<pre><code>self.ids.myimage
</code></pre>
<p>Therefore removing the unnecessary stuff is enough:</p>
<pre><code>self.triangle_down_color = (1,0,1,1)
</code></pre>
<p>It's also nice to print what you are actually looking for - if it prints some object, or if that thing doesn't even exist. And binding is nicer than putting something manually into <code>on_press</code> :)</p>
<pre><code>t = TriangleButton()
t.bind(on_press=function)
</code></pre>
| 0 | 2016-10-16T23:12:14Z | [
"python",
"kivy"
] |
How is numpy pad implemented (for constant value) | 40,076,280 | <p>I'm trying to implement the numpy pad function in theano for the constant mode. How is it implemented in numpy? Assume that pad values are just 0.</p>
<p>Given an array </p>
<pre><code>a = np.array([[1,2,3,4],[5,6,7,8]])
# pad values are just 0 as indicated by constant_values=0
np.pad(a, pad_width=[(1,2),(3,4)], mode='constant', constant_values=0)
</code></pre>
<p>would return</p>
<pre><code>array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0],
[0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
</code></pre>
<p>Now if I know the number of dimensions of a beforehand, I can just implement this by creating a new array of the new dimensions filled the pad value and fill in the corresponding elements in this array. But what if I don't know the dimensions of the input array? While I can still infer the dimensions of the output array from the input array, I have no way of indexing it without knowing the number of dimensions in it. Or am I missing something?</p>
<p>That is, if I know that the input dimension is say, 3, then I could do:</p>
<pre><code>zeros_array[pad_width[0][0]:-pad_width[0][1], pad_width[1][0]:-pad_width[1][1], pad_width[2][0]:-pad_width[2][1]] = a
</code></pre>
<p>where zeros array is the new array created with the output dimensions.</p>
<p>But if I don't know the ndim before hand, I cannot do this.</p>
| 2 | 2016-10-16T22:41:30Z | 40,077,302 | <p>My instinct is to do:</p>
<pre><code>def ...(arg, pad):
out_shape = <arg.shape + padding> # math on tuples/lists
idx = [slice(x1, x2) for ...] # again math on shape and padding
res = np.zeros(out_shape, dtype=arg.dtype)
res[idx] = arg # may need tuple(idx)
return res
</code></pre>
<p>In other words, make the target array, and copy the input with the appropriate indexing tuple. It will require some math and maybe iteration to construct the required shape and slicing, but that should be straight forward if tedious.</p>
<p>However it appears that <code>np.pad</code> iterates on the axes (if I've identified the correct alternative:</p>
<pre><code> newmat = narray.copy()
for axis, ((pad_before, pad_after), (before_val, after_val)) \
in enumerate(zip(pad_width, kwargs['constant_values'])):
newmat = _prepend_const(newmat, pad_before, before_val, axis)
newmat = _append_const(newmat, pad_after, after_val, axis)
</code></pre>
<p>where <code>_prepend_const</code> is:</p>
<pre><code>np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr), axis=axis)
</code></pre>
<p>(and <code>append</code> would be similar). So it is adding each pre and post piece separately for each dimension. Conceptually that is simple even if it might not be the fastest.</p>
<pre><code>In [601]: np.lib.arraypad._prepend_const(np.ones((3,5)),3,0,0)
Out[601]:
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
In [604]: arg=np.ones((3,5),int)
In [605]: for i in range(2):
...: arg=np.lib.arraypad._prepend_const(arg,1,0,i)
...: arg=np.lib.arraypad._append_const(arg,2,2,i)
...:
In [606]: arg
Out[606]:
array([[0, 0, 0, 0, 0, 0, 2, 2],
[0, 1, 1, 1, 1, 1, 2, 2],
[0, 1, 1, 1, 1, 1, 2, 2],
[0, 1, 1, 1, 1, 1, 2, 2],
[0, 2, 2, 2, 2, 2, 2, 2],
[0, 2, 2, 2, 2, 2, 2, 2]])
</code></pre>
| 0 | 2016-10-17T01:29:20Z | [
"python",
"arrays",
"numpy",
"pad"
] |
string in range is not working | 40,076,292 | <p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p>
<p>Here my code:</p>
<pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black']
my_hanes_len = len(my_hanes)
for h in range(0, my_hanes_len):
print(my_hanes_len[h])
</code></pre>
<p>Every time, the message pop up and said "'int' object is not subscriptable"</p>
<p>How do you solve this problem?</p>
<p>Thank you!</p>
| 0 | 2016-10-16T22:43:17Z | 40,076,334 | <p>You can iterate over each object of a list more simply, as you're trying to do</p>
<pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black']
for hanes in my_hanes:
print hanes
</code></pre>
<p>This will print each item in list <code>my_hanes</code>.</p>
| 1 | 2016-10-16T22:49:35Z | [
"python",
"int",
"range"
] |
string in range is not working | 40,076,292 | <p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p>
<p>Here my code:</p>
<pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black']
my_hanes_len = len(my_hanes)
for h in range(0, my_hanes_len):
print(my_hanes_len[h])
</code></pre>
<p>Every time, the message pop up and said "'int' object is not subscriptable"</p>
<p>How do you solve this problem?</p>
<p>Thank you!</p>
| 0 | 2016-10-16T22:43:17Z | 40,076,377 | <p>You need <code>print(my_hanes[h])</code> instead of <code>print(my_hanes_len[h])</code>.</p>
| 2 | 2016-10-16T22:55:58Z | [
"python",
"int",
"range"
] |
string in range is not working | 40,076,292 | <p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p>
<p>Here my code:</p>
<pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black']
my_hanes_len = len(my_hanes)
for h in range(0, my_hanes_len):
print(my_hanes_len[h])
</code></pre>
<p>Every time, the message pop up and said "'int' object is not subscriptable"</p>
<p>How do you solve this problem?</p>
<p>Thank you!</p>
| 0 | 2016-10-16T22:43:17Z | 40,076,397 | <p>The problem with your code is that my_hanes is an array of strings. So len(my_hanes) is an integer value (4) indicating the length of your array (aka python list). If you want to get the length of each element of my_hanes as a list, you can iterate to make one:</p>
<pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black']
my_hanes_len = list()
for hanes in my_hanes:
my_hanes_len.append(len(hanes))
print(my_hanes_len)
</code></pre>
| 0 | 2016-10-16T22:58:51Z | [
"python",
"int",
"range"
] |
Catch anything and save it into a variable | 40,076,310 | <p>I'm wondering if there is a keyword for "all" in python <code>except</code>. I've ran into this seemingly simple problem:</p>
<pre><code>try:
#do stuff
except any as error:
print('error: {err}'.format(err=error))
</code></pre>
<p>I know that you can do <code>except:</code> to catch all errors, but I don't know how to add an <code>as</code> keyword to get a <code>print</code>able object. I want to catch any error and be able to get an object for use in printing or something else.</p>
| -1 | 2016-10-16T22:46:38Z | 40,076,331 | <p>Yes, just catch <code>Exception</code>:</p>
<p><code>except Exception as ex:</code></p>
| 3 | 2016-10-16T22:49:15Z | [
"python",
"except"
] |
Catch anything and save it into a variable | 40,076,310 | <p>I'm wondering if there is a keyword for "all" in python <code>except</code>. I've ran into this seemingly simple problem:</p>
<pre><code>try:
#do stuff
except any as error:
print('error: {err}'.format(err=error))
</code></pre>
<p>I know that you can do <code>except:</code> to catch all errors, but I don't know how to add an <code>as</code> keyword to get a <code>print</code>able object. I want to catch any error and be able to get an object for use in printing or something else.</p>
| -1 | 2016-10-16T22:46:38Z | 40,076,340 | <p>You can catch almost anything this way:</p>
<pre><code>try:
#do stuff
except Exception as error:
print('error: {err}'.format(err=error))
</code></pre>
<p>But to catch really everything, you can do this:</p>
<pre><code>import sys
try:
#do stuff
except:
err_type, error, traceback = sys.exc_info()
print('error: {err}'.format(err=error))
</code></pre>
| 11 | 2016-10-16T22:50:05Z | [
"python",
"except"
] |
pygame: how do I get my game to actually run at 60fps? | 40,076,353 | <p>In my main loop I have:</p>
<pre><code>clock.tick_busy_loop(60)
pygame.display.set_caption("fps: " + str(clock.get_fps()))
</code></pre>
<p>However, the readout says the game is reading at 62.5fps.
I then tried to input <code>clock.tick_busy_loop(57.5)</code>, which gave me a readout of 58.82...fps. When I set <code>clock.tick_busy_loop(59)</code> I get 62.5fps again. It looks like there is a threshold between 58.8fps and 62.5fps that I can't overcome here. How do I get my game to actually run at 60fps? I'm mainly looking for this kind of control because I executing events that are contingent on musical timing.</p>
| 0 | 2016-10-16T22:51:38Z | 40,077,658 | <p>So I whipped up a simple demo based on my comment above that uses the system time module instead of the pygame.time module. You can ignore the OpenGL stuff as I just wanted to render something simple on screen. The most important part is the timing code at the end of each frame, which I have commented about in the code.</p>
<pre><code>import pygame
import sys
import time
from OpenGL.GL import *
from OpenGL.GLU import *
title = "FPS Timer Demo"
target_fps = 60
(width, height) = (300, 200)
flags = pygame.DOUBLEBUF|pygame.OPENGL
screen = pygame.display.set_mode((width, height), flags)
rotation = 0
square_size = 50
prev_time = time.time()
while True:
#Handle the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#Do computations and render stuff on screen
rotation += 1
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(width/2.0, height/2.0, 0)
glRotate(rotation, 0, 0, 1)
glTranslate(-square_size/2.0, -square_size/2.0, 0)
glBegin(GL_QUADS)
glVertex(0, 0, 0)
glVertex(50, 0, 0)
glVertex(50, 50, 0)
glVertex(0, 50, 0)
glEnd()
pygame.display.flip()
#Timing code at the END!
curr_time = time.time()#so now we have time after processing
diff = curr_time - prev_time#frame took this much time to process and render
delay = max(1.0/target_fps - diff, 0)#if we finished early, wait the remaining time to desired fps, else wait 0 ms!
time.sleep(delay)
fps = 1.0/(delay + diff)#fps is based on total time ("processing" diff time + "wasted" delay time)
prev_time = curr_time
pygame.display.set_caption("{0}: {1:.2f}".format(title, fps))
</code></pre>
| 0 | 2016-10-17T02:26:27Z | [
"python",
"pygame",
"pygame-clock"
] |
matplotlib/pyplot not plotting data from specific .txt file | 40,076,368 | <p>I have data saved via numpy's savetxt function and am extracting it to plot. When I plot it the script executes without errors but does not show the curves--only empty windows. This is strange because:</p>
<ol>
<li><p>The same script makes a fine plot when I import .txt data from another file (also saved using savetxt).</p></li>
<li><p>If I create data points inside the script, e.g. with arange, it plots. </p></li>
<li><p>The .txt data <em>is</em> getting loaded--I have printed it to the screen.</p></li>
<li><p>I checked my backend and it is TkAgg, which the internet agrees it's supposed to be. </p></li>
</ol>
<p>My code is</p>
<pre><code> # this script makes the plots of the eigenvalue distributions for the AAS 17-225 paper
# import python modules
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
# set plot options
mpl.rcParams['xtick.major.size'] = 7
mpl.rcParams['xtick.major.width'] = 3.0
mpl.rcParams['ytick.major.size'] = 7
mpl.rcParams['ytick.major.width'] = 3.0
mpl.rcParams['axes.linewidth'] = 3.5
plt.rc('text',usetex=True)
mpl.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
plt.rc('font',family='serif')
plt.rc('axes',labelsize=24)
plt.rc('xtick',labelsize=24)
plt.rc('ytick',labelsize=24)
plt.rc('font',weight='bold')
plt.rc('axes',titlesize=20)
# plot method arguments
lw = 2 # linewidth
left_adj = 0.055 # left adjustment
right_adj = 0.985 # left adjustment
top_adj = 0.975 # left adjustment
bottom_adj = 0.075 # left adjustment
wspace = 0.205 # horizontal space between plots
hspace = 0.2 # verticle space between plots
n_suplot_rows = 2 # number of subplot rows
n_suplot_columns = 3 # number of subplot columns
# load data
dataDir ='/mnt/E0BA55A7BA557B4C/research/independent/recursivequats/paperCode/'
df1 = dataDir+'lamda_0p1_0p1.txt'
df2 = dataDir+'lamda_0.1_0.5.txt'
df3 = dataDir+'lamda_0.1_1.0.txt'
df4 = dataDir+'lamda_0.5_0.5.txt'
df5 = dataDir+'lamda_0.5_1.0.txt'
df6 = dataDir+'lamda_1.0_1.0.txt'
profile1 = np.loadtxt(df1)
profile2 = np.loadtxt(df2)
profile3 = np.loadtxt(df3)
profile4 = np.loadtxt(df4)
profile5 = np.loadtxt(df5)
profile6 = np.loadtxt(df6)
fig = plt.figure()
ax1 = fig.add_subplot(n_suplot_rows,n_suplot_columns,1)
p1, = ax1.plot(profile1[:,1],profile1[:,0],linewidth=lw)
ax2 = fig.add_subplot(n_suplot_rows,n_suplot_columns,2)
p1, = ax2.plot(profile2[:,1],profile2[:,0],linewidth=lw)
ax3 = fig.add_subplot(n_suplot_rows,n_suplot_columns,3)
p1, = ax3.plot(profile3[:,1],profile3[:,0],linewidth=lw)
ax4 = fig.add_subplot(n_suplot_rows,n_suplot_columns,4)
p1, = ax4.plot(profile4[:,1],profile4[:,0],linewidth=lw)
ax5 = fig.add_subplot(n_suplot_rows,n_suplot_columns,5)
p1, = ax5.plot(profile5[:,1],profile5[:,0],linewidth=lw)
ax6 = fig.add_subplot(n_suplot_rows,n_suplot_columns,6)
p1, = ax5.plot(profile6[:,1],profile6[:,0],linewidth=lw)
plt.subplots_adjust(left=left_adj,right=right_adj,top=top_adj,bottom=bottom_adj,wspace=wspace,hspace=hspace)
plt.show()
</code></pre>
| 1 | 2016-10-16T22:53:53Z | 40,122,293 | <p>well, a bit more digging and the problem has been identified. The script <em>is</em> plotting, but the zoom on the plots is so poor that they are obscured by the thick lines on the border. So the problem was a user error. </p>
<p>This is why engineers shouldn't try to be artists... </p>
| 0 | 2016-10-19T04:42:56Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
Connecting to Google Cloud Storage using standalone Python script using service account | 40,076,417 | <p>I am trying to connect to Google Cloud Storage from a standalone python script using a service account. I am running this script from my local system. I have also activated the service account using gcloud auth and added "GOOGLE_APPLICATION_CREDENTIALS" to point to the client_secrets.json file. </p>
<p>The authentication does not work and fails with the following log:</p>
<pre><code>
Uploading object..
Traceback (most recent call last):
File "quickstart.py", line 122, in
main(args.bucket, args.filename, args.reader, args.owner)
File "quickstart.py", line 16, in main
resp = upload_object(bucket, filename, readers, owners)
File "quickstart.py", line 43, in upload_object
service = create_service()
File "quickstart.py", line 39, in create_service
return discovery.build('storage', 'v1', http=http_auth)
File "build/bdist.macosx-10.12-intel/egg/oauth2client/util.py", line 137, in positional_wrapper
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 214, in build
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 153, in new_request
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 765, in _refresh
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 797, in _do_refresh_request
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1036, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
self._context.load_verify_locations(ca_certs)
IOError: [Errno 13] Permission denied
</code></pre>
<p>Here is the code snipped I am trying to run to authenticate:</p>
<pre><code>
import oauth2client
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from googleapiclient import discovery
import argparse
import filecmp
import json
import tempfile
import logging
logging.basicConfig(filename='debug.log',level=logging.DEBUG)
def main(bucket, filename, readers=[], owners=[]):
print('Uploading object..')
resp = upload_object(bucket, filename, readers, owners)
print(json.dumps(resp, indent=2))
def create_service():
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scopes)
http_auth = credentials.authorize(Http())
return discovery.build('storage', 'v1', http=http_auth)
def upload_object(bucket, filename, readers, owners):
service = create_service()
# This is the request body as specified:
# http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
body = {
'name': filename,
}
# If specified, create the access control objects and add them to the
# request body
if readers or owners:
body['acl'] = []
for r in readers:
body['acl'].append({
'entity': 'user-%s' % r,
'role': 'READER',
'email': r
})
for o in owners:
body['acl'].append({
'entity': 'user-%s' % o,
'role': 'OWNER',
'email': o
})
# Now insert them into the specified bucket as a media insertion.
# http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
with open(filename, 'rb') as f:
req = service.objects().insert(
bucket=bucket, body=body,
# You can also just set media_body=filename, but for the sake of
# demonstration, pass in the more generic file handle, which could
# very well be a StringIO or similar.
media_body=http.MediaIoBaseUpload(f, 'application/octet-stream'))
resp = req.execute()
return resp
</code></pre>
<p>I tried looking at multiple examples from google developers forum as well as other blogs. All show the same code. Not sure what is going wrong here.</p>
| 0 | 2016-10-16T23:00:55Z | 40,076,473 | <p>The last line of the traceback indicates that your Python script cannot access a resource on disk with the correct permissions.</p>
<p><code>IOError: [Errno 13] Permission denied</code></p>
<p>A simple fix is to run this script with sudo.</p>
| 0 | 2016-10-16T23:07:56Z | [
"python",
"google-cloud-storage",
"google-api-python-client",
"service-accounts"
] |
Connecting to Google Cloud Storage using standalone Python script using service account | 40,076,417 | <p>I am trying to connect to Google Cloud Storage from a standalone python script using a service account. I am running this script from my local system. I have also activated the service account using gcloud auth and added "GOOGLE_APPLICATION_CREDENTIALS" to point to the client_secrets.json file. </p>
<p>The authentication does not work and fails with the following log:</p>
<pre><code>
Uploading object..
Traceback (most recent call last):
File "quickstart.py", line 122, in
main(args.bucket, args.filename, args.reader, args.owner)
File "quickstart.py", line 16, in main
resp = upload_object(bucket, filename, readers, owners)
File "quickstart.py", line 43, in upload_object
service = create_service()
File "quickstart.py", line 39, in create_service
return discovery.build('storage', 'v1', http=http_auth)
File "build/bdist.macosx-10.12-intel/egg/oauth2client/util.py", line 137, in positional_wrapper
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 214, in build
File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 153, in new_request
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 765, in _refresh
File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 797, in _do_refresh_request
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1036, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
ciphers=ciphers)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
self._context.load_verify_locations(ca_certs)
IOError: [Errno 13] Permission denied
</code></pre>
<p>Here is the code snipped I am trying to run to authenticate:</p>
<pre><code>
import oauth2client
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from googleapiclient import discovery
import argparse
import filecmp
import json
import tempfile
import logging
logging.basicConfig(filename='debug.log',level=logging.DEBUG)
def main(bucket, filename, readers=[], owners=[]):
print('Uploading object..')
resp = upload_object(bucket, filename, readers, owners)
print(json.dumps(resp, indent=2))
def create_service():
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scopes)
http_auth = credentials.authorize(Http())
return discovery.build('storage', 'v1', http=http_auth)
def upload_object(bucket, filename, readers, owners):
service = create_service()
# This is the request body as specified:
# http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
body = {
'name': filename,
}
# If specified, create the access control objects and add them to the
# request body
if readers or owners:
body['acl'] = []
for r in readers:
body['acl'].append({
'entity': 'user-%s' % r,
'role': 'READER',
'email': r
})
for o in owners:
body['acl'].append({
'entity': 'user-%s' % o,
'role': 'OWNER',
'email': o
})
# Now insert them into the specified bucket as a media insertion.
# http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
with open(filename, 'rb') as f:
req = service.objects().insert(
bucket=bucket, body=body,
# You can also just set media_body=filename, but for the sake of
# demonstration, pass in the more generic file handle, which could
# very well be a StringIO or similar.
media_body=http.MediaIoBaseUpload(f, 'application/octet-stream'))
resp = req.execute()
return resp
</code></pre>
<p>I tried looking at multiple examples from google developers forum as well as other blogs. All show the same code. Not sure what is going wrong here.</p>
| 0 | 2016-10-16T23:00:55Z | 40,076,479 | <p>From the error it looks like a simple permissions problem. Did you run the program with root priviges? If not then run the file from the command line with <code>sudo</code> at the beginning.</p>
<p>Note: IDLE doesn't run it with root.</p>
| 1 | 2016-10-16T23:08:45Z | [
"python",
"google-cloud-storage",
"google-api-python-client",
"service-accounts"
] |
Global array storing counters updated by each thread; main thread to read counters on demand? | 40,076,481 | <p>Here's the scenario: a main thread spawns upto N worker threads that each will update a counter (say they are counting number of requests handled by each of them).</p>
<p>The total counter also needs to be read by the main thread on an API request.</p>
<p>I was thinking of designing it like so:</p>
<p>1) Global hashmap/array/linked-list of counters. </p>
<p>2) Each worker thread accesses this global structure using the thread-ID as the key, so that there's no mutex required to protect one worker thread from another.</p>
<p>3) However, here's the tough part: no example I could find online handles this: I want the main thread to be able to read and sum up all counter values on demand, say to serve an API request. I will NEED a mutex here, right?</p>
<p>So, effectively, I will need a per-worker-thread mutex that will lock the mutex before updating the global array -- given each worker thread only contends with main thread, the mutex will fail only when main thread is serving the API request.</p>
<p>The main thread: when it receives API request, it will have to lock each of the worker-thread-specific mutex one by one, read that thread's counter to get the total count.</p>
<p>Am I overcomplicating this? I don't like requiring per-worker-thread mutex in this design.</p>
<p>Thanks for any inputs. </p>
| 0 | 2016-10-16T23:08:59Z | 40,076,739 | <p>Just use an <code>std::atomic<int></code> to keep a running count. When any thread updates its counter it also updates the running count. When the main thread needs the count it reads the running count. The result may be less than the actual total at any given moment, but whenever things settle down, the total will be right.</p>
| 0 | 2016-10-16T23:47:57Z | [
"java",
"python",
"c++",
"multithreading",
"pthreads"
] |
Global array storing counters updated by each thread; main thread to read counters on demand? | 40,076,481 | <p>Here's the scenario: a main thread spawns upto N worker threads that each will update a counter (say they are counting number of requests handled by each of them).</p>
<p>The total counter also needs to be read by the main thread on an API request.</p>
<p>I was thinking of designing it like so:</p>
<p>1) Global hashmap/array/linked-list of counters. </p>
<p>2) Each worker thread accesses this global structure using the thread-ID as the key, so that there's no mutex required to protect one worker thread from another.</p>
<p>3) However, here's the tough part: no example I could find online handles this: I want the main thread to be able to read and sum up all counter values on demand, say to serve an API request. I will NEED a mutex here, right?</p>
<p>So, effectively, I will need a per-worker-thread mutex that will lock the mutex before updating the global array -- given each worker thread only contends with main thread, the mutex will fail only when main thread is serving the API request.</p>
<p>The main thread: when it receives API request, it will have to lock each of the worker-thread-specific mutex one by one, read that thread's counter to get the total count.</p>
<p>Am I overcomplicating this? I don't like requiring per-worker-thread mutex in this design.</p>
<p>Thanks for any inputs. </p>
| 0 | 2016-10-16T23:08:59Z | 40,077,181 | <p>Your design sounds like the correct approach. Don't think of them as per-thread mutexes: think of them as per-counter mutexes (each element of your array should probably be a mutex/counter pair).</p>
<p>In the main thread there may be no need to lock all of the mutexes and then read all of the counters: you might be able to do the lock/read/unlock for each counter in sequence, if the value is something like your example (number of requests handled by each thread) where reading all the counters together doesn't give a "more correct" answer than reading them in sequence.</p>
<p>Alternatively, you could use atomic variables for the counters instead of locks if your language/environment offers that.</p>
| 0 | 2016-10-17T01:04:12Z | [
"java",
"python",
"c++",
"multithreading",
"pthreads"
] |
How to drop duplicate from DataFrame taking into account value of another column | 40,076,534 | <p>When I drop <code>John</code> as duplicate specifying 'name' as the column name: </p>
<pre><code>import pandas as pd
data = {'name':['Bill','Steve','John','John','John'], 'age':[21,28,22,30,29]}
df = pd.DataFrame(data)
df = df.drop_duplicates('name')
</code></pre>
<p>pandas drops all matching entities leaving the left-most:</p>
<pre><code> age name
0 21 Bill
1 28 Steve
2 22 John
</code></pre>
<p>Instead I would like to keep the row where John's age is the highest (in this example it is the age 30. How to achieve this?</p>
| 5 | 2016-10-16T23:15:38Z | 40,076,558 | <p>Try this:</p>
<pre><code>In [75]: df
Out[75]:
age name
0 21 Bill
1 28 Steve
2 22 John
3 30 John
4 29 John
In [76]: df.sort_values('age').drop_duplicates('name', keep='last')
Out[76]:
age name
0 21 Bill
1 28 Steve
3 30 John
</code></pre>
<p>or this depending on your goals:</p>
<pre><code>In [77]: df.drop_duplicates('name', keep='last')
Out[77]:
age name
0 21 Bill
1 28 Steve
4 29 John
</code></pre>
| 4 | 2016-10-16T23:19:54Z | [
"python",
"pandas",
"dataframe"
] |
MongoDB query syntax error | 40,076,599 | <p>I've run into an issue when querying a collection I've made of Twitch JSON objects. However, the following query throws "SyntaxError: invalid syntax".</p>
<pre><code>objflat = db.twitchstreams.find({'_links': [
'streams': [
{'channel':
{'game': gameName}
}
]
})
</code></pre>
<p>Any suggestions? I have all my fields in quotes, aside from gameName, which is a variable pulled from a config file of games for which I want data.</p>
| 0 | 2016-10-16T23:24:57Z | 40,076,678 | <p>In your nested data structure you do have a syntax error after 'streams'. A list only takes elements, not key/value pairs. </p>
<p>Example below is using IPython:</p>
<p>This works:</p>
<pre><code>In [5]: {"foo":["bar"]}
</code></pre>
<p>This doesn't:</p>
<pre><code>In [6]: {"foo":["bar": 1]}
File "<ipython-input-6-28ac5b9a1b6d>", line 1
{"foo":["bar": 1]}
^
</code></pre>
<p>SyntaxError: invalid syntax</p>
| 0 | 2016-10-16T23:37:03Z | [
"python",
"json",
"mongodb",
"twitch"
] |
I write this code of Simulated Annealing for TSP and I have been trying all day to debug it but something goes wrong | 40,076,618 | <p>This code suppose to reduce the distance of initial tour: distan(initial_tour) < distan(best) . Can you help me plz? I 've been trying all day now. <strong>Do I need to change my swapping method?</strong>
Something goes wrong and the simulated annealing does'not work:</p>
<pre><code>def prob(currentDistance,neighbourDistance,temp):
if neighbourDistance < currentDistance:
return 1.0
else:
return math.exp( (currentDistance - neighbourDistance) / temp)
def distan(solution):
#gives the distance of solution
listax, listay = [], []
for i in range(len(solution)):
listax.append(solution[i].x)
listay.append(solution[i].y)
dists = np.linalg.norm(np.vstack([np.diff(np.array(listax)), np.diff(np.array(listay))]), axis=0)
cumsum_dist = np.cumsum(dists)
return cumsum_dist[-1]
#simulated annealing
temp = 1000000
#creating initial tour
shuffle(greedys)
initial_tour=greedys
print (distan(initial_tour))
current_best = initial_tour
best = current_best
while(temp >1 ):
#create new neighbour tour
new_solution= current_best
#Get a random positions in the neighbour tour
tourPos1=random.randrange(0, len(dfar))
tourPos2=random.randrange(0, len(dfar))
tourCity1=new_solution[tourPos1]
tourCity2=new_solution[tourPos2]
#swapping
new_solution[tourPos1]=tourCity2
new_solution[tourPos2]=tourCity1
#get distance of both current_best and its neighbour
currentDistance = distan(current_best)
neighbourDistance = distan(new_solution)
# decide if we should accept the neighbour
# random.random() returns a number in [0,1)
if prob(currentDistance,neighbourDistance,temp) > random.random():
current_best = new_solution
# keep track of the best solution found
if distan(current_best) < distan(best):
best = current_best
#Cool system
temp = temp*0.99995
print(distan(best))
</code></pre>
| 2 | 2016-10-16T23:28:05Z | 40,077,348 | <p>Your problem is in the first line of your <code>while</code> loop, where you write</p>
<pre><code>new_solution= current_best
</code></pre>
<p>What this does is puts a reference to the <code>current_best</code> list into <code>new_solution</code>. This means that when you change <code>new_solution</code>, you're actually changing <code>current_best</code> as well, which was not your intention. </p>
<p>The problem could be solved by replacing the problematic line with one that copies the list into a new list, like so:</p>
<pre><code>new_solution = list(current_best)
</code></pre>
| 0 | 2016-10-17T01:35:46Z | [
"python",
"traveling-salesman",
"simulated-annealing"
] |
Where do you save a notepad file so python can open it in the program? | 40,076,672 | <p>My program can't locate the file. How do I save the text file in the python directory on Windows? I've looked through other similar questions but cant find a basic guide to save into the same directory. Thanks for the help</p>
<pre><code>user_input = input("file name")
fh=open(user_input,"r",encoding="utf-8")
</code></pre>
| -4 | 2016-10-16T23:36:04Z | 40,076,708 | <p>If i understood your question right, all you have to do is search for the python directory, press the Windows key and type the name of a folder, and the folder will show up among the Start menu search results. Save the notepad file in that directory. Hopefully that helps you.</p>
| 0 | 2016-10-16T23:43:31Z | [
"python",
"file"
] |
Where do you save a notepad file so python can open it in the program? | 40,076,672 | <p>My program can't locate the file. How do I save the text file in the python directory on Windows? I've looked through other similar questions but cant find a basic guide to save into the same directory. Thanks for the help</p>
<pre><code>user_input = input("file name")
fh=open(user_input,"r",encoding="utf-8")
</code></pre>
| -4 | 2016-10-16T23:36:04Z | 40,076,762 | <p>You are probably giving relative paths to <code>user_input</code>. Relative paths are resolved based on the <em>current working directory</em> (cwd). cwd is the directory from which python was started, which can be anything (not only where it is located), depending on how you start the script.</p>
<p>To find out what the cwd is:</p>
<pre><code>print(os.getcwd())
</code></pre>
<p>But instead of basing everything on CWD, I suggest you should do something else.</p>
<p>1st option: choose a different base directory:</p>
<pre><code>base_directory = 'C:\\My Favourite Directory'
user_input = input("file name")
file_path = os.path.join(base_directory, user_input)
fh = open(file_path, "r", encoding="utf-8")
</code></pre>
<p>2nd option: specify absolute paths as input:</p>
<p>When asked, for file name, type:</p>
<blockquote>
<p>C:\My Favourite Directory\my file.txt</p>
</blockquote>
| 0 | 2016-10-16T23:53:03Z | [
"python",
"file"
] |
python how to debug errors by logging issues | 40,076,683 | <p>I'm very new to python and have a script that runs when an email is sent to the server. My issue is trying to debug the script. How can I push any errors to a log file?</p>
<p>Here is the script:</p>
<pre><code>#!/usr/bin/python
import sys, email
email_input = email.message_from_string(sys.stdin.read())
directory = "/home/someuser/files"
counter = 1
for part in email_input.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
fp = open(os.path.join(directory, filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
</code></pre>
| 0 | 2016-10-16T23:37:36Z | 40,076,754 | <p>There are at least a couple ways to do this:</p>
<ol>
<li><p>You can print to stdout and redirect to a file. Here is an example</p>
<p>â ~ python print_this.py &> log.txt</p>
<p>â ~ cat log.txt </p>
<p>this message</p>
<p>â ~ cat print_this.py </p>
<p>print("this message")</p></li>
<li><p>You can use the logging library and attach a file handler:</p></li>
</ol>
<p><a href="https://docs.python.org/2/library/logging.handlers.html#filehandler" rel="nofollow">https://docs.python.org/2/library/logging.handlers.html#filehandler</a></p>
<p>This is slightly complicated. But you can see an example of some code I wrote here where you can see where to put the handler: </p>
<p><a href="https://github.com/nogibjj/sensible/blob/master/sensible/loginit.py" rel="nofollow">https://github.com/nogibjj/sensible/blob/master/sensible/loginit.py</a></p>
<p>How to Add This As An Example Using Print:</p>
<pre><code>import sys, email
email_input = email.message_from_string(sys.stdin.read())
directory = "/home/someuser/files"
counter = 1
for part in email_input.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
print("part: %s Found multipart" % part)
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
fp = open(os.path.join(directory, filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
</code></pre>
| 0 | 2016-10-16T23:51:42Z | [
"python"
] |
multiples section on Restplus swagger documentation | 40,076,752 | <p>On Restplus documentation (using B!ueprints) we see : a full example: <a href="https://flask-restplus.readthedocs.io/en/0.2.3/example.html" rel="nofollow">https://flask-restplus.readthedocs.io/en/0.2.3/example.html</a></p>
<p>The created swagger documentation has only one section "todos : TODO operations "</p>
<p>How can I have multiples sections ? </p>
| 0 | 2016-10-16T23:51:33Z | 40,078,477 | <p>You need to use Namespaces to achieve this. Each Namespace becomes a separate section in swagger doc.</p>
<p><a href="http://flask-restplus.readthedocs.io/en/stable/scaling.html" rel="nofollow">http://flask-restplus.readthedocs.io/en/stable/scaling.html</a></p>
| 1 | 2016-10-17T04:24:57Z | [
"python",
"swagger",
"flask-restplus"
] |
Pandas merge not keeping 'on' column | 40,076,806 | <p>I'm trying to merge two dataframes in <code>pandas</code> on a common column name (orderid). The resulting dataframe (the merged dataframe) is dropping the orderid from the 2nd data frame. Per the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow" title="documentation">documentation</a>, the 'on' column should be kept unless you explicitly tell it not to. </p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,'a'], [2, 'b'], [3, 'c']], columns=['orderid', 'ordervalue'])
df['orderid'] = df['orderid'].astype(str)
df2 = pd.DataFrame([[1,200], [2, 300], [3, 400], [4,500]], columns=['orderid', 'ordervalue'])
df2['orderid'] = df2['orderid'].astype(str)
pd.merge(df, df2, on='orderid', how='outer', copy=True, suffixes=('_left', '_right'))
</code></pre>
<p>Which outputs this:</p>
<pre><code>| |orderid | ordervalue_left | ordervalue_right |
|------|--------|-----------------|------------------|
| 0 | 1 | a | 200 |
| 1 | 2 | b | 300 |
| 2 | 3 | c | 400 |
| 3 | 4 | | 500 |
</code></pre>
<p>What I am trying to create is this:</p>
<pre><code>| | orderid_left | ordervalue_left | orderid_left | ordervalue_right |
|------|--------------|-----------------|--------------|------------------|
| 0 | 1 | a | 1 | 200 |
| 1 | 2 | b | 2 | 300 |
| 2 | 3 | c | 3 | 400 |
| 3 | NaN | NaN | 4 | 500 |
</code></pre>
<p>How should I write this?</p>
| 3 | 2016-10-17T00:00:59Z | 40,076,945 | <p>Rename the <code>orderid</code> columns so that <code>df</code> has a column named <code>orderid_left</code>,
and <code>df2</code> has a column named <code>orderid_right</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1,'a'], [2, 'b'], [3, 'c']], columns=['orderid', 'ordervalue'])
df['orderid'] = df['orderid'].astype(str)
df2 = pd.DataFrame([[1,200], [2, 300], [3, 400], [4,500]], columns=['orderid', 'ordervalue'])
df2['orderid'] = df2['orderid'].astype(str)
df = df.rename(columns={'orderid':'orderid_left'})
df2 = df2.rename(columns={'orderid':'orderid_right'})
result = pd.merge(df, df2, left_on='orderid_left', right_on='orderid_right',
how='outer', suffixes=('_left', '_right'))
print(result)
</code></pre>
<p>yields</p>
<pre><code> orderid_left ordervalue_left orderid_right ordervalue_right
0 1 a 1 200
1 2 b 2 300
2 3 c 3 400
3 NaN NaN 4 500
</code></pre>
| 3 | 2016-10-17T00:24:10Z | [
"python",
"pandas"
] |
install nvidia digits - ImportError: No module named wtforms | 40,076,808 | <pre><code> ___ ___ ___ ___ _____ ___
| \_ _/ __|_ _|_ _/ __|
| |) | | (_ || | | | \__ \
|___/___\___|___| |_| |___/ 5.0.0-rc.1
Traceback (most recent call last):
File "/home/jj/anaconda2/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/home/jj/anaconda2/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/jj/digits/digits/__main__.py", line 66, in <module>
main()
File "/home/jj/digits/digits/__main__.py", line 49, in main
import digits.config
File "digits/config/__init__.py", line 7, in <module>
from . import caffe
File "digits/config/caffe.py", line 13, in <module>
from digits.utils import parse_version
File "digits/utils/__init__.py", line 158, in <module>
from . import constants, image, time_filters, errors, forms, routing, auth
File "digits/utils/forms.py", line 5, in <module>
import wtforms
ImportError: No module named wtforms
</code></pre>
<p>which python</p>
<p>/home/jj/anaconda2/bin/python</p>
<p>which pip<br>
/home/jj/anaconda2/bin/pip</p>
<p>But
sudo pip install wtforms </p>
<pre><code>The directory '/home/jj/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/jj/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied (use --upgrade to upgrade): wtforms in /usr/lib/python2.7/dist-packages
</code></pre>
<p>It might be path problem... Could you help..? </p>
| 0 | 2016-10-17T00:01:23Z | 40,077,092 | <p>This is one of the canonical use cases for virtualenv. Because you are using sudo to install, there are now two potential paths where items could be installed: User and Root paths.</p>
<p>Try creating a virtualenv:</p>
<p>then pip install from inside virtualenv.</p>
| 0 | 2016-10-17T00:48:48Z | [
"python",
"deep-learning",
"nvidia",
"caffe",
"digits"
] |
How to merge two DataFrames into single matching the column values | 40,076,861 | <p>Two DataFrames have matching values stored in their corresponding 'names' and 'flights' columns.
While the first DataFrame stores the distances the other stores the dates:</p>
<pre><code>import pandas as pd
distances = {'names': ['A', 'B','C'] ,'distances':[100, 200, 300]}
dates = {'flights': ['C', 'B', 'A'] ,'dates':['1/1/16', '1/2/16', '1/3/16']}
distancesDF = pd.DataFrame(distances)
datesDF = pd.DataFrame(dates)
</code></pre>
<p>distancesDF:</p>
<pre><code> distances names
0 100 A
1 200 B
2 300 C
</code></pre>
<p>datesDF:</p>
<pre><code> dates flights
0 1/1/16 A
1 1/2/16 B
2 1/3/16 C
</code></pre>
<p>I would like to merge them into single Dataframe in a such a way that the matching entities are synced with the corresponding distances and dates. So the resulted DataFame would look like this:</p>
<p>resultDF:</p>
<pre><code> distances names dates
0 100 A 1/1/16
1 200 B 1/2/16
2 300 C 1/3/16
</code></pre>
<p>What would be the way of accomplishing it?</p>
| 5 | 2016-10-17T00:09:22Z | 40,076,983 | <p>There is nothing that ties these dataframes together other than the positional index. You can accomplish your desired example output with <code>pd.concat</code></p>
<pre><code>pd.concat([distancesDF, datesDF.dates], axis=1)
</code></pre>
<p><a href="https://i.stack.imgur.com/5YLVN.png" rel="nofollow"><img src="https://i.stack.imgur.com/5YLVN.png" alt="enter image description here"></a></p>
<hr>
<p>To address the edit and @kartik's comment</p>
<p>if we create the dfs to match what's displayed.</p>
<pre><code>distances = {'names': ['A', 'B','C'] ,'distances':[100, 200, 300]}
dates = {'flights': ['A', 'B', 'C'] ,'dates':['1/1/16', '1/2/16', '1/3/16']}
distancesDF = pd.DataFrame(distances)
datesDF = pd.DataFrame(dates)
</code></pre>
<p>then the following two options produce the same and probably desired result.</p>
<p><strong><em>merge</em></strong></p>
<pre><code> distancesDF.merge(datesDF, left_on='names', right_on='flights')[['distances', 'names', 'dates']]
</code></pre>
<p><strong><em>join</em></strong></p>
<pre><code>distancesDF.join(datesDF.set_index('flights'), on='names')
</code></pre>
<p>both produce</p>
<p><a href="https://i.stack.imgur.com/5YLVN.png" rel="nofollow"><img src="https://i.stack.imgur.com/5YLVN.png" alt="enter image description here"></a></p>
| 3 | 2016-10-17T00:30:21Z | [
"python",
"pandas",
"dataframe"
] |
Vectorized lookup of MySQL, and add to DataFrame | 40,076,884 | <p>I'm trying to do the following:</p>
<ol>
<li>Go through a DataFrame, that contains Columns 'Col1' and 'Col2'</li>
<li>Take each row in 'Col1', Search MySQL db using that value</li>
<li>Replace the value on the same row in 'Col2' with the result</li>
</ol>
<p>I'm leaning towards a For loop approach, but is there a faster vectorized approach. Rough code I'm using thus far:</p>
<pre><code> rsp_df = pd.DataFrame(pd.read_csv(raw_data_path))
cur = mydb.cursor()
for x in rsp_df['Col1']:
query = ("SELECT stuff FROM some-table WHERE Asin = '%s'" % str(x))
cur.execute(query)
rows = cur.fetchone()
print rows
</code></pre>
<p>Thanks a lot!</p>
| 0 | 2016-10-17T00:13:04Z | 40,077,565 | <p>Consider merging the MySQL query with the Pandas dataframe by importing the query into a separate dataframe. This way you match across all cases at once without looping and any conditional changes to columns can be done in one call.</p>
<p>Below is a <code>left</code> join merge to keep all records in <em>rsp_df</em> matched or not. Missing <em>stuff</em> from mydf denotes unmatched records. Then you can replace <em>Col2</em> with needed <em>result</em> (which I am not sure what you refer to as <em>result</em>, possibly a column in query's <em>stuff</em>):</p>
<pre><code>from sqlalchemy import create_engine
engine = create_engine('mysql://user:pwd@localhost/database')
mydf = pd.read_sql("SELECT stuff FROM some-table", con=engine)
merged_df = pd.merge(rsp_df, mydf, left_on=['Col1'], right_on=['Asin'], how='left')
mergedf.loc[pd.notnull(mergedf['Asin']), 'Col2'] = mergedf['result']
</code></pre>
| 1 | 2016-10-17T02:13:14Z | [
"python",
"mysql",
"dataframe"
] |
Convert python abbreviated month name to full name | 40,076,887 | <p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
| 3 | 2016-10-17T00:13:27Z | 40,076,927 | <p>a simple dictionary would work</p>
<p>eg</p>
<pre><code>month_dict = {"jan" : "January", "feb" : "February" .... }
</code></pre>
<blockquote>
<blockquote>
<blockquote>
<p>month_dict["jan"]</p>
<p>'January'</p>
</blockquote>
</blockquote>
</blockquote>
| 1 | 2016-10-17T00:20:43Z | [
"python",
"datetime"
] |
Convert python abbreviated month name to full name | 40,076,887 | <p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
| 3 | 2016-10-17T00:13:27Z | 40,076,928 | <p>If you insist on using <code>datetime</code> as per your tags, you can convert the short version of the month to a datetime object, then reformat it with the full name:</p>
<pre><code>import datetime
datetime.datetime.strptime('apr','%b').strftime('%B')
</code></pre>
| 3 | 2016-10-17T00:20:50Z | [
"python",
"datetime"
] |
Subsets and Splits