title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Find personal Dropbox folder path with Python | 38,943,239 | <p>I have found <a href="http://stackoverflow.com/questions/12118162/how-can-i-get-the-dropbox-folder-location-programmatically-in-python">this thread</a>. The answer suggested there works on my Mac, but not my Windows machine.</p>
<p>The last comment on the accepted answer mentions that "The dropbox host.db file doesn't exist anymore in latest version." so it seems the solution doesn't work anymore.</p>
<p>I've also found <a href="https://www.dropbox.com/help/4584" rel="nofollow">this official guide</a>, but the suggested code gives me an error</p>
<pre><code>import json
from pprint import pprint
with open('%LOCALAPPDATA%\Dropbox\info.json') as data_file:
data = json.load(data_file)
pprint(data)
</code></pre>
<p>Error: <code>IOError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Dropbox\\info.json'</code></p>
<p>An additional complication is that I have a personal and professional dropbox account on each machine. The personal folder is called 'Dropbox (Personal)'.</p>
<p>Any pointers on how to find this folder path on any machine where I've synced my Dropbox?</p>
| 0 | 2016-08-14T14:33:32Z | 38,943,334 | <p>Either install the pip package: <a href="http://ginstrom.com/code/winpaths.html" rel="nofollow">winpaths</a> and then do:</p>
<pre><code>import winpaths
appdata_path = winpaths.get_local_appdata()
</code></pre>
<p>or, do:</p>
<pre><code>import os
appdata_path = os.getenv('LOCALAPPDATA')
</code></pre>
<p>and then, eventually:</p>
<pre><code>with open(os.path.join(appdata_path, 'Dropbox', 'info.json')) as data_file:
</code></pre>
<p>If you want to try out App Data directory instead of Local App Data directory, then in the above code, replace <code>LOCALAPPDATA</code> with <code>APPDATA</code> or <code>get_local_appdata()</code> with <code>get_appdata()</code></p>
| 2 | 2016-08-14T14:46:20Z | [
"python",
"dropbox"
] |
Conditional List comprehension for tuples when length more than one | 38,943,315 | <p>I have a sentence with tuples which indicate the positions of where there is either a country or a number:</p>
<pre><code>sample = In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>And then:</p>
<pre><code>tokenIDs2number = {(22,): 592.00, (25,): 92630.00,(34,): 7734.00}
tokenIDs2location = {(8,9): Hong Kong}
</code></pre>
<p>I need to for different combinations of these tuples, create various combinations of sentences which I call slot sentences:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , NUMBER_SLOT passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than NUMBER_SLOT tons of cargo.
</code></pre>
<p>However, my current code essentially takes combinations of the elements within the tuples, so I have two sentences like:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT Kong 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 Hong LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>As an example.</p>
<p>How do I solve this so that when I have a tuple key of <code>len>1</code>, I fill in all slots in that key as one LOCATION or NUMBER slot as per my desire?</p>
<p>Current code:</p>
<pre><code> for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
sentenceDict = {}
sentenceDict["sentence"] = sample
sentenceDict["location-value-pair"] = {location:number}
for locationTokenID in locationTokenIDs:
for numberTokenID in numberTokenIDs:
finalTokens = cleanSample.split()
finalTokens[numberTokenID] = "NUMBER_SLOT"
finalTokens[locationTokenID] = "LOCATION_SLOT"
slotSentence = (" ").join(finalTokens)
sentenceDict["parsedSentence"] = slotSentence
</code></pre>
<p>Note, I have to create a dictionary that also keeps track of the location-value pair and the original sentence for each slot sentence combination . The key part is generating the right <code>slotSentence</code>.</p>
<p>Note this is only one example, the numbers may even be <code>24000000</code> where the value in the sentence was <code>24 million</code>, same trillion, million, billion and thousand.</p>
<p><strong>If this is impossible, one other option would be to fill in all slots in the combination</strong>:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p><strong>And then perhaps adapt the sentence to remove consecutive slots, but my preference would be to do everything in one shot.</strong></p>
| -1 | 2016-08-14T14:44:05Z | 38,944,057 | <p>The code is treating each locationTokenID as a slot, when the locationTokenIDs really represent endpoints of a slice of tokens that should be treated as a slot. So we need to remove the <code>for locationTokenID in locationTokenIDs:</code> loop (which loops over each locationTokenID as if it were a slot), and replace the corresponding slice of words defined by the pair of locationTokenIDs with a single slot. </p>
<p>The following code solves the problem addressed in the OP, though other problems remain (such as only the last generated <code>slotSentence</code> is being retained; I will let you address this as I do not know what data structures you want to store the slot sentences in):</p>
<pre><code>sample = "In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than 7,734 tons of cargo."
tokenIDs2number = {(21,): 592, (24,): 92630,(30,): 7734}
tokenIDs2location = {(7,8): 'Hong Kong'}
for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
sentenceDict = {}
sentenceDict["sentence"] = sample
sentenceDict["location-value-pair"] = {location:number}
for numberTokenID in numberTokenIDs:
finalTokens = sample.split()
finalTokens[numberTokenID] = "NUMBER_SLOT"
finalTokens[locationTokenIDs[0]:(locationTokenIDs[1]+1)] = "LOCATION_SLOT"
slotSentence = (" ").join(finalTokens)
sentenceDict["parsedSentence"] = slotSentence
print(slotSentence)
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p><p>In the first 11 months of 2004 <strong>L O C A T I O N _ S L O T</strong> 's
international airport at Chek Lap Kok handled daily an average of
<strong>NUMBER_SLOT</strong> flights , 92,630 passengers , and more than 7,734 tons of
cargo.
</p> <p>In the first 11 months of 2004 <strong>L O C A T I O N _ S L O T</strong>
's international airport at Chek Lap Kok handled daily an average of
592 flights , <strong>NUMBER_SLOT</strong> passengers , and more than 7,734 tons of
cargo.</p> <p>In the first 11 months of 2004 <strong>L O C A T I O N _ S L O T</strong>
's international airport at Chek Lap Kok handled daily an average of
592 flights , 92,630 passengers , and more than <strong>NUMBER_SLOT</strong> tons of
cargo.</p></p>
</blockquote>
<p>This can be extended to work for locations and numbers containing any number of spaces. We implement this by having both numberTokenIDs and locationTokenIDs be a 2-length tuple specifying a range of tokens for each location/number:</p>
<pre><code>sample = "In the first 11 months of 2004 Hong Kong Central 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92 630 passengers , and more than 7 734 tons of cargo."
tokenIDs2number = {(22,22): '592', (25,26): '92 630',(32,33): '7 734'}
tokenIDs2location = {(7,9): 'Hong Kong Central'}
for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
finalTokens = sample.split()
finalTokens[numberTokenIDs[0]:(numberTokenIDs[1]+1)] = "NUMBER_SLOT"
finalTokens[locationTokenIDs[0]:(locationTokenIDs[1]+1)] = "LOCATION_SLOT"
slotSentence = (" ").join(finalTokens)
print(slotSentence)
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>In the first 11 months of 2004 **L O C A T I O N _ S L O T** 's
international airport at Chek Lap Kok handled daily an average of 592
flights , **N U M B E R _ S L O T** passengers , and more than 7 734 tons
of cargo.</p>
<p>In the first 11 months of 2004 **L O C A T I O N _ S L O T** 's
international airport at Chek Lap Kok handled daily an average of 592
flights , 92 630 passengers , and more than **N U M B E R _ S L O T** tons
of cargo.</p>
<p>In the first 11 months of 2004 **L O C A T I O N _ S L O T** 's
international airport at Chek Lap Kok handled daily an average of **N U
M B E R _ S L O T** flights , 92 630 passengers , and more than 7 734
tons of cargo.</p>
</blockquote>
| 0 | 2016-08-14T16:08:40Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Conditional List comprehension for tuples when length more than one | 38,943,315 | <p>I have a sentence with tuples which indicate the positions of where there is either a country or a number:</p>
<pre><code>sample = In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>And then:</p>
<pre><code>tokenIDs2number = {(22,): 592.00, (25,): 92630.00,(34,): 7734.00}
tokenIDs2location = {(8,9): Hong Kong}
</code></pre>
<p>I need to for different combinations of these tuples, create various combinations of sentences which I call slot sentences:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , NUMBER_SLOT passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than NUMBER_SLOT tons of cargo.
</code></pre>
<p>However, my current code essentially takes combinations of the elements within the tuples, so I have two sentences like:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT Kong 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 Hong LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>As an example.</p>
<p>How do I solve this so that when I have a tuple key of <code>len>1</code>, I fill in all slots in that key as one LOCATION or NUMBER slot as per my desire?</p>
<p>Current code:</p>
<pre><code> for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
sentenceDict = {}
sentenceDict["sentence"] = sample
sentenceDict["location-value-pair"] = {location:number}
for locationTokenID in locationTokenIDs:
for numberTokenID in numberTokenIDs:
finalTokens = cleanSample.split()
finalTokens[numberTokenID] = "NUMBER_SLOT"
finalTokens[locationTokenID] = "LOCATION_SLOT"
slotSentence = (" ").join(finalTokens)
sentenceDict["parsedSentence"] = slotSentence
</code></pre>
<p>Note, I have to create a dictionary that also keeps track of the location-value pair and the original sentence for each slot sentence combination . The key part is generating the right <code>slotSentence</code>.</p>
<p>Note this is only one example, the numbers may even be <code>24000000</code> where the value in the sentence was <code>24 million</code>, same trillion, million, billion and thousand.</p>
<p><strong>If this is impossible, one other option would be to fill in all slots in the combination</strong>:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p><strong>And then perhaps adapt the sentence to remove consecutive slots, but my preference would be to do everything in one shot.</strong></p>
| -1 | 2016-08-14T14:44:05Z | 38,944,112 | <p>Consider using <code>str.replace()</code> instead of splitting and slicing the sentence string. In order to so do, you need to convert the elements in <code>tokenID2number</code> with thousands separator which as @JonClements comments can be handled with <code>format(int, ',')</code> for Python 2.7+:</p>
<pre><code>sample = "In the first 11 months of 2004 Hong Kong 's international airport " + \
"at Chek Lap Kok handled daily an average of 592 flights " + \
"92,630 passengers , and more than 7,734 tons of cargo."
tokenIDs2number = {(22,): 592, (25,): 92630,(34,): 7734}
tokenIDs2location = {(8,9): 'Hong Kong'}
sentenceList = []
# ITERATE ACROSS A LIST COMPREHENSION FOR ALL POSSIBLE COMBINATIONS
for item in [[s,i,j] for s in [sample] \
for i in tokenIDs2location.items() \
for j in tokenIDs2number.items()]:
sentenceDict = {}
sentenceDict["sentence"] = item[0]
sentenceDict["location-value-pair"] = {item[1][1]: item[2][1]}
sentenceDict["parsedSentence"] = sample.replace(item[1][1], 'LOCATION_SLOT').\
replace(format(item[2][1], ','), 'NUMBER_SLOT')
sentenceList.append(sentenceDict)
</code></pre>
<p><strong>Output</strong> <em>(of sentenceList)</em></p>
<pre><code>[{'sentence': "In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights 92,630 passengers , and more than 7,734 tons of cargo.", 'parsedSentence': "In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights 92,630 passengers , and more than NUMBER_SLOT tons of cargo.", 'location-value-pair': {'Hong Kong': 7734}}
{'sentence': "In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights 92,630 passengers , and more than 7,734 tons of cargo.", 'parsedSentence': "In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights 92,630 passengers , and more than 7,734 tons of cargo.", 'location-value-pair': {'Hong Kong': 592}}
{'sentence': "In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights 92,630 passengers , and more than 7,734 tons of cargo.", 'parsedSentence': "In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights NUMBER_SLOT passengers , and more than 7,734 tons of cargo.", 'location-value-pair': {'Hong Kong': 92630}}]
</code></pre>
| 0 | 2016-08-14T16:16:17Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Conditional List comprehension for tuples when length more than one | 38,943,315 | <p>I have a sentence with tuples which indicate the positions of where there is either a country or a number:</p>
<pre><code>sample = In the first 11 months of 2004 Hong Kong 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>And then:</p>
<pre><code>tokenIDs2number = {(22,): 592.00, (25,): 92630.00,(34,): 7734.00}
tokenIDs2location = {(8,9): Hong Kong}
</code></pre>
<p>I need to for different combinations of these tuples, create various combinations of sentences which I call slot sentences:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , NUMBER_SLOT passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of 592 flights , 92,630 passengers , and more than NUMBER_SLOT tons of cargo.
</code></pre>
<p>However, my current code essentially takes combinations of the elements within the tuples, so I have two sentences like:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT Kong 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
In the first 11 months of 2004 Hong LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p>As an example.</p>
<p>How do I solve this so that when I have a tuple key of <code>len>1</code>, I fill in all slots in that key as one LOCATION or NUMBER slot as per my desire?</p>
<p>Current code:</p>
<pre><code> for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
sentenceDict = {}
sentenceDict["sentence"] = sample
sentenceDict["location-value-pair"] = {location:number}
for locationTokenID in locationTokenIDs:
for numberTokenID in numberTokenIDs:
finalTokens = cleanSample.split()
finalTokens[numberTokenID] = "NUMBER_SLOT"
finalTokens[locationTokenID] = "LOCATION_SLOT"
slotSentence = (" ").join(finalTokens)
sentenceDict["parsedSentence"] = slotSentence
</code></pre>
<p>Note, I have to create a dictionary that also keeps track of the location-value pair and the original sentence for each slot sentence combination . The key part is generating the right <code>slotSentence</code>.</p>
<p>Note this is only one example, the numbers may even be <code>24000000</code> where the value in the sentence was <code>24 million</code>, same trillion, million, billion and thousand.</p>
<p><strong>If this is impossible, one other option would be to fill in all slots in the combination</strong>:</p>
<pre><code>In the first 11 months of 2004 LOCATION_SLOT LOCATION_SLOT 's international airport at Chek Lap Kok handled daily an average of NUMBER_SLOT flights , 92,630 passengers , and more than 7,734 tons of cargo.
</code></pre>
<p><strong>And then perhaps adapt the sentence to remove consecutive slots, but my preference would be to do everything in one shot.</strong></p>
| -1 | 2016-08-14T14:44:05Z | 38,950,662 | <p>I have solved my use case but using a roundabout way.</p>
<p>I first allow for slot sentences which contain multiple <code>LOCATION_SLOT</code> or <code>NUMBER_SLOT</code> - if one tuple in the combo contains 2 or more slots, I fill in all:</p>
<pre><code>sentences2location2values = []
for locationTokenIDs, location in tokenIDs2location.items():
for numberTokenIDs, number in tokenIDs2number.items():
sentenceDict = {}
sentenceDict["sentence"] = sample
sentenceDict["location-value-pair"] = {location:number}
for locationTokenID in locationTokenIDs:
sampleTokens[locationTokenID] = "LOCATION_SLOT"
for numberTokenID in numberTokenIDs:
sampleTokens[numberTokenID] = "NUMBER_SLOT"
slotSentence = (" ").join(sampleTokens)
sentenceDict["parsedSentence"] = slotSentence
sentences2location2values.append(sentenceDict)
</code></pre>
<p>Then, I change the parsed sentences to remove consecutive location and number slots:</p>
<pre><code>for i,sentence in enumerate(sentences2location2values):
sampleTokens = sentence['parsedSentence'].split()
newTokens = []
for i,token in enumerate(sampleTokens):
if i>0 and ((token == "LOCATION_SLOT" and sampleTokens[i-1]=="LOCATION_SLOT") or (token == "NUMBER_SLOT" and sampleTokens[i-1]=="NUMBER_SLOT")):
continue
else:
newTokens.append(token)
sentence['parsedSentence']=(' ').join(newTokens)
</code></pre>
| 0 | 2016-08-15T07:06:16Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Python Rest API - looping through dictionary object | 38,943,339 | <p>Python newbie here</p>
<p>I am querying an API and get a json string like this:</p>
<pre><code>{
"human": [
{
"h": 310,
"prob": 0.9588886499404907,
"w": 457,
"x": 487,
"y": 1053
},
{
"h": 283,
"prob": 0.8738606572151184,
"w": 455,
"x": 1078,
"y": 1074
},
{
"h": 216,
"prob": 0.8639854788780212,
"w": 414,
"x": 1744,
"y": 1159
},
{
"h": 292,
"prob": 0.7896996736526489,
"w": 442,
"x": 2296,
"y": 1088
}
]
}
</code></pre>
<p>I figured out how to get a dict object in python</p>
<p><code>json_data = json.loads(response.text)</code></p>
<p>But I am not sure how to loop through the dict object. I have tried this, but this prints out the key repeatedly, how do I access the parent object and child objects?</p>
<pre><code> for data in json_data:
print data
for sub in data:
print sub
</code></pre>
| 0 | 2016-08-14T14:46:53Z | 38,943,372 | <p>See the following examples:</p>
<pre><code>print json_data['human']
>> [
{
"h": 310,
"prob": 0.9588886499404907,
"w": 457,
"x": 487,
"y": 1053
},
{
"h": 283,
"prob": 0.8738606572151184,
"w": 455,
"x": 1078,
"y": 1074
},
.
.
]
for data in json_data['human']:
print data
>> {
"h": 310,
"prob": 0.9588886499404907,
"w": 457,
"x": 487,
"y": 1053
}
{
"h": 283,
"prob": 0.8738606572151184,
"w": 455,
"x": 1078,
"y": 1074
}
.
.
for data in json_data['human']:
print data['h']
>> 310
283
</code></pre>
<p>In order to loop through the keys:</p>
<pre><code>for type_ in json_data:
print type_
for location in json_data[type_]:
print location
</code></pre>
<p><code>type_</code> is used to avoid Python's built-it <code>type</code>. You can use whatever name you see fit.</p>
| 1 | 2016-08-14T14:50:58Z | [
"python",
"json",
"rest",
"dictionary"
] |
Python Rest API - looping through dictionary object | 38,943,339 | <p>Python newbie here</p>
<p>I am querying an API and get a json string like this:</p>
<pre><code>{
"human": [
{
"h": 310,
"prob": 0.9588886499404907,
"w": 457,
"x": 487,
"y": 1053
},
{
"h": 283,
"prob": 0.8738606572151184,
"w": 455,
"x": 1078,
"y": 1074
},
{
"h": 216,
"prob": 0.8639854788780212,
"w": 414,
"x": 1744,
"y": 1159
},
{
"h": 292,
"prob": 0.7896996736526489,
"w": 442,
"x": 2296,
"y": 1088
}
]
}
</code></pre>
<p>I figured out how to get a dict object in python</p>
<p><code>json_data = json.loads(response.text)</code></p>
<p>But I am not sure how to loop through the dict object. I have tried this, but this prints out the key repeatedly, how do I access the parent object and child objects?</p>
<pre><code> for data in json_data:
print data
for sub in data:
print sub
</code></pre>
| 0 | 2016-08-14T14:46:53Z | 38,943,399 | <p>I think you want to use iteritems to get the keys and values from your dictionary like this:</p>
<pre><code>for k, v in json_data.iteritems():
print "{0} : {1}".format(k, v)
</code></pre>
<p>If you instead meant to traverse the dictionary recursively, try something like this:</p>
<pre><code>def traverse(d):
for k, v in d.iteritems():
if isinstance(v, dict):
traverse(v)
else:
print "{0} : {1}".format(k, v)
traverse(json_data)
</code></pre>
| 3 | 2016-08-14T14:54:20Z | [
"python",
"json",
"rest",
"dictionary"
] |
Download files from an FTP server containing given string using python | 38,943,398 | <p>I'm trying to download a large number of files that all share a common string ('DEM') from an ftp sever. These files are nested inside multiple directories. For example, 'Adair>DEM*' and 'Adams>DEM*' </p>
<p>The FTP sever is located here:<a href="ftp://ftp.igsb.uiowa.edu/gis_library/counties/" rel="nofollow">ftp://ftp.igsb.uiowa.edu/gis_library/counties/</a> and requires no username and password.
So, I'd like to go through each county and download the files containing the string 'DEM'</p>
<p>I've read many questions here on stack and the documentation from python, but cannot figure out how to use ftplib.FTP() to get into the site without a username and password (which is not required), and I can't figure out how to grep or use glob.glob inside of ftplib or urllib.</p>
<p>Thanks in advance for your help</p>
| 1 | 2016-08-14T14:53:58Z | 38,943,548 | <p>Ok, seems to work. There may be issues if trying to download a directory, or scan a file. Exception handling may come handy to trap wrong filetypes and skip.</p>
<p><code>glob.glob</code> cannot work since you're on a remote filesystem, but you can use <code>fnmatch</code> to match the names</p>
<p>Here's the code: it download all files matching <code>*DEM*</code> in TEMP directory, sorting by directory.</p>
<pre><code>import ftplib,sys,fnmatch,os
output_root = os.getenv("TEMP")
fc = ftplib.FTP("ftp.igsb.uiowa.edu")
fc.login()
fc.cwd("/gis_library/counties")
root_dirs = fc.nlst()
for l in root_dirs:
sys.stderr.write(l + " ...\n")
#print(fc.size(l))
dir_files = fc.nlst(l)
local_dir = os.path.join(output_root,l)
if not os.path.exists(local_dir):
os.mkdir(local_dir)
for f in dir_files:
if fnmatch.fnmatch(f,"*DEM*"): # cannot use glob.glob
sys.stderr.write("downloading "+l+"/"+f+" ...\n")
local_filename = os.path.join(local_dir,f)
fh = open(local_filename, 'wb')
fc.retrbinary('RETR '+ l + "/" + f, fh.write)
fc.close()
</code></pre>
| 1 | 2016-08-14T15:11:39Z | [
"python",
"ftp",
"file-processing"
] |
Creating new numpy arrays based on condition | 38,943,403 | <p>I have 2 numpy arrays:</p>
<pre><code>aa = np.random.rand(5,5)
bb = np.random.rand(5,5)
</code></pre>
<p>How can I create a new array which has a value of 1 when both aa and bb exceed 0.5?</p>
| 2 | 2016-08-14T14:54:37Z | 38,943,482 | <p>What about this?</p>
<pre><code>import numpy as np
aa = np.random.rand(5, 5)
bb = np.random.rand(5, 5)
print aa
print bb
cc = 1 * ((aa > 0.5) & (bb > 0.5))
print cc
</code></pre>
| 3 | 2016-08-14T15:04:19Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Creating new numpy arrays based on condition | 38,943,403 | <p>I have 2 numpy arrays:</p>
<pre><code>aa = np.random.rand(5,5)
bb = np.random.rand(5,5)
</code></pre>
<p>How can I create a new array which has a value of 1 when both aa and bb exceed 0.5?</p>
| 2 | 2016-08-14T14:54:37Z | 38,943,530 | <p>when element of aa and bb at index i is exceed than 0.5 then new array
have 1 at index i </p>
<pre><code>aa = np.random.rand(5,5)
bb = np.random.rand(5,5)
new_arr = []
for i in range(5):
for j in range(5):
if aa[i] >0.5 and bb[i]>0.5:
new_arr[i] = 1
else:
new_arr[i] = "any Value You want
</code></pre>
| -3 | 2016-08-14T15:09:57Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Creating new numpy arrays based on condition | 38,943,403 | <p>I have 2 numpy arrays:</p>
<pre><code>aa = np.random.rand(5,5)
bb = np.random.rand(5,5)
</code></pre>
<p>How can I create a new array which has a value of 1 when both aa and bb exceed 0.5?</p>
| 2 | 2016-08-14T14:54:37Z | 38,988,035 | <p>With focus on performance and using two methods few aproaches could be added. One method would be to get the boolean array of valid ones and converting to <code>int</code> datatype with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow"><code>.astype() method</code></a>. Another way could involve using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> that lets us select between <code>0</code> and <code>1</code> based on the same boolean array. Thus, essentially we would have two methods, one that harnesses efficient datatype conversion and another that uses selection criteria. Now, the boolean array could be obtained in two ways - One using simple comparison and another using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow"><code>np.logical_and</code></a>. So, with two ways to get the boolean array and two methods to convert the boolean array to <code>int</code> array, we would end up with four implementations as listed below -</p>
<pre><code>out1 = ((aa>0.5) & (bb>0.5)).astype(int)
out2 = np.logical_and(aa>0.5, bb>0.5).astype(int)
out3 = np.where((aa>0.5) & (bb>0.5),1,0)
out4 = np.where(np.logical_and(aa>0.5, bb>0.5), 1, 0)
</code></pre>
<p>You can play around with the datatypes to use less precision types, which shouldn't hurt as we are setting the values to <code>0</code> and <code>1</code> anyway. The benefit should be noticeable speedup as it leverages memory efficiency. We could use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow"><code>int8</code>, <code>uint8</code>, <code>np.int8</code>, <code>np.uint8</code> types</a>. Thus, the variants of the earlier listed approaches using the new <code>int</code> datatypes would be -</p>
<pre><code>out5 = ((aa>0.5) & (bb>0.5)).astype('int8')
out6 = np.logical_and(aa>0.5, bb>0.5).astype('int8')
out7 = ((aa>0.5) & (bb>0.5)).astype('uint8')
out8 = np.logical_and(aa>0.5, bb>0.5).astype('uint8')
out9 = ((aa>0.5) & (bb>0.5)).astype(np.int8)
out10 = np.logical_and(aa>0.5, bb>0.5).astype(np.int8)
out11 = ((aa>0.5) & (bb>0.5)).astype(np.uint8)
out12 = np.logical_and(aa>0.5, bb>0.5).astype(np.uint8)
</code></pre>
<p>Runtime test (as we are focusing on performance with this post) -</p>
<pre><code>In [17]: # Input arrays
...: aa = np.random.rand(1000,1000)
...: bb = np.random.rand(1000,1000)
...:
In [18]: %timeit ((aa>0.5) & (bb>0.5)).astype(int)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(int)
...: %timeit np.where((aa>0.5) & (bb>0.5),1,0)
...: %timeit np.where(np.logical_and(aa>0.5, bb>0.5), 1, 0)
...:
100 loops, best of 3: 9.13 ms per loop
100 loops, best of 3: 9.16 ms per loop
100 loops, best of 3: 10.4 ms per loop
100 loops, best of 3: 10.4 ms per loop
In [19]: %timeit ((aa>0.5) & (bb>0.5)).astype('int8')
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype('int8')
...: %timeit ((aa>0.5) & (bb>0.5)).astype('uint8')
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype('uint8')
...:
...: %timeit ((aa>0.5) & (bb>0.5)).astype(np.int8)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(np.int8)
...: %timeit ((aa>0.5) & (bb>0.5)).astype(np.uint8)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(np.uint8)
...:
100 loops, best of 3: 5.6 ms per loop
100 loops, best of 3: 5.61 ms per loop
100 loops, best of 3: 5.63 ms per loop
100 loops, best of 3: 5.63 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.61 ms per loop
In [20]: %timeit 1 * ((aa > 0.5) & (bb > 0.5)) #@BPL's vectorized soln
100 loops, best of 3: 10.2 ms per loop
</code></pre>
| 4 | 2016-08-17T04:16:18Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Django forms selecting data based on request user | 38,943,555 | <p>I am developing a django application which has a form for creating ingredients. The form contains a dropdown for selecting Recipes. When a user creates an ingredient, in the dropdown, I want that only those recipes should appear that are created by the same user. </p>
<p>Here is my code:</p>
<pre><code>#forms.py
class IngredientForm(forms.ModelForm):
primal = forms.BooleanField()
class Meta:
model = Ingredient
fields = ('recipe_id', 'title', 'instructions', 'rules')
#models.py
class Recipe(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length=500)
description = models.TextField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
def __str__(self):
return self.title
class Ingredient(models.Model):
user = models.ForeignKey('auth.User')
recipe_id = models.ForeignKey(Recipe, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
instructions = models.CharField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
primal = models.CharField(default='0',max_length=500,blank=True)
def __str__(self):
return self.title
#views.py
def create_ingredient(request):
if request.method == 'POST':
form = IngredientForm(request.POST)
if form.is_valid():
current_user = request.user
data = form.cleaned_data
ingredient_data=Ingredient.objects.create(user=current_user, recipe_id=data['recipe_id'],title=data['title'], primal=data['primal'], instructions=data['instructions'], rules=data['rules'])
ingredient_data.save()
ingredient = Ingredient.objects.get(pk = ingredient_data.pk)
return redirect('ingredient_detail', pk=ingredient.pk)
else:
messages.error(request, "Error")
return render(request, 'create_ingredient.html', {'form': IngredientForm })
</code></pre>
<p>The problem is that right now, when the user tries to select a recipe, the recipes created by all users of the site appear in the 'recipe_id' dropdown. He should only be able to see recipes in the dropdown that are created by himself. Any ideas how to do it?</p>
<p>UPDATE FROM ANSWER:</p>
<p>If I use this:</p>
<pre><code>...
if request.method == 'POST':
form = IngredientForm(current_user=request.user, request.POST)
if form.is_valid():
...
</code></pre>
<p>it gives me this syntax error: <code>non-keyword arg after keyword arg</code> in this line <code>form = IngredientForm(current_user=request.user, request.POST)</code></p>
<p>UPDATE#2:</p>
<p>If I use:</p>
<pre><code>...
if request.method == 'POST':
form = IngredientForm( request.POST,current_user=request.user)
if form.is_valid():
...
</code></pre>
<p>It gives me error: <code>__init__() got multiple values of argument 'current.user'</code></p>
<p>If I use:</p>
<pre><code>...
if request.method == 'POST':
form = IngredientForm( request.POST)
if form.is_valid():
...
</code></pre>
<p>It gives me error: <code>'QueryDict' object has no attribute 'id'</code></p>
<p>UPDATE # 3:</p>
<p>After implementing the latest update from answer. It gives me error <code>name 'current_user' is not defined</code>
in the following piece of code:</p>
<pre><code>def create_ingredient(request):
form = IngredientForm(current_user=request.user)
</code></pre>
| 0 | 2016-08-14T15:12:24Z | 38,943,659 | <p>In the model form you can do this:</p>
<pre><code>class IngredientForm(ModelForm):
primal = forms.BooleanField()
class Meta:
model = Ingredient
fields = ('recipe_id', 'title', 'instructions', 'rules')
def __init__(self, current_user, *args, **kwargs):
super(IngredientForm, self).__init__(*args, **kwargs)
self.fields['recipe_id'].queryset = self.fields['recipe_id'].queryset.filter(user=current_user.id)
</code></pre>
<p>then instantiate the form like so</p>
<pre><code>form = IngredientForm(current_user=request.user)
</code></pre>
<p>EDIT #1:</p>
<p>Passing in the user to the POST request form:</p>
<pre><code>if request.method == "POST":
form = IngredientForm(request.POST, current_user=request.user)
if form.is_valid():
....
</code></pre>
<p>EDIT #2:</p>
<p>Try changing the init decleration to what is below and pop the user from the kwargs:</p>
<pre><code>def __init__(self, *args, **kwargs):
current_user = kwargs.pop('current_user', None)
super(IngredientForm, self).__init__(*args, **kwargs)
if current_user:
self.fields['recipe_id'].queryset = self.fields['recipe_id'].queryset.filter(user=current_user.id)
</code></pre>
<p>I think this might solve your problems, leave the rest of the code the same as my answer above (where you create the forms)</p>
| 1 | 2016-08-14T15:24:46Z | [
"python",
"django",
"django-forms"
] |
Append additional values to queryset in Django generic views before handing to template | 38,943,658 | <p>I have the following view:</p>
<pre><code>class AppointmentListView(LoginRequiredMixin, ListView):
queryset = Appointment.objects.prefetch_related('client','patients')
</code></pre>
<p>I need to be able to add an extra variable to each returned Appointment object based on the following:</p>
<pre><code>status_choices={
'STATUS_UPCOMING':'default',
'STATUS_ARRIVED':'primary',
'STATUS_IN_CONSULT': 'success',
'STATUS_WAITING_TO_PAY':'info',
'STATUS_PAYMENT_COMPLETE':'warning',
}
</code></pre>
<p>The values ('default', 'primary' etc) correspond to standard css classesin Bootcamp themes that I want to use according to the type of Appointment. For example, 'default' produces a gray button, 'warning' a red button etc.</p>
<p>I need to map each Appointment record to a certain css button based on the record's status ('upcoming' would display the 'default' class etc).</p>
<p>My initial idea was to loop over the query set and build a separate array/dictionary mapping the Appointment pk to a given css class such as
<code>1:'success', 2:'warning'</code>, and then pass that in as a context variable.</p>
<p>But I was wondering if I could just add the value to each Appointment object directly (perhaps saving the queryset as a list?) That would be a much cleaner solution but am not sure how that should be approached.</p>
<p>Any ideas much appreciated</p>
| 0 | 2016-08-14T15:24:30Z | 38,943,769 | <p>You should overload the get_queryset method of the ListView like so</p>
<pre><code>def get_queryset(self, **kwargs):
queryset = super(AppointmentListView, self).get_queryset(**kwargs)
# Add new elements here
...
return queryset
</code></pre>
| 1 | 2016-08-14T15:35:16Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Append additional values to queryset in Django generic views before handing to template | 38,943,658 | <p>I have the following view:</p>
<pre><code>class AppointmentListView(LoginRequiredMixin, ListView):
queryset = Appointment.objects.prefetch_related('client','patients')
</code></pre>
<p>I need to be able to add an extra variable to each returned Appointment object based on the following:</p>
<pre><code>status_choices={
'STATUS_UPCOMING':'default',
'STATUS_ARRIVED':'primary',
'STATUS_IN_CONSULT': 'success',
'STATUS_WAITING_TO_PAY':'info',
'STATUS_PAYMENT_COMPLETE':'warning',
}
</code></pre>
<p>The values ('default', 'primary' etc) correspond to standard css classesin Bootcamp themes that I want to use according to the type of Appointment. For example, 'default' produces a gray button, 'warning' a red button etc.</p>
<p>I need to map each Appointment record to a certain css button based on the record's status ('upcoming' would display the 'default' class etc).</p>
<p>My initial idea was to loop over the query set and build a separate array/dictionary mapping the Appointment pk to a given css class such as
<code>1:'success', 2:'warning'</code>, and then pass that in as a context variable.</p>
<p>But I was wondering if I could just add the value to each Appointment object directly (perhaps saving the queryset as a list?) That would be a much cleaner solution but am not sure how that should be approached.</p>
<p>Any ideas much appreciated</p>
| 0 | 2016-08-14T15:24:30Z | 38,950,497 | <p>I got this working by overriding get_queryset() and giving the objects (i.e. each row in the db) an extra on-the-fly key/value:</p>
<pre><code>class AppointmentListView(LoginRequiredMixin,ListView):
#friendly template context
context_object_name = 'appointments'
template_name = 'appointments/appointment_list.html'
def get_queryset(self):
qs = Appointment.objects.prefetch_related('client','patients')
for r in qs:
if r.status == r.STATUS_UPCOMING: r.css_button_class = 'default'
if r.status == r.STATUS_ARRIVED: r.css_button_class = 'warning'
if r.status == r.STATUS_IN_CONSULT: r.css_button_class = 'success'
if r.status == r.STATUS_WAITING_TO_PAY: r.css_button_class = 'danger'
if r.status == r.STATUS_PAYMENT_COMPLETE: r.css_button_class = 'info'
return list(qs)
</code></pre>
<p>A couple of things:</p>
<ol>
<li><p>I converted the queryset <code>qs</code> to a <strong>list</strong> to 'freeze' it. This prevents the queryset from being re-evaluated (e.g. slice) which, in turn, would cause the on-the-fly model changes to be lost as fresh data is pulled from DB.</p></li>
<li><p>I needed to assign a value to <code>template_name</code> explicitly. When overriding get_queryset the template name is not derived automagically. As a comparison, the code below whose <code>queryset</code> attribute is set, generates the template name automatically:</p>
<pre><code>class AppointmentListView(LoginRequiredMixin, ListView):
queryset = Appointment.objects.prefetch_related('client', 'patients')
#template name FOO_list derived automatically
#appointments/views.py
...
#can use derived name (FOO_list)
{% for appointment in appointment_list %}
...
</code></pre></li>
</ol>
| 0 | 2016-08-15T06:50:04Z | [
"python",
"django",
"django-templates",
"django-views"
] |
NotImplementedError when using Postgres search in Django 1.10 | 38,943,668 | <p>I'm using the full text search for Postgres offered by Django 1.10 and getting a NotImplementedError. The search query I'm using is:</p>
<pre><code>Application.objects.filter(applicant_data__search='test')
</code></pre>
<p>The error is:</p>
<pre><code>NotImplementedError: Add 'django.contrib.postgres' to settings.INSTALLED_APPS to use the search operator.
</code></pre>
<p>My INSTALLED_APPS setting includes django.contrib.postgres:</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
'main',
]
</code></pre>
<p>I'm using psycopg2 for my db engine:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'username',
'PASSWORD': '',
'HOST': 'localhost',
}
}
</code></pre>
<p>My model is:</p>
<pre><code>class Application(models.Model):
applicant_data = JSONField()
</code></pre>
<p>When I run get_app_config from the django shell, the postgres app returns correct values:</p>
<pre><code>from django.apps import apps
apps.get_app_config('postgres').name
'django.contrib.postgres'
</code></pre>
<p>The function throwing the NotImplementedError is the fulltext_search_sql from django.db.backends.postgres, so my guess is that django.contrib.postgres is either not being loaded correctly or is being replaced by the default django postgres backend. </p>
<p>Not sure where to go from here, anyone have a similar issue and/or insights?</p>
| 1 | 2016-08-14T15:25:41Z | 38,962,417 | <p>Figured out the cause of this error - the full text search operator does not work for JSON fields.</p>
| 1 | 2016-08-15T20:17:40Z | [
"python",
"django",
"postgresql"
] |
Write a dictionary containing lists in values into text file with keys repeated for each element in the list | 38,943,673 | <p>I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like: </p>
<pre><code>{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26', 2), ('24', 2)]}.
</code></pre>
<p>as you can see, the values in the dictionary are always lists. I would like to write the below into the text file:
17, 25, 5 \n
17, 23, 3 \n
12, 28, 3 \n
12, 22, 3 \n
13, 28, 3 \n
13, 23, 3 \n
...
\n stands for a new line</p>
<p>Which means, the keys to be repeated for each value inside the list that 'belongs' to those keys. The reason is because I need to read the text file again into database to do further analysis.
Have try searching for an answer for the past few days and tried many ways, just cannot make it into this format. Appreciate if any of you have a solution for this.
Thanks a lot!</p>
| 0 | 2016-08-14T15:25:55Z | 38,943,772 | <pre><code>>>> for k, v in data.items():
... for t in v:
... print "%s, %s, %s" % ((k,) +t)
...
11, 28, 3
11, 29, 1
13, 28, 3
13, 23, 3
12, 28, 3
12, 22, 3
15, 26, 2
15, 24, 2
14, 22, 3
14, 23, 3
17, 25, 5
17, 23, 3
16, 22, 3
16, 21, 3
>>>
</code></pre>
<p>First get each key and value (which are tuples). Then loop through the tuples and print each tuple value with the key. Note that dictionaries are not ordered, so the results will not likely be in the order of your dictionary</p>
| 0 | 2016-08-14T15:35:32Z | [
"python",
"list",
"file",
"dictionary"
] |
Write a dictionary containing lists in values into text file with keys repeated for each element in the list | 38,943,673 | <p>I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like: </p>
<pre><code>{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26', 2), ('24', 2)]}.
</code></pre>
<p>as you can see, the values in the dictionary are always lists. I would like to write the below into the text file:
17, 25, 5 \n
17, 23, 3 \n
12, 28, 3 \n
12, 22, 3 \n
13, 28, 3 \n
13, 23, 3 \n
...
\n stands for a new line</p>
<p>Which means, the keys to be repeated for each value inside the list that 'belongs' to those keys. The reason is because I need to read the text file again into database to do further analysis.
Have try searching for an answer for the past few days and tried many ways, just cannot make it into this format. Appreciate if any of you have a solution for this.
Thanks a lot!</p>
| 0 | 2016-08-14T15:25:55Z | 38,943,809 | <p>Here's a working example showing you how to dump your dictionary to string, first without any particular order and then sorted by keys, pick up what you wish:</p>
<pre><code>data = {
'17': [('25', 5), ('23', 3)],
'12': [('28', 3), ('22', 3)],
'13': [('28', 3), ('23', 3)],
'16': [('22', 3), ('21', 3)],
'11': [('28', 3), ('29', 1)],
'14': [('22', 3), ('23', 3)],
'15': [('26', 2), ('24', 2)]
}
lines = []
for k, v in data.iteritems():
for tupl in v:
row = [k] + map(lambda x: str(x), list(tupl))
lines.append(', '.join(row))
output = '\n'.join(lines)
print output
print '-' * 80
lines = []
for k, v in sorted(data.iteritems()):
for tupl in v:
row = [k] + map(lambda x: str(x), list(tupl))
lines.append(', '.join(row))
sorted_output = '\n'.join(lines)
print sorted_output
</code></pre>
<p><strong>EDIT:</strong></p>
<p>The above code was written to work with python 2.x, here's the 3.x version:</p>
<pre><code>data = {
'17': [('25', 5), ('23', 3)],
'12': [('28', 3), ('22', 3)],
'13': [('28', 3), ('23', 3)],
'16': [('22', 3), ('21', 3)],
'11': [('28', 3), ('29', 1)],
'14': [('22', 3), ('23', 3)],
'15': [('26', 2), ('24', 2)]
}
lines = []
for k, v in data.items():
for tupl in v:
row = [k] + list(map(lambda x: str(x), list(tupl)))
lines.append(', '.join(row))
output = '\n'.join(lines)
print(output)
print('-' * 80)
lines = []
for k, v in sorted(data.items()):
for tupl in v:
row = [k] + list(map(lambda x: str(x), list(tupl)))
lines.append(', '.join(row))
sorted_output = '\n'.join(lines)
print(sorted_output)
</code></pre>
| 0 | 2016-08-14T15:40:51Z | [
"python",
"list",
"file",
"dictionary"
] |
Write a dictionary containing lists in values into text file with keys repeated for each element in the list | 38,943,673 | <p>I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like: </p>
<pre><code>{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26', 2), ('24', 2)]}.
</code></pre>
<p>as you can see, the values in the dictionary are always lists. I would like to write the below into the text file:
17, 25, 5 \n
17, 23, 3 \n
12, 28, 3 \n
12, 22, 3 \n
13, 28, 3 \n
13, 23, 3 \n
...
\n stands for a new line</p>
<p>Which means, the keys to be repeated for each value inside the list that 'belongs' to those keys. The reason is because I need to read the text file again into database to do further analysis.
Have try searching for an answer for the past few days and tried many ways, just cannot make it into this format. Appreciate if any of you have a solution for this.
Thanks a lot!</p>
| 0 | 2016-08-14T15:25:55Z | 38,943,874 | <p>Assuming values of the hash consist of list with tuple of size 2. </p>
<pre><code>>>> f = open('test.txt', 'w')
>>> for key,value in d.iteritems():
... for v in value:
... f.write(key + ' ' + v[0] + ' ' + str(v[1]) + '\n')
...
>>> f.close()
</code></pre>
<p>Values in test.txt will be </p>
<pre><code>11, 28, 3
11, 29, 1
13, 28, 3
13, 23, 3
12, 28, 3
12, 22, 3
15, 26, 2
15, 24, 2
14, 22, 3
14, 23, 3
17, 25, 5
17, 23, 3
16, 22, 3
16, 21, 3
</code></pre>
| 0 | 2016-08-14T15:48:32Z | [
"python",
"list",
"file",
"dictionary"
] |
Integration error in SymPy 1.0 | 38,943,702 | <p>I'm trying to write my mathcad model in python language, but I get some mistake.
The integration function should look like this:</p>
<p><a href="http://i.stack.imgur.com/hqmeQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/hqmeQ.png" alt="http://iscr.ru/photo/1471186985_snimok.PNG"></a></p>
<p>In python I wrote such code</p>
<pre><code> from __future__ import division
import sympy as sp
import numpy as np
import math
from pylab import *
print(sp.__version__)
s = sp.Symbol('s')
x = sp.symbols('x')
t_start = 11
t_info = 1
t_transf = 2
t_stat_analyze = 3
t_repeat = 3.2
P = 0.1
def M1(s):
return P/(t_info*t_start*t_stat_analyze*t_transf*(1 - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_info)*(s + 1/t_start)*(s + 1/t_stat_analyze)*(s + 1/t_transf)**2) + P/( t_info*t_start*t_stat_analyze*t_transf*(1 - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_info)*(s + 1/t_start)*(s + 1/t_stat_analyze)**2*(s + 1/t_transf)) + P/(t_info*t_start*t_stat_analyze*t_transf*(1 - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_info)*(s + 1/t_start)**2*(s + 1/t_stat_analyze)*(s + 1/t_transf)) + P/(t_info*t_start*t_stat_analyze*t_transf*(1 - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/ t_transf)))*(s + 1/t_info)**2*(s + 1/t_start)*(s + 1/t_stat_analyze)*(s + 1/t_transf)) - P*(-(-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)**2) - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)**2*(s + 1/t_transf)))/( t_info*t_start*t_stat_analyze*t_transf*(1 - (-P + 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))**2*(s + 1/t_info)*(s + 1/t_start)*(s + 1/t_stat_analyze)*(s + 1/t_transf))
def M2(s):
return 2*P*((s + 1/t_transf)**(-2) + 1/((s + 1/t_stat_analyze)*(s + 1/t_transf)) + (s + 1/t_stat_analyze)**(-2) + 1/((s + 1/t_start)*(s + 1/t_transf)) + 1/((s + 1/t_start)*(s + 1/t_stat_analyze)) + (s + 1/t_start)**(-2) + 1/((s + 1/ t_info)*(s + 1/t_transf)) + 1/((s + 1/t_info)*(s + 1/t_stat_analyze)) + 1/((s + 1/t_info)*(s + 1/t_start)) + (s + 1/t_info)**(-2) - (P - 1)*((s + 1/t_transf)**(-2) + 1/((s + 1/t_repeat)*(s + 1/t_transf)) + (s + 1/t_repeat)**(-2))/( t_repeat*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_repeat)*(s + 1/t_transf)) - (P - 1)*(1/(s + 1/t_transf) + 1/(s + 1/t_repeat))/(t_repeat*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/ t_repeat)*(s + 1/t_transf)))*(s + 1/t_repeat)*(s + 1/t_transf)**2) - (P - 1)*(1/(s + 1/t_transf) + 1/(s + 1/t_repeat))/(t_repeat*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_repeat)*(s + 1/ t_stat_analyze)*(s + 1/t_transf)) - (P - 1)*(1/(s + 1/t_transf) + 1/(s + 1/t_repeat))/(t_repeat*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_repeat)*(s + 1/t_start)*(s + 1/t_transf)) - (P - 1)*(1/( s + 1/t_transf) + 1/(s + 1/t_repeat))/(t_repeat*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))*(s + 1/t_info)*(s + 1/t_repeat)*(s + 1/t_transf)) + (P - 1)**2*(1/(s + 1/t_transf) + 1/(s + 1/t_repeat))**2/( t_repeat**2*t_transf**2*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/t_transf)))**2*(s + 1/t_repeat)**2*(s + 1/t_transf)**2))/(t_info*t_start*t_stat_analyze*t_transf*(1 + (P - 1)/(t_repeat*t_transf*(s + 1/t_repeat)*(s + 1/ t_transf)))*(s + 1/t_info)*(s + 1/t_start)*(s + 1/t_stat_analyze)*(s + 1/t_transf))
T_realyze = M1(0)
D = M2(0)-M1(0)**2
alpha = T_realyze**2/D
myu = T_realyze/D
def F(t):
if t<0:
return 0
else:
return sp.integrate((myu**alpha)/(sp.gamma(alpha)*(x**(alpha-1))*sp.exp(myu*x)), (x, 0, t))
t=arange(0, 200, 1)
for i in t:
print(F(i))
i = i+1
</code></pre>
<p>So, when I'm trying to execute it, I had such error in </p>
<pre><code> return sp.integrate
</code></pre>
<p>function:</p>
<pre><code> $ python2.7 nta.py
1.0
('T_realyze = ', 63.800000000000026)
('D = ', 2696.760000000001)
('alpha = ', 1.5093816283243602)
('myu = ', 0.02365801925273291)
0
('myu*x = ', 0.0236580192527329*x)
('sp.exp(myu*x)', exp(0.0236580192527329*x))
0
1
('myu*x = ', 0.0236580192527329*x)
('sp.exp(myu*x)', exp(0.0236580192527329*x))
Traceback (most recent call last):
File "nta.py", line 48, in <module>
print(F(i))
File "nta.py", line 43, in F
return sp.integrate((myu**alpha)/(sp.gamma(alpha)*(x**(alpha-1))*sp.exp(myu*x)), (x, 0, t))
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/integrals.py", line 1280, in integrate
risch=risch, manual=manual)
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/integrals.py", line 486, in doit
conds=conds)
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/integrals.py", line 887, in _eval_integral
h = heurisch_wrapper(g, x, hints=[])
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/heurisch.py", line 130, in heurisch_wrapper
unnecessary_permutations)
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/heurisch.py", line 657, in heurisch
solution = _integrate('Q')
File "/root/anaconda2/lib/python2.7/site-packages/sympy/integrals/heurisch.py", line 646, in _integrate
numer = ring.from_expr(raw_numer)
File "/root/anaconda2/lib/python2.7/site-packages/sympy/polys/rings.py", line 371, in from_expr
raise ValueError("expected an expression convertible to a polynomial in %s, got %s" % (self, expr))
ValueError: expected an expression convertible to a polynomial in Polynomial ring in _x0, _x1, _x2, _x3 over RR[_A0,_A1,_A2,_A3,_A4,_A5,_A6,_A7,_A8,_A9,_A10,_A11,_A12,_A13,_A14,_A15,_A16,_A17,_A18,_A19,_A20,_A21,_A22,_A23,_A24,_A25,_A26,_A27,_A28,_A29,_A30,_A31,_A32,_A33,_A34] with lex order, got 0.50938162832436*_x3**2.96316463805253*(_A0 + _A10*_x0*_x1 + 2*_A11*_x1*_x3 + _x0**2*_A12 + _A14*_x0*_x2 + _A2*_x0 + 2*_A20*_x0*_x3 + _A24*_x1*_x2 + _x2**2*_A27 + 2*_A28*_x3 + _x1**2*_A30 + 3*_x3**2*_A31 + 2*_A6*_x2*_x3 + _A8*_x2 + _A9*_x1) + 1.50938162832436*_x3**4.92632927610506*(_A10*_x1*_x3 + 2*_A12*_x0*_x3 + _A13*_x1*_x2 + _A14*_x2*_x3 + 2*_A15*_x0 + _A16*_x2 + _x2**2*_A18 + _A2*_x3 + _x3**2*_A20 + _A21 + _x1**2*_A3 + 2*_A33*_x0*_x2 + _A34*_x1 + 3*_x0**2*_A5 + 2*_A7*_x0*_x1) - _A10*_x0*_x3 - _x3**2*_A11 - _A13*_x0*_x2 - _x2**2*_A17 - 2*_A19*_x1*_x2 - _A22 - _A24*_x2*_x3 - 2*_A25*_x1 - 3*_x1**2*_A29 - 2*_A3*_x0*_x1 - 2*_A30*_x1*_x3 - _A34*_x0 - _A4*_x2 - _x0**2*_A7 - _A9*_x3 + _x2*_x3 + 0.0236580192527329*_x2*(_A13*_x0*_x1 + _A14*_x0*_x3 + _A16*_x0 + 2*_A17*_x1*_x2 + 2*_A18*_x0*_x2 + _x1**2*_A19 + 2*_A23*_x2 + _A24*_x1*_x3 + 3*_x2**2*_A26 + 2*_A27*_x2*_x3 + _A32 + _x0**2*_A33 + _A4*_x1 + _x3**2*_A6 + _A8*_x3)
</code></pre>
| 3 | 2016-08-14T15:29:36Z | 38,946,744 | <p>Sympy appears to have difficulties evaluating the integral with floating point coefficients (in this case). However, it can find the integral in closed form when the constants of the integrand expression are symbolic. </p>
<pre><code>a, b, c, t = sp.symbols('a,b,c,t', positive = True)
f = sp.Integral(a * sp.exp(-c*x)/(x**b),(x,0,t)).doit()
print f
</code></pre>
<p>Output:</p>
<pre><code>-a*(-b*c**b*gamma(-b + 1)*lowergamma(-b + 1, 0)/(c*gamma(-b + 2)) + c**b*gamma(-b + 1)*lowergamma(-b + 1, 0)/(c*gamma(-b + 2))) + a*(-b*c**b*gamma(-b + 1)*lowergamma(-b + 1, c*t)/(c*gamma(-b + 2)) + c**b*gamma(-b + 1)*lowergamma(-b + 1, c*t)/(c*gamma(-b + 2)))
</code></pre>
<p>You can substitute the constants in this expression to get numerical results as follows (here, I use an example value of <code>t=4</code>):</p>
<pre><code>f.subs({a:(myu**alpha)/sp.gamma(alpha), b:(alpha-1), c:myu, t:4}).n()
</code></pre>
<blockquote>
<pre><code>0.0154626407404632
</code></pre>
</blockquote>
<p>Another option is to use <code>quad</code> from scipy (again using <code>t=4</code>):</p>
<pre><code>from scipy.integrate import quad
quad(lambda x: (myu**alpha)/(sp.gamma(alpha)*(x**(alpha-1))*sp.exp(myu*x)), 0 ,4)[0]
</code></pre>
<blockquote>
<pre><code>0.015462640740458165
</code></pre>
</blockquote>
| 2 | 2016-08-14T21:21:39Z | [
"python",
"python-2.7",
"integration",
"sympy"
] |
How to put all print result in a function into a variable? | 38,943,716 | <p>I have a function in Python:</p>
<pre><code>def f():
...
a lot of code
...
print "hello"
...
a lot of code
...
</code></pre>
<p>I want to call this function, however, the print result will be put into a variable instead print on the screen directly. How can I do this with Python?
ps:
please don't just return, sometimes I don't know where the print statement is.</p>
| -1 | 2016-08-14T15:30:54Z | 38,943,850 | <p>Assuming that <code>print</code> is writing to <code>sys.stdout</code>, you can temporarily replace that with something like a <code>StringIO</code> object.</p>
<pre><code>stdout = sys.stdout
sys.stdout = StringIO()
f()
x = sys.stdout.getvalue()
sys.stdout = stdout
</code></pre>
<p>Or, if you have a reference to the file handle that <code>print</code> is using, you can use that instead of <code>sys.stdout</code>.</p>
<p>If there are multiple uses of <code>print</code> from inside <code>f</code>, and you only want to capture <em>some</em> of them (say, only from a function <code>g</code> called from inside <code>f</code>), I'm afraid you are out of luck. The amount of introspection you would need to do would make it possible would allow you to simply re-implement the function to accumulate the desired output in a variable instead of using <code>print</code>.</p>
| 3 | 2016-08-14T15:45:07Z | [
"python",
"python-2.7",
"printing",
"io-redirection"
] |
How to put all print result in a function into a variable? | 38,943,716 | <p>I have a function in Python:</p>
<pre><code>def f():
...
a lot of code
...
print "hello"
...
a lot of code
...
</code></pre>
<p>I want to call this function, however, the print result will be put into a variable instead print on the screen directly. How can I do this with Python?
ps:
please don't just return, sometimes I don't know where the print statement is.</p>
| -1 | 2016-08-14T15:30:54Z | 38,943,877 | <pre><code>def f():
#code
variable = 'hello\n'
#code
variable += 'hello2\n'
#code
...
print(variable)
</code></pre>
<p>or</p>
<pre><code>def f():
#code
variable = 'hello\n'
#code
variable += 'hello2\n'
#code
...
return(variable)
</code></pre>
<p>and then</p>
<pre><code>print(f())
</code></pre>
| -1 | 2016-08-14T15:48:43Z | [
"python",
"python-2.7",
"printing",
"io-redirection"
] |
How to put all print result in a function into a variable? | 38,943,716 | <p>I have a function in Python:</p>
<pre><code>def f():
...
a lot of code
...
print "hello"
...
a lot of code
...
</code></pre>
<p>I want to call this function, however, the print result will be put into a variable instead print on the screen directly. How can I do this with Python?
ps:
please don't just return, sometimes I don't know where the print statement is.</p>
| -1 | 2016-08-14T15:30:54Z | 38,943,995 | <p>Use a decorator like below</p>
<pre><code>import sys
from StringIO import StringIO
s = StringIO()
def catch_stdout(user_method):
sys.stdout = s
def decorated(*args, **kwargs):
user_method(*args, **kwargs)
sys.stdout = sys.__stdout__
print 'printing result of all prints in one go'
s.seek(0, 0)
print s.read()
return decorated
@catch_stdout
def test():
print 'hello '
print 'world '
test()
</code></pre>
| 1 | 2016-08-14T16:01:29Z | [
"python",
"python-2.7",
"printing",
"io-redirection"
] |
How to put all print result in a function into a variable? | 38,943,716 | <p>I have a function in Python:</p>
<pre><code>def f():
...
a lot of code
...
print "hello"
...
a lot of code
...
</code></pre>
<p>I want to call this function, however, the print result will be put into a variable instead print on the screen directly. How can I do this with Python?
ps:
please don't just return, sometimes I don't know where the print statement is.</p>
| -1 | 2016-08-14T15:30:54Z | 38,944,004 | <p>You could also define your own context manager if you find you need to do this a lot so you can capture the output for a block of statements, eg:</p>
<pre><code>import contextlib
from StringIO import StringIO
import sys
@contextlib.contextmanager
def capture_stdout():
old_stdout = sys.stdout
sys.stdout = StringIO()
yield sys.stdout, old_stdout
sys.stdout = old_stdout
</code></pre>
<p>Then use as follows:</p>
<pre><code>def something():
print 'this is something'
# All prints that go to stdout inside this block either called
# directly or indirectly will be put into a StringIO object instead
# unless the original stdout is used directly...
with capture_print() as (res, stdout):
print 'hello',
print >> stdout, "I'm the original stdout!"
something()
print res.getvalue() + 'blah' # normal print to stdout outside with block
</code></pre>
<p>Gives you:</p>
<pre><code>I'm the original stdout
hello this is something
blah
</code></pre>
| 1 | 2016-08-14T16:02:22Z | [
"python",
"python-2.7",
"printing",
"io-redirection"
] |
Python - json comparison using sets only working occasionally | 38,943,727 | <p>I have a pretty peculiar problem on my hands. I'm not too experienced with python (my language of choice being swift for mobile development), but what I have to do for this project is to pull some csv files from a database, download them locally and upload them to Amazon's DynamoDB.</p>
<p>I have managed to get everything working - The program downloads the csv file as a zip, extracts it using zipfile, converts the csv file to a json file, and then begins uploading the json to DynamoDB.</p>
<p>However, these csv files contain around 100,000 rows each, and to reupload each item every time makes no sense when only 5-10 items are changed in the csv file daily. So, what I've decided to do is before uploading the new json to DynamoDB, get the program to compare the new json to the old json, get only the new items, and upload those. </p>
<p>Now, to get on to the actual problem. What i've been attempting is this:</p>
<pre><code>import json
with open ("C:\\Users\Me\Desktop\staff\oldfile.json") as json1:
list1 = json.load(json1)
with open ("C:\\Users\Me\Desktop\staff\newfile.json") as json2:
list2 = json.load(json2)
set_1 = set(repr(x) for x in list1)
set_2 = set(repr(x) for x in list2)
differences = (set_2 - set_1)
print(differences)
</code></pre>
<p>Which actually works pretty well. The result will be set() if the sets are identical, or contain only the new additional items. </p>
<p><strong>However</strong></p>
<p>I have noticed that when I convert the csv file to json, the orders of the sets change between the two objects in the different files. For example, in the first json file an object might be: </p>
<pre><code>[{"name": "jack", "id": "3100", "photo": "http://imagesdatabase.com/is/image/jack/I_063017263_50_20141112", "category": "male employees", "commissions": "4500", "department": "Beauty > Skincare", "department_id": "709010788", "store_id": "", "additional duties": "5", "spreadsheet": "http://spreadsheetdatabase.com/previpew/01/32100/88/07/709310788.csv", "description": "Jack is a talented young man, has worked with us for over three years and, although initially starting slowly, has worked his way up to becoming the top earner of the month several times.", "join_date": "12/5/2008", "mornings": "YES", "staff_link": "http://staffdatabase.com/244234/654", "show": "NO", "retailers_id": "6017263", "head_id": "2909", "products_sold": "Skincare", "commissions_report": "http://commissionsdatabase.com/jck1/2453"}]
</code></pre>
<p>This same object in the new json file might be:</p>
<pre><code>[{"id": "3100", "name": "jack", "photo": "http://imagesdatabase.com/is/image/jack/I_063017263_50_20141112", "category": "male employees", "commissions": "4500", "department": "Beauty > Skincare", "department_id": "709010788", "store_id": "", "additional duties": "5", "spreadsheet": "http://spreadsheetdatabase.com/previpew/01/32100/88/07/709310788.csv", "description": "Jack is a talented young man, has worked with us for over three years and, although initially starting slowly, has worked his way up to becoming the top earner of the month several times.", "join_date": "12/5/2008", "mornings": "YES", "staff_link": "http://staffdatabase.com/244234/654", "show": "NO", "retailers_id": "6017263", "head_id": "2909", "products_sold": "Skincare", "commissions_report": "http://commissionsdatabase.com/jck1/2453"}]
</code></pre>
<p>These are both still the same object, no?</p>
<p>But when I try to compare these two using python sometimes I get set(), and sometimes it tries to tell me that it's a new object - what's happening? </p>
<p><a href="http://i.stack.imgur.com/RE4Q7.png" rel="nofollow"><img src="http://i.stack.imgur.com/RE4Q7.png" alt="json comparison fail"></a></p>
<p>Honestly, I've been troubleshooting this for almost a whole day now and I'm pretty much at my wit's end - I really can't understand why it would work when I run it once, and then not the next time with the same exact json objects. Any help would be greatly appreciated!</p>
| 0 | 2016-08-14T15:31:18Z | 38,943,841 | <p>Your code relies on the ordering of dictionaries. Dictionary order depends on <a href="https://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary">insertion and deletion history</a>, varies between Python interpreter runs thanks to hash randomisation and should not be relied upon.</p>
<p>If your dictionaries are not nested, you can store them in sets as tuples of their key-value pairs, sorted:</p>
<pre><code>set_1 = set(tuple(sorted(x.items())) for x in list1)
set_2 = set(tuple(sorted(x.items())) for x in list2)
</code></pre>
<p>This creates an immutable representation that retains the original key-value pairing but avoids any issues with ordering. These tuples can trivially be fed back into the <code>dict()</code> type to re-create the dictionary.</p>
| 2 | 2016-08-14T15:44:03Z | [
"python",
"json",
"set"
] |
Choppy audio from separating and then joining .wav stereo channels | 38,943,778 | <p>I am currently working on processing .wav files with python, using Pyaudio for streaming the audio, and the python wave library for loading the file data.
I plan to later on include processing of the individual stereo channels, with regards to amplitude of the signal, and panning of the stereo signal, but for now i'm just trying to seperate the two channels of the wave file, and stitch them back together - Hopefully ending up with data that is identical to the input data.</p>
<p>Below is my code.
The method getRawSample works perfectly fine, and i can stream audio through that function.
The problem is my getSample method. Somewhere along the line, where i'm seperating the two channels of audio, and joining them back together, the audio gets distorted. I have even commented out the part where i do amplitude and panning adjustment, so in theory it's data in -> data out.<br>
Below is an example of my code:</p>
<pre><code>class Sample(threading.Thread) :
def __init__(self, filepath, chunk):
super(Sample, self).__init__()
self.CHUNK = chunk
self.filepath = filepath
self.wave = wave.open(self.filepath, 'rb')
self.amp = 0.5 # varies from 0 to 1
self.pan = 0 # varies from -pi to pi
self.WIDTH = self.wave.getsampwidth()
self.CHANNELS = self.wave.getnchannels()
self.RATE = self.wave.getframerate()
self.MAXFRAMEFEEDS = self.wave.getnframes()/self.CHUNK # maximum even number of chunks
self.unpstr = '<{0}h'.format(self.CHUNK*self.WIDTH) # format for unpacking the sample byte string
self.pckstr = '<{0}h'.format(self.CHUNK*self.WIDTH) # format for unpacking the sample byte string
self.framePos = 0 # keeps track of how many chunks of data fed
# panning and amplitude adjustment of input sample data
def panAmp(self, data, panVal, ampVal): # when panning, using constant power panning
[left, right] = self.getChannels(data)
#left = np.multiply(0.5, left) #(np.sqrt(2)/2)*(np.cos(panVal) + np.sin(panVal))
#right = np.multiply(0.5, right) # (np.sqrt(2)/2)*(np.cos(panVal) - np.sin(panVal))
outputList = self.combineChannels(left, right)
dataResult = struct.pack(self.pckstr, *outputList)
return dataResult
def getChannels(self, data):
dataPrepare = list(struct.unpack(self.unpstr, data))
left = dataPrepare[0::self.CHANNELS]
right = dataPrepare[1::self.CHANNELS]
return [left, right]
def combineChannels(self, left, right):
stereoData = left
for i in range(0, self.CHUNK/self.WIDTH):
index = i*2+1
stereoData = np.insert(stereoData, index, right[i*self.WIDTH:(i+1)*self.WIDTH])
return stereoData
def getSample(self, panVal, ampVal):
data = self.wave.readframes(self.CHUNK)
self.framePos += 1
if self.framePos > self.MAXFRAMEFEEDS: # if no more audio samples to process
self.wave.rewind()
data = self.wave.readframes(self.CHUNK)
self.framePos = 1
return self.panAmp(data, panVal, ampVal)
def getRawSample(self): # for debugging, bypasses pan and amp functions
data = self.wave.readframes(self.CHUNK)
self.framePos += 1
if self.framePos > self.MAXFRAMEFEEDS: # if no more audio samples to process
self.wave.rewind()
data = self.wave.readframes(self.CHUNK)
self.framePos = 1
return data
</code></pre>
<p>i am suspecting that the error is in the way that i stitch together the left and right channel, but not sure.
I load the project with 16 bit 44100khz .wav files.
Below is a link to an audio file so that you can hear the resulting audio output.
The first part is running two files (both two channel) through the getSample method, while the next part is running those same files, through the getRawSample method. </p>
<p><a href="https://dl.dropboxusercontent.com/u/24215404/pythonaudiosample.wav" rel="nofollow">https://dl.dropboxusercontent.com/u/24215404/pythonaudiosample.wav</a></p>
<p>Basing on the audio, as said earlier, it seems like the stereo file gets distorted. Looking at the waveform of above file, it seems as though the right and left channels are exactly the same after going through the getSample method.</p>
<p>If needed, i can also post my code including the main function.
Hopefully my question isn't too vague, but i am grateful for any help or input!</p>
| 0 | 2016-08-14T15:36:28Z | 38,954,816 | <p>As it so often happens, i slept on it, and woke up the next day with a solution.<br>
The problem was in the combineChannels function.
Following is the working code:</p>
<pre><code> def combineChannels(self, left, right):
stereoData = left
for i in range(0, self.CHUNK):
index = i*2+1
stereoData = np.insert(stereoData, index, right[i:(i+1)])
return stereoData
</code></pre>
<p>The changes are</p>
<ul>
<li>For loop bounds: as i have 1024 items (the same as my chunk size) in the lists <em>left</em> and <em>right</em>, i ofcourse need to iterate through every one of those.</li>
<li>index: the index definition remains the same</li>
<li>stereoData: Again, here i remember that im working with lists, each containing a frame of audio. The code in the question assumes that my list is stored as a bytestring, but this is ofcourse not the case. And as you see, the resulting code is much simpler.</li>
</ul>
| 0 | 2016-08-15T12:10:09Z | [
"python",
"audio",
"byte",
"wave",
"pyaudio"
] |
How to back check classification using sklearn | 38,943,884 | <p>I am running two different classification algorithms on my data logistic regression and naive bayes but it is giving me same accuracy even if I change the training and testing data ratio. Following is the code I am using </p>
<pre><code>import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
df = pd.read_csv('Speed Dating.csv', encoding = 'latin-1')
X = pd.DataFrame()
X['d_age'] = df ['d_age']
X['match'] = df ['match']
X['importance_same_religion'] = df ['importance_same_religion']
X['importance_same_race'] = df ['importance_same_race']
X['diff_partner_rating'] = df ['diff_partner_rating']
# Drop NAs
X = X.dropna(axis=0)
# Categorical variable Match [Yes, No]
y = X['match']
# Drop y from X
X = X.drop(['match'], axis=1)
# Transformation
scalar = StandardScaler()
X = scalar.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Logistic Regression
model = LogisticRegression(penalty='l2', C=1)
model.fit(X_train, y_train)
print('Accuracy Score with Logistic Regression: ', accuracy_score(y_test, model.predict(X_test)))
#Naive Bayes
model_2 = GaussianNB()
model_2.fit(X_train, y_train)
print('Accuracy Score with Naive Bayes: ', accuracy_score(y_test, model_2.predict(X_test)))
print(model_2.predict(X_test))
</code></pre>
<p>Is it possible that every time the accuracy is same ?</p>
| 1 | 2016-08-14T15:49:11Z | 38,984,063 | <p>This is common phenomena occurring if the class frequencies are unbalanced, e.g. nearly all samples belong to one class. For examples if 80% of your samples belong to class "No", then classifier will often tend to predict "No" because such a trivial prediction reaches the highest overall accuracy on your train set. </p>
<p>In general, when evaluating the performance of a binary classifier, you should not only look at the overall accuracy. You have to consider other metrics such as the ROC Curve, class accuracies, f1 scores and so on.</p>
<p>In your case you can use sklearns <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html" rel="nofollow">classification report</a> to get a better feeling what your classifier is actually learning:</p>
<pre><code>from sklearn.metrics import classification_report
print(classification_report(y_test, model_1.predict(X_test)))
print(classification_report(y_test, model_2.predict(X_test)))
</code></pre>
<p>It will print the precision, recall and accuracy for every class. </p>
<p>There are three options on how to reach a better classification accuracy on your class "Yes"</p>
<ul>
<li>use sample weights, you can increase the importance of the samples of the "Yes" class thus forcing the classifier to predict "Yes" more often</li>
<li>downsample the "No" class in the original X to reach more balanced class frequencies </li>
<li>upsample the "Yes" class in the original X to reach more balanced class frequencies</li>
</ul>
| 1 | 2016-08-16T20:38:50Z | [
"python",
"scikit-learn",
"classification",
"logistic-regression",
"naivebayes"
] |
Page not found (404) | 38,943,891 | <p>I looked at my files more than 50 times and i'm getting frustrated.
This is the error i'm getting:</p>
<pre><code>Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order:
^admin/
^music/
The current URL, , didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
</code></pre>
<p>Here is my urls.py in project1 folder:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/', include('music.urls')),
]
</code></pre>
<p>Here is my urls.py in music folder</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
</code></pre>
<p>This is the installed apps in my settings.py for whatever reason:</p>
<pre><code>INSTALLED_APPS = [
'music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</code></pre>
<p>Please help, thank you!</p>
| 0 | 2016-08-14T15:50:22Z | 38,943,946 | <p>Either try the below url </p>
<pre><code>http://127.0.0.1:8000/music/
</code></pre>
<p>or remove <code>music</code> from the url pattern</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('music.urls')),
]
</code></pre>
| 1 | 2016-08-14T15:57:01Z | [
"python",
"django",
"templates",
"http-status-code-404"
] |
Page not found (404) | 38,943,891 | <p>I looked at my files more than 50 times and i'm getting frustrated.
This is the error i'm getting:</p>
<pre><code>Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order:
^admin/
^music/
The current URL, , didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
</code></pre>
<p>Here is my urls.py in project1 folder:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/', include('music.urls')),
]
</code></pre>
<p>Here is my urls.py in music folder</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
</code></pre>
<p>This is the installed apps in my settings.py for whatever reason:</p>
<pre><code>INSTALLED_APPS = [
'music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</code></pre>
<p>Please help, thank you!</p>
| 0 | 2016-08-14T15:50:22Z | 38,943,979 | <p>Take a good look at what Django tells you, why it couldn't find a corresponding page for your request URL:</p>
<blockquote>
<p>Using the URLconf defined in project1.urls, Django tried these URL
patterns, in this order: </p>
<pre><code>^admin/
^music/
</code></pre>
<p>The current URL, , didn't match any of these.</p>
</blockquote>
<p>It basically has just two views, that can handle your request and they are only reachable via <code>127.0.0.1:8000/admin/</code> and <code>127.0.0.1:8000/admin/</code>. You're trying to access content at <code>/</code> which just isn't there.</p>
<p>A solution would be to add another view as a root page or index page at the URL <code>127.0.0.1:8000</code> or change the URL of one of the two existing urlpatterns to match the root. </p>
<p>The following example adds a new view <code>index</code> to the root of your app:</p>
<pre><code>urlpatterns = [
url(r'^$', index), # this is important and matches "/"
url(r'^help/', include('apps.help.urls')),
url(r'^credit/', include(extra_patterns)),
]
</code></pre>
| 2 | 2016-08-14T15:59:56Z | [
"python",
"django",
"templates",
"http-status-code-404"
] |
Using Pandas to Change Data in an entire Excel Workbook | 38,943,902 | <p>I have an excel workbook that is very large in size. Here is what I would
like to do using Python's pandas. I am running python 3.4. </p>
<ol>
<li>Open the workbook in pandas. </li>
<li>Change values in one cell to something different - for example,
change the string in cell A2 that is currently named "Jane Doe"
to "Bob Smith"</li>
<li>Bear in mind that I would like to select the entire workbook, not just one sheet. My goal is to make multiple mass changes. </li>
</ol>
<p>Here is my code:</p>
<pre><code>import pandas as pd
xls = pd.ExcelFile('Data.xlsx')
df = xls.parse('Data')
df1 = df.replace('Jane Doe', 'Bob Smith')
</code></pre>
<p>Edit from answer:</p>
<p>Ayhan, thank you kindly for your response. </p>
<p>When I try to load the data using your method I get the following error:</p>
<pre><code>fs = pd.read_excel('filename.xlsx', sheetname=None)
</code></pre>
<p>AssertionError Traceback (most recent call last)
in ()
----> 1 df = pd.read_excel("Data.xlsx")</p>
<pre><code>/home/minx/anaconda3/lib/python3.4/site-packages/pandas/io/excel.py in read_excel(io, sheetname, header, skiprows, skip_footer, index_col, names, parse_cols, parse_dates, date_parser, na_values, thousands, convert_float, has_index_names, converters, engine, squeeze, **kwds)
167 """
168 if not isinstance(io, ExcelFile):
--> 169 io = ExcelFile(io, engine=engine)
170
171 return io._parse_excel(
/home/minx/anaconda3/lib/python3.4/site-packages/pandas/io/excel.py in __init__(self, io, **kwds)
216 self.book = xlrd.open_workbook(file_contents=data)
217 else:
--> 218 self.book = xlrd.open_workbook(io)
219 elif engine == 'xlrd' and isinstance(io, xlrd.Book):
220 self.book = io
/home/minx/.local/lib/python3.4/site-packages/xlrd/__init__.py in open_workbook(filename, logfile, verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows)
420 formatting_info=formatting_info,
421 on_demand=on_demand,
--> 422 ragged_rows=ragged_rows,
423 )
424 return bk
/home/minx/.local/lib/python3.4/site-packages/xlrd/xlsx.py in open_workbook_2007_xml(zf, component_names, logfile, verbosity, use_mmap, formatting_info, on_demand, ragged_rows)
792 x12sheet = X12Sheet(sheet, logfile, verbosity)
793 heading = "Sheet %r (sheetx=%d) from %r" % (sheet.name, sheetx, fname)
--> 794 x12sheet.process_stream(zflo, heading)
795 del zflo
796 comments_fname = 'xl/comments%d.xml' % (sheetx + 1)
/home/minx/.local/lib/python3.4/site-packages/xlrd/xlsx.py in own_process_stream(self, stream, heading)
532 elem.clear() # destroy all child elements (cells)
533 elif elem.tag == U_SSML12 + "dimension":
--> 534 self.do_dimension(elem)
535 elif elem.tag == U_SSML12 + "mergeCell":
536 self.do_merge_cell(elem)
/home/minx/.local/lib/python3.4/site-packages/xlrd/xlsx.py in do_dimension(self, elem)
566 # print >> self.logfile, "dimension: ref=%r" % ref
567 last_cell_ref = ref.split(':')[-1] # example: "Z99"
--> 568 rowx, colx = cell_name_to_rowx_colx(last_cell_ref)
569 self.sheet._dimnrows = rowx + 1
570 self.sheet._dimncols = colx + 1
/home/minx/.local/lib/python3.4/site-packages/xlrd/xlsx.py in cell_name_to_rowx_colx(cell_name, letter_value)
89 else: # start of row number; can't be '0'
90 colx = colx - 1
---> 91 assert 0 <= colx < X12_MAX_COLS
92 break
93 except KeyError:
AssertionError:
</code></pre>
| -3 | 2016-08-14T15:52:14Z | 38,945,415 | <p>Read all sheets into a dictionary:</p>
<pre><code>dfs = pd.read_excel('filename.xlsx', sheetname=None)
</code></pre>
<p>Create a writer object and iterate over dictionary while replacing based on key-value pairs:</p>
<pre><code>repl_dict = {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'i': 'j'}
writer = pd.ExcelWriter('filename.xlsx')
for sheetname, df in dfs.items():
df = df.replace(repl_dict)
df.to_excel(writer, sheetname, index=False)
writer.save()
</code></pre>
<p>You may need to adjust some parameters of both <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow"><code>read_excel</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow"><code>to_excel</code></a> like header, index, etc.</p>
| 0 | 2016-08-14T18:39:38Z | [
"python",
"pandas"
] |
plot arrays by row with matplotlib | 38,943,920 | <p>I have two numpy arrays (a and b) with shape (16, 850) each. I'm displaying them row by row, e.g.</p>
<pre><code>plt.figure()
plt.plot(a[0], b[0])
plt.plot(a[1], b[1])
plt.plot(a[2], b[2])
...
plt.show()
</code></pre>
<p>Should I have to use a for loop to do it in a more pythonic way?</p>
| 2 | 2016-08-14T15:54:19Z | 38,943,974 | <p>You can pass a multi-dimensional array to <code>plot</code> and each column will be created as a separate plot object. We transpose both inputs so that it will plot each row separately.</p>
<pre><code>a = np.random.rand(16, 850)
b = np.random.rand(16, 850)
plt.plot(a.T, b.T)
plt.show()
</code></pre>
| 2 | 2016-08-14T15:59:32Z | [
"python",
"matplotlib"
] |
plot arrays by row with matplotlib | 38,943,920 | <p>I have two numpy arrays (a and b) with shape (16, 850) each. I'm displaying them row by row, e.g.</p>
<pre><code>plt.figure()
plt.plot(a[0], b[0])
plt.plot(a[1], b[1])
plt.plot(a[2], b[2])
...
plt.show()
</code></pre>
<p>Should I have to use a for loop to do it in a more pythonic way?</p>
| 2 | 2016-08-14T15:54:19Z | 38,943,976 | <p>This will work:</p>
<pre><code>plt.figure()
for i in range(len(a)):
plt.plot(a[i], b[i])
plt.show()
</code></pre>
<p>But the way that Suever shows is much Pythonic. However, not every function has something like that built-in. </p>
| 0 | 2016-08-14T15:59:38Z | [
"python",
"matplotlib"
] |
Trouble creating multiple copies of folders and altering specific values on a certain line, on a unique file, in each copied folder | 38,944,085 | <p>I am trying to create multiple copies of a single folder. Then what I want to do is change some words in a specific line in a specific file, on all folders i.e.:</p>
<ol>
<li>copy folderX -> folder1, folder2, ..., folderN (N could be let's say 200)</li>
<li>find file ( the file has a specific extension, for example a .txt file in a folder full of .jpgs')</li>
<li>change words, example: sot 1 1 1 -> sot 2 2 2 (each file will have a different new value (one would be sot 2 2 2, the other sot 3 3 3 etc.))</li>
</ol>
<p>What I have tried so far, first to make a copy of the folder:</p>
<ol>
<li><code>for i in {0...200}; do cp -r test/ test_$i; done</code> (didn't work)</li>
<li><code>for i in (i=0; i<=200; i++); do cp -r test/ test_$i; done</code> (worked but not as intended, it sometimes raised errors)</li>
</ol>
<p>So I figured a workaround in Python, </p>
<pre><code>for i in range(3):
os.system('cp -r orig_test test-%s' % (i))
</code></pre>
<p>This works like a charm. But when I try to change the words in the files it only displays the contents of the line.</p>
<pre><code>"grep -r "sot = 1" 1RWT_HpH-* | xargs sed -i "s/1/2/g"
</code></pre>
<p>As I told you the line has the form sot 1 1 1 and the value needs to be changed from 1 1 1 to different value on each iteration. The values will be provided from a list.</p>
<p>If it helps I am using Mac OS, maybe that is why some features supposed to be working on Linux don't give the exact same results.</p>
<p><strong>P.S.</strong> If possible I would prefer an educational answer not a super efficient that does it all in just one line code. </p>
<p>Thank you so very much in advance. Cheers!!!</p>
| 1 | 2016-08-14T16:12:58Z | 38,953,184 | <p>For the first part: to count in a shell, you need to do a little more work. Assuming you are using <code>bash</code>, you can do the following (this is very similar to what you tried, but you needed double brackets):</p>
<pre><code> for ((n=0; n<=100; n++))
do
cp -r test test_$n
done
</code></pre>
<p>Note that shell is quite picky about where you put spaces and newlines. I realise that <code>man bash</code> is a long read, but it's worth it if you need to do more of this.
If you want to experiment, best to put an <code>echo</code> in place of the <code>cp</code> command, so you can try things without messing up your files:</p>
<pre><code> for ((n=0; n<=100; n++))
do
echo $n
done
</code></pre>
<p>Regarding your second question: the <code>grep</code> will return the line from the file, not just the filename. For that, you need the <code>-l</code> flag (that's <em>ell</em>, not <em>one</em>). So, you can try:</p>
<pre><code>grep -lr "sot = 1" 1RWT_HpH-* | xargs sed -i "s/1/2/g"
</code></pre>
| 0 | 2016-08-15T10:11:49Z | [
"python",
"terminal"
] |
how to pass variable value from c++ to python? | 38,944,172 | <p>I have a sensor value which can be read using the C++ only because it was implemented using it , I want to pass location value(two float variable ) of one sensor to python, I have been reading a lot and I found shared memory , piping and more any idea what is the best way to do it ?</p>
<p>any help will be much appreciated </p>
| 0 | 2016-08-14T16:23:10Z | 38,944,186 | <p>It's not clear from your question whether this is a standalone C++ program or a library.</p>
<p>If it's a standalone program, use the <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module to invoke it and read its output.</p>
<p>If it's a library, use <a href="http://cython.org/" rel="nofollow">Cython</a> to construct a Python extension module that wraps the library. (It is not <em>necessary</em> to use Cython; Python extensions <em>can</em> be written by hand. But it will make the task significantly easier.)</p>
| 2 | 2016-08-14T16:25:56Z | [
"python",
"c++",
"subprocess",
"piping"
] |
how to pass variable value from c++ to python? | 38,944,172 | <p>I have a sensor value which can be read using the C++ only because it was implemented using it , I want to pass location value(two float variable ) of one sensor to python, I have been reading a lot and I found shared memory , piping and more any idea what is the best way to do it ?</p>
<p>any help will be much appreciated </p>
| 0 | 2016-08-14T16:23:10Z | 38,959,204 | <p>@ramtha Z28 with the limited information you provided... do you have access to the C++ code itself or are you calling a DLL? You can wrap a function in Cython easily to communicate between Python and C++ if you have the source code. Wrap all the C++ blocks in <code>cpdef</code> statements which are accessible from Python and C++. Example files are here which show you how to include a C program in Cython and interact with Python: <a href="https://github.com/cythonbook/examples/tree/master/07-wrapping-c/01-wrapping-c-functions-mt-random" rel="nofollow">https://github.com/cythonbook/examples/tree/master/07-wrapping-c/01-wrapping-c-functions-mt-random</a></p>
<p>If it is a DLL you have to declare all the constants, functions, return values. Actually this example may be something like what you're using already: <a href="http://people.seas.harvard.edu/~krussell/html-tutorial/wrap_dll.html" rel="nofollow">http://people.seas.harvard.edu/~krussell/html-tutorial/wrap_dll.html</a></p>
| 0 | 2016-08-15T16:40:02Z | [
"python",
"c++",
"subprocess",
"piping"
] |
how to pass variable value from c++ to python? | 38,944,172 | <p>I have a sensor value which can be read using the C++ only because it was implemented using it , I want to pass location value(two float variable ) of one sensor to python, I have been reading a lot and I found shared memory , piping and more any idea what is the best way to do it ?</p>
<p>any help will be much appreciated </p>
| 0 | 2016-08-14T16:23:10Z | 38,959,725 | <p>I'm not familiar with python however, a simple approach is to use some communication protocols such as serial ports or udp which is a network protocol. For real-time applications, UDP protocol is a preferable choice. </p>
| 0 | 2016-08-15T17:14:54Z | [
"python",
"c++",
"subprocess",
"piping"
] |
Python Fabric Parallel Execution Failure on EC2: Updated | 38,944,236 | <p>So, background first. I was running Ubuntu 14.04 and running the following script without issue, where I <code>put</code> file on an EC2 instances. <strong>Note</strong>: I used the same IP's to illustrate both the success and failure, but pretend I had run this script from the start both times, generating new IP's everytime.</p>
<pre><code>import boto.ec2
import os
from fabric.api import run, parallel, env, sudo
from fabric.tasks import execute
from fabric.operations import put
# file path python scripts and data
rps_file = "review_page_scraper.py"
# make sure hosts are clear before we add to them
env.hosts = []
# how many instances to start and how to split up the data frame
num_instances = 3
# EC2 access keys
access_key = 'my_access_key'
secret_key = 'my_secret_key'
# get a connection to the east region
conn = boto.ec2.connect_to_region("us-east-1",
aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
# create the reservation of instances
reservation = conn.run_instances('my_ami_id',
key_name='original_key', # my original key
security_groups=['my_sec_grp'],
instance_type='t2.micro',
min_count=num_instances,
max_count=num_instances)
# get list of instances
instance_lst = reservation.instances
# get a status update and wait if the instance isn't up and running yet
for instance in instance_lst:
while instance.state != "running":
sleep(5)
instance.update()
print "%s is running" % instance.ip_address
# get username and host, add 'ubuntu' as username
hosts = ["ubuntu@" + ip.ip_address for ip in instance_lst]
env.hosts = hosts # set environment variable
@parallel
def upload_scripts_data(file_name):
path = "~/amazon_proj/amazon/"
put(path + file_name, "~") # put it in the home dir of EC2 instance
# execute functions w/ rps_file
execute(upload_scripts_data, rps_file) # send review_page_scraper helpers
</code></pre>
<p>Here's the output:</p>
<pre><code>In [25]: execute(upload_scripts_data, rps_file) # send review_page_scraper helpers
[ubuntu@52.90.34.75] Executing task 'upload_scripts_data'
[ubuntu@54.173.57.59] Executing task 'upload_scripts_data'
[ubuntu@54.165.186.168] Executing task 'upload_scripts_data'
[ubuntu@52.90.34.75] put: /home/rerwin21/amazon_proj/amazon/review_page_scraper.py -> /home/ubuntu/review_page_scraper.py
[ubuntu@54.165.186.168] put: /home/rerwin21/amazon_proj/amazon/review_page_scraper.py -> /home/ubuntu/review_page_scraper.py
[ubuntu@54.173.57.59] put: /home/rerwin21/amazon_proj/amazon/review_page_scraper.py -> /home/ubuntu/review_page_scraper.py
Out[25]:
{u'ubuntu@52.90.34.75': None,
u'ubuntu@54.165.186.168': None,
u'ubuntu@54.173.57.59': None}
</code></pre>
<p><strong>Now, the Problem:</strong>
I ruined my Ubuntu install and lost my key-pair, generated using <code>ssh-keygen -t rsa</code>, which I called 'original_key' when I imported the public key to AWS. So, I had to re-install Ubuntu and I chose 16.04. I generated a new key using <code>ssh-keygen -t rsa</code> and saved it to <code>~/.ssh/id_rsa</code> and ~/.ssh/id_rsa.pub, for the private and public keys respectively.</p>
<p>I then imported the public key and saved it with the "id_rsa_pub" name. So, now I run the same script above, changing the <code>key_name</code> argument to "id_rsa_pub". Also, I ran <code>chmod 0400 id_rsa</code> per AWS's directions. The ouptut is:</p>
<pre><code>In [22]: execute(upload_scripts_data, rps_file)
[ubuntu@52.90.34.75] Executing task 'upload_scripts_data'
[ubuntu@54.173.57.59] Executing task 'upload_scripts_data'
[ubuntu@54.165.186.168] Executing task 'upload_scripts_data'
!!! Parallel execution exception under host u'ubuntu@54.165.186.168':
Process ubuntu@54.165.186.168:
Traceback (most recent call last):
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/tasks.py", line 242, in inner
submit(task.run(*args, **kwargs))
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/tasks.py", line 174, in run
return self.wrapped(*args, **kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/decorators.py", line 181, in inner
Traceback (most recent call last):
File "<ipython-input-22-ed18eb00cc62>", line 1, in <module>
execute(upload_scripts_data, rps_file)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/tasks.py", line 412, in execute
ran_jobs = jobs.run()
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/job_queue.py", line 168, in run
self._fill_results(results)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/job_queue.py", line 191, in _fill_results
datum = self._comms_queue.get_nowait()
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/queues.py", line 152, in get_nowait
return self.get(False)
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/queues.py", line 135, in get
res = self._recv()
TypeError: ('__init__() takes exactly 2 arguments (3 given)', <class 'paramiko.ssh_exception.NoValidConnectionsError'>, (None, 'Unable to connect to port 22 on or 54.165.186.168'))
return func(*args, **kwargs)
File "<ipython-input-19-ed4344124d24>", line 4, in upload_scripts_data
put(path + file_name, "~")
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 677, in host_prompting_wrapper
return func(*args, **kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/operations.py", line 345, in put
ftp = SFTP(env.host_string)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/sftp.py", line 33, in __init__
self.ftp = connections[host_string].open_sftp()
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 159, in __getitem__
self.connect(key)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 151, in connect
user, host, port, cache=self, seek_gateway=seek_gateway)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 603, in connect
raise NetworkError(msg, e)
NetworkError: Low level socket error connecting to host 54.165.186.168 on port 22: Unable to connect to port 22 on or 54.165.186.168 (tried 1 time)
[ubuntu@52.90.34.75] put: /home/rerwin21/amazon_proj/amazon/review_page_scraper.py -> /home/ubuntu/review_page_scraper.py
!!! Parallel execution exception under host u'ubuntu@54.173.57.59':
Process ubuntu@54.173.57.59:
Traceback (most recent call last):
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/rerwin21/anaconda2/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/tasks.py", line 242, in inner
submit(task.run(*args, **kwargs))
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/tasks.py", line 174, in run
return self.wrapped(*args, **kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/decorators.py", line 181, in inner
return func(*args, **kwargs)
File "<ipython-input-19-ed4344124d24>", line 4, in upload_scripts_data
put(path + file_name, "~")
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 677, in host_prompting_wrapper
return func(*args, **kwargs)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/operations.py", line 345, in put
ftp = SFTP(env.host_string)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/sftp.py", line 33, in __init__
self.ftp = connections[host_string].open_sftp()
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 159, in __getitem__
self.connect(key)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 151, in connect
user, host, port, cache=self, seek_gateway=seek_gateway)
File "/home/rerwin21/anaconda2/lib/python2.7/site-packages/fabric/network.py", line 603, in connect
raise NetworkError(msg, e)
NetworkError: Timed out trying to connect to 54.173.57.59 (tried 1 time)
</code></pre>
<p>I apologize for such a verbose question and output. I've exhausted my knowledge and didn't see anything online that was quite the same as my issue. </p>
<p><strong>UPDATE:</strong><br>
A few things to note. I'm using the same security group and AMI that I used with the old key-pair. Next, even more confusing, if I run the <code>execute(upload_scripts_data, rps_file)</code> command again and it runs with no errors. </p>
| 0 | 2016-08-14T16:30:33Z | 38,948,451 | <p><strong>UPDATE</strong> This does not solve it. The only thing that solves the issue is to run the parallel command a second time.</p>
<p>Very embarrassing, but I have to post. As I mentioned, I was forced to completely reinstall Ubuntu, and lost my key-pair. What I overlooked was my <code>ssh_config</code> file. To fix the problem:</p>
<pre><code>sudo gedit
</code></pre>
<p>Once in gedit, uncomment Port 22:</p>
<pre><code># Port 22
</code></pre>
<p>to</p>
<pre><code>Port 22
</code></pre>
<p>Save, and now I'm up and running again! </p>
| 0 | 2016-08-15T02:15:13Z | [
"python",
"ssh",
"amazon-ec2",
"boto",
"fabric"
] |
Creating class in python tkinter (object is frame with things inside) | 38,944,265 | <p>I wanted to create a gui application in python consisting of multiple objects of a class i would define. Each object would be <strong>a frame</strong> with <strong>image</strong> and <strong>a label</strong> inside.</p>
<p>I tried this: </p>
<pre><code> `class MyClass:
def __init__(self)
self.frame = Frame(root)
self.image = None (???)
self.label = Label(self.frame, text='default')`
</code></pre>
<p>How can i define a image without a default image? These images would be added programatically when defining that object.</p>
| -2 | 2016-08-14T16:33:56Z | 38,991,683 | <p>I figured it myself:</p>
<p>Just add a path to the image to the <strong>init</strong> function:</p>
<pre><code>def __init__(self, imagepath)
</code></pre>
<p>Rest is the same, just define the image using this path.</p>
| 0 | 2016-08-17T08:30:07Z | [
"python",
"image",
"class",
"tkinter",
"frame"
] |
My Python Bot Can connect to the IRC server but doesnt join the channel | 38,944,275 | <p>so i made an IRC bot, this is the code:</p>
<pre><code>import socket
import sys
server = "irc.esper.net"
channel = "#stencyl"
botnick = "MrGutsy"
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "connecting to:"+server
irc.connect((server, 6667))
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!\n")
irc.send("NICK "+ botnick +"\n")
irc.send("PRIVMSG nickserv :iNOOPE\r\n")
irc.send("JOIN "+ channel +"\n")
while 1:
text=irc.recv(2040)
print text
if text.find('PING') != -1:
irc.send('PONG ' + text.split() [1] + '\r\n')
if text.find(':!hi') !=-1:
t = text.split(':!hi')
to = t[1].strip()
irc.send('PRIVMSG '+channel+' :Hello '+str(to)+'! \r\n')
if text.find(':!water') !=-1:
t = text.split(':!hi')
to = t[1].strip()
irc.send('PRIVMSG '+channel+' :*brings water '+str(to)+'! \r\n')
</code></pre>
<p>This is the outcome i get when i execute the programm:</p>
<pre><code>ThinkPad-T420:~$ python test.py
connecting to:irc.esper.net
:stormlight.esper.net NOTICE * :*** Looking up your hostname...
:stormlight.esper.net NOTICE * :*** Checking Ident
:stormlight.esper.net NOTICE * :*** Found your hostname
:stormlight.esper.net NOTICE * :*** No Ident response
PING :0C882AF0
:stormlight.esper.net 451 * :You have not registered
:stormlight.esper.net 001 MrGutsy :Welcome to the EsperNet Internet Relay Chat Network MrGutsy
:stormlight.esper.net 002 MrGutsy :Your host is stormlight.esper.net[45.79.137.210/6667], running version charybdis-3.5.0-dev
:stormlight.esper.net 003 MrGutsy :This server was created Sat May 21 2016 at 23:51:37 UTC
:stormlight.esper.net 004 MrGutsy stormlight.esper.net charybdis-3.5.0-dev DQRSZagiloswz CFILPQTbcefgijklmnopqrstvz bkloveqjfI
:stormlight.esper.net 005 MrGutsy SAFELIST ELIST=CTU CHANTYPES=# EXCEPTS INVEX CHANMODES=eIbq,k,flj,CFLPQTcgimnprstz CHANLIMIT=#:50 PREFIX=(ov)@+ MAXLIST=bqeI:100 MODES=4 NETWORK=EsperNet KNOCK :are supported by this server
:stormlight.esper.net 005 MrGutsy STATUSMSG=@+ CALLERID=g CASEMAPPING=rfc1459 NICKLEN=30 MAXNICKLEN=30 CHANNELLEN=50 TOPICLEN=390 ETRACE CPRIVMSG CNOTICE DEAF=D MONITOR=100 :are supported by this server
:stormlight.esper.net 005 MrGutsy FNC TARGMAX=NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:,MONITOR: EXTBAN=$,acjorsxz WHOX CLIENTVER=3.0 :are supported by this server
:stormlight.esper.net 251 MrGutsy :There are 9 users and 6825 invisible on 15 servers
:stormlight.esper.net 252 MrGutsy 34 :IRC Operators online
:stormlight.esper.net 253 MrGutsy 1 :unknown connection(s)
:stormlight.esper.net 254 MrGutsy 5328 :channels formed
:stormlight.esper.net 255 MrGutsy :I have 1181 clients and 1 servers
:stormlight.esper.net 265 MrGutsy 1181 1395 :Current local users 1181, max 1395
:stormlight.esper.net 266 MrGutsy 6834 7714 :Current global users 6834, max 7714
:stormlight.esper.net 250 MrGutsy :Highest connection count: 1396 (1395 clients) (91268 connections received)
:stormlight.esper.net 375 MrGutsy :- stormlight.esper.net Message of the Day -
:stormlight.esper.net 372 MrGutsy :- __ .__ .__ .__ __
:stormlight.esper.net 372 MrGutsy :- _______/ |_ ___________ _____ | | |__| ____ | |___/ |_
:stormlight.esper.net 372 MrGutsy :- / ___/\ __\/ _ \_ __ \/ \| | | |/ ___\| | \ __\
:stormlight.esper.net 372 MrGutsy :- \___ \ | | ( <_> ) | \/ Y Y \ |_| / /_/ > Y \ |
:stormlight.esper.net 372 MrGutsy :- /____ > |__| \____/|__| |__|_| /____/__\___ /|___| /__|
:stormlight.esper.net 372 MrGutsy :- \/ stormlight.esper.net \/ /_____/ \/
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Location: Newark NJ, United States
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Ports: 5555, 6665 - 6669, 6697 (SSL), 7000.
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Knight Radiant (Administrator): brynjar (brynjar at esper.net)
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Shardbearers (Operators): Raiden (raiden at esper.net)
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Terms of Service:
:stormlight.esper.net 372 MrGutsy :- Your use of this network constitutes an agreement to abide by the
:stormlight.esper.net 372 MrGutsy :- rules presented in the EsperNet AUP - http://esper.net/charter.php
:stormlight.esper.net 372 MrGutsy :- as well as any applicable U.S. and International laws.
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Further, your use of this network implies consent to a port scan
:stormlight.esper.net 372 MrGutsy :- to detect open proxies and otherwise compromised systems.
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Properly configured bots are permitted, but are required to follow
:stormlight.esper.net 372 MrGutsy :- the same rules as users. FServes are strictly prohibited.
:stormlight.esper.net 372 MrGutsy :- See http:/www.esper.net/bots.php for more information.
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- We reserve the right to remove anyone at any time for any reason.
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- New to IRC? Helpful information:
:stormlight.esper.net 372 MrGutsy :- http://www.esper.net/getting_started.php
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- USEFUL CHANNELS
:stormlight.esper.net 372 MrGutsy :- #dragonweyr - Network staff assistance
:stormlight.esper.net 372 MrGutsy :- #coders - Help with programming
:stormlight.esper.net 372 MrGutsy :- #lobby - General chat
:stormlight.esper.net 372 MrGutsy :- #help - General IRC help
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 372 MrGutsy :- Curious about our name? Check out The Stormlight Archive by Brandon
:stormlight.esper.net 372 MrGutsy :- Sanderson!
:stormlight.esper.net 372 MrGutsy :-
:stormlight.esper.net 376 MrGutsy :End of /MOTD command.
:MrGutsy MODE MrGutsy :+i
</code></pre>
<p>It appears to be connecting to the IRC server, but doesnt join the channel....
Whats wrong?? </p>
| 0 | 2016-08-14T16:34:37Z | 38,944,575 | <p>As @spectras noticed, you have to wait a little bit before sending JOINs.</p>
<p>The key is this reply from the server:</p>
<pre><code>:stormlight.esper.net 451 * :You have not registered
</code></pre>
<p>Which means you sent a command (the PRIVMSG and/or the JOIN) before your completed the registration process, which I guess it replying to the PING.</p>
<p>A usual (and good) practice is to send the initial messages after the MOTD is finished, ie. when you receive the <code>376</code> command.</p>
<hr>
<p>Off-topic remark: you should consider <a href="http://ircv3.net/specs/extensions/sasl-3.1.html" rel="nofollow">using SASL</a> instead of sending a PRIVMSG to NickServ. It is the standard for authenticating on IRC now.</p>
| 1 | 2016-08-14T17:09:31Z | [
"python",
"irc"
] |
Steps to Troubleshoot "django.db.utils.ProgrammingError: permission denied for relation django_migrations" | 38,944,551 | <p>What are some basic steps for troubleshooting and narrowing down the cause for the "django.db.utils.ProgrammingError: permission denied for relation django_migrations" error from Django?</p>
<p>I'm getting this message after what was initially a stable production server but has since had some changes to several aspects of Django, Postgres, Apache, and a pull from Github. In addition, it has been some time since those changes were made and I don't recall or can't track every change that may be causing the problem.</p>
<p>I get the message when I run <code>python manage.py runserver</code> or any other <code>python manage.py ...</code> command except <code>python manage.py check</code>, which states the system is good.</p>
| 0 | 2016-08-14T17:06:54Z | 39,070,745 | <p>I was able to solve my issue based on instructions from this <a href="http://stackoverflow.com/questions/12233046/django-permission-denied-when-trying-to-access-database-after-restore-migratio">question</a>. Basically, postgres privileges needed to be re-granted to the db user. In my case, that was the user I had setup in the virtual environment settings file. Run the following from the commandline (or within postgres) where <code>mydatabase</code> and <code>dbuser</code> should be your own database and user names: </p>
<pre><code>psql mydatabase -c "GRANT ALL ON ALL TABLES IN SCHEMA public to dbuser;"
psql mydatabase -c "GRANT ALL ON ALL SEQUENCES IN SCHEMA public to dbuser;"
psql mydatabase -c "GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to dbuser;"
</code></pre>
| 0 | 2016-08-22T02:50:14Z | [
"python",
"django",
"apache",
"postgresql",
"github"
] |
Detect grid nodes using OpenCV (or using something else) | 38,944,594 | <p>I have a grid on pictures (they are from camera). After binarization they look like this (red is 255, blue is 0):
<a href="http://i.stack.imgur.com/59Kz5.png"><img src="http://i.stack.imgur.com/59Kz5.png" alt="grid"></a></p>
<p>What is the best way to detect grid nodes (crosses) on these pictures?
Note: grid is distorted from cell to cell non-uniformly.</p>
<p><strong>Update:</strong></p>
<p>Some examples of different grids and thier distortions before binarization:
<a href="http://i.stack.imgur.com/z2nfJ.png"><img src="http://i.stack.imgur.com/z2nfJ.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/AxXl5.png"><img src="http://i.stack.imgur.com/AxXl5.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/qoWtt.png"><img src="http://i.stack.imgur.com/qoWtt.png" alt="enter image description here"></a></p>
| 10 | 2016-08-14T17:12:14Z | 39,003,571 | <p>I suppose that this can be a potential answer (actually mentioned in comments): <a href="http://opencv.itseez.com/2.4/modules/imgproc/doc/feature_detection.html?highlight=hough#houghlinesp" rel="nofollow">http://opencv.itseez.com/2.4/modules/imgproc/doc/feature_detection.html?highlight=hough#houghlinesp</a></p>
<p>There can also be other ways using skimage tools for feature detection. </p>
<p>But actually I think that instead of Hough transformation that could contribute to huge bloat and and lack of precision (straight lines), I would suggest trying Harris corner detection - <a href="http://docs.opencv.org/2.4/doc/tutorials/features2d/trackingmotion/harris_detector/harris_detector.html" rel="nofollow">http://docs.opencv.org/2.4/doc/tutorials/features2d/trackingmotion/harris_detector/harris_detector.html</a> . </p>
<p>This can be further adjusted (cross corners, so local maximum should depend on crossy' distribution) to your specific issue. Then some curves approximation can be done based on points got.</p>
| 1 | 2016-08-17T18:09:20Z | [
"python",
"opencv",
"pattern-recognition"
] |
Detect grid nodes using OpenCV (or using something else) | 38,944,594 | <p>I have a grid on pictures (they are from camera). After binarization they look like this (red is 255, blue is 0):
<a href="http://i.stack.imgur.com/59Kz5.png"><img src="http://i.stack.imgur.com/59Kz5.png" alt="grid"></a></p>
<p>What is the best way to detect grid nodes (crosses) on these pictures?
Note: grid is distorted from cell to cell non-uniformly.</p>
<p><strong>Update:</strong></p>
<p>Some examples of different grids and thier distortions before binarization:
<a href="http://i.stack.imgur.com/z2nfJ.png"><img src="http://i.stack.imgur.com/z2nfJ.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/AxXl5.png"><img src="http://i.stack.imgur.com/AxXl5.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/qoWtt.png"><img src="http://i.stack.imgur.com/qoWtt.png" alt="enter image description here"></a></p>
| 10 | 2016-08-14T17:12:14Z | 39,099,412 | <p>In cases like this I first try to find the best starting point.
So, first I thresholded your image (however I could also skeletonize it and just then threshold. But this way some data is lost irrecoverably):</p>
<p><img src="http://i.imgur.com/3497JwU.png" alt="Imgur"></p>
<p>Then, I tried loads of tools to get the most prominent features emphasized in bulk. Finally, playing with Gimp's G'MIC plugin I found this:</p>
<p><img src="http://i.imgur.com/RC7YRmx.png" alt="Imgur"></p>
<p>Based on the above I prepared a universal pattern that looks like this:</p>
<p><img src="http://i.imgur.com/0CD7TJF.png" alt="Imgur"></p>
<p>Then I just got a part of this image:</p>
<p><img src="http://i.imgur.com/xvkbn2k.png" alt="Imgur"></p>
<p>To help determine angle I made local Fourier freq graph - this way you can obtain your pattern local angle:</p>
<p><img src="http://i.imgur.com/D0X7iWE.png" alt="Imgur"></p>
<p>Then you can make a simple thick that works fast on modern GPUs - get difference like this (missed case):</p>
<p><img src="http://i.imgur.com/9QlqndS.png" alt="Imgur"></p>
<p>When there is hit the difference is minimal; what I had in mind talking about local maximums refers more or less to how the resulting difference should be treated. It wouldn't be wise to weight outside of the pattern circle difference the same as inside due to scale factor sensitivity. Thus, inside with cross should be weighted more in used algorithm. Nevertheless differenced pattern with image looks like this:</p>
<p><img src="http://i.imgur.com/qhmwVeJ.png" alt="Imgur"></p>
<p>As you can see it's possible to differentiate between hit and miss. What is crucial is to set proper tolerance and use Fourier frequencies to obtain angle (with thresholded images Fourier usually follows overall orientation of image analyzed).
The above way can be later complemented by Harris detection, or Harris detection can be modified using above patterns to distinguish two to four closely placed corners.
Unfortunately, all techniques are scale dependent in such case and should be adjusted to it properly.
There are also other approaches to your problem, for instance by watershedding it first, then getting regions, then disregarding foreground, then simplifying curves, then checking if their corners form a consecutive equidistant pattern. But to my nose it would not produce correct results.</p>
<p>One more thing - libgmic is G'MIC library from where you can directly or through bindings use transformations shown above. Or get algorithms and rewrite them in your app.</p>
| 2 | 2016-08-23T11:03:38Z | [
"python",
"opencv",
"pattern-recognition"
] |
Detect grid nodes using OpenCV (or using something else) | 38,944,594 | <p>I have a grid on pictures (they are from camera). After binarization they look like this (red is 255, blue is 0):
<a href="http://i.stack.imgur.com/59Kz5.png"><img src="http://i.stack.imgur.com/59Kz5.png" alt="grid"></a></p>
<p>What is the best way to detect grid nodes (crosses) on these pictures?
Note: grid is distorted from cell to cell non-uniformly.</p>
<p><strong>Update:</strong></p>
<p>Some examples of different grids and thier distortions before binarization:
<a href="http://i.stack.imgur.com/z2nfJ.png"><img src="http://i.stack.imgur.com/z2nfJ.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/AxXl5.png"><img src="http://i.stack.imgur.com/AxXl5.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/qoWtt.png"><img src="http://i.stack.imgur.com/qoWtt.png" alt="enter image description here"></a></p>
| 10 | 2016-08-14T17:12:14Z | 39,120,700 | <p>Maybe you cloud calculate <a href="https://en.wikipedia.org/wiki/Hough_transform" rel="nofollow">Hough Lines</a> and determine the intersections. An OpenCV documentation can be found <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html" rel="nofollow">here</a></p>
| 0 | 2016-08-24T10:25:19Z | [
"python",
"opencv",
"pattern-recognition"
] |
Pandas Timestamp - Cannot convert arg to a time error | 38,944,599 | <p>I am trying to find the <code>min()</code> value between two points using <code>between_time</code>. I have created two columns that I would like to use as my start and end time to find the minimum value and add the output to a new column:</p>
<p>This is a snip of the df: </p>
<pre><code>df[['Date_Time','d1_idx_last','Low']]
Date_Time d1_idx_last Low
Timestamp
2015-09-01 09:30:00.000 2015-09-01 09:30:00.000 2015-09-01 16:14:51.000 1887.750
2015-09-01 09:30:01.000 2015-09-01 09:30:01.000 2015-09-01 16:14:51.000 1888.250
2015-09-01 09:30:01.200 2015-09-01 09:30:01.200 2015-09-01 16:14:51.000 1888.000
2015-09-01 09:30:10.100 2015-09-01 09:30:10.100 2015-09-01 16:14:51.000 1889.250
2015-09-01 09:30:11.100 2015-09-01 09:30:11.100 2015-09-01 16:14:51.000 1889.500
</code></pre>
<p>I am trying to use this code:</p>
<pre><code>df.Low.between_time(df.Date_Time, df.d1_idx_last, include_start=True, include_end=True)
</code></pre>
<p>and get this error:</p>
<pre><code>Cannot convert arg [1441099800000000000 1441099801000000000 1441099801200000000 ...,
1470924200100000000 1470924369230000000 1470924793157000000] to a time
</code></pre>
<p>The columns <code>'Date_Time'</code> & <code>'d1_idx_last'</code> are both type <code>pandas.tslib.Timestamp</code>.</p>
<p><strong>Update to clarify:</strong></p>
<p>So if we look at the first row it shows </p>
<p><code>'Date_Time' 2015-09-01 09:30:00.000</code>
<code>'d1_idx_last'2015-09-01 16:14:51.000</code></p>
<p>On this row the time between <code>'Date_Time'</code> & <code>'d1_idx_last'</code> captures a full trading day (09:30-16:15) and I want the low of the time between these two points.</p>
<p>On this day the market went as low as 1863.500 so that would be the min value for (09:30-16:15). </p>
<pre><code>df[['Low']]['2015-09-01'].min()
Low 1863.500
dtype: float64
</code></pre>
<p>If the low of 1863.500 came at 13:00 the rolling low would be higher after this point.</p>
<p>I want a new column called <code>df['subset_low']</code> that checks <code>'Date_Time'</code> & <code>'d1_idx_last'</code> on each row and finds the low between this period and adds it to df['subset_low']. It is checking the current time and the last point of the day and showing what the low will be between this time.</p>
<p>Another example for @Maxu using fake data in the <code>Low</code> and (desired) <code>subset_low</code> columns:
<a href="http://i.stack.imgur.com/ARpuV.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ARpuV.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-14T17:12:59Z | 38,944,679 | <p><strong>UPDATE:</strong> using ugly method - <code>apply(..., axis=1)</code>: </p>
<pre><code>In [170]: df['subset_low'] = df.apply(lambda r: df.query('@r.Date_Time <= index <= @r.d1_idx_last').Low.min(), axis=1)
In [171]: df
Out[171]:
Date_Time d1_idx_last Low subset_low
idx
2015-09-01 09:30:00.000 2015-09-01 09:30:00.000 2015-09-01 16:14:51 2 1
2015-09-01 09:30:01.000 2015-09-01 09:30:01.000 2015-09-01 16:14:51 1 1
2015-09-01 09:30:01.200 2015-09-01 09:30:01.200 2015-09-01 16:14:51 3 3
2015-09-01 09:30:10.100 2015-09-01 09:30:10.100 2015-09-01 16:14:51 4 3
2015-09-01 09:30:11.100 2015-09-01 09:30:11.100 2015-09-01 16:14:51 3 3
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>as @JonClements already <a href="http://stackoverflow.com/questions/38944599/pandas-timestamp-cannot-convert-arg-to-a-time-error/38944679#comment65244189_38944599">said</a> the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">between_time()</a> method expects scalar values for the first two arguments- (<code>start_time</code>, <code>end_time</code>) and it checks only the time part.</p>
<p>Demo:</p>
<pre><code>In [72]: df.between_time('09:30:10','09:30:15')
Out[72]:
Date_Time d1_idx_last Low
idx
2015-09-01 09:30:10.100 2015-09-01 09:30:10.100 2015-09-01 16:14:51 1889.25
2015-09-01 09:30:11.100 2015-09-01 09:30:11.100 2015-09-01 16:14:51 1889.50
</code></pre>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow">query()</a> method instead</p>
<pre><code>In [70]: df.query('Date_Time <= index <= d1_idx_last')
Out[70]:
Date_Time d1_idx_last Low
idx
2015-09-01 09:30:00.000 2015-09-01 09:30:00.000 2015-09-01 16:14:51 1887.75
2015-09-01 09:30:01.000 2015-09-01 09:30:01.000 2015-09-01 16:14:51 1888.25
2015-09-01 09:30:01.200 2015-09-01 09:30:01.200 2015-09-01 16:14:51 1888.00
2015-09-01 09:30:10.100 2015-09-01 09:30:10.100 2015-09-01 16:14:51 1889.25
2015-09-01 09:30:11.100 2015-09-01 09:30:11.100 2015-09-01 16:14:51 1889.50
</code></pre>
<p>How do I get the <code>min()</code> of <code>df.Low</code> between <code>Date_Time</code> and <code>d1_idx_last</code> using <code>df.query</code>?</p>
<pre><code>In [74]: df.query('Date_Time <= index <= d1_idx_last').Low.min()
Out[74]: 1887.75
</code></pre>
| 2 | 2016-08-14T17:21:21Z | [
"python",
"pandas"
] |
python: can't open file 'scriptbootstrap.py' | 38,944,608 | <p>I am trying to start the electron app on windows via <a href="https://github.com/electron/electron/blob/master/docs/development/build-instructions-windows.md" rel="nofollow">https://github.com/electron/electron/blob/master/docs/development/build-instructions-windows.md</a></p>
<p>I have completed the first two steps successfully and is stuck at the building section.</p>
<p>When I try to run <code>python script\build.py</code>, the following errors occur:</p>
<pre><code>python: can't open file 'scriptbootstrap.py': [Errno 2] No such file or directory
</code></pre>
<p>and not just this command specifically. Any command along that line such as <code>python script\build.py -c D</code> i run, gets me into trouble as well. I am running the command via windows bash</p>
<p>I think it should be looking for script/bootstrap.py but instead look for </p>
| 0 | 2016-08-14T17:13:48Z | 38,945,384 | <p>First, I would like to know whether the <code>python script\bootstrap.py -v</code> worked for you.</p>
<p>See sample output, on my machine, (using git bash)</p>
<pre><code>Anubhavs@DDSPL1392 MINGW64 /e/Projects/electron (master)
$ python script/bootstrap.py -v
Submodule 'vendor/boto' (https://github.com/boto/boto.git) registered for path 'vendor/boto'
Submodule 'vendor/breakpad' (https://github.com/electron/chromium-breakpad.git) registered for path 'vendor/breakpad'
Submodule 'vendor/brightray' (https://github.com/electron/brightray.git) registered for path 'vendor/brightray'
Submodule 'vendor/crashpad' (https://github.com/electron/crashpad.git) registered for path 'vendor/crashpad'
Submodule 'vendor/depot_tools' (https://chromium.googlesource.com/chromium/tools/depot_tools.git) registered for path 'vendor/depot_tools'
Submodule 'vendor/native_mate' (https://github.com/zcbenz/native-mate.git) registered for path 'vendor/native_mate'
Submodule 'vendor/node' (https://github.com/electron/node.git) registered for path 'vendor/node'
Submodule 'vendor/requests' (https://github.com/kennethreitz/requests) registered for path 'vendor/requests'
Cloning into 'vendor/boto'...
remote: Counting objects: 42186, done.
<more lines cloning different dependencies.>
.
.
.
</code></pre>
<p>Second,
I would recommend using '/' in paths instead of '\' . This works well in windows cmd. But, is not how paths are handled across different scripts. '/' always works.</p>
<p>Run both commands, <code>python script\bootstrap.py -v</code> as <code>python script/bootstrap.py -v</code>, and <code>python script\build.py</code> as <code>python script/build.py</code></p>
| 0 | 2016-08-14T18:35:50Z | [
"javascript",
"python",
"node.js",
"electron"
] |
Python import failure | 38,944,665 | <p>Got some strange import error which is as much strangely reported by interpreter.</p>
<p>I use CPython-3.5</p>
<p>Directory structure:</p>
<pre><code>.
+-- outer
| +-- inner
| | +-- __init__.py
| | +-- first.py
| | +-- second.py
| +-- __init__.py
+-- main.py
</code></pre>
<p>main.py:</p>
<pre><code>import outer.inner
print(outer.inner.var)
</code></pre>
<p>outer/__init__.py: empty</p>
<p>outer/inner/__init__.py:</p>
<pre><code>import outer.inner.first
var = outer.inner.first.var
</code></pre>
<p>outer/inner/first.py:</p>
<pre><code>import outer.inner.second
var = outer.inner.second.var
</code></pre>
<p>outer/inner/second.py:</p>
<pre><code>var = 1337
</code></pre>
<p>then, I run <code>main.py</code> and script fails with this stack trace:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 1, in <module>
import outer.inner
File "/outer/inner/__init__.py", line 1, in <module>
import outer.inner.first
File "/outer/inner/first.py", line 2, in <module>
var = outer.inner.second.var
AttributeError: module 'outer' has no attribute 'inner'
</code></pre>
<p>So, Python does not want to bind names correctly. Although import statement in first.py: <code>import outer.inner.second</code> is executed without crashing, this statement binds to name <code>outer</code> something like an empty package, which doesn't have (but should) the module named <code>inner</code> </p>
<p>What do I do wrong?</p>
| 0 | 2016-08-14T17:19:41Z | 38,945,102 | <p>It's better to import relative paths, not absolute ones. I do not know what you are trying to achieve, but correct way to import something from a file on the same level is to use a dot <code>.</code> so In your <code>first</code> file use something like:</p>
<pre><code>from .second import var as second_var
var = second_var
</code></pre>
<p>And in your <code>inner/__init__.py</code> file something like:</p>
<pre><code>from .first import var as first_var
var = first_var
</code></pre>
<p>This allows you to avoid name conflicts as well as keep names simple, unique and generally more readible code.</p>
<p>EDIT:</p>
<p>Also if you are nw to python consider adding interpreter comment in your <code>main.py</code> module. It's convenient for users of Unix-like systems (OS X, Linux etc.)</p>
<pre><code>#!/usr/bin/env python3
</code></pre>
| 0 | 2016-08-14T18:07:24Z | [
"python",
"python-3.x"
] |
How to Drop All The Rows Based on Multiple Values Found in the "Fruit "Column? | 38,944,673 | <p>I have this simple dataframe</p>
<pre><code>Num Fruit Price
1 Apple 1.00
1 Apple 1.00
2 Apple 1.50
2 Orange 1.50
3 Orange 1.00
3 Banana 0.50
</code></pre>
<p>I want to drop all the rows which have the fruit <code>Apple</code> or <code>Orange</code></p>
<p>The expected output should be like this:</p>
<pre><code>Num Fruit Price
3 Banana 0.50
</code></pre>
<p>I tried to doing the following syntax, but somehow it did not drop all the rows in the dataframe</p>
<pre><code>>>> df.drop(df.Fruit.isin(["Apple","Orange"]))
Fruit Num Price
2 Apple 2 1.50
3 Orange 2 1.50
4 Orange 3 1.00
5 Banana 3 0.50
</code></pre>
<p>Any suggestion how to solve this?</p>
| -1 | 2016-08-14T17:20:15Z | 38,944,700 | <p>You need to pass the indices of the rows to be dropped, but you are passing a boolean array. You can change it to:</p>
<pre><code>df.drop(df[df.Fruit.isin(["Apple", "Orange"])].index)
Out:
Num Fruit Price
5 3 Banana 0.5
</code></pre>
<p>Or you can select the rows that don't contain apple or orange:</p>
<pre><code>df[~(df.Fruit.isin(["Apple", "Orange"]))]
Out:
Num Fruit Price
5 3 Banana 0.5
</code></pre>
| 3 | 2016-08-14T17:24:45Z | [
"python",
"pandas",
"dataframe"
] |
Python - CSS Not Working in Embedded HTML | 38,944,721 | <p>I am having trouble getting the CSS to link properly. It's named correctly. It just doesn't want to work. I've tried every possible way to type it out. I've heard a bunch of different things. Some say you have to type the entire project URL out (simple-login/css/style.css). I've also heard you just have to go up one level (../css/style.css). I've also heard you don't have to do that (css/style.css). Nothing seems to want to work. It always works fine in regular HTML files. Do I have to import something? I'm really getting frustrated. I'm not supposed to embed the CSS directly in this project. It's got to be a separate file.</p>
<pre><code>import webapp2 #Use the webapp2 Library
class MainHandler(webapp2.RequestHandler): #declaring a class
def get(self):
if self.request.GET: #variables that store the information from the forms. This information will be used in the write() method to put the information on the page. Parts of the html, stored in variables, are strung together in the write() method.
user = self.request.GET['user']
email = self.request.GET['email']
games = self.request.GET['games']
city = self.request.GET['city']
state = self.request.GET['state']
gender = self.request.GET['gender']
self.response.write(Page.interface_head + Page.interface_body + Page.interface_info + Page.info_name + user + '</br>' + Page.info_email + email + '</br>' + Page.info_games + games + '</br>' + Page.info_city + city + ', ' + state + '</br>' + Page.info_gender + gender + Page.info_close + Page.interface_closing)
else: #This is what the write method does when there is no response to the request. Meaning this is the page you are met with in the beginning. Parts of the html, stored in variables, are strung together in the write() method.
self.response.write(Page.interface_head + Page.interface_body + Page.interface_forms + Page.interface_closing)
class Page(object):
interface_head = '''<!Doctype HTML> <!--This houses all code in the head of my HTML including the style portion.-->
<html>
<head>
<title>Simple Form</title>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>'''
interface_body = '''<nav><h2>Game<span>Stuff</span></h2></nav> <!--This is the code for the nav all the way down to the forms.-->'''
interface_info = '''<div class='info_background'> <!--This is the start of the div that houses the information entered from the forms. Below are all the labels split up into vriables. This is for organization and will be reassembled in the if and else statement.-->
<h3>Is this information correct?</h3>'''
info_name = '''<label>Name: </label>'''
info_email = '''<label>Email: </label>'''
info_games = '''<label>Favorite Games: </label>'''
info_city = '''<label>City/State: </label>'''
info_gender = '''<label>Gender: </label>'''
info_close = '''
</br><button>Yes</button><button>No</button></div>'''
interface_forms = '''<form method='GET'><!--These forms enter the information to be stored in the variables in the if statement.-->
<h3>Sign Up for a free account!</h3>
<label>Name: </label><input type='text' name='user' />
<label>Email: </label><input type='text' name='email' /></br>
<label>Favorite Games: </label><input type='text' name='games' />
<label>City: </label><input type='text' name='city' style='width: 120px;' />
<label>State: </label><select name='state'>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<label>Gender: </label><input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other
<input type="submit" value='Create Account'/> <!--This submit button finalizes all the information put in the forms.-->
</form>'''
interface_closing = '''
<footer>&copy;Made by Matt Lee</footer> <!--This is a footer I made just so there was something final on the page.-->
</body>
</html>'''
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
</code></pre>
| 1 | 2016-08-14T17:25:39Z | 39,115,229 | <p>I would like to suggest you to use <a href="https://cloud.google.com/appengine/docs/python/getting-started/generating-dynamic-content-templates" rel="nofollow">Jinja 2</a>. It will help you to organize your code. It is a template language which is really good to use with Webapp2.</p>
| 0 | 2016-08-24T05:41:47Z | [
"python",
"html",
"css"
] |
Trying to get lxml to print a specific number in python | 38,944,759 | <p>I'm trying to get lxml to print the selected in python:
<a href="http://imgur.com/a/joeql" rel="nofollow">http://imgur.com/a/joeql</a></p>
<p>The code I have isn't much but here it is</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://www.pathofexile.com/forum/view-thread/1703834')
tree = html.fromstring(page.content)
winner = tree.xpath(//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7])
print,winner
</code></pre>
| 1 | 2016-08-14T17:29:47Z | 38,944,910 | <p>A syntax error means you are writing invalid python, and that does not necessarily mean there is something wrong with your logic/approach.</p>
<p>Make sure to surround the argument inside your invocation of tree.xpath with single quotes.</p>
<pre><code>winner = tree.xpath('//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7]')
</code></pre>
| 1 | 2016-08-14T17:45:55Z | [
"python",
"web-scraping",
"lxml"
] |
Trying to get lxml to print a specific number in python | 38,944,759 | <p>I'm trying to get lxml to print the selected in python:
<a href="http://imgur.com/a/joeql" rel="nofollow">http://imgur.com/a/joeql</a></p>
<p>The code I have isn't much but here it is</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://www.pathofexile.com/forum/view-thread/1703834')
tree = html.fromstring(page.content)
winner = tree.xpath(//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7])
print,winner
</code></pre>
| 1 | 2016-08-14T17:29:47Z | 38,944,941 | <p>The syntax error you see is because you have not enclosed the XPath string into quotes, fix it:</p>
<pre><code>winner = tree.xpath('//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7]')
</code></pre>
<p>The <em>actual</em> problem is that the <em>table content is dynamically formed</em> via JavaScript that is executed in the browser. What you can do is to parse the <code>script</code> tag that has the desired data inside the JSON object, extract the JSON string and load it into the Python data structure via <code>json.loads()</code>:</p>
<pre><code>import json
import re
from lxml import html
import requests
page = requests.get('https://www.pathofexile.com/forum/view-thread/1703834')
tree = html.fromstring(page.content)
script = tree.xpath('//script[contains(., "var json")]/text()')[0]
obj_string = re.search(r"var json = (\{.*?\}),$", script, re.MULTILINE).group(1)
obj = json.loads(obj_string)
# print entries
entries = obj['ladder']['entries']
for entry in entries:
print(entry['account']['name'])
</code></pre>
<p>Prints account names (just as a proof it is working):</p>
<pre><code>Havoc6
Steelmage
Olecgolec
...
Anafobia
nokieka2
HoGji
</code></pre>
| 1 | 2016-08-14T17:49:04Z | [
"python",
"web-scraping",
"lxml"
] |
Filter out all lists of a dictionary based on a condition applied to one of the lists | 38,944,769 | <p>I have this dictionary:</p>
<pre><code>d={'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'], 'weight': [165, 189,
220, 141, 260, 174], 'height': [66, 71, 72, 68, 58, 62]}
</code></pre>
<p>And I want to filter out all its lists so that they contain only the items that correspond to a height of greater than 70.</p>
<p>I know how to filter lists individually. For instance, the height list:</p>
<pre><code>d["height"]=[height for height in d["height"] if height>70]
</code></pre>
<p>And that will return the dictionary with the height list filtered out:</p>
<pre><code>{'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'], 'weight': [165, 189,
220, 141, 260, 174], 'height': [71, 72]}
</code></pre>
<p>However, that's not what I want. What I want is:</p>
<pre><code>{'names': ['Amir', 'Matt'], 'weight': [189,220], 'height': [71, 72]}
</code></pre>
<p>Anyone can think of how to do this?</p>
| -1 | 2016-08-14T17:30:36Z | 38,944,805 | <p>You can use dictionary comprehension.</p>
<pre><code>d = {
'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'],
'weight': [165, 189, 220, 141, 260, 174],
'height': [66, 71, 72, 68, 58, 62]
}
filtered_dict = {
key: [value for i, value in enumerate(d[key]) if d['height'][i] > 70]
for key in d
}
print filtered_dict # {'names': ['Amir', 'Matt'], 'weight': [189, 220], 'height': [71, 72]}
</code></pre>
| 3 | 2016-08-14T17:35:00Z | [
"python",
"list",
"dictionary"
] |
Why do I get an AttributeError with Python3.4's `unittest` library? | 38,944,798 | <p>So here is my code:</p>
<pre><code>import unittest
class Primes:
@staticmethod
def first(n):
<python code here>
class Test(unittest.TestCase):
def __init__(self):
pass
def assert_equals(self, l, m):
self.assertEqual(l, m)
Test = Test()
Test.assert_equals(Primes.first(1), [2])
</code></pre>
<p>Whenever I run my code, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "firstNPrimes.py", line 37, in <module>
Test.assert_equals(Primes.first(1), [2])
File "firstNPrimes.py", line 34, in assert_equals
self.assertEqual(l, m)
File "/usr/lib/python3.4/unittest/case.py", line 796, in assertEqual
assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python3.4/unittest/case.py", line 777, in _getAssertEqualityFunc
asserter = self._type_equality_funcs.get(type(first))
AttributeError: 'Test' object has no attribute '_type_equality_funcs'
</code></pre>
<p>I don't understand what the problem is here.</p>
| 0 | 2016-08-14T17:34:32Z | 38,944,921 | <p>You get the error because you're using <code>unittest</code> incorrectly. Per <a href="https://docs.python.org/3/library/unittest.html#basic-example" rel="nofollow">the example in the docs</a>, your tests should look like:</p>
<pre><code>import unittest
class TestPrimes(unittest.TestCase):
def test_singlePrime_returnsListContainingTwo(self):
self.assertEqual(Primes.first(1), [2])
def test_whateverCase_expectedOutcome(self):
self.assertEqual(Primes.first(...), ...)
if __name__ == '__main__': #Â optional, but makes import and reuse easier
unittest.main()
</code></pre>
<p>You can't just instantiate the test case class yourself and call the methods, that skips all of the test discovery and setup.</p>
| 1 | 2016-08-14T17:47:00Z | [
"python",
"python-unittest"
] |
How to add data-attribute to django modelform modelchoicefield | 38,944,814 | <p>I have a django modelform 'Recipe' with a foreignkey field to a model 'Ingredient'.</p>
<p>When rendering the form I get a SELECT list that have an ID matching the ingredients ID and text display equal to the string representation of the field.</p>
<p>However, I want to add a data-attribute to the select list that matches the rendered option from the Ingredient queryset.</p>
<p>For example, lets say this is what is currently being rendered:</p>
<pre><code><option value="1158">Carrots</option>
<option value="1159">Strawberry</option>
<option value="1160">Onion</option>
<option value="1161">Spinach</option>
</code></pre>
<p>But I want to add a data attribute for the related objects:</p>
<pre><code><option value="1158" data-ingredient-type="vegetable">Carrots</option>
<option value="1159" data-ingredient-type="fruit">Strawberry</option>
<option value="1160" data-ingredient-type="vegetable">Onion</option>
<option value="1161" data-ingredient-type="vegetable">Spinach</option>
</code></pre>
| 0 | 2016-08-14T17:35:53Z | 38,945,002 | <p>Why not <a href="https://docs.djangoproject.com/en/dev/topics/forms/#rendering-fields-manually" rel="nofollow">render the fields manually</a>?<br>
It''ll be something like </p>
<pre><code><select>
{% for option in form.ingredient.choices %}
<option value="{{ option.id }}" data-ingredient-type={{ option.type }}>{{ option.name }}</option>
{% endfor %}
</select>
</code></pre>
<p>Or maybe in you model form class you add the <a href="https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs" rel="nofollow">attribute</a> to it, but this must be a string (or probably a function) </p>
<pre><code>widgets = { ...
'ingredients' = forms.Select(attrs={'data-ingredient-type': 'fruit'}),
...}
</code></pre>
| 0 | 2016-08-14T17:54:26Z | [
"python",
"django",
"django-forms"
] |
Scipy: sparse matrix conditional removal of columns | 38,945,093 | <p>I have a large (79 000 x 480 000) sparse csr matrix. I am trying to remove all columns (within a certain range) for which each value < k.</p>
<p>In regular numpy matrices this is simply done by a mask:</p>
<pre><code>m = np.array([[0,2,1,1],
[0,4,2,0],
[0,3,4,0]])
mask = (arr < 2)
idx = mask.all(axis=0)
result = m[:, ~idx]
print result
>>> [[2 1]
[4 2]
[3 4]]
</code></pre>
<p>The unary bitwise negation operator ~ and boolean mask functionality are not available for sparse matrices however. What is the best method to:</p>
<ol>
<li>Obtain the indices of columns where all values fulfill condition e < k.</li>
<li>Remove these columns based on the list of indices.</li>
</ol>
<p>Some things to note:</p>
<ol>
<li>The columns represent ngram text features: there are no columns in the matrix for which each element is zero. </li>
</ol>
<p>Is using the csr matrix format even a plausible choice for this?
Do I transpose and make use of .nonzero()? I have a fair amount of working memory (192GB) so time efficiency is preferable to memory efficiency.</p>
| 2 | 2016-08-14T18:06:10Z | 38,945,428 | <p>If I do</p>
<pre><code>M = sparse.csr_matrix(m)
M < 2
</code></pre>
<p>I get an efficiency warning; all the 0 values of M satisfy the condition,</p>
<pre><code>In [1754]: print(M)
(0, 1) 2
(0, 2) 1
(0, 3) 1
(1, 1) 4
(1, 2) 2
(2, 1) 3
(2, 2) 4
In [1755]: print(M<2)
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:275: SparseEfficiencyWarning: Comparing a sparse matrix with a scalar greater than zero using < is inefficient, try using >= instead.
warn(bad_scalar_msg, SparseEfficiencyWarning)
(0, 0) True # not in M
(0, 2) True
(0, 3) True
(1, 0) True # not in M
(1, 3) True
(2, 0) True # not in M
(2, 3) True
In [1756]: print(M>=2) # all a subset of M
(0, 1) True
(1, 1) True
(1, 2) True
(2, 1) True
(2, 2) True
</code></pre>
<p>If <code>I=M>=2</code>; there isn't an <code>all</code> method, but there is a <code>sum</code>.</p>
<pre><code>In [1760]: I.sum(axis=0)
Out[1760]: matrix([[0, 3, 2, 0]], dtype=int32)
</code></pre>
<p><code>sum</code> is actually performed using a matrix multiplication</p>
<pre><code>In [1769]: np.ones((1,3),int)*I
Out[1769]: array([[0, 3, 2, 0]], dtype=int32)
</code></pre>
<p>Using <code>nonzero</code> to find the nonzero columns:</p>
<pre><code>In [1778]: np.nonzero(I.sum(axis=0))
Out[1778]: (array([0, 0], dtype=int32), array([1, 2], dtype=int32))
In [1779]: M[:,np.nonzero(I.sum(axis=0))[1]]
Out[1779]:
<3x2 sparse matrix of type '<class 'numpy.int32'>'
with 6 stored elements in Compressed Sparse Row format>
In [1780]: M[:,np.nonzero(I.sum(axis=0))[1]].A
Out[1780]:
array([[2, 1],
[4, 2],
[3, 4]], dtype=int32)
</code></pre>
<p>General points:</p>
<ul>
<li><p>watch out for those 0 values when doing comparisons</p></li>
<li><p>watch out for False values when doing logic on sparse matrices</p></li>
<li><p>sparse matrices are optimized for math, especially matrix multiplication</p></li>
<li><p>sparse indexing isn't quite as powerful as array indexing; and not as fast either.</p></li>
<li><p>note when operations produce a dense matrix</p></li>
</ul>
| 3 | 2016-08-14T18:40:33Z | [
"python",
"numpy",
"matrix",
"scipy",
"sparse-matrix"
] |
monitoring jboss process with icinga/nagios | 38,945,299 | <p>I want to monitor jboss if its running or not through Icinga.</p>
<p>I don't want to check <code>/etc/inid.d/jboss status</code> as sometimes service is up but some of the jboss is killed or hang & jboss doesn't work properly.</p>
<p>I would like to create a script to monitor all of its process from <code>ps</code> output. But few servers are running in standalone mode, domain(master,slave) and processes are different for each case.</p>
<p>I'm not sure from where do I start. Anyone here who did same earlier? Just looking for the idea to do this.</p>
| 0 | 2016-08-14T18:26:52Z | 38,962,513 | <p>Reading about the availability of plugins from a quick Google search led me to JMX. And obviously check_jmx4perl and Jolokia which have been a swiss army knife for monitoring java application servers. I've used it with tomcat and websphere but it should work with jboss as well.</p>
<p>In case you're using Icinga 2, there already is a contributed plugin check command definition available.</p>
<p><a href="http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/plugin-check-commands?highlight-search=jmx#plugin-check-command-jmx4perl" rel="nofollow">http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/plugin-check-commands?highlight-search=jmx#plugin-check-command-jmx4perl</a></p>
| 1 | 2016-08-15T20:25:56Z | [
"python",
"shell",
"jboss",
"nagios",
"icinga"
] |
monitoring jboss process with icinga/nagios | 38,945,299 | <p>I want to monitor jboss if its running or not through Icinga.</p>
<p>I don't want to check <code>/etc/inid.d/jboss status</code> as sometimes service is up but some of the jboss is killed or hang & jboss doesn't work properly.</p>
<p>I would like to create a script to monitor all of its process from <code>ps</code> output. But few servers are running in standalone mode, domain(master,slave) and processes are different for each case.</p>
<p>I'm not sure from where do I start. Anyone here who did same earlier? Just looking for the idea to do this.</p>
| 0 | 2016-08-14T18:26:52Z | 39,252,775 | <p>You can find it here : <a href="https://exchange.nagios.org/components/com_mtree/attachment.php?link_id=1274&cf_id=24" rel="nofollow">check_jmx</a>, this will monitor jboss process. You need to add some $JAVA_OPTS to enable this in jboss.</p>
| 0 | 2016-08-31T14:47:25Z | [
"python",
"shell",
"jboss",
"nagios",
"icinga"
] |
monitoring jboss process with icinga/nagios | 38,945,299 | <p>I want to monitor jboss if its running or not through Icinga.</p>
<p>I don't want to check <code>/etc/inid.d/jboss status</code> as sometimes service is up but some of the jboss is killed or hang & jboss doesn't work properly.</p>
<p>I would like to create a script to monitor all of its process from <code>ps</code> output. But few servers are running in standalone mode, domain(master,slave) and processes are different for each case.</p>
<p>I'm not sure from where do I start. Anyone here who did same earlier? Just looking for the idea to do this.</p>
| 0 | 2016-08-14T18:26:52Z | 39,367,798 | <p>I did this by monitored jboss process using <code>ps aux | grep "\-D\[Standalone\]</code>" for standalone mode and <code>ps aux | grep "\-D\[Server"</code> for domain mode.</p>
| 0 | 2016-09-07T10:46:33Z | [
"python",
"shell",
"jboss",
"nagios",
"icinga"
] |
Trying to make an apk file online with Python/Kivy, but it does not work. Why? | 38,945,376 | <p>I'm trying to learn to program in <code>Python2.7/Kivy</code> and build applications for Android platform.</p>
<p>So I uploaded a zip-file containing a <code>main.py</code> and a <code>kv</code> file to <a href="http://android.kivy.org" rel="nofollow">http://android.kivy.org</a>, but as I push the <code>submit</code> button I get:</p>
<blockquote>
<p>500 Internal Server Error</p>
</blockquote>
<p>I couldn't find any other questions dealing with this problem. What am I doing wrong? The program runs perfectly fine under Windows 7 and I filled the textboxes on the site correctly (as far as I can tell).</p></p>
| 0 | 2016-08-14T18:34:58Z | 38,945,406 | <p>if it's 500 internal server error, it's most probably from the server side not your fault.<br>
May be should try later.</p>
| 0 | 2016-08-14T18:38:22Z | [
"android",
"python",
"apk",
"kivy",
"internal-server-error"
] |
How to check if window is on Fullscreen in Tkinter? | 38,945,412 | <p>I made <strong>F11</strong> toggle fullscreen on. But how can I make it so that <strong>F11</strong> can both toggle fullscreen on and off ?</p>
<p>I tried to make an [if] statement so it will turn it off if the window was previously toggled to fullscreen but I couldn't find a way to check if the window was already toggled or not.</p>
<p>Any help is appreciated, thank you.</p>
<p>Updated Solution :This is the final code that seems to work without a problem.</p>
<pre><code>def toggle_fullscreen(event):
if (root.attributes('-fullscreen')):
root.attributes('-fullscreen', False)
else:
root.attributes('-fullscreen', True)
root.bind("<F11>", toggle_fullscreen)
</code></pre>
| -2 | 2016-08-14T18:39:19Z | 38,945,602 | <p>This is the method I mentioned in my comment above:</p>
<pre><code>from tkinter import *
root = Tk()
root.focus_set()
var = 0
def f(event):
global var
if var == 0:
root.attributes("-fullscreen", True)
var = 1
else:
root.attributes("-fullscreen", False)
var = 0
root.bind("<F11>", f)
</code></pre>
| 1 | 2016-08-14T18:59:20Z | [
"python",
"tkinter",
"fullscreen"
] |
How to check if window is on Fullscreen in Tkinter? | 38,945,412 | <p>I made <strong>F11</strong> toggle fullscreen on. But how can I make it so that <strong>F11</strong> can both toggle fullscreen on and off ?</p>
<p>I tried to make an [if] statement so it will turn it off if the window was previously toggled to fullscreen but I couldn't find a way to check if the window was already toggled or not.</p>
<p>Any help is appreciated, thank you.</p>
<p>Updated Solution :This is the final code that seems to work without a problem.</p>
<pre><code>def toggle_fullscreen(event):
if (root.attributes('-fullscreen')):
root.attributes('-fullscreen', False)
else:
root.attributes('-fullscreen', True)
root.bind("<F11>", toggle_fullscreen)
</code></pre>
| -2 | 2016-08-14T18:39:19Z | 38,945,757 | <p><code>root.attributes</code> can be called with only a single argument to get the value of that argument. </p>
<pre><code>if (root.attribute('-fullscreen')):
...
else
...
</code></pre>
| 1 | 2016-08-14T19:18:57Z | [
"python",
"tkinter",
"fullscreen"
] |
How to put a " inside of a variable python | 38,945,413 | <p>I have been trying to make a encryption program recently, and I cant quite figure out how to place double quotes inside a variable, in this case 'alphabet'. Currently I have every character I need except for " and a tab key, keep in mind I'm just a beginner and help would be appreciated. - Thanks!</p>
<pre><code>while True:
plaintext = input('Enter messege: ')
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,!?#@$%^&*()-_=+[]{}|\:;`~<>/ '"
key = not telling you what I am
cipher = ''
for c in plaintext:
if c in alphabet:
cipher += alphabet[(alphabet.index(c)+key)%(len(alphabet))]
print ('your encrypted message is: ' + cipher)
</code></pre>
| 0 | 2016-08-14T18:39:26Z | 38,945,444 | <p>You can use <code>\"</code></p>
<p>Sample:</p>
<pre><code>print ("Hello \"")
</code></pre>
<p>Output:</p>
<pre><code>Hello "
</code></pre>
| 2 | 2016-08-14T18:42:23Z | [
"python"
] |
Trying to flatten array in numpy | 38,945,499 | <p>I'm new to numpy and trying to flatten a 1000,1000 array created from a pandas dataframe. the code i've used is:</p>
<pre><code> lidor_array=lidor_df.values
print(lidor_array.shape)
lidor_array.flatten()
print(lidor_array.shape)
</code></pre>
<p>the shapes are output as (1000,1000) for both the pre and post flattened array. what am i missing?</p>
<p>many thanks for your help</p>
| 0 | 2016-08-14T18:48:01Z | 38,945,549 | <p><code>flatten</code> is not performed in-place. It returns a copy:</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html</a></p>
<p>You could either do:</p>
<pre><code>lidor_array.flatten().shape
</code></pre>
<p>or </p>
<pre><code>lidor_array_flat = arr.flatten()
print lidor_array_flat.shape
</code></pre>
| 1 | 2016-08-14T18:52:52Z | [
"python",
"numpy"
] |
How does cv2.fitEllipse handle width/height with regards to rotation? | 38,945,695 | <p>An ellipse of width 50, height 100, and angle 0, would be identical to an ellipse of width 100, height 50, and angle 90 - i.e. one is the rotation of the other.</p>
<p>How does cv2.fitEllipse handle this? Does it return ellipses in some normalized form (i.e. angle is picked such that width is always < height), or can it provide any output?</p>
<p>I ask as I'm trying to determine whether two fit ellipses are similar, and am unsure whether I have to account for these things. The documentation doesn't address this at all.</p>
| 0 | 2016-08-14T19:11:03Z | 38,945,813 | <p>Empirically, I ran code matching thousands of ellipses, and I never got one return value where the returned width was greater than the returned height. So it seems OpenCV normalizes the ellipse such that <code>height >= width</code>.</p>
| 0 | 2016-08-14T19:27:44Z | [
"python",
"opencv",
"ellipse",
"data-fitting"
] |
How does cv2.fitEllipse handle width/height with regards to rotation? | 38,945,695 | <p>An ellipse of width 50, height 100, and angle 0, would be identical to an ellipse of width 100, height 50, and angle 90 - i.e. one is the rotation of the other.</p>
<p>How does cv2.fitEllipse handle this? Does it return ellipses in some normalized form (i.e. angle is picked such that width is always < height), or can it provide any output?</p>
<p>I ask as I'm trying to determine whether two fit ellipses are similar, and am unsure whether I have to account for these things. The documentation doesn't address this at all.</p>
| 0 | 2016-08-14T19:11:03Z | 38,947,299 | <p>You can see in the OpenCV source code for <a href="https://github.com/opencv/opencv/blob/2f4e38c8313ff313de7c41141d56d945d91f47cf/modules/imgproc/src/shapedescr.cpp#L435" rel="nofollow">fitEllipse</a> that the height of the ellipse is always larger than the width.</p>
<p>If the width is larger than the height, then <code>width</code> and <code>height</code> are swapped, and the <code>angle</code> is corrected. <code>box</code> is the <code>RotatedRect</code> that defines the ellipse:</p>
<pre><code>if( box.size.width > box.size.height )
{
float tmp;
CV_SWAP( box.size.width, box.size.height, tmp );
box.angle = (float)(90 + rp[4]*180/CV_PI);
}
</code></pre>
| 1 | 2016-08-14T22:50:16Z | [
"python",
"opencv",
"ellipse",
"data-fitting"
] |
Prevent input type url default behavior using Flask | 38,945,815 | <p>I have input type url in a form and Im trying to get the list of validation errors in the same page, but I want the form first send the data to the server and then render the error list but when the input type is set to url and I enter some other text It shows a popup and say Enter valid Url
It does it on the client side before sending any data to the server
I can use it with js and preventDefault but how can I overcome this default behavior using Flask</p>
<p>Here is my code</p>
<pre><code>from flask_wtf import Form
from wtforms.fields import StringField
from flask.ext.wtf.html5 import URLField
from wtforms.validators import DataRequired, url
class BookmarkForm(Form):
url = URLField('url', validators = [DataRequired(), url()])
description = StringField('description')
</code></pre>
<p>the main py file</p>
<pre><code>@app.route('/add', methods = ['GET', 'POST'])
def add():
form = BookmarkForm()
if form.validate_on_submit():
url = form.url.data
description = form.description.data
store_bookmark(url, description)
flash('stored "{}"'.format(description))
return redirect(url_for('index'))
return render_template('add.html', form = form)
</code></pre>
<p>and the template</p>
<pre><code><form id='addUrl' action='' method='post'
{% if form.url.errors %} class ='error'
{% endif %}>
{{ form.hidden_tag() }}
<p>Please enter your bookmark here</p>
{{ form.url(size = 50) }}
<p>Please enter additional description</p>
{{ form.description(size = 50) }}
<ul>
{% for error in form.url.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
<button type='submit'>Submit</button>
</form>
</code></pre>
| 0 | 2016-08-14T19:27:55Z | 38,947,071 | <p>It depends on the browser support of HTML5 and It causes client-side validation and prevents data to passed to the server. You can overcome that default behavior of the HTML5 URL field by adding the tag <code>novalidate</code> to your form.</p>
<p>Your template will look like this</p>
<pre><code><form id='addUrl' action='' method='post' novalidate
{% if form.url.errors %} class ='error'
{% endif %}>
{{ form.hidden_tag() }}
<p>Please enter your bookmark here</p>
{{ form.url(size = 50) }}
<p>Please enter additional description</p>
{{ form.description(size = 50) }}
{# <input type='text' name='url' required> #}
<ul>
{% for error in form.url.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
<button type='submit'>Submit</button>
</form>
</code></pre>
| 0 | 2016-08-14T22:12:43Z | [
"python",
"validation",
"flask",
"html-form",
"wtforms"
] |
How can I replace Python Pandas table text values with unique IDs? | 38,945,840 | <p>I am using Pandas to read a file in this format:</p>
<pre><code>fp = pandas.read_table("Measurements.txt")
fp.head()
"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1
</code></pre>
<p>I want to replace each name with a unique ID so output looks like:</p>
<pre><code>"1", 3, 5, 7
"1", 3, 6, 9
"1", 3, 6, 10
"2", 4, 6, 0
"2", 3, 6, 1
</code></pre>
<p>How can I do that?</p>
<p>Thanks!</p>
| 1 | 2016-08-14T19:31:28Z | 38,945,903 | <p>You can do that via a simple dictionary mapping.
Say for instance your data looks like this:</p>
<pre><code>col1, col2, col3, col4
"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1
</code></pre>
<p>then simply do </p>
<pre><code>myDict = {"Aaron":"1", "Brave":"2"}
fp["col1"] = fp["col1"].map(myDict)
</code></pre>
<p>if you don't want to construct a dictionary use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow">pandas.factorize</a> which is going to take care of encoding the column for you starting from 0. You can find an example on how to use it <a href="http://stackoverflow.com/questions/15376475/unique-zero-based-id-for-values-in-pandas">here</a>. </p>
| 3 | 2016-08-14T19:38:33Z | [
"python",
"python-3.x",
"pandas"
] |
How can I replace Python Pandas table text values with unique IDs? | 38,945,840 | <p>I am using Pandas to read a file in this format:</p>
<pre><code>fp = pandas.read_table("Measurements.txt")
fp.head()
"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1
</code></pre>
<p>I want to replace each name with a unique ID so output looks like:</p>
<pre><code>"1", 3, 5, 7
"1", 3, 6, 9
"1", 3, 6, 10
"2", 4, 6, 0
"2", 3, 6, 1
</code></pre>
<p>How can I do that?</p>
<p>Thanks!</p>
| 1 | 2016-08-14T19:31:28Z | 38,945,917 | <p>Why not using a hash on the name</p>
<pre><code>df["col0"] = df["col0"].apply(lambda x: hashlib.sha256(x.encode("utf-8")).hexdigest())
</code></pre>
<p>In this way you do not need to care about the names that occurring, i.e. you do not need to know them upfront to build a dictionary for mapping.</p>
| 0 | 2016-08-14T19:40:31Z | [
"python",
"python-3.x",
"pandas"
] |
How can I replace Python Pandas table text values with unique IDs? | 38,945,840 | <p>I am using Pandas to read a file in this format:</p>
<pre><code>fp = pandas.read_table("Measurements.txt")
fp.head()
"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1
</code></pre>
<p>I want to replace each name with a unique ID so output looks like:</p>
<pre><code>"1", 3, 5, 7
"1", 3, 6, 9
"1", 3, 6, 10
"2", 4, 6, 0
"2", 3, 6, 1
</code></pre>
<p>How can I do that?</p>
<p>Thanks!</p>
| 1 | 2016-08-14T19:31:28Z | 38,945,947 | <p>I would make use of <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow">categorical</a> dtype:</p>
<pre><code>In [97]: x['ID'] = x.name.astype('category').cat.rename_categories(range(1, x.name.nunique()+1))
In [98]: x
Out[98]:
name v1 v2 v3 ID
0 Aaron 3 5 7 1
1 Aaron 3 6 9 1
2 Aaron 3 6 10 1
3 Brave 4 6 0 2
4 Brave 3 6 1 2
</code></pre>
<p>if you need string IDs instead of numerical ones, you can use:</p>
<pre><code>x.name.astype('category').cat.rename_categories([str(x) for x in range(1,x.name.nunique()+1)])
</code></pre>
<p>or, as @MedAli has mentioned in <a href="http://stackoverflow.com/a/38945903/5741205">his answer</a>, using <code>factorize()</code> method - demo:</p>
<pre><code>In [141]: x['cat'] = pd.Categorical((pd.factorize(x.name)[0] + 1).astype(str))
In [142]: x
Out[142]:
name v1 v2 v3 ID cat
0 Aaron 3 5 7 1 1
1 Aaron 3 6 9 1 1
2 Aaron 3 6 10 1 1
3 Brave 4 6 0 2 2
4 Brave 3 6 1 2 2
In [143]: x.dtypes
Out[143]:
name object
v1 int64
v2 int64
v3 int64
ID category
cat category
dtype: object
In [144]: x['cat'].cat.categories
Out[144]: Index(['1', '2'], dtype='object')
</code></pre>
<p>or having categories as integer numbers:</p>
<pre><code>In [154]: x['cat'] = pd.Categorical((pd.factorize(x.name)[0] + 1))
In [155]: x
Out[155]:
name v1 v2 v3 ID cat
0 Aaron 3 5 7 1 1
1 Aaron 3 6 9 1 1
2 Aaron 3 6 10 1 1
3 Brave 4 6 0 2 2
4 Brave 3 6 1 2 2
In [156]: x['cat'].cat.categories
Out[156]: Int64Index([1, 2], dtype='int64')
</code></pre>
<p>explanation:</p>
<pre><code>In [99]: x.name.astype('category')
Out[99]:
0 Aaron
1 Aaron
2 Aaron
3 Brave
4 Brave
Name: name, dtype: category
Categories (2, object): [Aaron, Brave]
In [100]: x.name.astype('category').cat.categories
Out[100]: Index(['Aaron', 'Brave'], dtype='object')
In [101]: x.name.astype('category').cat.rename_categories([1,2])
Out[101]:
0 1
1 1
2 1
3 2
4 2
dtype: category
Categories (2, int64): [1, 2]
</code></pre>
<p>explanation for the <code>factorize()</code> method:</p>
<pre><code>In [157]: (pd.factorize(x.name)[0] + 1)
Out[157]: array([1, 1, 1, 2, 2])
In [158]: pd.Categorical((pd.factorize(x.name)[0] + 1))
Out[158]:
[1, 1, 1, 2, 2]
Categories (2, int64): [1, 2]
</code></pre>
| 2 | 2016-08-14T19:43:37Z | [
"python",
"python-3.x",
"pandas"
] |
How can I replace Python Pandas table text values with unique IDs? | 38,945,840 | <p>I am using Pandas to read a file in this format:</p>
<pre><code>fp = pandas.read_table("Measurements.txt")
fp.head()
"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1
</code></pre>
<p>I want to replace each name with a unique ID so output looks like:</p>
<pre><code>"1", 3, 5, 7
"1", 3, 6, 9
"1", 3, 6, 10
"2", 4, 6, 0
"2", 3, 6, 1
</code></pre>
<p>How can I do that?</p>
<p>Thanks!</p>
| 1 | 2016-08-14T19:31:28Z | 38,946,041 | <p>It looks like this <a href="http://stackoverflow.com/questions/25698710/replace-all-occurrences-of-a-string-in-a-pandas-dataframe-python">Replace all occurrences of a string in a pandas dataframe</a> might hold your answer. According to the documentation, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow">pandas.read_table</a> creates a dataframe and a dataframe has a replace function.</p>
<pre><code>fp.replace({'Aaron': '1'}, regex=True)
</code></pre>
<p>Although you probably don't need to have the regex=True part as it's a direct replacement in full.</p>
| 0 | 2016-08-14T19:55:22Z | [
"python",
"python-3.x",
"pandas"
] |
How to read specific multiple lines using for loop at the same time? | 38,945,848 | <p>contents are in <code>list[info]</code> from a text file:</p>
<pre><code>1,1,1703,385,157,339,1,-1,-1,-1
1,3,1293,455,83,213,1,-1,-1,-1
1,4,259,449,101,261,1,-1,-1,-1
1,5,1253,529,55,127,1,-1,-1,-1
2,1,1699,383,159,341,1,-1,-1,-1
2,3,1293,455,83,213,1,-1,-1,-1
2,4,261,447,101,263,1,-1,-1,-1
2,5,1253,529,55,127,1,-1,-1,-1
3,1,1697,383,159,343,1,-1,-1,-1
3,3,1293,455,83,213,1,-1,-1,-1
3,4,263,447,101,263,1,-1,-1,-1
3,5,1255,529,55,127,1,-1,-1,-1
4,1,1695,383,159,343,1,-1,-1,-1
4,3,1293,455,83,213,1,-1,-1,-1
4,4,265,447,101,263,1,-1,-1,-1
4,5,1257,529,55,127,1,-1,-1,-1
.
.
.
</code></pre>
<p>they consist of like these</p>
<p>I am going to show some pictures. so I think that you don't have to care about image_list and files. anyway, I want to read like these:</p>
<p>conclusion = if info[0] is 1, i want to read info[2], info[3], info[4] info[5] of lines that they starts as info[0] is 1.</p>
<p>in other words, </p>
<p>if info[0] is 1, I want to print like below</p>
<pre><code>1703,385,157,339
1293,455,83,213
259,449,101,261
1253,529,55,127
</code></pre>
<p>at the same time</p>
<p>my code is below:</p>
<pre><code>**marks = [int(info[0])]
for i, images_files in zip(marks, image_list):
for s in range(i, i):
print int(info[2]), int(info[3]), int(info[4]), int(info[5])**
</code></pre>
<p>please help me :)</p>
| 0 | 2016-08-14T19:32:35Z | 38,945,966 | <p>You can create a dictionary of integer value to list of those four values you want to print:</p>
<pre><code>from collections import defaultdict
lines = [
'1,1,1703,385,157,339,1,-1,-1,-1',
'1,3,1293,455,83,213,1,-1,-1,-1',
'1,4,259,449,101,261,1,-1,-1,-1',
'1,5,1253,529,55,127,1,-1,-1,-1',
'2,1,1699,383,159,341,1,-1,-1,-1',
'2,3,1293,455,83,213,1,-1,-1,-1',
'2,4,261,447,101,263,1,-1,-1,-1',
'2,5,1253,529,55,127,1,-1,-1,-1',
'3,1,1697,383,159,343,1,-1,-1,-1',
'3,3,1293,455,83,213,1,-1,-1,-1',
'3,4,263,447,101,263,1,-1,-1,-1',
'3,5,1255,529,55,127,1,-1,-1,-1',
'4,1,1695,383,159,343,1,-1,-1,-1',
'4,3,1293,455,83,213,1,-1,-1,-1',
'4,4,265,447,101,263,1,-1,-1,-1',
'4,5,1257,529,55,127,1,-1,-1,-1',
]
line_map = defaultdict(list)
for line in lines:
values = line.split(',')
line_map[int(values[0])].append(','.join(values[2:6]))
print line_map[1] # ['1703,385,157,339', '1293,455,83,213', '259,449,101,261', '
</code></pre>
| 2 | 2016-08-14T19:46:29Z | [
"python",
"for-loop"
] |
kivy on android and app engine? | 38,945,932 | <p>Is it possible to use google app engine with kivy on Android?</p>
<p>I've tried but after running buildozer I ve got an error in dowloading app-engine. I've got this error in log:</p>
<pre><code> ------------------------------------------------------------
/media/projekty/kiwi/.buildozer/venv/bin/pip run on Sun Aug 14 21:35:33 2016
Downloading/unpacking google-appengine
Getting page https://pypi.python.org/simple/google-appengine/
URLs to search for versions for google-appengine:
* https://pypi.python.org/simple/google-appengine/
Analyzing links from page https://pypi.python.org/simple/google-appengine/
Found link https://pypi.python.org/packages/8d/f1/405f6a85407673cd628fb29fadf84a3dd9f533551a9236609e55e04ad22c/google-appengine-1.5.1.tar.gz#md5=9ebf2f7ab04ce3cfeffa05a34f1aaaf5 (from https://pypi.python.org/simple/google-appengine/), version: 1.5.1
Found link https://pypi.python.org/packages/9c/e5/dac1d88cd4231a95a2324ddf07f3d8731ee59a1ebce6e4921d85a60e6c09/google-appengine-1.5.1.zip#md5=13b33d6741741025ac4d8b1c23dad163 (from https://pypi.python.org/simple/google-appengine/), version: 1.5.1
Using version 1.5.1 (newest of versions: 1.5.1, 1.5.1)
Downloading from URL https://pypi.python.org/packages/8d/f1/405f6a85407673cd628fb29fadf84a3dd9f533551a9236609e55e04ad22c/google-appengine-1.5.1.tar.gz#md5=9ebf2f7ab04ce3cfeffa05a34f1aaaf5 (from https://pypi.python.org/simple/google-appengine/)
Running setup.py (path:/media/projekty/kiwi/.buildozer/venv/build/google-appengine/setup.py) egg_info for package google-appengine
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/media/projekty/kiwi/.buildozer/venv/build/google-appengine/setup.py", line 2, in <module>
import ez_setup
ImportError: No module named ez_setup
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/media/projekty/kiwi/.buildozer/venv/build/google-appengine/setup.py", line 2, in <module>
import ez_setup
ImportError: No module named ez_setup
</code></pre>
<hr>
<pre><code>Cleaning up...
Removing temporary dir /media/projekty/kiwi/.buildozer/venv/build...
Command python setup.py egg_info failed with error code 1 in /media/projekty/kiwi/.buildozer/venv/build/google-appengine
Exception information:
Traceback (most recent call last):
File "/media/projekty/kiwi/.buildozer/venv/local/lib/python2.7/site-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/media/projekty/kiwi/.buildozer/venv/local/lib/python2.7/site-packages/pip/commands/install.py", line 278, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/media/projekty/kiwi/.buildozer/venv/local/lib/python2.7/site-packages/pip/req.py", line 1229, in prepare_files
req_to_install.run_egg_info()
File "/media/projekty/kiwi/.buildozer/venv/local/lib/python2.7/site-packages/pip/req.py", line 325, in run_egg_info
command_desc='python setup.py egg_info')
File "/media/projekty/kiwi/.buildozer/venv/local/lib/python2.7/site-packages/pip/util.py", line 697, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg_info failed with error
</code></pre>
<p>I'm working on linux. I have installed google app enigne and added google-appengine in buildozer.spec requirements.</p>
<p>requirements = kivy,google-appengine</p>
| 0 | 2016-08-14T19:41:56Z | 38,961,357 | <p>It looks like <code>ez_setup.py</code> comes from <a href="https://pypi.python.org/pypi/setuptools" rel="nofollow"><code>setuptools</code></a>. Do you have setuptools installed on your machine?</p>
| 0 | 2016-08-15T19:04:58Z | [
"android",
"python",
"google-app-engine",
"kivy"
] |
How can I close a file handle while function exit with exception in Python? | 38,945,949 | <p>For instance, I have a function like:</p>
<pre><code>def example():
fp = open('example.txt','w+')
fp.write(str(1/0))
fp.close()
</code></pre>
<p>Then it will throw an exception because 1/0 is not defined. However, I can neither remove <code>example.txt</code> nor modify <code>example.txt</code>. But I have some important data in Python, so that I can't simply kill Python and run it again.</p>
<p>How could I finish opening the file when the function finish with an exception.</p>
<p><strong>What shall we do if we didn't place a try:.. except:.. ?</strong></p>
| 0 | 2016-08-14T19:43:52Z | 38,945,980 | <p>You can wrap that in a try/except to handle the error and close the file reader before the program ends.</p>
<pre><code>def example():
fp = open('example.txt', 'w+')
try:
fp.write(str(1/0))
except ZeroDivisionError:
fp.close()
fp.close()
</code></pre>
<p>Edit: The answer by @IanAuld is better than mine. It would be best to accept that one.</p>
| 2 | 2016-08-14T19:48:14Z | [
"python"
] |
How can I close a file handle while function exit with exception in Python? | 38,945,949 | <p>For instance, I have a function like:</p>
<pre><code>def example():
fp = open('example.txt','w+')
fp.write(str(1/0))
fp.close()
</code></pre>
<p>Then it will throw an exception because 1/0 is not defined. However, I can neither remove <code>example.txt</code> nor modify <code>example.txt</code>. But I have some important data in Python, so that I can't simply kill Python and run it again.</p>
<p>How could I finish opening the file when the function finish with an exception.</p>
<p><strong>What shall we do if we didn't place a try:.. except:.. ?</strong></p>
| 0 | 2016-08-14T19:43:52Z | 38,946,031 | <pre><code>with open('example.txt','w+') as fp:
try:
fp.write(...)
except ZeroDivisionError as e:
print('there was an error: {}'.format(e))
</code></pre>
<p>Using the <code>with</code> context manager any files opened by it will be closed automatically once they go out of scope. </p>
| 3 | 2016-08-14T19:54:11Z | [
"python"
] |
Protocol Error on basket download request | 38,946,159 | <p>I am trying to download a Pypi package using basket. but the command shows "<strong><code>ProtocolError for pypi.python.org/pypi: 403 Must access using HTTPS instead of HTTP</code></strong>" message.</p>
<p>My command is : <code>sudo basket download unittest2</code></p>
<p>The response is : </p>
<pre><code>`Traceback (most recent call last):
File "/usr/local/bin/basket", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/basket/main.py", line 338, in main
return basket.cmd_download(argv)
File "/usr/local/lib/python2.7/dist-packages/basket/main.py", line 220, in cmd_download
info = self._find_package_name(package)
File "/usr/local/lib/python2.7/dist-packages/basket/main.py", line 88, in _find_package_name
for info in self.client.search({'name': query}):
File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
verbose=self.__verbose
File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python2.7/xmlrpclib.py", line 1331, in single_request
response.msg,
xmlrpclib.ProtocolError: <ProtocolError for pypi.python.org/pypi: 403 Must access using HTTPS instead of HTTP>`
</code></pre>
<p>but pip download command is working fine for me.</p>
<p>My command and response is : `</p>
<pre><code>pip download unittest2
Collecting unittest2
Downloading unittest2-1.1.0-py2.py3-none-any.whl (96kB)
100% |ââââââââââââââââââââââââââââââââ| 102kB 107kB/s
Saved ./unittest2-1.1.0-py2.py3-none-any.whl
Collecting argparse (from unittest2)
Downloading argparse-1.4.0-py2.py3-none-any.whl
Saved ./argparse-1.4.0-py2.py3-none-any.whl
Collecting traceback2 (from unittest2)
Downloading traceback2-1.4.0-py2.py3-none-any.whl
Saved ./traceback2-1.4.0-py2.py3-none-any.whl
Collecting six>=1.4 (from unittest2)
Downloading six-1.10.0-py2.py3-none-any.whl
Saved ./six-1.10.0-py2.py3-none-any.whl
Collecting linecache2 (from traceback2->unittest2)
Downloading linecache2-1.0.0-py2.py3-none-any.whl
Saved ./linecache2-1.0.0-py2.py3-none-any.whl
Successfully downloaded unittest2 argparse traceback2 six linecache2
</code></pre>
<p>`</p>
<p>what is the problem with basket? and how to resolve it?</p>
| 0 | 2016-08-14T20:09:32Z | 39,277,908 | <p>You have to go into /path-to-python-site-packages/basket/main.py, and edit the following line:</p>
<pre><code>PYPI_ENDPOINT = 'http://pypi.python.org/pypi'
</code></pre>
<p>And Change it to "https":</p>
<pre><code>PYPI_ENDPOINT = 'https://pypi.python.org/pypi'
</code></pre>
<p>Then your downloads should work. Issue is related to "http" being provided to "xmlrpclib.ServerProxy"</p>
| 0 | 2016-09-01T17:48:04Z | [
"python",
"pip",
"pypi"
] |
Displaying Raspberry Pi clock on LCD display | 38,946,173 | <p>I have a Raspberry Pi running an LCD display. I found the Python script below which displays the time on the display, but I notice there's a delay of almost a second between the Pi's time and the LCD.</p>
<p>I tried removing the last line of the code (<b>sleep(1)</b>) and that removed the delay but the LCD flickers a lot.</p>
<p>Can anyone please explain the function of that last line, and whether there's a way to display the time on the LCD without a delay?</p>
<p>Thanks.</p>
<pre><code>#!/usr/bin/python
import RPi.GPIO as GPIO
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
lcd = Adafruit_CharLCD()
lcd.begin(16,1)
GPIO.setup(18, 0)
GPIO.output(18, 1)
while 1:
lcd.clear()
lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n'))
sleep(1)
</code></pre>
| 2 | 2016-08-14T20:10:51Z | 38,946,200 | <p>The sleep(1) instructs the program to "sleep" for 1 second. This is actually very significant because that means that the while loop (which is always true) will then only run once every second. When you take away the sleep(1) line, that means the while loop never takes a break and continues running as fast as the computer can go infinitely. One thing you might try is just reducing the sleep(1) to some smaller value. For example, you can specify sleep(0.1)</p>
<p>By reducing the amount of time it sleeps, that means the clock will update more frequently. Right now with sleep(1) the clock updates once every second, which makes perfect sense. However, you might increase accuracy by having the clock update 10 times every second with sleep(0.1). Let me know if this all makes sense.</p>
<p>The flickering is likely caused by the fact that the program is clearing and repopulating the display so many times a second.</p>
<p>Edit: Documentation suggests that sending decimal values to the sleep() function is valid</p>
<p>Edit 2: An extra bit about how to only refresh the display if right at the turn of a second</p>
<pre><code>from datetime import datetime
from time import sleep, mktime
dti = mktime(datetime.now().timetuple())
while 1:
ndti = mktime(datetime.now().timetuple())
if dti < ndti:
dti = ndti
lcd.clear()
lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n'))
sleep(0.95)
else:
sleep(0.01)
</code></pre>
<p>In essence, here's how it works:</p>
<p>When starting the program, create a datetime in integer form (our var <code>dti</code>). By "integer form" I mean add up all the seconds from some arbitrary start date (e.g. <code>1970-01-01 00:00:00</code>) and use that as a reference for time. For example, today (2016-08-18 00:00:00) might be something like 1471478400 seconds since 1970. Once we have that value, we start our loop.</p>
<p>At the beginning of the loop, we always create a new datetime integer (<code>ndti</code>) to track where we are since the last time we ran the loop. With this information handy, we hop into the <code>if</code> conditional. <code>if</code> our new datetime integer (<code>ndti</code>) has changed fully by one second compared to our old datetime integer (<code>dti</code>) then that means, obviously, one second has passed. Since that is the case, we will now set our reference datetime integer to the datetime now (<code>dti = ndti</code>). Then we display our message (<code>lcd.clear()</code> and <code>lcd.message()</code>). After that we will sleep the program for just under 1 whole second (<code>sleep(0.95)</code>). Since some computers can possibly sleep more than the exact allotted time, this gives us .05 seconds of cushion to be inaccurate. In the event that we are running through the <code>if</code> conditional and a second has not passed yet, we would sleep the program for a short time and continue repeating until a second has actually passed (<code>sleep(0.01)</code>).</p>
<p>If everything goes exactly as planned, then for each second our program should be refreshing the lcd screen only once, and it should also be sleeping for roughly 95% of that second, so that we aren't spinning our wheels for no reason the whole time. Another part to note is that since our <code>else</code> clause tells the program to sleep for 0.01 seconds, that means that, in most cases, our clock can only ever be inaccurate by a margin of 0.01 seconds, which is quite good. This is low enough to be mostly undetectable by humans. Let me know if all this makes sense.</p>
<p>I tested this out via command line (replacing the lcd stuff with simple print statements) and it seemed to line up exactly with another time tracking resource (<a href="http://time.is/" rel="nofollow">http://time.is/</a>)</p>
<p>Try it out and see if it works for you.</p>
| 1 | 2016-08-14T20:13:50Z | [
"python",
"time",
"raspberry-pi",
"lcd",
"adafruit"
] |
Append Numpy ndarray to pandas dataframe | 38,946,206 | <p>I have ten numpy ndarrys each having one row and 100 columns. Now I want to append them sequentially to a pandas dataframe (should have 10 rows and 100 columns in the end). How can I achieve that in python:</p>
<pre><code># create empty dataframe
data = pd.DataFrame()
# Loop
for i in range(1, 11):
# Simulate ndarrys
one_row = np.array([range(1, 101)])
# Trying to append
data = data.append(data, one_row)
</code></pre>
| -2 | 2016-08-14T20:14:30Z | 38,946,282 | <p>Create iteratively the array, to make it 10x100, then pass it to <code>DataFrame</code>.</p>
<p>You can use <code>np.insert</code> or <code>np.vstack</code> to create the 10x100 array.</p>
| 0 | 2016-08-14T20:23:12Z | [
"python",
"pandas",
"numpy"
] |
Get rid of unicode error | 38,946,269 | <p>I have the following code attempting to print the edge lists of graphs. It looks like the edges are cycled but it's my intention to test whether all edges are contained while going through the function for further processing.</p>
<pre><code>def mapper_network(self, _, info):
info[0] = info[0].encode('utf-8')
for i in range(len(info[1])):
info[1][i] = str(info[1][i])
l_lst = len(info[1])
packed = [(info[0], l) for l in info[1]] #each pair of nodes (edge)
weight = [1 /float(l_lst)] #each edge weight
G = nx.Graph()
for i in range(len(packed)):
edge_from = packed[i][0]
edge_to = packed[i][1]
#edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
edge_to = edge_to.encode("utf-8")
weight = weight
G.add_edge(edge_from, edge_to, weight=weight)
#print G.size() #yes, this works :)
G_edgelist = []
G_edgelist = G_edgelist.append(nx.generate_edgelist(G).next())
print G_edgelist
</code></pre>
<p>With this code, I obtain the error</p>
<pre><code>Traceback (most recent call last):
File "MRQ7_trevor_2.py", line 160, in <module>
MRMostUsedWord2.run()
File "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 433, in run
mr_job.execute()
File "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 442, in execute
self.run_mapper(self.options.step_num)
File "/tmp/MRQ7_trevor_2.vagrant.20160814.201259.655269/job_local_dir/1/mapper/27/mrjob.tar.gz/mrjob/job.py", line 507, in run_mapper
for out_key, out_value in mapper(key, value) or ():
File "MRQ7_trevor_2.py", line 91, in mapper_network
G_edgelist = G_edgelist.append(nx.generate_edgelist(G).next())
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/readwrite/edgelist.py", line 114, in generate_edgelist
yield delimiter.join(map(make_str,e))
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/utils/misc.py", line 82, in make_str
return unicode(str(x), 'unicode-escape')
UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 0: \ at end of string
</code></pre>
<p>With the modification below</p>
<pre><code>edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
</code></pre>
<p>I obtained</p>
<pre><code>edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
TypeError: must be unicode, not str
</code></pre>
<p>How to get rid of the error of unicode? It seems very troublesome and I highly appreciate your assistance. Thank you!!</p>
| 0 | 2016-08-14T20:21:39Z | 38,946,410 | <p>I highly recommend reading this <a href="https://www.azavea.com/blog/2014/03/24/solving-unicode-problems-in-python-2-7/" rel="nofollow">article on unicode</a>. It gives a nice explanation of unicode vs. strings in Python 2.</p>
<p>For your problem specifically, when you call <code>unicodedata.normalize("NFKD", edge_to)</code>, <code>edge_to</code> must be a unicode string. However, it is not unicode since you set it in this line: <code>info[1][i] = str(info[1][i])</code>. Here's a quick test:</p>
<pre><code>import unicodedata
edge_to = u'edge' # this is unicode
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
print edge_to # prints 'edge' as expected
edge_to = 'edge' # this is not unicode
edge_to = unicodedata.normalize("NFKD", edge_to).encode('utf-8', 'ignore')
print edge_to # TypeError: must be unicode, not str
</code></pre>
<p>You can get rid of the problem by casting <code>edge_to</code> to unicode.</p>
<p>As an aside, it seems like the encoding/decoding of the whole code chunk is a little confusing. Think out exactly where you want strings to be unicode vs. bytes. You may not need to be doing so much encoding/decoding/normalization.</p>
| 0 | 2016-08-14T20:39:00Z | [
"python",
"unicode",
"encoding",
"networkx"
] |
How can I connect graphviz nodes that are in records with pygraphviz? | 38,946,271 | <p>I am working with pygraphviz to interface with dot/graphviz. I am creating records through labels but I am wondering how to connect ports that are in the records rather than record nodes themselves.</p>
<p>In dot it would look something like this:</p>
<pre><code> a00 [shape = "record" label="{{RecordThing1}|{<1>A|<2>B|<3>C|<4>D|<5>E|<6>F}}"];
a01 [shape = "record" label="{{RecordThing2}|{<1>A|<2>B|<3>C|<4>D|<5>E|<6>F}}"];
a00:1 -> a01:1
</code></pre>
| 1 | 2016-08-14T20:22:07Z | 38,947,969 | <p>I found a solution: The headport and tailport attributes of edges can be used.
e.g.</p>
<pre><code> agraph.add_node('a00', 'a01', tailport=1, headport=1)
</code></pre>
<p>Read more at: <a href="http://www.graphviz.org/content/attrs#aheadport" rel="nofollow">http://www.graphviz.org/content/attrs#aheadport</a></p>
| 1 | 2016-08-15T00:49:56Z | [
"python",
"graphviz",
"pygraphviz"
] |
python selenium choose random firefox profile | 38,946,361 | <p>In my script folder I have copied my firefox profiles folders</p>
<p>My code</p>
<pre><code>#Creating profile for browser
profile = webdriver.FirefoxProfile('.\profiles\profile1')
profile.set_preference("general.useragent.override", user_agent)
profile.update_preferences()
</code></pre>
<p>What I would like to do is</p>
<pre><code>#Creating profile for browser
profile = webdriver.FirefoxProfile('.\profiles\random_profile_from_profiles_folder')
profile.set_preference("general.useragent.override", user_agent)
profile.update_preferences()
</code></pre>
| 0 | 2016-08-14T20:33:24Z | 38,963,122 | <p>The only modification I perform is 1) list profiles directory, 2) filter to keep only directories 3) apply random on the list</p>
<p>I hope it's what you want:</p>
<pre><code>import os,random
profile_dir="profiles"
# pick a directory
randdir = random.choice(list(filter(os.path.isdir,os.listdir(profile_dir))))
profile = webdriver.FirefoxProfile(os.path.join(profile_dir,randdir))
profile.set_preference("general.useragent.override", user_agent)
profile.update_preferences()
</code></pre>
| 0 | 2016-08-15T21:10:18Z | [
"python",
"selenium",
"firefox"
] |
Django, url not found? | 38,946,371 | <p>I'm trying out Python Django. With eclipse pyDev. But I'm unable to simply get my first url to display.</p>
<p>This urls.py is from the Cr package.</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index')
]
</code></pre>
<p>This urlspy is from the Crowd package.</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'Crowd/', include('Cr.urls'))
]
</code></pre>
<p>So what I've understood from this the <code>Crowd package</code> is the "main" webservice(?), and by using <code>include</code> I can whenever the regular expression matches <code>Crowd</code>, will pass it on to the other <code>urls.py(Cr)</code>. But the debugger passes:</p>
<pre><code>Using the URLconf defined in Crowd.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, crowd, didn't match any of these.
</code></pre>
<p>my views.py file</p>
<pre><code>from django.shortcuts import HttpResponse
def index(request):
return HttpResponse('<h1>Hello World!</h1>')
</code></pre>
<p>I tried to access it with <code>http://127.0.0.1:8000/Crowd</code></p>
<p>Below is an image of the project folder.</p>
<p><a href="http://i.stack.imgur.com/LSRfn.png" rel="nofollow"><img src="http://i.stack.imgur.com/LSRfn.png" alt="enter image description here"></a></p>
| 0 | 2016-08-14T20:34:21Z | 38,946,409 | <p>Can we see your settings.py file? There is a place in there where you define your project's url file. I'm assuming it's right now either not there or it's pointing to the wrong place, because Django can't find your urls.py file.</p>
<p>For example, in my settings.py file for one of my projects, I have:</p>
<pre><code>ROOT_URLCONF = 'Freya.urls'
</code></pre>
<p>Where "Freya" is my project name</p>
<p>Just for reference, not that I know this will solve your problem, this is what (part of) my urls.py file looks like for one of my projects:</p>
<pre><code>from django.conf.urls import patterns, url
import views
urlpatterns = patterns(
'',
url(r'^$', views.index, name='index'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
)
</code></pre>
| 0 | 2016-08-14T20:38:54Z | [
"python",
"django"
] |
Django, url not found? | 38,946,371 | <p>I'm trying out Python Django. With eclipse pyDev. But I'm unable to simply get my first url to display.</p>
<p>This urls.py is from the Cr package.</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index')
]
</code></pre>
<p>This urlspy is from the Crowd package.</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'Crowd/', include('Cr.urls'))
]
</code></pre>
<p>So what I've understood from this the <code>Crowd package</code> is the "main" webservice(?), and by using <code>include</code> I can whenever the regular expression matches <code>Crowd</code>, will pass it on to the other <code>urls.py(Cr)</code>. But the debugger passes:</p>
<pre><code>Using the URLconf defined in Crowd.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, crowd, didn't match any of these.
</code></pre>
<p>my views.py file</p>
<pre><code>from django.shortcuts import HttpResponse
def index(request):
return HttpResponse('<h1>Hello World!</h1>')
</code></pre>
<p>I tried to access it with <code>http://127.0.0.1:8000/Crowd</code></p>
<p>Below is an image of the project folder.</p>
<p><a href="http://i.stack.imgur.com/LSRfn.png" rel="nofollow"><img src="http://i.stack.imgur.com/LSRfn.png" alt="enter image description here"></a></p>
| 0 | 2016-08-14T20:34:21Z | 38,946,479 | <pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'Crowd/', include('Cr.urls'))
</code></pre>
<p>]</p>
<p>just use this urls.py file </p>
| 0 | 2016-08-14T20:48:25Z | [
"python",
"django"
] |
Python 3.4 Dice Rolling Simulator Code Error | 38,946,377 | <p>So I have my code here for a dice rolling simulator game that I am creating using PyDev in Eclipse Neon Python 3.4. Where you guess a number and a number from 1-6 will randomly generate and if you get the number right, you move on, etc.</p>
<pre><code>guess1 = input("Enter your first guess as to which side the dice will roll on (1-6): ")
import random
dice_side = ['1','2','3','4','5','6']
game = print(random.choice(dice_side))
if guess1 == game:
print("Congrats that's the correct guess!")
else:
print("That's the wrong guess!")
</code></pre>
<p>I tested out the code and everytime I put in a number, the console always print "That's the wrong guess!". Even when the number I guess matched the generated number. I can't quite figure out what's wrong with this. I was thinking maybe I should use a <em>while</em> loop instead. However, I wanted to know if I can do it this way and what's wrong with this particular code. I am new to Python so any help is appreciated. Thanks in advance!</p>
| -1 | 2016-08-14T20:35:14Z | 38,946,400 | <p><code>print()</code> returns <code>None</code>. If you print <code>game</code> after that line you will see it's value. To fix:</p>
<pre><code>game = random.choice(dice_side)
</code></pre>
| 1 | 2016-08-14T20:37:56Z | [
"python",
"eclipse",
"python-3.4"
] |
Python 3.4 Dice Rolling Simulator Code Error | 38,946,377 | <p>So I have my code here for a dice rolling simulator game that I am creating using PyDev in Eclipse Neon Python 3.4. Where you guess a number and a number from 1-6 will randomly generate and if you get the number right, you move on, etc.</p>
<pre><code>guess1 = input("Enter your first guess as to which side the dice will roll on (1-6): ")
import random
dice_side = ['1','2','3','4','5','6']
game = print(random.choice(dice_side))
if guess1 == game:
print("Congrats that's the correct guess!")
else:
print("That's the wrong guess!")
</code></pre>
<p>I tested out the code and everytime I put in a number, the console always print "That's the wrong guess!". Even when the number I guess matched the generated number. I can't quite figure out what's wrong with this. I was thinking maybe I should use a <em>while</em> loop instead. However, I wanted to know if I can do it this way and what's wrong with this particular code. I am new to Python so any help is appreciated. Thanks in advance!</p>
| -1 | 2016-08-14T20:35:14Z | 38,946,571 | <p>In order to understand why your game isn't working you should try to understand first what's wrong with this line <code>game = print(random.choice(dice_side))</code>. Here's a modified version of your game which will give you some clues, try to run it and understand it, then just review your script:</p>
<pre><code>import random
dice_side = ['1', '2', '3', '4', '5', '6']
game = random.choice(dice_side)
print("Dice has been rolled... :D {0}".format(game))
guess = -1
number_attempts = 0
while True:
guess = raw_input("Which side the dice has rolled on (1-6): ")
number_attempts += 1
if guess == game:
print("Congrats that's the correct guess! You've tried {0} times".format(
number_attempts))
break
print("That's the wrong guess!")
</code></pre>
<p>One advice, once you've discovered why isn't working, just try to add more and more new features till your game becomes really addictive and interesting... but the most important, just have fun :)</p>
| 0 | 2016-08-14T20:57:41Z | [
"python",
"eclipse",
"python-3.4"
] |
python selenium log number of times page refreshes | 38,946,423 | <p>I want to know if there is any way to log the number of times my page has refreshed in command prompt when running. </p>
<p>want it to tell me the number of times it has refreshed. Refresh is located between while true: and continue. thanks </p>
<pre><code>driver = webdriver.Chrome(chrome_path)
driver.get(link)
while True:
size = driver.find_elements_by_xpath(".//*[@id='atg_store_picker']/div/div[2]/div[1]/div[1]/span[2]/a[4]")
if len(size) <= 0:
time.sleep(0.5)
print "PAGE NOT LIVE"
driver.refresh()
continue
else:`enter code here`
print 'LIVE!!!!'
break
</code></pre>
| 0 | 2016-08-14T20:40:46Z | 38,948,046 | <p>the answer to my question was very simple...</p>
<pre><code>driver = webdriver.Chrome(chrome_path)
driver.get(link)
count = 0
while True:
size = driver.find_elements_by_xpath(".//*[@id='atg_store_picker']/div/div[2]/div[1]/div[1]/span[2]/a[4]")
if len(size) <= 0:
count +=1
print 'Refresh Count:', count
time.sleep(2)
driver.refresh()
continue
else:
print 'LIVE!!!!'
break
</code></pre>
| 1 | 2016-08-15T01:02:48Z | [
"python",
"selenium"
] |
Select Days from Pandas DataFrame | 38,946,472 | <p>I have a Pandas DataFrame like this:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-07 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-08 â 2 â
â âââââââââââââ¬ââââââââ£
â 2011-01-09 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-10 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I want do do now is to select three days starting from 2011-01-20. Selecting via <code>df.loc['2011-01-20' - pd.Timedelta(3, unit='d'):'2011-01-20']</code> results in the following date frame:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I want to accomplish is the following data frame:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-09 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-10 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I don't want to do is to <code>groupby</code> or resample the data frame or anything like that because I need to preserve the structure for the following processing. Does anybody know how I can solve this problem? Thanks in advance!</p>
| -1 | 2016-08-14T20:47:23Z | 38,946,920 | <p>You can create a consecutive id column so that each date has a unique id which increases with the date and then subset based on the id column:</p>
<pre><code>import pandas as pd
# sort the `DATE` column and create an id for each date
df['DATE'] = pd.to_datetime(df.DATE).sort_values()
df['DateId'] = df.groupby('DATE').grouper.group_info[0]
# find out the id for the target date
MaxId = df.DateId[df.DATE == '2011-01-20'].drop_duplicates().values
# subset based on the id column and the MaxId
df.loc[df.DateId.isin(range(MaxId - 2, MaxId + 1)),['DATE', 'VALUE']]
# DATE VALUE
# 2 2011-01-09 1
# 3 2011-01-10 1
# 4 2011-01-20 1
# 5 2011-01-20 1
</code></pre>
| 2 | 2016-08-14T21:50:00Z | [
"python",
"pandas",
"dataframe"
] |
Select Days from Pandas DataFrame | 38,946,472 | <p>I have a Pandas DataFrame like this:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-07 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-08 â 2 â
â âââââââââââââ¬ââââââââ£
â 2011-01-09 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-10 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I want do do now is to select three days starting from 2011-01-20. Selecting via <code>df.loc['2011-01-20' - pd.Timedelta(3, unit='d'):'2011-01-20']</code> results in the following date frame:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I want to accomplish is the following data frame:</p>
<pre>
ââââââââââââââ¦ââââââââ
â DATE â VALUE â
â âââââââââââââ¬ââââââââ£
â 2011-01-09 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-10 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
â âââââââââââââ¬ââââââââ£
â 2011-01-20 â 1 â
ââââââââââââââ©ââââââââ
</pre>
<p>What I don't want to do is to <code>groupby</code> or resample the data frame or anything like that because I need to preserve the structure for the following processing. Does anybody know how I can solve this problem? Thanks in advance!</p>
| -1 | 2016-08-14T20:47:23Z | 38,947,251 | <p>Try this using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow">pandas.ix</a>
Hint: <code>df.ix(start, stop)</code></p>
<pre><code>df['Date'] =pd.to_datetime(df['Date']).sort_values()
df.ix[df[df.Date =='2011-01-20'].index[0]-2: max(df[df.Date =='2011-01-20'].index)]
Date Value
2 2011-01-09 1
3 2011-01-10 1
4 2011-01-20 1
5 2011-01-20 1
6 2011-01-20 1
</code></pre>
| 0 | 2016-08-14T22:41:42Z | [
"python",
"pandas",
"dataframe"
] |
Pandas manipulate dataframe | 38,946,492 | <p>I am querying a database and populating a pandas dataframe. I am struggling to aggregate the data (via groupby) and then manipulate the dataframe index such that the dates in the table become the index.
Here is an example of how the data looks like before and after the groupby and what I ultimately am looking for.</p>
<p>dataframe - populated data</p>
<pre><code>firm | dates | received | Sent
-----------------------------------------
A 10/08/2016 2 8
A 12/08/2016 4 2
B 10/08/2016 1 0
B 11/08/2016 3 5
A 13/08/2016 5 1
C 14/08/2016 7 3
B 14/08/2016 2 5
</code></pre>
<ol>
<li><p>First I want to Group By "firm" and "dates" and "received/sent".</p></li>
<li><p>Then manipulate the DataFrame such that the dates becomes the index - rather than the row-index.</p></li>
<li><p>Finally to add a total column for each day</p></li>
<li><p>Some of the firms do not have 'activity' during some days or at least no activity in either received or sent. However as I want a view of the past X days back, empty values aren't possible rather I need to fill in a zero as a value instead.</p></li>
</ol>
<blockquote>
<pre><code>dates | 10/08/2016 | 11/08/2016| 12/08/2016| 13/08/2016| 14/08/2016
firm |
----------------------------------------------------------------------
A received 2 0 4 5 0
sent 8 0 2 1 0
B received 1 3 1 0 2
sent 0 5 0 0 5
C received 0 0 2 0 1
sent 0 0 1 2 0
Totals r. 3 3 7 5 3
Totals s. 8 0 3 3 5
</code></pre>
</blockquote>
<p>I've tried the following code:</p>
<pre><code>df = > mysql query result
n_received = df.groupby(["firm", "dates"
]).received.size()
n_sent = df.groupby(["firm", "dates"
]).sent.size()
tables = pd.DataFrame({ 'received': n_received, 'sent': n_sent,
},
columns=['received','sent'])
this = pd.melt(tables,
id_vars=['dates',
'firm',
'received', 'sent']
this = this.set_index(['dates',
'firm',
'received', 'sent'
'var'
])
this = this.unstack('dates').fillna(0)
this.columns = this.columns.droplevel()
this.columns.name = ''
this = this.transpose()
</code></pre>
<p>Basically, I am not getting to the result I want based on this code.
- How can I achieve this?
- Conceptually is there a better way of achieving this result ? Say aggregating in the SQL statement or does the aggregation in Pandas make more sense from an optimisation point of view and logically.</p>
| 0 | 2016-08-14T20:50:35Z | 38,946,607 | <p>You can use <code>stack</code>(<code>unstack</code>) to transform data from long to wide(wide to long) format:</p>
<pre><code>import pandas as pd
# calculate the total received and sent grouped by dates
df1 = df.drop('firm', axis = 1).groupby('dates').sum().reset_index()
# add total category as the firm column
df1['firm'] = 'total'
# concatenate the summary data frame and original data frame use stack and unstack to
# transform the data frame so that dates appear as columns while received and sent stack as column.
pd.concat([df, df1]).set_index(['firm', 'dates']).stack().unstack(level = 1).fillna(0)
# dates 10/08/2016 11/08/2016 12/08/2016 13/08/2016 14/08/2016
# firm
# A Sent 8.0 0.0 2.0 1.0 0.0
# received 2.0 0.0 4.0 5.0 0.0
# B Sent 0.0 5.0 0.0 0.0 5.0
# received 1.0 3.0 0.0 0.0 2.0
# C Sent 0.0 0.0 0.0 0.0 3.0
# received 0.0 0.0 0.0 0.0 7.0
# total Sent 8.0 5.0 2.0 1.0 8.0
# received 3.0 3.0 4.0 5.0 9.0
</code></pre>
| 0 | 2016-08-14T21:02:15Z | [
"python",
"datetime",
"pandas",
"data-manipulation"
] |
Referencing a table in web2py before defining it | 38,946,510 | <p>My code is the following im trying to assign a department to employees and also create a manager in a department table</p>
<pre><code>db = DAL(lazy_tables=True)
db.define_table('employee',
Field('fullname','string',label='Name'),
Field('email','string'),
Field('phone','string'),
Field('kids', 'string'),
Field('phone', 'string'),
#Field('date','datetime'),
Field('dob', 'datetime', label='Date'),
Field('department', 'reference department',
requires=IS_IN_DB(db, db.department.id, '%(department_name)s')),
auth.signature,
format='%(fullname)s'
)
db = DAL(lazy_tables=True)
db.define_table('department',
Field('department_name', 'string', label='Department Name'),
# Field('department_name', 'string', label='Department Name'),
Field('manager', 'reference employee', required='true',
requires=IS_IN_DB(db, db.employee.id, '%(fullname)s')),
auth.signature,
format='%(department_name)s'
)
</code></pre>
| 0 | 2016-08-14T20:52:07Z | 38,948,788 | <pre><code> Field('department', 'reference department',
requires=IS_IN_DB(db, db.department.id, '%(department_name)s')),
</code></pre>
<p>In the above line, you reference <code>db.department.id</code>, but the <code>department</code> table has not yet been defined, so the <code>db</code> object will not yet have a <code>department</code> attribute.</p>
<p>You should instead be able to use this alternative syntax:</p>
<pre><code>IS_IN_DB(db, 'department.id', '%(department_name)s')
</code></pre>
<p>Alternatively, you can define the <code>requires</code> attribute after defining the <code>department</code> table:</p>
<pre><code>db.employee.department.requires = IS_IN_DB(db, db.department.id, '%(department_name)s')
</code></pre>
| 1 | 2016-08-15T03:07:42Z | [
"python",
"web2py"
] |
Referencing a table in web2py before defining it | 38,946,510 | <p>My code is the following im trying to assign a department to employees and also create a manager in a department table</p>
<pre><code>db = DAL(lazy_tables=True)
db.define_table('employee',
Field('fullname','string',label='Name'),
Field('email','string'),
Field('phone','string'),
Field('kids', 'string'),
Field('phone', 'string'),
#Field('date','datetime'),
Field('dob', 'datetime', label='Date'),
Field('department', 'reference department',
requires=IS_IN_DB(db, db.department.id, '%(department_name)s')),
auth.signature,
format='%(fullname)s'
)
db = DAL(lazy_tables=True)
db.define_table('department',
Field('department_name', 'string', label='Department Name'),
# Field('department_name', 'string', label='Department Name'),
Field('manager', 'reference employee', required='true',
requires=IS_IN_DB(db, db.employee.id, '%(fullname)s')),
auth.signature,
format='%(department_name)s'
)
</code></pre>
| 0 | 2016-08-14T20:52:07Z | 39,027,729 | <p>If you remove the 2nd <code>db = DAL(lazy_tables=True)</code>, you should be fine.</p>
<p>The problem you have is that you essentially overwrote the first db object by declaring/instantiating it again after the first table definition (employee). </p>
<p>This gives you a new db object (with no tables defined) in which you define a table (department) that references another table (employee) that no longer exists.</p>
| 0 | 2016-08-18T21:23:58Z | [
"python",
"web2py"
] |
AttributeError: 'tuple' object has no attribute 'copy' | 38,946,556 | <p>Can any one explain this error message to me?</p>
<pre><code># make a copy or hand is destroyed by your test
remaining = hand.copy()
</code></pre>
<p>Result:</p>
<pre><code>AttributeError: 'tuple' object has no attribute 'copy'
</code></pre>
<p>I can do this:</p>
<pre><code>remaining = copy.copy(hand)
</code></pre>
<p>which returns this:</p>
<pre><code>(None, {hand...})
</code></pre>
<p>Which throws off what i'm trying to accomplish because the function is returning False when it searches the None return value.</p>
<p>This is the function that creates the hand:</p>
<pre><code>def deal_hand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
num_vowels = n / 3
for i in range(num_vowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(num_vowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
</code></pre>
<p>EDIT:
I changed hand further along the way and created a tuple out of it instead of a dictionary. Thanks!</p>
| -1 | 2016-08-14T20:56:39Z | 38,946,578 | <p>The error is very clear: You have a tuple, on which you try to call <code>copy</code>. </p>
<p>It seems that the object you have in <code>hand</code> is not the object you intended, but a tuple, instead. </p>
| 1 | 2016-08-14T20:58:49Z | [
"python",
"copy",
"attributeerror"
] |
Python 2.7.10 Pygame 1.9.1. I'm trying to change the values of a list by 5 either increasing or decreasing | 38,946,599 | <pre><code>import pygame, sys, random, math, os
from random import randint, uniform
from pygame.locals import*
from locations import*
pygame.init()
brick=pygame.image.load("resources/images/brick.png")
cave_block=pygame.image.load("resources/images/cave_block1.jpg")
background=pygame.image.load("resources/images/bg.png")
player_img=pygame.image.load("resources/images/spaceship.png")
screenX=1024
screenY=768
screen=pygame.display.set_mode((screenX,screenY))
clock=pygame.time.Clock()
game=True
block_top=0
block_bottom=0
block_left=0
make_top=[(0,0)]
make_bottom=[(0,704)]
make_left=[(0,64)]
cave_top=0
make_cave_top=[(0,0)]
move_playerU=False
move_playerL=False
move_playerD=False
move_playerR=False
cave=[(640,400)]
backgrounS_pos=([0,0])
player_imgS_pos=([512,384])
</code></pre>
<p>the lists i want to change, they are positions for where to blit images.</p>
<p>it would also be nice to have these lists saved in another file and read from there while still being changeable.</p>
<pre><code>cave_block1S_pos=([(0,0),(32,0),(64,0),(96,0),(128,0),(160,0),(192,0),(224,0),(256,0),(288,0),(320,0),(352,0),(384,0),(416,0),(448,0),(480,0),(512,0),(544,0),(576,0),(608,0),(640,0),(672,0),(704,0),(736,0),(768,0),(800,0),(832,0),(864,0),(896,0),(928,0),(960,0),(992,0),(1024,0)])
cave_block2S_pos=([(0,736),(32,736),(64,736),(96,736),(128,736),(160,736),(192,736),(224,736),(256,736),(288,736),(320,736),(352,736),(384,736),(416,736),(448,736),(480,736),(512,736),(544,736),(576,736),(608,736),(640,736),(672,736),(704,736),(736,736),(768,736),(800,736),(832,736),(864,736),(896,736),(928,736),(960,736),(992,736),(1024,736)])
cave_block3S_pos=([(0,0),(0,32),(0,64),(0,96),(0,128),(0,160),(0,192),(0,224),(0,256),(0,288),(0,320),(0,352),(0,384),(0,416),(0,448),(0,480),(0,512),(0,544),(0,576),(0,608),(0,640),(0,672),(0,704),(0,736),(0,768)])
while game:
clock.tick(30)
screen.blit(background,(backgrounS_pos))
screen.blit(player_img,(player_imgS_pos))
</code></pre>
<p>where i'm trying to change the values of the list.</p>
<pre><code> for blocks in cave_block1S_pos:
screen.blit(cave_block,blocks)
if move_playerR==True:
cave_block1S_pos[0]-=5
for blocks in cave_block2S_pos:
screen.blit(cave_block,blocks)
for blocks in cave_block3S_pos:
screen.blit(cave_block,blocks)
#cave.append([random.randint(player_imgS_pos[0]-512,player_imgS_pos[1]+684), random.randint(player_imgS_pos[0]-512,player_imgS_pos[0]+384)])
#for rocks in cave:
#screen.blit(cave_block, rocks)
#if move_playerR==True:
#rocks[0]+=5
if backgrounS_pos[0]>=32:
backgrounS_pos[0]=32
if backgrounS_pos[0]<=-905:
backgrounS_pos[0]=-905
if backgrounS_pos[1]>=32:
backgrounS_pos[1]=32
if backgrounS_pos[1]<=-470:
backgrounS_pos[1]=-470
if move_playerR==True:
backgrounS_pos[0]-=5
if move_playerL==True:
backgrounS_pos[0]+=5
if move_playerD==True:
backgrounS_pos[1]-=5
if move_playerU==True:
backgrounS_pos[1]+=5
print(backgrounS_pos)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key==K_ESCAPE:
pygame.quit()
exit(0)
if event.key==K_w:
move_playerU=True
if event.key==K_a:
move_playerL=True
if event.key==K_s:
move_playerD=True
if event.key==K_d:
move_playerR=True
if event.type==pygame.KEYUP:
if event.key==K_w:
move_playerU=False
if event.key==K_a:
move_playerL=False
if event.key==K_s:
move_playerD=False
if event.key==K_d:
move_playerR=False
if event.type==pygame.QUIT:
pygame.quit
exit(0)
pygame.display.update()
</code></pre>
| 0 | 2016-08-14T21:00:59Z | 38,961,242 | <p><code>cave_block1S_pos[0] -= 5</code> is the same as <code>cave_block1S_pos[0] = cave_block1S_pos[0] - 5</code>, which in your case is <code>cave_block1S_pos[0] = (0, 0) - 5</code>. You cannot subtract 5 from a tuple, hence gets the error <code>TypeError: unsupported operand type(s) for -=: 'tuple' and 'int'</code></p>
| 0 | 2016-08-15T18:57:00Z | [
"python",
"windows",
"pygame"
] |
Having trouble with a python bezier surface plot- keeps returning an empty plot | 38,946,639 | <p>I'm trying to plot a Bezier surface in matplotlib. I have my functions for x,y, and z (I didnt type them out, I had sympy automatically generate them) but whenever I run my code, I just get a blank plot. By the way, px, py, and pz refer to matrix of control points. Can anyone tell me what I did wrong and what I need to correct? Or maybe suggest another way to plot a bezier surface using python?</p>
<pre><code>fig = plt.figure()
ax = fig.gca(projection='3d')
u = np.linspace(0, 1, 10)
v = np.linspace(0, 1, 10)
x = px[0][0]*u**3*v**3 + px[0][1]*3*u**3*v**2*(-v + 1) + px[0][2]*3*u**3*v* (-v + 1)**2 + px[0][3]*u**3*(-v + 1)**3 + \
px[1][0]*3*u**2*v**3*(-u + 1) + px[1][1]*9*u**2*v**2*(-u + 1)*(-v + 1) + px[1][2]*9*u**2*v*(-u + 1)*(-v + 1)**2 + \
px[1][3]*3*u**2*(-u + 1)*(-v + 1)**3 + px[2][0]*3*u*v**3*(-u + 1)**2 + px[2][1]*9*u*v**2*(-u + 1)**2*(-v + 1) + \
px[2][2]*9*u*v*(-u + 1)**2*(-v + 1)**2 + px[2][3]*3*u*(-u + 1)**2*(-v + 1)**3 + px[3][0]*v**3*(-u + 1)**3 + \
px[3][1]*3*v**2*(-u + 1)**3*(-v + 1) + px[3][2]*3*v*(-u + 1)**3*(-v + 1)**2 + px[3][3]*(-u + 1)**3*(-v + 1)**3
y = py[0][0]*u**3*v**3 + py[0][1]*3*u**3*v**2*(-v + 1) + py[0][2]*3*u**3*v*(-v + 1)**2 + py[0][3]*u**3*(-v + 1)**3 +\
py[1][0]*3*u**2*v**3*(-u + 1) + py[1][1]*9*u**2*v**2*(-u + 1)*(-v + 1) + py[1][2]*9*u**2*v*(-u + 1)*(-v + 1)**2 + \
py[1][3]*3*u**2*(-u + 1)*(-v + 1)**3 + py[2][0]*3*u*v**3*(-u + 1)**2 + py[2][1]*9*u*v**2*(-u + 1)**2*(-v + 1) + \
py[2][2]*9*u*v*(-u + 1)**2*(-v + 1)**2 + py[2][3]*3*u*(-u + 1)**2*(-v + 1)**3 + py[3][0]*v**3*(-u + 1)**3 + \
py[3][1]*3*v**2*(-u + 1)**3*(-v + 1) + py[3][2]*3*v*(-u + 1)**3*(-v + 1)**2 + py[3][3]*(-u + 1)**3*(-v + 1)**3
z = pz[0][0]*u**3*v**3 + pz[0][1]*3*u**3*v**2*(-v + 1) + pz[0][2]*3*u**3*v*(-v + 1)**2 + pz[0][3]*u**3*(-v + 1)**3 + \
pz[1][0]*3*u**2*v**3*(-u + 1) + pz[1][1]*9*u**2*v**2*(-u + 1)*(-v + 1) + pz[1][2]*9*u**2*v*(-u + 1)*(-v + 1)**2 +\
pz[1][3]*3*u**2*(-u + 1)*(-v + 1)**3 + pz[2][0]*3*u*v**3*(-u + 1)**2 + pz[2][1]*9*u*v**2*(-u + 1)**2*(-v + 1) + \
pz[2][2]*9*u*v*(-u + 1)**2*(-v + 1)**2 + pz[2][3]*3*u*(-u + 1)**2*(-v + 1)**3 + pz[3][0]*v**3*(-u + 1)**3 + \
pz[3][1]*3*v**2*(-u + 1)**3*(-v + 1) + pz[3][2]*3*v*(-u + 1)**3*(-v + 1)**2 + pz[3][3]*(-u + 1)**3*(-v + 1)**3
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')
plt.show()
</code></pre>
| 0 | 2016-08-14T21:06:42Z | 38,946,791 | <p>Here's a couple of examples to plot bezier curves with matplotlib:</p>
<p><strong>EXAMPLE1</strong></p>
<p>From <a href="http://stackoverflow.com/a/12644499/3809375">stackoverflow</a></p>
<pre><code>import numpy as np
from scipy.misc import comb
from matplotlib import pyplot as plt
def bernstein_poly(i, n, t):
return comb(n, i) * (t**(n - i)) * (1 - t)**i
def bezier_curve(points, nTimes=1000):
nPoints = len(points)
xPoints = np.array([p[0] for p in points])
yPoints = np.array([p[1] for p in points])
t = np.linspace(0.0, 1.0, nTimes)
polynomial_array = np.array(
[bernstein_poly(i, nPoints - 1, t) for i in range(0, nPoints)])
xvals = np.dot(xPoints, polynomial_array)
yvals = np.dot(yPoints, polynomial_array)
return xvals, yvals
if __name__ == "__main__":
nPoints = 4
points = np.random.rand(nPoints, 2) * 200
xpoints = [p[0] for p in points]
ypoints = [p[1] for p in points]
xvals, yvals = bezier_curve(points, nTimes=1000)
plt.plot(xvals, yvals)
plt.plot(xpoints, ypoints, "ro")
for nr in range(len(points)):
plt.text(points[nr][0], points[nr][1], nr)
plt.show()
</code></pre>
<p><strong>EXAMPLE2</strong></p>
<p>From <a href="http://matplotlib.org/users/path_tutorial.html" rel="nofollow">matplotlib tutorial</a></p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
verts = [
(0., 0.), # P0
(0.2, 1.), # P1
(1., 0.8), # P2
(0.8, 0.), # P3
]
codes = [Path.MOVETO,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4,
]
path = Path(verts, codes)
fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='none', lw=2)
ax.add_patch(patch)
xs, ys = zip(*verts)
ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10)
ax.text(-0.05, -0.05, 'P0')
ax.text(0.15, 1.05, 'P1')
ax.text(1.05, 0.85, 'P2')
ax.text(0.85, -0.05, 'P3')
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-0.1, 1.1)
plt.show()
</code></pre>
<p>If you ask me... my favourite way to think about parametric curves is using their matrix form, like showed in this <a href="http://www.blackpawn.com/texts/splines/" rel="nofollow">website</a></p>
<p><strong>EDIT:</strong></p>
<p>If you want to extend it to the 3d case, here's a working example:</p>
<pre><code>import matplotlib as mpl
import numpy as np
from scipy.misc import comb
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def bernstein_poly(i, n, t):
return comb(n, i) * (t**(n - i)) * (1 - t)**i
def bezier_curve(points, nTimes=1000):
nPoints = len(points)
xPoints = np.array([p[0] for p in points])
yPoints = np.array([p[1] for p in points])
zPoints = np.array([p[2] for p in points])
t = np.linspace(0.0, 1.0, nTimes)
polynomial_array = np.array(
[bernstein_poly(i, nPoints - 1, t) for i in range(0, nPoints)])
xvals = np.dot(xPoints, polynomial_array)
yvals = np.dot(yPoints, polynomial_array)
zvals = np.dot(zPoints, polynomial_array)
return xvals, yvals, zvals
if __name__ == "__main__":
nPoints = 4
points = np.random.rand(nPoints, 3) * 200
xpoints = [p[0] for p in points]
ypoints = [p[1] for p in points]
zpoints = [p[2] for p in points]
xvals, yvals, zvals = bezier_curve(points, nTimes=1000)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(xvals, yvals, zvals, label='bezier')
ax.plot(xpoints, ypoints, zpoints, "ro")
for nr in range(len(points)):
ax.text(points[nr][0], points[nr][1], points[nr][2], nr)
plt.show()
</code></pre>
| 0 | 2016-08-14T21:29:32Z | [
"python",
"matplotlib"
] |
Erase part of image on Tkinter canvas, exposing another image underneath | 38,946,666 | <p>(Python 2.7). I have a Tkinter canvas with two images that are both the height and width of the canvas, so they cover the whole window. One image is on top of the other. I want to, using the mouse, be able to erase part of the top image wherever I want, thus exposing the bottom image. Is this possible?</p>
<p>I'm curious in how to implement the Home.erase method below which is bound to a Tkinter motion event.</p>
<pre><code># -*- coding: utf-8 -*-
import io
from PIL import Image, ImageTk
import Tkinter as tk
#Image 2 is on top of image 1.
IMAGE1_DIR = "C:/path_to_image/image1.png"
IMAGE2_DIR = "C:/path_to_image/image2.png"
def create_image(filename, width=0, height=0):
"""
Returns a PIL.Image object from filename - sized
according to width and height parameters.
filename: str.
width: int, desired image width.
height: int, desired image height.
1) If neither width nor height is given, image will be returned as is.
2) If both width and height are given, image will resized accordingly.
3) If only width or only height is given, image will be scaled so specified
parameter is satisfied while keeping image's original aspect ratio the same.
"""
with open(filename, "rb") as f:
fh = io.BytesIO(f.read())
#Create a PIL image from the data
img = Image.open(fh, mode="r")
#Resize if necessary.
if not width and not height:
return img
elif width and height:
return img.resize((int(width), int(height)), Image.ANTIALIAS)
else: #Keep aspect ratio.
w, h = img.size
scale = width/float(w) if width else height/float(h)
return img.resize((int(w*scale), int(h*scale)), Image.ANTIALIAS)
class Home(object):
"""
master: tk.Tk window.
screen: tuple, (width, height).
"""
def __init__(self, master, screen):
self.screen = w, h = screen
self.master = master
self.frame = tk.Frame(self.master)
self.frame.pack()
self.can = tk.Canvas(self.frame, width=w, height=h)
self.can.pack()
#Photos will be as large as the screen.
p1 = ImageTk.PhotoImage(image=create_image(IMAGE1_DIR, w, h))
p2 = ImageTk.PhotoImage(image=create_image(IMAGE2_DIR, w, h))
## Place photos in center of screen.
## Create label to retain a reference to image so it doesn't dissapear.
self.photo1 = self.can.create_image((w//2, h//2), image=p1)
label1 = tk.Label(image=p1)
label1.image = p1
#On top.
self.photo2 = self.can.create_image((w//2, h//2), image=p2)
label2 = tk.Label(image=p2)
label2.image = p2
#Key bindings.
self.master.bind("<Return>", self.reset)
self.master.bind("<Motion>", self.erase)
#### Key Bindings ####
def reset(self, event):
""" Enter/Return key. """
self.frame.destroy()
self.__init__(self.master, self.screen)
def erase(self, event):
"""
Mouse motion binding.
Erase part of top image (self.photo2) at location (event.x, event.y),
consequently exposing part of the bottom image (self.photo1).
"""
pass
def main(screen=(500, 500)):
root = tk.Tk()
root.resizable(0, 0)
Home(root, screen)
#Place window in center of screen.
root.eval('tk::PlaceWindow %s center'%root.winfo_pathname(root.winfo_id()))
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-08-14T21:11:32Z | 38,957,833 | <p>Thanks to @martineau for the suggestions! Here is the working code.</p>
<pre><code>from PIL import Image, ImageTk
import Tkinter as tk
#Image 2 is on top of image 1.
IMAGE1_DIR = "C:/path/image1.PNG"
IMAGE2_DIR = "C:/path/image2.PNG"
#Brush size in pixels.
BRUSH = 5
#Actual size is 2*BRUSH
def create_image(filename, width=0, height=0):
"""
Returns a PIL.Image object from filename - sized
according to width and height parameters.
filename: str.
width: int, desired image width.
height: int, desired image height.
1) If neither width nor height is given, image will be returned as is.
2) If both width and height are given, image will resized accordingly.
3) If only width or only height is given, image will be scaled so specified
parameter is satisfied while keeping image's original aspect ratio the same.
"""
#Create a PIL image from the file.
img = Image.open(filename, mode="r")
#Resize if necessary.
if not width and not height:
return img
elif width and height:
return img.resize((int(width), int(height)), Image.ANTIALIAS)
else: #Keep aspect ratio.
w, h = img.size
scale = width/float(w) if width else height/float(h)
return img.resize((int(w*scale), int(h*scale)), Image.ANTIALIAS)
class Home(object):
"""
master: tk.Tk window.
screen: tuple, (width, height).
"""
def __init__(self, master, screen):
self.screen = w, h = screen
self.master = master
self.frame = tk.Frame(self.master)
self.frame.pack()
self.can = tk.Canvas(self.frame, width=w, height=h)
self.can.pack()
self.image1 = create_image(IMAGE1_DIR, w, h)
self.image2 = create_image(IMAGE2_DIR, w, h)
#Center of screen.
self.center = w//2, h//2
#Start with no photo on the screen.
self.photo = False
#Draw photo on screen.
self.draw()
#Key bindings.
self.master.bind("<Return>", self.reset)
self.master.bind("<Motion>", self.erase)
def draw(self):
"""
If there is a photo on the canvas, destroy it.
Draw self.image2 on the canvas.
"""
if self.photo:
self.can.delete(self.photo)
self.label.destroy()
p = ImageTk.PhotoImage(image=self.image2)
self.photo = self.can.create_image(self.center, image=p)
self.label = tk.Label(image=p)
self.label.image = p
#### Key Bindings ####
def reset(self, event):
""" Enter/Return key. """
self.frame.destroy()
self.__init__(self.master, self.screen)
def erase(self, event):
"""
Mouse motion binding.
Erase part of top image (self.photo2) at location (event.x, event.y),
consequently exposing part of the bottom image (self.photo1).
"""
for x in xrange(event.x-BRUSH, event.x+BRUSH+1):
for y in xrange(event.y-BRUSH, event.y+BRUSH+1):
try:
p = self.image1.getpixel((x, y))
self.image2.putpixel((x, y), p)
except IndexError:
pass
self.draw()
def main(screen=(500, 500)):
root = tk.Tk()
root.resizable(0, 0)
Home(root, screen)
#Place window in center of screen.
root.eval('tk::PlaceWindow %s center'%root.winfo_pathname(root.winfo_id()))
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 2016-08-15T15:11:18Z | [
"python",
"python-2.7",
"canvas",
"tkinter"
] |
re.sub not matching nested dictionary | 38,946,697 | <p>with the following dict:</p>
<pre><code>interfaces = {'A':{'568':'A1','590':'A2'},'B':{'590':'B2'}}
</code></pre>
<p>i what to replace the value='590' with A2 while setting the A element and B2 while setting the B element.</p>
<p>I've tried :</p>
<pre><code>pattern_interfaces = r'\b({})\b'.format('|'.join(sorted(re.escape(k) for k in interfaces['A']))) #=>(568|590)
re_value = re.sub(pattern_interfaces, lambda m: interfaces.get(m.group(0).upper()), value, flags=re.IGNORECASE)
</code></pre>
<p>but <code>re_value</code> is blank. </p>
<p>Can anyone explain why is that.</p>
<p>Thx.</p>
<p>[update]</p>
<p>ok , i see where i was wrong lambda m: interfaces['A'] does what i needed.</p>
| -1 | 2016-08-14T21:16:15Z | 38,946,875 | <p>You matched keys from <code>interfaces['A']</code>, not from <code>interfaces</code>. Use that nested dictionary if you are going to generate a regex from that keys :</p>
<pre><code>re_value = re.sub(
pattern_interfaces,
lambda m: interfaces['A'][m.group(0).upper()],
value, flags=re.IGNORECASE)
</code></pre>
<p>I replaced the <code>dict.get()</code> call with direct subscription; you can only match existing keys with your regex, no need to account for missing keys here.</p>
<p>Your sample also matched numbers, not letters, so neither the <code>.upper()</code> call nor the <code>re.IGNORECASE</code> will make a difference here.</p>
| 0 | 2016-08-14T21:43:06Z | [
"python",
"dictionary"
] |
Using Random to call a dictionary from a different class | 38,946,716 | <p>I'm making a small game and I'm trying to have the EncounterM class get a random Monster and Dmg from the monster class dictionary. (New at Python) </p>
<pre><code> class Monster:
monster_health = {'goblin': 15, 'giant': 50}
monster_damage = {'goblin': 3, 'giant': 1}
class EncounterM(Monster):
import random
# I tried using random.choice(monster_health.keys())
</code></pre>
| -2 | 2016-08-14T21:18:09Z | 38,946,753 | <p>I'll ignore the not-working-at-all object constructions to focus on your question. Read more about object, instances, classes and post another question.
(Edit: I couldn't resist to change it a little to make it a little more object-like, but I won't go further)</p>
<p>With Python 3, <code>keys()</code> do not return a list anymore. You have to cast to <code>list</code> explicitly for it to work</p>
<pre><code>import random
class Monster:
health = {'goblin': 15, 'giant': 50}
damage = {'goblin': 3, 'giant': 1}
print(random.choice(list(Monster.health.keys())))
</code></pre>
<p>output:</p>
<pre><code>giant
(or goblin)
</code></pre>
| 1 | 2016-08-14T21:23:05Z | [
"python",
"dictionary"
] |
Python on Zapier issue | 38,946,834 | <p>Any Ideas what I am doing wrong it won't run!</p>
<p><a href="http://i.stack.imgur.com/pux3J.png" rel="nofollow"><img src="http://i.stack.imgur.com/pux3J.png" alt="enter image description here"></a></p>
| -4 | 2016-08-14T21:35:48Z | 39,008,787 | <p>Don't forget your <code>:</code> at the end of your if statement!</p>
| 0 | 2016-08-18T01:52:52Z | [
"python",
"zapier"
] |
Using shutil.rmtree() in a recursive function (Windows 10) | 38,947,001 | <p>I am encountering an error that can probably be worked around but conceptually confusing to me and wondering if someone could shed some light.</p>
<p>When I recurse through directory structure calling shutil.rmtree() under certain condition, I get an error that amounts to an attempt to delete an already deleted object. Here is a simplest example:</p>
<pre><code>def deleteFolder(path):
for obj in glob.glob(os.path.join(path, '*')):
print('obj name is ',obj)
if os.path.isdir(obj):
deleteFolder(obj)
print('removing path ',path)
print(os.listdir(path))
shutil.rmtree(path,False)
WindowsError Traceback (most recent call last)
<ipython-input-36-ad9561d5fc92> in <module>()
2 #path = 'C:\Users\Wes\Desktop\Test\Morphine\Album1'
3 #shutil.rmtree(path)
----> 4 deleteFolder('C:\Users\Wes\Desktop\Test\Level1')
<ipython-input-35-14a315bc6a80> in deleteFolder(path)
30 print('removing path ',path)
31 print(os.listdir(path))
---> 32 shutil.rmtree(path,False)
C:\Users\Wes\Anaconda2\lib\shutil.pyc in rmtree(path, ignore_errors, onerror)
250 os.remove(fullname)
251 except os.error, err:
--> 252 onerror(os.remove, fullname, sys.exc_info())
253 try:
254 os.rmdir(path)
C:\Users\Wes\Anaconda2\lib\shutil.pyc in rmtree(path, ignore_errors, onerror)
248 else:
249 try:
--> 250 os.remove(fullname)
251 except os.error, err:
252 onerror(os.remove, fullname, sys.exc_info())
WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2'
</code></pre>
<p>Directory structure is /Level1/Level2/Level3 and fx is called w/ arg Level1.
Obviously this is a stupid example, it is doing the recursion that shutil.rmtree is built for, but when you add a condition to whether or not to delete the directory it makes more sense.</p>
<p>Here is the print output:</p>
<pre><code>('obj name is ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2')
('obj name is ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2\\Level3')
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2\\Level3')
[]
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2')
[]
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1')
['Level2']
</code></pre>
<p>So it seems to travel down to Level3, delete Level3, moves up to Level2, has no problem seeing that Level3 is no longer a subdir of Level2, deletes Level2, but then Level1 still see Level2 and errors. There seems to be some subtlety of scoping as it relates to os.path that I am missing.</p>
<p>Ultimately, I would like to go explore an entire tree starting at some root and prune directories which have no descendants that meet some certain criteria (contain audio files).</p>
| 1 | 2016-08-14T22:02:25Z | 38,949,679 | <p>I think, your problem can be linked with this one: <a href="http://stackoverflow.com/questions/16373747/permission-denied-doing-os-mkdird-after-running-shutil-rmtreed-in-python">Permission denied doing os.mkdir(d) after running shutil.rmtree(d) in Python</a></p>
<p><code>shutil.rmtree</code> on Windows happens to return not when files are actually deleted. You can imagine that this is done in some asynchronous manner so that consequent <code>rmtree</code> calls <a href="https://en.wikipedia.org/wiki/Race_condition" rel="nofollow">may conflict</a>. Also that's why <code>pip install</code> fails sometimes when deletes its cached files using <code>shutil.rmtree</code> during the cleanup phase.</p>
<p>Try to put <code>time.sleep(1)</code> after each <code>rmtree</code> call - does it help?
If it does, your solution would be either the retrying to delete files after such an error or collecting the directories to delete and remove them selectively to avoid conflicts.</p>
| 0 | 2016-08-15T05:20:54Z | [
"python",
"windows",
"python-2.7",
"recursion",
"shutil"
] |
Read data from qabstractitemmodel via qdatawidgetmapper with BackgroundRole | 38,947,141 | <p>I have the following question reagrding Qt (using PyQt 5):</p>
<p>I have modified one of the examples which I found for QDataWidgetMapper and QAbstractTableModel and added an additional if-clause for the role Qt.BackgroundRole to the data method.</p>
<p>The goal is to get different background colors depending on the content of my model (e.g. red background if the array element is equal to "error")</p>
<p>That works well for the qlistview2, but does not work for the qLineEdits, which are mapped to the model. I'm aware that this is not intended by the default QDataWidgetMapper (only one-by-one mapping of a section of the model to one property of a widget).</p>
<p>What would be the best practice to map additional properties/information to the line edits (to modify their style like background color, visibility, line edit enabled/not enabled)?</p>
<p>I need to do the computing for such properties inside the model (for a much more complex model) and do not want to subclass the QLineEdit (to implement there specific methods for changing the colors based on the QLineEdit text content).</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import (QWidget, QDataWidgetMapper,
QLineEdit, QApplication, QGridLayout, QListView)
from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex
from PyQt5.QtGui import QBrush
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# Set up the widgets.
self.nameEdit = QLineEdit()
self.nameEdit2 = QLineEdit()
# set up the layout
layout = QGridLayout()
layout.addWidget(self.nameEdit, 0, 1, 1, 1)
layout.addWidget(self.nameEdit2, 0, 2, 1, 1)
self.setLayout(layout)
self.mapper = None
def setModel(self, model):
# Set up the mapper.
self.mapper = QDataWidgetMapper(self)
self.mapper.setModel(model)
self.mapper.addMapping(self.nameEdit, 0)
self.mapper.addMapping(self.nameEdit2, 1)
self.mapper.toFirst()
class MyModel(QAbstractTableModel):
def __init__(self, data, parent=None):
QAbstractTableModel.__init__(self, parent)
self.lst = data
def columnCount(self, parent=QModelIndex()):
return len(self.lst[0])
def rowCount(self, parent=QModelIndex()):
return len(self.lst)
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
if role == Qt.EditRole:
return self.lst[row][col]
elif role == Qt.DisplayRole:
return self.lst[row][col]
elif role == Qt.BackgroundRole:
redBackground = QBrush(Qt.red)
greenBackground = QBrush(Qt.green)
if self.lst[row][col] == "error":
return redBackground
else:
return greenBackground
def flags(self, index):
flags = super(MyModel, self).flags(index)
if index.isValid():
flags |= Qt.ItemIsEditable
flags |= Qt.ItemIsDragEnabled
else:
flags = Qt.ItemIsDropEnabled
return flags
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid() or role != Qt.EditRole:
return False
self.lst[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
myModel = MyModel([['row 1 col1', 'error'],
['error', 'row 2 col2'],
['row 3 col1', 'row 3 col2'],
['error', 'row 4 col2']])
# myModel = MyModel()
mywindow = Window()
mywindow.setModel(myModel)
qlistview2 = QListView()
qlistview2.setModel(myModel)
mywindow.show()
qlistview2.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-08-14T22:22:26Z | 39,067,439 | <p>I have found the simple solution: I have to work with custom delegates to solve the problem.</p>
<pre><code>class LineDelegate(QStyledItemDelegate):
def __init__(self, parent = None):
QStyledItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
pass
def setEditorData(self, editor, index):
editor.setText(index.model().data(index, Qt.EditRole))
color = index.model().data(index, Qt.BackgroundColorRole)
palette = QPalette()
palette.setBrush(QPalette.Base,color)
editor.setPalette(palette)
editor.repaint()
def setModelData(self, editor, model, index):
model.setData(index, editor.text(), Qt.EditRole)
</code></pre>
<p>As I need multiple delegates to handle both QLineEdits, <a href="http://stackoverflow.com/a/10368966/2343241">the question and answer given by AlexVhr</a> helped a lot.</p>
<p>The complete modified source code is in the <a href="http://pastebin.com/ckvG85Ey" rel="nofollow">pastebin</a>.</p>
| 0 | 2016-08-21T18:18:18Z | [
"python",
"qt",
"pyqt",
"pyqt5"
] |
ImportError: cannot import name App | 38,947,154 | <p>I am trying to follow the tutorial on <a href="https://www.youtube.com/watch?v=CYNWK2GpwgA&list=PLQVvvaa0QuDe_l6XiJ40yGTEqIKugAdTy&index=1" rel="nofollow">this youtube video</a>.</p>
<p>But <code>from kivy import App</code> gives <code>ImportError: cannot import name App</code>. How can I fix this?</p>
<p>I have installed kivy 1.8.0 and cython 0.20</p>
<p><code>pip freeze</code> returns</p>
<pre><code>adium-theme-ubuntu==0.3.4
Cython==0.20
Kivy==1.8.0
Kivy-Garden==0.1.1
numpy==1.11.0
pygame===1.9.1release
requests==2.11.0
unity-lens-photos==1.0
virtualenv==15.0.3
</code></pre>
| 0 | 2016-08-14T22:24:31Z | 38,947,166 | <p>Try <code>from kivy.app import App</code> (<a href="https://kivy.org/docs/api-kivy.app.html" rel="nofollow">documentation</a>).</p>
| 3 | 2016-08-14T22:26:31Z | [
"python",
"kivy"
] |
Why am I getting the error message name 'datestr' is not defined? Python 2.7 | 38,947,170 | <p>So datestr() is supposed to convert a number into a date. But I keep getting this Name error message. Am I not loading the correct module. I have searched the Matplotlib documenation but do not see any specific module that must be imported. </p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,\
DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
import pandas as pd
import datetime
import pandas.io.data as web
from datetime import date
import matplotlib
date = 731613
print datestr(date)
#NameError: name 'datestr' is not defined
</code></pre>
| 0 | 2016-08-14T22:27:35Z | 38,947,356 | <p>Yes I was not using the correct function. I did a search on the problem and I ran into the soltution I tried above the correct format is below.</p>
<pre><code>from datetime import date
dte = 731613
print date.fromordinal(dte)
#out put is >> 2004-02-02
# (Year, Month, day)
</code></pre>
| 0 | 2016-08-14T22:58:48Z | [
"python",
"matplotlib"
] |
Why am I getting the error message name 'datestr' is not defined? Python 2.7 | 38,947,170 | <p>So datestr() is supposed to convert a number into a date. But I keep getting this Name error message. Am I not loading the correct module. I have searched the Matplotlib documenation but do not see any specific module that must be imported. </p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,\
DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
import pandas as pd
import datetime
import pandas.io.data as web
from datetime import date
import matplotlib
date = 731613
print datestr(date)
#NameError: name 'datestr' is not defined
</code></pre>
| 0 | 2016-08-14T22:27:35Z | 38,947,358 | <p>It looks like you want the function <code>mathplotlib.dates.num2date()</code>. From there you can convert to a string with <code>str()</code> or <code>strftime()</code>:</p>
<pre><code>>>> from matplotlib.dates import num2date
>>> num2date(731613)
datetime.datetime(2004, 2, 2, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x7f64861fa5d0>)
>>> print(num2date(731613))
2004-02-02 00:00:00+00:00
>>> str(num2date(731613))
'2004-02-02 00:00:00+00:00'
</code></pre>
| 1 | 2016-08-14T22:59:05Z | [
"python",
"matplotlib"
] |
df.mean is not the real mean of the Series? | 38,947,278 | <p>I'm debugging and run into the following strange behavior.
I'm calculating the mean of a pandas series which contains all exactly the same numbers. However, the <code>pd.mean()</code> gives a different number.</p>
<p>question1: why mean of this Series is a different number?</p>
<p>question2: <code>tmm[-1]== tmm.mean()</code> gives <code>False</code> now. Any way to ignore this small difference and make the results True? I don't prefer <code>abs(tmm[-1]-tmm.mean()) < xxx</code> </p>
<p>methods because not sure how to define <code>xxx</code>.</p>
<pre><code>import pandas as pd
import decimal
tmm = pd.Series(14.9199999999999999289457264239899814128875732421875,
index=range(30))
for t in tmm:
print(decimal.Decimal(t))
print('mean is')
print(decimal.Decimal(tmm.mean()))
</code></pre>
<p>results:</p>
<pre><code>14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
mean is
14.9200000000000034816594052244909107685089111328125
</code></pre>
| 1 | 2016-08-14T22:46:30Z | 38,947,348 | <p>The answer to your 2 questions is basically this:</p>
<pre><code>import pandas as pd
import decimal
tmm = pd.Series(decimal.Decimal(14.9199999999999999289457264239899814128875732421875),
index=range(30))
for t in tmm:
print(decimal.Decimal(t))
print('mean is')
print(decimal.Decimal(tmm.mean()))
</code></pre>
<p>Make sure you use decimal.Decimal constructor when you're creating tmm, that's pretty much.</p>
| 0 | 2016-08-14T22:57:18Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.