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 |
|---|---|---|---|---|---|---|---|---|---|
Passing variable for module import and use | 39,070,053 | <p>so I am trying to use a variable brand which is selected by the user. The variable is then to be used to call a given module in Python. currently on line 7 you can see 'apple.solutions()'. However, I essentially want to be able to use something on the lines 'brand.solutions()' - although I know this will not work as it requires the attribute. I am looking for a solution to select the module based on the variable brands. I would appreciate any solutions or advice. Thanks,</p>
<p>Main program:</p>
<pre><code>import apple, android, windows
brands = ["apple", "android", "windows"]
brand = None
def Main():
query = input("Enter your query: ").lower()
brand = selector(brands, query, "brand", "brands")
solutions = apple.solutions()
print(solutions)
</code></pre>
<p>Apple.py Module File (same directory as main program):</p>
<pre><code>def solutions():
solutions = ["screen", "battery", "speaker"]
return solutions
</code></pre>
| 0 | 2016-08-22T00:38:47Z | 39,070,515 | <pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import apple, android, windows
brands = ["apple", "android", "windows"]
def selector(brands, query):
if query in brands:
exec("import %s as brand" % query)
else:
brand = None
return brand
def Main():
query = raw_input("Enter your query: ").lower()
brand = selector(brands, query)
solutions = brand.solutions()
print(solutions)
if __name__ == '__main__':
Main()
</code></pre>
<p>I have a simple way by using the <code>exec</code> function to dynamically import models</p>
| 0 | 2016-08-22T02:06:23Z | [
"python",
"arrays",
"variables",
"parameter-passing",
"python-module"
] |
Python Looping through File and downloading Images | 39,070,060 | <p>I am trying to loop through a text file with different website links to download the images. I also want them to have a unique file name. Just a loop counter as you see so the three images would be <code>1.jpg</code>, <code>2.jpg</code>, <code>3.jpg</code>. Yet I am only getting the last image and the file is named <code>0.jpg</code>. I have tried a couple of different methods but this seemed the best but still no luck. Any suggestions on next steps?</p>
<pre><code>import urllib
input_file = open('Urls1.txt','r')
x=0
for line in input_file:
URL= line
urllib.urlretrieve(URL, str(x) + ".jpg")
x+=1
</code></pre>
| 1 | 2016-08-22T00:40:14Z | 39,082,132 | <p>rewrite the code by indenting the last two lines thus</p>
<pre><code>import urllib
input_file = open('Urls1.txt','r')
x=0
for line in input_file:
URL= line
urllib.urlretrieve(URL, str(x) + ".jpg")
x+=1
</code></pre>
<p>Indentation is significant in Python. Without it, the last two statements are only executed after the loop has completed. Thus you only retrieve the last URL in the file.</p>
| 1 | 2016-08-22T14:28:09Z | [
"python"
] |
Python re replace group values | 39,070,119 | <p>I have a regular expression through which I want to replace values with those values minus 10.
The re is:</p>
<pre><code>re.compile(r'<stuff[^\>]*translate\((?P<x>\d*),(?P<y>\d*)\)"/>')
</code></pre>
<p>I want to replace the x and y groups. To do this, I want to use <code>re.sub</code> and passing it a function. However, in the function, how can I most easily build a string which is the same as the input, only with the x and y values replaced by themselves minus 10?</p>
| 1 | 2016-08-22T00:52:22Z | 39,070,188 | <p>The <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code> docs</a> show a good example of using a replacer function. In your case, this would work:</p>
<pre class="lang-python prettyprint-override"><code>import re
def less10(string):
return int(string) - 10
def replacer(match):
return '%s%d,%d%s' % (match.group('prefix'),
less10(match.group('x')),
less10(match.group('y')),
match.group('suffix'))
print re.sub(r'(?P<prefix><stuff[^>]*translate\()(?P<x>\d*),(?P<y>\d*)(?P<suffix>\)/>)',
replacer,
'<stuff translate(100,200)/>')
</code></pre>
<p><a href="http://ideone.com/tQS4wK" rel="nofollow">http://ideone.com/tQS4wK</a></p>
| 0 | 2016-08-22T01:10:01Z | [
"python",
"regex",
"replace"
] |
boxplot (from seaborn) would not plot as expected | 39,070,135 | <p><strong>The boxplot would not plot as expected.
This is what it actually plotted:</strong>
<a href="http://i.stack.imgur.com/rAdwz.png" rel="nofollow"><img src="http://i.stack.imgur.com/rAdwz.png" alt="enter image description here"></a></p>
<p><strong>This is what it is supposed to plot:</strong>
<a href="http://i.stack.imgur.com/dhZrP.png" rel="nofollow"><img src="http://i.stack.imgur.com/dhZrP.png" alt="enter image description here"></a></p>
<p><strong>This is the code and data:</strong></p>
<pre><code> from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
scores = []
for ne in range(1,41): ## ne is the number of trees
clf = RandomForestClassifier(n_estimators = ne)
score_list = cross_val_score(clf, X, Y, cv=10)
scores.append(score_list)
sns.boxplot(scores) # scores are list of arrays
plt.xlabel('Number of trees')
plt.ylabel('Classification score')
plt.title('Classification score as a function of the number of trees')
plt.show()
scores =
[array([ 0.8757764 , 0.86335404, 0.75625 , 0.85 , 0.86875 ,
0.81875 , 0.79375 , 0.79245283, 0.8490566 , 0.85534591]),
array([ 0.89440994, 0.8447205 , 0.79375 , 0.85 , 0.8625 ,
0.85625 , 0.86875 , 0.88050314, 0.86792453, 0.8427673 ]),
array([ 0.91304348, 0.9068323 , 0.83125 , 0.84375 , 0.8875 ,
0.875 , 0.825 , 0.83647799, 0.83647799, 0.87421384]),
array([ 0.86956522, 0.86956522, 0.85 , 0.875 , 0.88125 ,
0.86875 , 0.8625 , 0.8490566 , 0.86792453, 0.89308176]),
</code></pre>
<p>....]</p>
| 2 | 2016-08-22T00:56:32Z | 39,070,235 | <p>I would first create pandas DF out of <code>scores</code>:</p>
<pre><code>import pandas as pd
In [15]: scores
Out[15]:
[array([ 0.8757764 , 0.86335404, 0.75625 , 0.85 , 0.86875 , 0.81875 , 0.79375 , 0.79245283, 0.8490566 , 0.85534591]),
array([ 0.89440994, 0.8447205 , 0.79375 , 0.85 , 0.8625 , 0.85625 , 0.86875 , 0.88050314, 0.86792453, 0.8427673 ]),
array([ 0.91304348, 0.9068323 , 0.83125 , 0.84375 , 0.8875 , 0.875 , 0.825 , 0.83647799, 0.83647799, 0.87421384]),
array([ 0.86956522, 0.86956522, 0.85 , 0.875 , 0.88125 , 0.86875 , 0.8625 , 0.8490566 , 0.86792453, 0.89308176])]
In [16]: df = pd.DataFrame(scores)
In [17]: df
Out[17]:
0 1 2 3 4 5 6 7 8 9
0 0.875776 0.863354 0.75625 0.85000 0.86875 0.81875 0.79375 0.792453 0.849057 0.855346
1 0.894410 0.844720 0.79375 0.85000 0.86250 0.85625 0.86875 0.880503 0.867925 0.842767
2 0.913043 0.906832 0.83125 0.84375 0.88750 0.87500 0.82500 0.836478 0.836478 0.874214
3 0.869565 0.869565 0.85000 0.87500 0.88125 0.86875 0.86250 0.849057 0.867925 0.893082
</code></pre>
<p>now we can easily plot boxplots:</p>
<pre><code>In [18]: sns.boxplot(data=df)
Out[18]: <matplotlib.axes._subplots.AxesSubplot at 0xd121128>
</code></pre>
<p><a href="http://i.stack.imgur.com/6JdeA.png" rel="nofollow"><img src="http://i.stack.imgur.com/6JdeA.png" alt="enter image description here"></a></p>
| 2 | 2016-08-22T01:16:31Z | [
"python",
"arrays",
"python-2.7",
"scikit-learn",
"seaborn"
] |
Difference between <type 'generator'> and <type 'xrange'> | 39,070,168 | <p>I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.</p>
<ol>
<li>I want to know the exact difference between type 'xrange' and type 'generator'</li>
<li><p>If xrange is an iterator/generator, it is supposed to have .next() method. I do not understand why the .next() method doesn't work for the case below.</p>
<pre><code>def generator():
for i in xrange(20): yield i
</code></pre>
<p>In the above example, </p>
<pre><code> numbers = generator()
for i in numbers:
if i == 6: break
for i in numbers:
if i == 10: break
print i
>>> 7
8
9
>>> print numbers.next()
11
</code></pre>
<p>The above functionalities also hold true for a object generator of the type:</p>
<pre><code> >>> numbers = (x for x in range(100))
</code></pre>
<p>If I do with xrange operation, the loop starts iterating from the beginning and there is no next() operation. I know that we can do the smart way of:</p>
<pre><code> for i in xrange(20):
if (#something):
var = i
break
#perform some operations
for i in range(var,20):
#Do something
</code></pre></li>
</ol>
<p>But I want to loop to continue after var without using var.</p>
<p>To be short, is there a next() kind of operation for xrange. If yes : 'How?' , else : 'Why?'</p>
| 3 | 2016-08-22T01:05:08Z | 39,070,192 | <p><code>xrange</code> is an iterable, so you can call <code>iter</code> to get an iterator out of it.</p>
<pre><code>>>> x = xrange(20)
>>> iterator = iter(x)
>>> for i in iterator:
... if i == 6: break
...
>>> iterator.next()
7
</code></pre>
| 4 | 2016-08-22T01:10:04Z | [
"python",
"iterator",
"generator"
] |
Difference between <type 'generator'> and <type 'xrange'> | 39,070,168 | <p>I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.</p>
<ol>
<li>I want to know the exact difference between type 'xrange' and type 'generator'</li>
<li><p>If xrange is an iterator/generator, it is supposed to have .next() method. I do not understand why the .next() method doesn't work for the case below.</p>
<pre><code>def generator():
for i in xrange(20): yield i
</code></pre>
<p>In the above example, </p>
<pre><code> numbers = generator()
for i in numbers:
if i == 6: break
for i in numbers:
if i == 10: break
print i
>>> 7
8
9
>>> print numbers.next()
11
</code></pre>
<p>The above functionalities also hold true for a object generator of the type:</p>
<pre><code> >>> numbers = (x for x in range(100))
</code></pre>
<p>If I do with xrange operation, the loop starts iterating from the beginning and there is no next() operation. I know that we can do the smart way of:</p>
<pre><code> for i in xrange(20):
if (#something):
var = i
break
#perform some operations
for i in range(var,20):
#Do something
</code></pre></li>
</ol>
<p>But I want to loop to continue after var without using var.</p>
<p>To be short, is there a next() kind of operation for xrange. If yes : 'How?' , else : 'Why?'</p>
| 3 | 2016-08-22T01:05:08Z | 39,070,721 | <p>Also, you should understand that an iterator and an generator are not the same thing. An <em>iterable</em> is any Python object that implements an <code>__iter__</code> method that returns an <em>iterator</em>. An iterator also must implement an <code>__iter__</code> method but also a <code>next</code> method (<code>__next__</code> in Python 3). So <code>xrange</code> is iterable, but not an iterator. Here is an iterator:</p>
<pre><code>class NumberCounter(object):
def __init__(self, size):
self.size = size
self.start = 0
def __iter__(self):
return self
def next(self):
if self.start < self.size:
self.start += 1
return self.start
raise StopIteration
</code></pre>
<p>In the interactive interpreter:</p>
<pre><code>>>> nc6 = NumberCounter(6)
>>> it = iter(nc6)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
6
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in next
StopIteration
>>> for i in NumberCounter(6):
... print(i)
...
1
2
3
4
5
6
>>>
</code></pre>
<p>A generator is a Python construct that helps you create iterators easily. </p>
<p>From the <a href="https://docs.python.org/2.7/tutorial/classes.html#generator-expressions" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Generators are a simple and powerful tool for creating iterators. They
are written like regular functions but use the yield statement
whenever they want to return data. Each time next() is called on it,
the generator resumes where it left off (it remembers all the data
values and which statement was last executed)... Anything that can be
done with generators can also be done with class-based iterators as
described in the previous section. What makes generators so compact is
that the __iter__() and next() methods are created automatically...In
addition to automatic method creation and saving program state, when
generators terminate, they automatically raise StopIteration. In
combination, these features make it easy to create iterators with no
more effort than writing a regular function.</p>
</blockquote>
<p>Here is a generator:</p>
<pre><code>def number_counter(x):
curr = 1
while curr <= x:
yield curr
curr += 1
</code></pre>
<p>In the interactive interpreter:</p>
<pre><code>>>> for i in number_counter(6):
... print(i)
...
1
2
3
4
5
6
>>>
</code></pre>
<p>Here's another:</p>
<pre><code>def wacky_gen():
yield 88
yield 2
yield 15
</code></pre>
<p>Finally...</p>
<pre><code>>>> for i in wacky_gen():
... print(i)
...
88
2
15
>>>
</code></pre>
| 1 | 2016-08-22T02:46:45Z | [
"python",
"iterator",
"generator"
] |
Forcing response charset in CherryPy | 39,070,269 | <p>I want to specify the HTTP response charset by modifying the <code>Content-Type</code> header. However, it doesn't work.</p>
<p>Here is a short example:</p>
<pre><code>#coding=utf-8
import cherrypy
class Website:
@cherrypy.expose()
def index(self):
cherrypy.response.headers['Content-Type']='text/plain; charset=gbk'
return 'ããã'.encode('gbk')
cherrypy.quickstart(Website(),'/',{
'/': {
'tools.response_headers.on':True,
}
})
</code></pre>
<p>And when I visit that page, the <code>Content-Type</code> is changed mysteriously to <code>text/plain;charset=utf-8</code>, causing mojibake in the browser.</p>
<pre><code>C:\Users\Administrator>ncat 127.0.0.1 8080 -C
GET / HTTP/1.1
Host: 127.0.0.1:8080
HTTP/1.1 200 OK
Server: CherryPy/7.1.0
Content-Length: 6
Content-Type: text/plain;charset=utf-8
Date: Mon, 22 Aug 2016 01:08:13 GMT
ããã^C
</code></pre>
<p>It seems that CherryPy detect content encoding and override the charset automatically. If so, how can I disable this feature?</p>
| 0 | 2016-08-22T01:22:38Z | 39,070,736 | <p>All right. Solved this problem by tampering <code>cherrypy.response.header_list</code> directly.</p>
<pre><code>#coding=utf-8
import cherrypy
def set_content_type():
header=(b'Content-Type',cherrypy.response._content_type.encode())
for ind,(key,_) in enumerate(cherrypy.response.header_list):
if key.lower()==b'content-type':
cherrypy.response.header_list[ind]=header
break
else:
cherrypy.response.header_list.append(header)
cherrypy.tools.set_content_type=cherrypy.Tool('on_end_resource',set_content_type)
class Website:
@cherrypy.expose()
@cherrypy.tools.set_content_type()
def index(self):
cherrypy.response._content_type='text/plain; charset=gbk'
return 'ããã'.encode('gbk')
cherrypy.quickstart(Website(),'/')
</code></pre>
| 0 | 2016-08-22T02:49:31Z | [
"python",
"character-encoding",
"cherrypy"
] |
TypeError: unorderable types: str() <= int() | 39,070,317 | <p>I am trying to take a list, <code>share_list</code>, and then cycle through the list one by one and produce an output tailored to the result. I have two problems: I don't know how to cycle through the list using a <code>for</code> loop, and I am getting this error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "C:\Users\Andrew\Documents\Python Projects\DataAnalytics\algorithm.py", line 9, in <module>
if check_pb_ratio.get_price_book() <= 1:
TypeError: unorderable types: str() <= int()
</code></pre>
<pre><code>from yahoo_finance import Share
share_list = ['AAPL', 'GEVO', 'PTX']
for ticker in share_list:
check_pb_ratio = Share(share_list[0])
if check_pb_ratio.get_price_book() <= 1:
print(str(check_pb_ratio.get_price_book()))
else:
print("P/B Ratio is too high.")
</code></pre>
| 0 | 2016-08-22T01:34:47Z | 39,070,373 | <p>The reason to this is that the function <code>check_pb_ratio.get_price_book()</code> returns a string, not an int. Python doesn't want to know the similarity between '1' and 1.<br> So, the way to fix it is: add <code>int()</code> or <code>float()</code> around <code>check_pb_ratio.get_price_book()</code></p>
| 0 | 2016-08-22T01:45:03Z | [
"python",
"typeerror",
"python-3.5"
] |
TypeError: unorderable types: str() <= int() | 39,070,317 | <p>I am trying to take a list, <code>share_list</code>, and then cycle through the list one by one and produce an output tailored to the result. I have two problems: I don't know how to cycle through the list using a <code>for</code> loop, and I am getting this error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "C:\Users\Andrew\Documents\Python Projects\DataAnalytics\algorithm.py", line 9, in <module>
if check_pb_ratio.get_price_book() <= 1:
TypeError: unorderable types: str() <= int()
</code></pre>
<pre><code>from yahoo_finance import Share
share_list = ['AAPL', 'GEVO', 'PTX']
for ticker in share_list:
check_pb_ratio = Share(share_list[0])
if check_pb_ratio.get_price_book() <= 1:
print(str(check_pb_ratio.get_price_book()))
else:
print("P/B Ratio is too high.")
</code></pre>
| 0 | 2016-08-22T01:34:47Z | 39,070,379 | <p>Thanks to @Rawing</p>
<p>This code now works, I just need to fix a NoneType issue. Thanks!</p>
<pre><code>from yahoo_finance import Share
share_list = ['AAPL', 'GEVO', 'PTX']
for ticker in share_list:
check_pb_ratio = Share(ticker)
if float(check_pb_ratio.get_price_book()) <= 1:
print(str(check_pb_ratio.get_price_book()))
else:
print("P/B Ratio is too high.")
</code></pre>
| 0 | 2016-08-22T01:46:10Z | [
"python",
"typeerror",
"python-3.5"
] |
Pandas - Merge two data frames, create new column, append values to array | 39,070,329 | <p>I am looking to merge two data frames on the same <code>id</code> in each dataframe, but to create a new column and append any values in a specified column to an array in the new dataframe column. I would expect to see multiple matching ids in the second data frame. </p>
<p>Here is an example to clarify what I am looking for:</p>
<pre><code>import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randint(3, size=(5, 4)), columns=('ID', 'X1', 'X2', 'X3')))
ID X1 X2 X3
0 1 1 0 2
1 0 1 0 1
2 0 1 2 2
3 1 2 2 0
4 2 1 0 0
d = {'ID' : pd.Series([1, 2, 1, 4, 5]), 'Tag' : pd.Series(['One', 'Two', 'Two', 'Four', 'Five'])}
df2 = (pd.DataFrame(d))
print(df2)
ID Tag
0 1 One
1 2 Two
2 1 Two
3 4 Four
4 5 Five
</code></pre>
<p>This is what I am expecting to see for the first row:</p>
<pre><code> ID X1 X2 X3 Merged_Tags
0 1 1 0 2 ['One', 'Two']
</code></pre>
<p>I want to join on the <code>id</code> column of df1 by looking through all of df2 for matching <code>ids</code> (<strong>there will be multiple matching ids</strong>). When a matching <code>id</code> is found, the value stored in <code>df2['Tag']</code> should be appended to a column in df1, perhaps an array. </p>
<p>I managed this iteratively but my dataset is relativity large and so have not found it viable. </p>
| 2 | 2016-08-22T01:36:06Z | 39,070,346 | <p>try this:</p>
<pre><code>In [35]: pd.merge(df1, df2.groupby('ID').Tag.apply(list).reset_index(), on='ID', how='left')
Out[35]:
ID X1 X2 X3 Tag
0 2 1 1 2 [Two]
1 1 0 1 1 [One, Two]
2 0 2 1 2 NaN
3 1 0 2 2 [One, Two]
4 0 0 2 2 NaN
</code></pre>
<p>alternatively you can use <code>map()</code> method:</p>
<pre><code>In [38]: df1['Merged_Tags'] = df1.ID.map(df2.groupby('ID').Tag.apply(list))
In [39]: df1
Out[39]:
ID X1 X2 X3 Merged_Tags
0 2 1 1 2 [Two]
1 1 0 1 1 [One, Two]
2 0 2 1 2 NaN
3 1 0 2 2 [One, Two]
4 0 0 2 2 NaN
</code></pre>
| 1 | 2016-08-22T01:39:27Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - Merge two data frames, create new column, append values to array | 39,070,329 | <p>I am looking to merge two data frames on the same <code>id</code> in each dataframe, but to create a new column and append any values in a specified column to an array in the new dataframe column. I would expect to see multiple matching ids in the second data frame. </p>
<p>Here is an example to clarify what I am looking for:</p>
<pre><code>import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randint(3, size=(5, 4)), columns=('ID', 'X1', 'X2', 'X3')))
ID X1 X2 X3
0 1 1 0 2
1 0 1 0 1
2 0 1 2 2
3 1 2 2 0
4 2 1 0 0
d = {'ID' : pd.Series([1, 2, 1, 4, 5]), 'Tag' : pd.Series(['One', 'Two', 'Two', 'Four', 'Five'])}
df2 = (pd.DataFrame(d))
print(df2)
ID Tag
0 1 One
1 2 Two
2 1 Two
3 4 Four
4 5 Five
</code></pre>
<p>This is what I am expecting to see for the first row:</p>
<pre><code> ID X1 X2 X3 Merged_Tags
0 1 1 0 2 ['One', 'Two']
</code></pre>
<p>I want to join on the <code>id</code> column of df1 by looking through all of df2 for matching <code>ids</code> (<strong>there will be multiple matching ids</strong>). When a matching <code>id</code> is found, the value stored in <code>df2['Tag']</code> should be appended to a column in df1, perhaps an array. </p>
<p>I managed this iteratively but my dataset is relativity large and so have not found it viable. </p>
| 2 | 2016-08-22T01:36:06Z | 39,070,466 | <pre><code>>>> df1.join(df2.groupby('ID').Tag.apply(lambda group: list(group)), on='ID')
ID X1 X2 X3 Tag
0 1 1 0 2 [One, Two]
1 0 1 0 1 NaN
2 0 1 2 2 NaN
3 1 2 2 0 [One, Two]
4 2 1 0 0 [Two]
</code></pre>
| 0 | 2016-08-22T02:00:24Z | [
"python",
"pandas",
"dataframe"
] |
How can I move a sprite using the keyboard with Pythons PyGame? | 39,070,388 | <p>I am making a remake of a video game to learn pygame and livewires. I am using livewires because it seems to be a good way to have the background graphics loaded with a sprite. </p>
<p>I am trying to have a pre-loaded sprite move horizontally, while staying mobile on the correct location (in this case it is 50 pixels up). </p>
<p>I can get the sprite move using pygame or I can have the background with the sprite loaded in the right position or I can have the sprite move, but both seems to not occur at the same time. </p>
<p>For added bonus, I am also going to need the screen to scroll right when the character moves a different position. </p>
<p>Here is my code:</p>
<pre><code>import pygame, sys
from livewires import games
from pygame.locals import *
games.init(screen_width = 640, screen_height = 480, fps = 50) #setup up the window siz
class Mario(games.Sprite):
def update(self, pressed_keys):
move = 50 #Setup the origianl position of the character
if pressed_keys[K_RIGHT]: move += 1 #press right key to move forward
if pressed_keys[K_LEFT]: move -= 1 #press left key to move back
def main():
pygame.init()
screen_image = games.load_image("World 1-1.bmp", transparent = False) #setup the background image
games.screen.background = screen_image
mario_image = games.load_image("Mario3.bmp")
mario = games.Sprite(image = mario_image, x = move, y=370) #setup the position of the character
sprites.add(mario)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT: return pygame.quit() #if the player quits
keys_pressed = pygame.key.get_pressed()
games.screen.mainloop()
main()
</code></pre>
| -1 | 2016-08-22T01:47:24Z | 39,071,457 | <p>It seems much simpler to me if you just use Pygame or use Livewires. Dont' try to force two modules to work together if they were not meant to. Besides, the Livewires's intro page says that the module is meant to be an <strong>add-on</strong> to a Python course, not a stand-alone game module. I recommend that you just use Pygame, as it <strong>is</strong> a stand-alone game module.</p>
<p>Also, you code above seems a bit sloppy(please to not take that personally), and I'll show you below how to make a starter Pygame file.</p>
<p>the main part of a Pygame file, is the game loop.
A typical Pygame game loop(or any game loop really), has three basic parts:</p>
<ol>
<li>A event checker, to check for any events</li>
<li>A event executer, to do certain actions when the corresponding events happen.</li>
<li>A place where the graphics are rendered.</li>
</ol>
<p>To give a general idea of a good starting file for Pygame games, here is an example:</p>
<pre><code>import pygame #import the pygame moudle into the namespace <module>
WIDTH = 640 # define a constant width for our window
HEIGHT = 480 # define a constant height for our window
display = pygame.display.set_mode((WIDTH, HEIGHT)) #create a pygame window, and
#initialize it with our WIDTH and HEIGHT constants
running = True # our variable for controlling our game loop
while running:
for e in pygame.event.get(): # iterate ofver all the events pygame is tracking
if e.type == pygame.QUIT: # is the user trying to close the window?
running = False # if so break the loop
pygame.quit() # quit the pygame module
quit() # quit is for IDLE friendliness
display.fill((255, 255, 255)) # fill the pygame screen with white
pygame.display.flip() # update the screen
</code></pre>
<p>The above would be a good starting point for making Pygame games.</p>
<p>But getting back to the problem at hand:</p>
<p>With me assuming that your using Pygame exclusively, there are several ways to make sprites/shapes move in Pygame.</p>
<h2>Method 1: Using a sprite class</h2>
<p>To make a your Mario sprite move, you could use a sprite class like the one below.</p>
<pre><code>class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("path\to\file.png")
self.image.set_colorkey() # make this the color of your outlines around your image(if any exit)
self.rect = self.image.get_rect()
self.rect.x = WIDTH / 2
self.rect.y = HEIGHT / 2
self.vx = 0
self.vy = 0
def update(self):
self.vx = 0
self.vy = 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.vx = -5
elif key[pygame.K_RIGHT]:
self.vx = 5
if key[pygame.K_UP]:
self.vy = -5
elif key[pygame.K_DOWN]:
self.vy = 5
self.rect.x += self.vx
self.rect.y += self.vy
</code></pre>
<p>Since your class is inheriting from Pygame's sprite class, You must name your image self.image and you must name your rectangle for the image self.rect. As you can also see, the class has two main methods. One for creating the sprite(<strong>init</strong>) and one for updating the sprite(update)</p>
<p>To use your class, make a Pygame sprite group to hold all your sprites, and then add your player object to the group:</p>
<pre><code>sprites = pygame.sprite.Group()
player = Player()
sprtites.add(player)
</code></pre>
<p>And to actual render your sprites to the screen call sprites.update() and sprites.draw() in your game loop, where you update the screen:</p>
<pre><code>sprites.update()
window_name.fill((200, 200, 200))
sprites.draw(window_name)
pygame.display.flip()
</code></pre>
<p>The reason i highly recommended using sprite classes, is that it will make your code look much cleaner, and be much easier to maintain. You could even move each sprite class to their own separate file.</p>
<p>Before diving fully into the method above however, you should read up on <a href="http://www.pygame.org/docs/ref/rect.html" rel="nofollow">pygame.Rect</a> objects and <a href="http://www.pygame.org/docs/ref/sprite.html" rel="nofollow">pygame.sprite</a> objects, as you'll be using them. </p>
<h2>Method 2: Using A function</h2>
<p>If you prefer not to get into sprite classes, you can create your game entities using a function similar to the one below.</p>
<pre><code>def create_car(surface, x, y, w, h, color):
rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(surface, color, rect)
return rect
</code></pre>
<p>If you would still like to use a sprites, but don't want to make a class just modify the function above slightly:</p>
<pre><code>def create_car(surface, x, y, color, path_to_img):
img = pygame.image.load(path_to_img)
rect = img.get_rect()
surface.blit(img, (x, y))
</code></pre>
<p>Here is an example of how i would use the functions above to make a movable rectangle/sprite:</p>
<pre><code>import pygame
WIDTH = 640
HEIGHT = 480
display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Player Test")
clock = pygame.time.Clock()
FPS = 60
def create_car(surface, x, y, w, h, color):
rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(surface, color, rect)
return rect
running = True
vx = 0
vy = 0
player_x = WIDTH / 2 # middle of screen width
player_y = HEIGHT / 2 # middle of screen height
player_speed = 5
while running:
clock.tick(FPS)
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
pygame.quit()
quit()
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
vx = -player_speed
elif e.key == pygame.K_RIGHT:
vx = player_speed
if e.key == pygame.K_UP:
vy = -player_speed
elif e.key == pygame.K_DOWN:
vy = player_speed
if e.type == pygame.KEYUP:
if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT or\
e.key == pygame.K_UP or e.key == pygame.K_DOWN:
vx = 0
vy = 0
player_x += vx
player_y += vy
display.fill((200, 200, 200))
####make the player#####
player = create_car(display, player_x, player_y, 10, 10, (255, 0, 0))
pygame.display.flip()
</code></pre>
<p>I should note, I'm assuming a few things with each method outlined above.</p>
<p>That your either using a circle, square, or some type of pygame shape object.
Or that your using a sprite.
If your not currently using any of the methods outlined above, I suggest that you do. Doing so will make your code much easier to maintain once you begin to build larger and more complex games.</p>
| 2 | 2016-08-22T04:31:26Z | [
"python",
"pygame",
"livewires"
] |
How to write python script to read two excel worksheets and delete any repeats in one if both have values? | 39,070,409 | <p>I have 2 worksheets in excel. They both contain 3 columns a,b and c. I need to delete any row in worksheet 1 if the data items for columns a,b,c are the same between the two worksheets. How would I do this using the Pandas python library?</p>
<pre><code>import pandas as pd
ws1 = pd.read_excel(pathname/worksheet1.xlsx)
ws2 = pd.read_excel(pathname/worksheet2.xlsx)
</code></pre>
<p>Basically <code>worksheet1</code> looks something like this (dummy numbers assume they're different in actual data):</p>
<pre><code>a b c d e f
1 2 3 4 4 4
1 2 3 4 4 4
1 2 3 4 4 4
1 2 3 4 4 4
1 2 3 4 4 4
</code></pre>
<p><code>worksheet2</code> looks something like this:</p>
<pre><code>a b f d e c
1 2 4 4 4 3
1 2 4 4 4 3
1 2 4 4 4 3
1 2 4 4 4 3
1 2 4 4 4 3
</code></pre>
<p>I have to check columns a,b and c in <code>worksheet1</code> and if the same data shows up in <code>worksheet2</code>, I would delete that row in <code>worksheet1</code>. </p>
<p>For example, in <code>worksheet1</code> the values 1,2 and 3 are returned for columns a,b and c. I need to check if 1,2 and 3 show up in columns a,b and c in <code>worksheet2</code> (located differently). If they do show up in <code>worksheet2</code>, I need to delete the row in <code>worksheet1</code> with the values 1,2 and 3. </p>
| -2 | 2016-08-22T01:51:01Z | 39,070,443 | <p>Try this (assuming that worksheets list1 and list 2 - two separate excel files):</p>
<pre><code>df1 = pd.read_excel('/path/to/file_name1.xlsx')
df2 = pd.read_excel('/path/to/file_name2.xlsx')
df1 = df1[~df1.email.isin(df2.email)]
</code></pre>
<p>The third line of code removes those rows from <code>df1</code> which are found in the <code>df2</code> (assuming that the column name is <code>email</code> in both DFs)</p>
| 2 | 2016-08-22T01:55:42Z | [
"python",
"excel",
"pandas",
"dataframe"
] |
Get text between two closed tags XML - Python | 39,070,427 | <p>I downloaded my Foursquare data and it comes in KML format. I'm parsing through it as an XML file with Python and cannot figure out how to get the text between the closed a tag and closed description tag. (It's the text that I typed when I checked in, in the example below it's "FINALLY HERE!! With Sonya and co" but there's also a hyphen).</p>
<p>This is an example of what the data looks like. </p>
<pre><code><Placemark>
<name>hummus grill</name>
<description>@<a href="https://foursquare.com/v/hummus-grill/4aab4f71f964a520625920e3">hummus grill</a>- FINALLY HERE!! With Sonya and co</description>
<updated>Tue, 24 Jan 12 17:14:00 +0000</updated>
<published>Tue, 24 Jan 12 17:14:00 +0000</published>
<visibility>1</visibility>
<Point>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates>-75.20104383595685,39.9528387056977</coordinates>
</Point>
</Placemark>
</code></pre>
<p>So far I've been able to get the lat/longs, published dates, name, and link with code something like this for all: </p>
<pre><code>latitudes = []
longitudes = []
for d in dom.getElementsByTagName('coordinates'):
#Break them up into latitude and longitude
coords = d.firstChild.data.split(',')
longitudes.append(float(coords[0]))
latitudes.append(float(coords[1]))
</code></pre>
<p>I tried this (below is the beginning of the data has this header thing, haven't figured out how to handle it yet) </p>
<pre><code>for d in dom.getElementsByTagName('description'):
description.append(d.firstChild.data.encode('utf-8'))
<?xml version="1.0" encoding="UTF-8"?>
<kml><Folder><name>foursquare checkin history </name><description>foursquare checkin history </description>:
</code></pre>
<p>and then accessing it by this d.firstChild.nextSibling.firstChild.data.encode('utf-8'), but it just gives me "hummus grill", what I'm assuming to be the text between the a tags (instead of from the name tag).</p>
| 1 | 2016-08-22T01:52:58Z | 39,070,499 | <p>Have you tried using sub-strings?</p>
<p>Lets say that all of your xml is in the variable "foo" for example.</p>
<pre><code>foo = '<description>@<a href="https://foursquare.com/v/hummus-grill/4aab4f71f964a520625920e3">hummus grill</a>- FINALLY HERE!! With Sonya and co</description>'
</code></pre>
<p>You could extract this data by printing the following.</p>
<pre><code>foo[foo.index('</a>')+4:foo.index('</description>')]
</code></pre>
<p>This should give you what you want.</p>
<pre><code>- FINALLY HERE!! With Sonya and co
</code></pre>
<p>Just read up on substrings and you'll be able to manipulate the text easier.</p>
| 0 | 2016-08-22T02:05:00Z | [
"python",
"xml"
] |
Get text between two closed tags XML - Python | 39,070,427 | <p>I downloaded my Foursquare data and it comes in KML format. I'm parsing through it as an XML file with Python and cannot figure out how to get the text between the closed a tag and closed description tag. (It's the text that I typed when I checked in, in the example below it's "FINALLY HERE!! With Sonya and co" but there's also a hyphen).</p>
<p>This is an example of what the data looks like. </p>
<pre><code><Placemark>
<name>hummus grill</name>
<description>@<a href="https://foursquare.com/v/hummus-grill/4aab4f71f964a520625920e3">hummus grill</a>- FINALLY HERE!! With Sonya and co</description>
<updated>Tue, 24 Jan 12 17:14:00 +0000</updated>
<published>Tue, 24 Jan 12 17:14:00 +0000</published>
<visibility>1</visibility>
<Point>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates>-75.20104383595685,39.9528387056977</coordinates>
</Point>
</Placemark>
</code></pre>
<p>So far I've been able to get the lat/longs, published dates, name, and link with code something like this for all: </p>
<pre><code>latitudes = []
longitudes = []
for d in dom.getElementsByTagName('coordinates'):
#Break them up into latitude and longitude
coords = d.firstChild.data.split(',')
longitudes.append(float(coords[0]))
latitudes.append(float(coords[1]))
</code></pre>
<p>I tried this (below is the beginning of the data has this header thing, haven't figured out how to handle it yet) </p>
<pre><code>for d in dom.getElementsByTagName('description'):
description.append(d.firstChild.data.encode('utf-8'))
<?xml version="1.0" encoding="UTF-8"?>
<kml><Folder><name>foursquare checkin history </name><description>foursquare checkin history </description>:
</code></pre>
<p>and then accessing it by this d.firstChild.nextSibling.firstChild.data.encode('utf-8'), but it just gives me "hummus grill", what I'm assuming to be the text between the a tags (instead of from the name tag).</p>
| 1 | 2016-08-22T01:52:58Z | 39,070,535 | <p>The following works for me:</p>
<pre><code>In [44]: description = []
In [45]: for d in dom.getElementsByTagName('description'):
....: description.append(d.firstChild.nextSibling.nextSibling.data.encode('utf-8'))
....:
In [46]: description
Out[46]: ['- FINALLY HERE!! With Sonya and co']
</code></pre>
<p>Or, if you want the entire text in the description tag:</p>
<pre><code>from xml.dom.minidom import parse, parseString
def getText(node, recursive = False):
"""
Get all the text associated with this node.
With recursive == True, all text from child nodes is retrieved
"""
L = ['']
for n in node.childNodes:
if n.nodeType in (dom.TEXT_NODE, dom.CDATA_SECTION_NODE):
L.append(n.data)
else:
if not recursive:
return None
L.append(getText(n))
return ''.join(L)
dom = parseString("""<Placemark>
<name>hummus grill</name>
<description>@<a href="https://foursquare.com/v/hummus-grill/4aab4f71f964a520625920e3">hummus grill</a>- FINALLY HERE!! With Sonya and co</description>
<updated>Tue, 24 Jan 12 17:14:00 +0000</updated>
<published>Tue, 24 Jan 12 17:14:00 +0000</published>
<visibility>1</visibility>
<Point>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates>-75.20104383595685,39.9528387056977</coordinates>
</Point>
</Placemark>""")
description = []
for d in dom.getElementsByTagName('description'):
description.append(getText(d, recursive = True))
print description
</code></pre>
<p>This will print: <code>[u'@hummus grill- FINALLY HERE!! With Sonya and co']</code></p>
| 0 | 2016-08-22T02:10:59Z | [
"python",
"xml"
] |
Python - Post File to Django With Extra Data | 39,070,568 | <p>I'm trying to have my django rest framework app accept file uploads. The uploads should be accompanied by additional data that is descriptive of the file and is necessary for post-processing. Uploading the file seems to work fine, however, I can't seem to get the django app to access the other data. For example, I have the file <code>more_info.html</code> which I am trying to upload to my app:</p>
<pre><code>import requests
url = "http://www.example.com/fileupload"
files = {'file':open('more_info.html','rb')
data = {'brand':'my brand','type':'html','level':'dev'}
headers = {'Content-type': 'multipart/form-data', 'Content-Disposition': 'attachment; filename="more_info.html"'}
r = requests.post(url,files=files,data=,headers=headers)
</code></pre>
<p>In my Django view I am trying to view my POST data with the following:</p>
<pre><code>def post(self, request):
print(request.POST)
print(request.FILEs)
</code></pre>
<p>Both print statements are returning:</p>
<pre><code>{u'file': <InMemoryUploadedFile: more_info.html (multipart/form-data)>}
</code></pre>
<p>How can I access the rest of the data in the request POST?</p>
| 0 | 2016-08-22T02:17:08Z | 39,071,806 | <p>This line </p>
<pre><code>r = requests.post(url,files=files,data=,headers=headers)
</code></pre>
<p>You seem to be missing assigning data to data=.</p>
| 0 | 2016-08-22T05:16:11Z | [
"python",
"django"
] |
python input EOFError after set io encoding as utf8 | 39,070,621 | <p>Python Version :3.5<br>
OS Version: Windows7</p>
<p>After I set environment variable <code>PYTHONIOENCODING=utf-8</code>, I can print some utf8 string (like love symbol \u2665, Korea words and Japanese words) as I expect.<br>
(Before that i can only input Chinese word with gbk encoding but its totally worked fine.)<br>
But now I can't use <code>input()</code> to get any non-alphanumeric character, it would raise a EOFError.</p>
<pre><code>ä½ å¥½:â¥ã»
Traceback (most recent call last):
File "codeTest2.py", line 9, in <module>
key = input('ä½ å¥½:')
')
EOFError
</code></pre>
<p><br><br><br><hr>BTW:
when I use <code>print()</code> to print some utf8 string, (here are Chinese words, alphabet, Korea words, emoji characters and special character)</p>
<pre><code>s2 = 'ì¡íëãâ¥ãâ¥ã»'
print('ä½è
id'+s2+'\n')
</code></pre>
<p>Terminal print:(a weird "inverted taper tower")</p>
<pre><code>ä½è
idì¡íëãâ¥ãâ¥ã»
ëãâ¥ãâ¥ã»
�ãâ¥ã»
�ã»
</code></pre>
| 1 | 2016-08-22T02:28:16Z | 39,071,930 | <p>What kind of compiler and terminal are you using?</p>
<p>In Python 3.5 IDLE, this works fine:</p>
<pre><code>key=input('è¾å
¥:')
</code></pre>
<p>And in Python 2.7 IDLE, this works fine:</p>
<pre><code>key=raw_input('è¾å
¥:')
</code></pre>
<p>But in sublime Text 3, i should use this to declare using utf-8:</p>
<pre><code># coding=u8
</code></pre>
<p>So please give out your situation and code :)</p>
| 0 | 2016-08-22T05:30:12Z | [
"python",
"encoding",
"utf-8",
"eof"
] |
Python How to run two loops at the same time? | 39,070,641 | <p>So simpley put I want different objects to have there own tick loop code running independintley of eatchother. (As in one tickloop does not stop all other tick loops in my app) </p>
<p>Ive created a basic module that has a class for shapes and a main body for spawning them however the tickloop of the class holds up the main parts loop.</p>
<p>I have even tryed splitting the code in to two modules to see if that would work.
but that did nothing</p>
<p>here is my code:</p>
<p>(main code)</p>
<pre><code>from random import *
from tkinter import *
from time import *
import RdmCirClass
size = 500
window = Tk()
count = 0
d = 0
shapes = []
canv = Canvas(window, width=size, height=size)
canv.pack()
window.update()
while True:
col = choice(['#EAEA00'])
x0 = randint(0, size)
y0 = randint(0, size)
#d = randint(0, size/5)
d = (d + 0.01)
outline = 'white'
shapes.append(1)
shapes[count] = RdmCirClass.Shape("shape" + str(count), canv, col, x0, y0, d, outline)
shapes[count].spawn()
count = count+1
print("Circle Count: ",count)
window.update()
</code></pre>
<p>(Shape Class)</p>
<pre><code>from random import *
from tkinter import *
from time import *
class Shape(object):
def __init__(self,name, canv, col, x, y,d,outline):
self.name = name
self.canv = canv
self.col = col
self.x = x
self.y = y
self.d = d
self.outline = outline
self.age=0
self.born = time()
def death(self):
pass
def tick(self):
self.age = time() - self.born
def spawn(self):
self.canv.create_oval(self.x, self.y, self.x + self.d, self.y + self.d, outline=self.outline, fill = self.col)
while True:
self.tick()
</code></pre>
| 0 | 2016-08-22T02:31:54Z | 39,070,826 | <p>I don't understand what your code is doing, but my suggestion is to use threading: <a href="https://pymotw.com/2/threading/" rel="nofollow">https://pymotw.com/2/threading/</a></p>
| 0 | 2016-08-22T03:01:21Z | [
"python",
"loops"
] |
Python How to run two loops at the same time? | 39,070,641 | <p>So simpley put I want different objects to have there own tick loop code running independintley of eatchother. (As in one tickloop does not stop all other tick loops in my app) </p>
<p>Ive created a basic module that has a class for shapes and a main body for spawning them however the tickloop of the class holds up the main parts loop.</p>
<p>I have even tryed splitting the code in to two modules to see if that would work.
but that did nothing</p>
<p>here is my code:</p>
<p>(main code)</p>
<pre><code>from random import *
from tkinter import *
from time import *
import RdmCirClass
size = 500
window = Tk()
count = 0
d = 0
shapes = []
canv = Canvas(window, width=size, height=size)
canv.pack()
window.update()
while True:
col = choice(['#EAEA00'])
x0 = randint(0, size)
y0 = randint(0, size)
#d = randint(0, size/5)
d = (d + 0.01)
outline = 'white'
shapes.append(1)
shapes[count] = RdmCirClass.Shape("shape" + str(count), canv, col, x0, y0, d, outline)
shapes[count].spawn()
count = count+1
print("Circle Count: ",count)
window.update()
</code></pre>
<p>(Shape Class)</p>
<pre><code>from random import *
from tkinter import *
from time import *
class Shape(object):
def __init__(self,name, canv, col, x, y,d,outline):
self.name = name
self.canv = canv
self.col = col
self.x = x
self.y = y
self.d = d
self.outline = outline
self.age=0
self.born = time()
def death(self):
pass
def tick(self):
self.age = time() - self.born
def spawn(self):
self.canv.create_oval(self.x, self.y, self.x + self.d, self.y + self.d, outline=self.outline, fill = self.col)
while True:
self.tick()
</code></pre>
| 0 | 2016-08-22T02:31:54Z | 39,070,933 | <p>Roughly speaking, there are three ways to accomplish what you want. Which is best depends greatly on what exactly you're trying to do with each independent unit, and what performance constraints and requirements you have.</p>
<p>The first solution is to have an independent loop that simply calls the <code>tick()</code> method of each object on each iteration. Conceptually this is perhaps the simplest to implement.</p>
<p>The other two solutions involve multiple threads, or multiple processes. These solutions come with sometimes considerably complexity, but the benefit is that you get the OS to schedule the running of the <code>tick()</code> method for each object.</p>
| 1 | 2016-08-22T03:18:29Z | [
"python",
"loops"
] |
Variable error in Python | 39,070,643 | <p>I'm in a Python course and can't figure out why my code won't work: </p>
<pre class="lang-py prettyprint-override"><code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
<p>The code above returns:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Kyle/Desktop/renamepy.py", line 5, in <module>
for file_name in file_list:
NameError: name 'file_list' is not defined
>>>
</code></pre>
<p>Why <code>file_name</code> is not defined?</p>
| 0 | 2016-08-22T02:32:40Z | 39,070,656 | <p>This is an indentation error. Your <code>for</code> loop is outside of the scope of <code>rename_files()</code> since it was not indented. It should be:</p>
<pre><code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
| 2 | 2016-08-22T02:35:04Z | [
"python",
"variables"
] |
Variable error in Python | 39,070,643 | <p>I'm in a Python course and can't figure out why my code won't work: </p>
<pre class="lang-py prettyprint-override"><code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
<p>The code above returns:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Kyle/Desktop/renamepy.py", line 5, in <module>
for file_name in file_list:
NameError: name 'file_list' is not defined
>>>
</code></pre>
<p>Why <code>file_name</code> is not defined?</p>
| 0 | 2016-08-22T02:32:40Z | 39,070,657 | <p>Let's walk-through your code:</p>
<pre><code>def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
</code></pre>
<p>In you <code>rename_files()</code> function, you have defined a function that returns nothing. You have set a local scoped <code>file_list</code> that will be released and cannot be accessed once you're outside the function.</p>
<pre><code>for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
<p>Then when you're outside of the <code>rename_files()</code> function, you try to access a <code>file_list</code> that has not previously been initialized in the for-loop, so it throws the <code>NameError</code></p>
<pre><code>NameError: name 'file_list' is not defined
</code></pre>
<p>And then you called the <code>rename_files()</code> function but still <code>file_list</code> will not exist outside of the function.</p>
<p>There's several ways to ensure that <code>file_list</code> is materialized before you go through the for-loop.</p>
<p><strong>Solution 1</strong>: Use the global variable.</p>
<pre><code>file_list = []
def rename_files():
global file_list
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
rename_files()
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
</code></pre>
<p><strong>Solution 2</strong>: take the <code>file_list</code> initialization outside of the function.</p>
<pre><code>file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
</code></pre>
<p><strong>Solution 3</strong> (as suggested by Karin): Put the for-loop into the function:</p>
<pre><code>def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
</code></pre>
<p>Note: this is similar to Solution 2 since they are trying to put both the <code>file_list</code> initialization and the for-loop under the same scope.</p>
| 0 | 2016-08-22T02:35:19Z | [
"python",
"variables"
] |
Variable error in Python | 39,070,643 | <p>I'm in a Python course and can't figure out why my code won't work: </p>
<pre class="lang-py prettyprint-override"><code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
<p>The code above returns:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Kyle/Desktop/renamepy.py", line 5, in <module>
for file_name in file_list:
NameError: name 'file_list' is not defined
>>>
</code></pre>
<p>Why <code>file_name</code> is not defined?</p>
| 0 | 2016-08-22T02:32:40Z | 39,070,658 | <p>You need to indent your for loop so its within the body of your <code>rename_file</code> function:</p>
<pre><code>import os
def rename_files():
file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
</code></pre>
<p>As <code>file_list</code> is only in scope within the method.</p>
| 0 | 2016-08-22T02:35:21Z | [
"python",
"variables"
] |
Odd behavior in Fibonacci series in python 3? | 39,070,729 | <p>This does not print the correct Fibonacci series i.e. 1 1 2 3 5 8... </p>
<pre><code>print ('Fibonacci series...')
a,b = 0,1
while b<50:
print(b)
a=b
b = a+b
</code></pre>
<p>This does print the correct Fibonacci series. Aren't these two code snippets the same logically ? Please help, I am really confused. </p>
<pre><code>print ('Fibonacci series...')
a,b = 0,1
while b<50:
print(b)
a,b = b, a+b
</code></pre>
| -2 | 2016-08-22T02:48:13Z | 39,070,757 | <pre><code>a=b
b = a+b
</code></pre>
<p>in the first code sample is equivalent to <code>b = b * 2</code>. Instead you want <code>b += original_value(a)</code>. So you either need to do tuple assignment, as in the second code sample (<code>a,b = b, a+b</code>), or use a temp variable:</p>
<pre><code>temp = a
a = b
b += temp
</code></pre>
<p>to get the desired value changes.</p>
| 2 | 2016-08-22T02:51:54Z | [
"python",
"python-2.7",
"python-3.x"
] |
Odd behavior in Fibonacci series in python 3? | 39,070,729 | <p>This does not print the correct Fibonacci series i.e. 1 1 2 3 5 8... </p>
<pre><code>print ('Fibonacci series...')
a,b = 0,1
while b<50:
print(b)
a=b
b = a+b
</code></pre>
<p>This does print the correct Fibonacci series. Aren't these two code snippets the same logically ? Please help, I am really confused. </p>
<pre><code>print ('Fibonacci series...')
a,b = 0,1
while b<50:
print(b)
a,b = b, a+b
</code></pre>
| -2 | 2016-08-22T02:48:13Z | 39,070,801 | <p>Firstly, there is an indentation error in the first code snippet. The last two lines should be indented so they are executed within the <code>while</code> loop.</p>
<pre><code>print ('Fibonacci series...')
a,b = 0,1
while b<50:
print(b)
a = b
b = a+b
</code></pre>
<p>However, this still won't produce the correct result. Let's look at why these two code snippets are different.</p>
<ol>
<li><p><code>a, b = b, a + b</code>: This will assign <code>a</code> to <code>b</code> and <code>b</code> to <code>a + b</code>, with the evaluation of the right-hand side before the left-hand side. This means before looking at what variables to assign new values to, Python will first see what <code>b</code> and <code>a + b</code> are. This means the old value of <code>a</code> will be used for setting <code>b = a + b</code>. You can read more about this <a href="http://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python/14836456#14836456">here</a>.</p>
<pre><code>a = 1
b = 2
a, b = b, a + b # set a to 2, set b to 1 + 2
print(a) # 2
print(b) # 3
</code></pre></li>
<li><p><code>a = b; b = a + b</code>: This does assignment sequentially, such that <code>a</code> is first set to <code>b</code>, then used in the assignment calculation.</p>
<pre><code>a = 1
b = 2
a = b # set a to 2
b = a + b # set b to 2 + 2
print(a) # 2
print(b) # 4
</code></pre></li>
</ol>
| 4 | 2016-08-22T02:57:44Z | [
"python",
"python-2.7",
"python-3.x"
] |
Tracking an object via OpenCV | 39,070,794 | <p>I am trying to track an object and mask or Hide it (a CODE in this case) using OpenCV and Python. As example I am using this video , the code will showing on 1min19s :
<a href="https://www.dropbox.com/s/eu01hxoxmd3ns5f/capture-3.mp4?dl=0" rel="nofollow">https://www.dropbox.com/s/eu01hxoxmd3ns5f/capture-3.mp4?dl=0</a></p>
<p>What I need is to keep track on the CODE and mask or Hide it as the video without detecting other parts of the video as the code. Tracking by colour doesn't work here. </p>
<p>Any idea for a good approach on this problem?</p>
| 0 | 2016-08-22T02:56:48Z | 39,070,948 | <p>Tracking is much more complex than searching the similar colour. OpenCV has implemented some tracking algorithms, what you need to do is to use the existing apis to solve the problem. <a href="http://docs.opencv.org/3.1.0/d2/d0a/tutorial_introduction_to_tracker.html" rel="nofollow" title="Here">Here</a> is an introduction to OpenCV tracker.</p>
<p>If you do not stick to OpenCV, <a href="http://dlib.net/" rel="nofollow">dlib</a> is also a c++ library with python interface which also implements object tracking algorithms.</p>
| 0 | 2016-08-22T03:20:43Z | [
"python",
"opencv"
] |
License plate Detection from car camera | 39,070,837 | <p>I am using Python and Opencv. I am doing a project to recognize the license plate from a car camera.</p>
<p>I have tried to use <code>Canny()</code>, but I still cant recognize the plate.</p>
<p>Here is the frame I captured.
<a href="http://i.stack.imgur.com/rSu3d.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/rSu3d.jpg" alt="enter image description here"></a></p>
<p>1)</p>
<p>First, I convert the image into <strong>gray-scale</strong>, increase the <strong>contract of color</strong> and finally convert it into "<strong>edged image</strong>"</p>
<pre><code>img = cv2.imread("plate.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
edged = cv2.Canny(gray, 200, 255)
</code></pre>
<p>Here is the result that what I get:
<a href="http://i.stack.imgur.com/52Wwe.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/52Wwe.jpg" alt="enter image description here"></a></p>
<p>2)</p>
<p>Afterwards, I try to find a <strong>rectangle contour</strong> as following, I tried to filter out the <strong>irrelevant rectangle</strong> by area and length and <strong>irregular polygon</strong> by <code>convexHull()</code>:</p>
<pre><code>(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:10]
# loop over our contours
plate_candidates = []
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
area = cv2.contourArea(approx)
if len(approx) == 4 and area <=1000 and area >=500 and self._length_checking(approx):
hull = cv2.convexHull(approx,returnPoints = True)
if len(hull) ==4:
plate_candidates.append(approx)
cv2.drawContours(show, [approx], -1, (0,255,0), 3)
</code></pre>
<p>But still, I cannot recognize the plate. I am looking for help how can I detect the license plate. Thank you.</p>
| 2 | 2016-08-22T03:02:56Z | 39,071,471 | <p>You could use minimal bounding rectangle of the convex hull to calculate the "rectangleness" of your candidate contours (in the latest version of openCV you can use <code>cv2.boxPoints</code> to calculate <code>rectPoints</code>):</p>
<pre><code>def rectangleness(hull):
rect = cv2.boundingRect(hull)
rectPoints = np.array([[rect[0], rect[1]],
[rect[0] + rect[2], rect[1]],
[rect[0] + rect[2], rect[1] + rect[3]],
[rect[0], rect[1] + rect[3]]])
intersection_area = cv2.intersectConvexConvex(np.array(rectPoints), hull)[0]
rect_area = cv2.contourArea(rectPoints)
rectangleness = intersection_area/rect_area
return rectangleness
</code></pre>
<p>However in your case this is actually overkill, it's enough to use the area of the polygon â either of the polygons within your area cutoff (the first two contours in <code>cnts</code>) could be used to obtain the bounding rectangle surrounding the licence plate.</p>
| 1 | 2016-08-22T04:33:13Z | [
"python",
"image",
"opencv",
"image-processing"
] |
How can I use get_next_by_FOO() in django? | 39,070,840 | <p>I am building blog website and trying to put <code>next</code> and <code>prev</code> buttons for next post and previous post respectively.</p>
<p>In the official document, it explains <code>get_next_by_FOO(**kwargs)</code> and <code>where FOO is the name of the field. This returns the next and previous object with respect to the date field</code>.</p>
<p>So my models.py and views.py are following.</p>
<p>models.py</p>
<pre><code>class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
ordering = ["-timestamp", "-updated"]
</code></pre>
<p>views.py</p>
<pre><code>def post_detail(request, id=None):
instance = get_object_or_404(Post, id=id)
the_next = instance.get_next_by_title()
context ={
"title": instance.title,
"instance": instance,
"the_next" : the_next,
}
return render(request, "post_detail.html", context)
</code></pre>
<p>Do I misunderstand its concept?? If I do, how can I deal with it?
Thanks in advance! </p>
| 0 | 2016-08-22T03:03:20Z | 39,071,005 | <p><code>get_next_by_FOO</code> works on the date field, think of it like "get me the next record ordered by the date (or datetime) field <em>FOO</em>".</p>
<p>So <em>FOO</em> is the name of a date or datetime field.</p>
<p>In your model, you can say "get me the next record based on timestamp", and this would be <code>get_next_by_timestamp()</code> or "get me the next record based on the updated date", and this would be <code>get_next_by_updated()</code>.</p>
| 1 | 2016-08-22T03:29:40Z | [
"python",
"django",
"blogs"
] |
Python: Killing children's children process | 39,070,857 | <p>I have a process that calls:</p>
<pre><code>p=multiprocessing.Process(target=func_a)
</code></pre>
<p>Then <code>func_a</code> starts a subprocess:</p>
<pre><code>subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w"))
</code></pre>
<p>My problem is that when I call p.terminate(), it only kills the first child. p.terminate() is a <code>SIGKILL</code> so how could I make the subprocess die when I call p.terminte() into the <code>multiprocessing.Process</code>.</p>
| 1 | 2016-08-22T03:06:19Z | 39,073,176 | <p>Register a handler with signal.signal like this:</p>
<pre><code>#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
#iterate over your subprocess and kill them
sys.exit(0)
signal.signal(signal."the signal", signal_handler)
print('Press Ctrl+C')
signal.pause()
</code></pre>
<p>More documentation on signal can be found <a href="http://docs.python.org/library/signal.html" rel="nofollow">here</a>.</p>
| 1 | 2016-08-22T07:05:16Z | [
"python",
"subprocess",
"multiprocessing",
"signals",
"kill"
] |
Python: Killing children's children process | 39,070,857 | <p>I have a process that calls:</p>
<pre><code>p=multiprocessing.Process(target=func_a)
</code></pre>
<p>Then <code>func_a</code> starts a subprocess:</p>
<pre><code>subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w"))
</code></pre>
<p>My problem is that when I call p.terminate(), it only kills the first child. p.terminate() is a <code>SIGKILL</code> so how could I make the subprocess die when I call p.terminte() into the <code>multiprocessing.Process</code>.</p>
| 1 | 2016-08-22T03:06:19Z | 39,074,190 | <p>I found a way to <strong>make sure the sub-process is killed before the multiprocessing process is killed</strong>:</p>
<p>Create a class like this:</p>
<pre><code>import subprocess
import multiprocessing
import time
import os
class MyProcess(multiprocessing.Process):
def __init__(self):
super(MyProcess,self).__init__()
self.q = multiprocessing.Queue()
def run(self):
# do something else
child = subprocess.Popen(['Your CMD'])
self.q.put(child.pid)
def MyTerminate(self):
pid = self.q.get()
os.kill(pid, 9) # works in windows and linux
# os.popen('taskkill.exe /pid '+str(pid)+' /F') # works only in windows
self.terminate()
</code></pre>
<p>Then you can use the function <code>MyTerminate()</code> to kill the process safely.</p>
<p>For example:</p>
<pre><code>def main():
mp = MyProcess()
mp.start()
time.sleep(1)
mp.MyTerminate()
</code></pre>
<p>The sub-process "child" will be killed after 1 second.</p>
| 1 | 2016-08-22T08:03:55Z | [
"python",
"subprocess",
"multiprocessing",
"signals",
"kill"
] |
read line from match string in file .. python | 39,070,861 | <p>I have this script that prints pool names from a F5 config file.. I want to run this on multiple F5 config files.. I want to be able to read from ^pool|^} (pool OR } bring start of line)... At the moment i am getting my desired output as i am telling the script to read from line 2348.. </p>
<p>I want to eliminate the use of i in xrange(2348) as other files F5 config files are smaller.. </p>
<p>The way it will work is if i get the script to start reading line by line of the file from ^pool OR ^}<br>
Current script:</p>
<pre><code>import re
seenrule = 'false'
File = open("/home/t816874/F5conf/unzip/config/bigip.conf", "r")
for i in xrange(2348):
File.next()
for line in File:
if re.match("(^pool p)", line, re.IGNORECASE):
a = line.lstrip("pool p")
ONE = a[:-2]
print "Pool Name:", ONE
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d] {1,3})', line):
if seenrule == 'false':
x = line.lstrip("members ")
print x
if re.match("(^rule )", line):
seenrule = 'true'
</code></pre>
<h1>---------------------------------------------------------------</h1>
<p>My Attempt:</p>
<pre><code>import re
seenrule = 'false'
startline = 'false'
File = open("/home/t816874/F5conf/unzip/config/bigip.conf", "r")
if re.match("(^pool|^})", line):
startline = 'true'
for line in File:
if re.match("(^pool p)", line, re.IGNORECASE):
a = line.lstrip("pool p")
ONE = a[:-2]
print "Pool Name:", ONE
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d] {1,3})', line):
if seenrule == 'false':
x = line.lstrip("members ")
print x
if re.match("(^rule )", line):
seenrule = 'true'
</code></pre>
<p>Thanks for your help guys !</p>
<h1>-----------</h1>
<p>conf file is similar to:</p>
<pre><code>node 172.0.0.0 {
screen ab2583-1.2
}
node 172.0.0.1 {
screen ab2583-1.3
}
node 172.0.0.3 {
screen ab2584-1.2
}
pool pWWW_abcd_HTTPS {
lb method member predictive
monitor all mWWW_staging.telecom_TCP
members {
0.0.0.0:8421 {}
0.0.0.1:18431 {
session user disabled
}
0.0.0.2:8421 {}
0.0.0.3:18431 {
session user disabled
}
}
}
pool pWWW_vcm2APP.defg_HTTP {
lb method member predictive
monitor all mWWW_vcm2APP.defg_TCP
members 0.0.0.5:27110 {}
}
node..
....
.
</code></pre>
| 0 | 2016-08-22T03:06:48Z | 39,072,419 | <p>It is not completely clear what you want, but I'll try to guess. You are trying to get members for each pool. You didn't mention anything about <code>seenrule</code> - so I dropped it.</p>
<p>If you don't want to parse this data structure, and if top-level block always and exlusively ends with line <code>'}\n'</code>, you can do something like this:</p>
<pre><code>import re
f = open('/home/t816874/F5conf/unzip/config/bigip.conf', 'r')
# Iterate over lines.
for line in f:
# If pool block is met.
if line.startswith('pool p'):
pname = line.split()[1]
pmembers = []
# Iterate over block.
# Block is expected to be terminated by line '}\n'.
for pline in iter(lambda: next(f), '}\n'):
members = re.findall(r'\d{1,3}(?:\.\d{1,3}){3}:\d{1,5}', pline)
pmembers.extend(members)
print(pname, pmembers)
f.close()
</code></pre>
<p>output:</p>
<pre><code>pWWW_abcd_HTTPS ['0.0.0.0:8421', '0.0.0.1:18431', '0.0.0.2:8421', '0.0.0.3:18431']
pWWW_vcm2APP.defg_HTTP ['0.0.0.5:27110']
</code></pre>
| 0 | 2016-08-22T06:14:04Z | [
"python",
"regex"
] |
4 spaces for Indentation - Syntax error | 39,070,917 | <p>I'm using 4 spaces for indentation, but get a Syntax error. When I use the indentation in the Text editor, works fine. The text editor creates just 1 block, that I'm unable to edit it. Are spaces not able to be used as indentation?</p>
<pre><code>def replace_line(file_name, line_num, text):
try:
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()
if not var and not var2:
return
</code></pre>
<p>I get the syntax error on the if not var line.</p>
| 1 | 2016-08-22T03:16:10Z | 39,071,022 | <p>If you're getting Syntax Error because of indentations it is most probably related to the fact that your code includes both <em>TABS</em> and <em>SPACES</em> as methods of indentation. Even though the code might appear to be be indented the same amount from the left, a <em>TAB</em> is a single symbol, whereas the same indentation using <em>SPACE</em>s takes 4 (in your case) symbols. Python freaks out and throws an error, because it doesn't see the rendering of code you see, it sees an inconsistent number of symbols used before the line. </p>
<p>To fix this, firstly substitute <strong>all</strong> tabs with the appropriate equivalent of spaces, and then go through your code and make sure that all the indentation in your code is valid and correct. If you're using an editor like Sublime Text then you can do this with one or two clicks, with a more primitive editor finding the <em>TAB</em>/<em>SPACE</em> difference might be much more tedious.</p>
<p>Hope this helps</p>
| 6 | 2016-08-22T03:32:13Z | [
"python",
"indentation"
] |
4 spaces for Indentation - Syntax error | 39,070,917 | <p>I'm using 4 spaces for indentation, but get a Syntax error. When I use the indentation in the Text editor, works fine. The text editor creates just 1 block, that I'm unable to edit it. Are spaces not able to be used as indentation?</p>
<pre><code>def replace_line(file_name, line_num, text):
try:
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()
if not var and not var2:
return
</code></pre>
<p>I get the syntax error on the if not var line.</p>
| 1 | 2016-08-22T03:16:10Z | 39,085,312 | <p>Throwing an exception: pass solves it. It is not needed when using indentation from a Text editor. That's weird.</p>
| 0 | 2016-08-22T17:21:50Z | [
"python",
"indentation"
] |
updating a deep key in a Nested JSON file | 39,070,919 | <p>I have a json file which looks like this:</p>
<pre><code>{
"email": "abctest@xxx.com",
"firstName": "name01",
"surname": "Optional"
"layer01": {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"layer02": {
"key1": "value1",
"key2": "value2"
},
"layer03": [
{
"inner_key01": "inner value01"
},
{
"inner_key02": "inner_value02"
}
]
},
"surname": "Required only$uid"
}
</code></pre>
<p>am expecting a update request as:</p>
<pre><code>{
"email": "XYZTEST@gmail.com",
"firstName": "firstName",
"layer01.key3": "newvalue03",
"layer01.layer02.key1": "newvalue01"
},
</code></pre>
<p>the deeper keys are separated using <code>"."</code></p>
<p>am using python2.7. Can anyone advice me on this.. am really stuck at this!!</p>
<p>this is what i was working with:</p>
<pre><code>def updateTemplate(self,templatename, data):
template= self.getTemplatedata(templatename) # gets the python object with the data from original file
for ref in data:
k= ref
keys= ref.split(".")
temp= template
if len(keys)>1:
temp= template[keys[0]]
for i in range(1,lens(keys)-1):
print keys[i]
if type(temp) is dict:
temp =temp[keys[i]]
temp[keys[len(keys)-1]]= data[k]
print temp
template.update(temp)
else:
template[k]= data[k]
print template
</code></pre>
<p>update added a whole new key in the template object. I need to update the key in last temp to template object </p>
<p>the template object displayed this:</p>
<pre><code>{ u'email': u'abctest@xxx.com',
u'firstName': u'Valid AU$uid',
u'key1': u'value1',
u'key2': u'value2',
u'key3': u'value03',
u'key4': u'value4',
u'layer01': { u'key1': u'value1',
u'key2': u'value2',
u'key3': u'value03',
u'key4': u'value4',
u'layer02': { u'key1': u'value01', u'key2': u'value2'},
u'layer03': [ { u'inner_key01': u'inner value01'},
{ u'inner_key02': u'inner_value02'}]},
u'layer02': { u'key1': u'value01', u'key2': u'value2'},
u'layer03': [ { u'inner_key01': u'inner value01'},
{ u'inner_key02': u'inner_value02'}],
u'surname': u'Required only$uid'}
</code></pre>
| 0 | 2016-08-22T03:16:14Z | 39,095,509 | <p>As much as I'd like to help you out, I find your code confusing, but I'll do my best. Here it goes</p>
<p>For starters, by <code>temp= template</code> do you mean to do <code>temp= copy.deepcopy(template)</code>? Remember to <code>import copy</code> <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">Reference</a> </p>
<p>I get that template is a dictionary, but what do you want to achieve by referencing <code>template</code> to <code>temp</code>, tweaking <code>temp</code> then <strong>adding</strong> </p>
<blockquote>
<p><code>template.update(temp)</code></p>
</blockquote>
<p><code>temp</code> to <code>template</code> which in fact <code>temp</code> is a reference to <code>template</code>?</p>
<p>How about we scrap the code and start off fresh. </p>
<p>i.e. Input is</p>
<pre><code>{
"email": "XYZTEST@gmail.com",
"firstName": "firstName",
"layer01.key3": "newvalue03",
"layer01.layer02.key1": "newvalue01"
}
</code></pre>
<p>Existing data is:</p>
<pre><code>{
"email": "abctest@xxx.com",
"firstName": "name01",
"surname": "Optional"
"layer01": {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"layer02": {
"key1": "value1",
"key2": "value2"
},
"layer03": [
{
"inner_key01": "inner value01"
},
{
"inner_key02": "inner_value02"
}
]
},
"surname": "Required only$uid"
}
</code></pre>
<p>Expected Output:</p>
<pre><code>{
"email": "XYZTEST@gmail.com",
"firstName": "firstName",
"surname": "Optional"
"layer01": {
"key1": "value1",
"key2": "value2",
"key3": "newvalue03",
"key4": "value4",
"layer02": {
"key1": "newvalue01",
"key2": "value2"
},
"layer03": [
{
"inner_key01": "inner value01"
},
{
"inner_key02": "inner_value02"
}
]
},
"surname": "Required only$uid"
}
</code></pre>
<p>Kindly confirm if this is the result your expecting, so I can help you with your brainstorming.</p>
| 0 | 2016-08-23T07:59:52Z | [
"python",
"json"
] |
updating a deep key in a Nested JSON file | 39,070,919 | <p>I have a json file which looks like this:</p>
<pre><code>{
"email": "abctest@xxx.com",
"firstName": "name01",
"surname": "Optional"
"layer01": {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"layer02": {
"key1": "value1",
"key2": "value2"
},
"layer03": [
{
"inner_key01": "inner value01"
},
{
"inner_key02": "inner_value02"
}
]
},
"surname": "Required only$uid"
}
</code></pre>
<p>am expecting a update request as:</p>
<pre><code>{
"email": "XYZTEST@gmail.com",
"firstName": "firstName",
"layer01.key3": "newvalue03",
"layer01.layer02.key1": "newvalue01"
},
</code></pre>
<p>the deeper keys are separated using <code>"."</code></p>
<p>am using python2.7. Can anyone advice me on this.. am really stuck at this!!</p>
<p>this is what i was working with:</p>
<pre><code>def updateTemplate(self,templatename, data):
template= self.getTemplatedata(templatename) # gets the python object with the data from original file
for ref in data:
k= ref
keys= ref.split(".")
temp= template
if len(keys)>1:
temp= template[keys[0]]
for i in range(1,lens(keys)-1):
print keys[i]
if type(temp) is dict:
temp =temp[keys[i]]
temp[keys[len(keys)-1]]= data[k]
print temp
template.update(temp)
else:
template[k]= data[k]
print template
</code></pre>
<p>update added a whole new key in the template object. I need to update the key in last temp to template object </p>
<p>the template object displayed this:</p>
<pre><code>{ u'email': u'abctest@xxx.com',
u'firstName': u'Valid AU$uid',
u'key1': u'value1',
u'key2': u'value2',
u'key3': u'value03',
u'key4': u'value4',
u'layer01': { u'key1': u'value1',
u'key2': u'value2',
u'key3': u'value03',
u'key4': u'value4',
u'layer02': { u'key1': u'value01', u'key2': u'value2'},
u'layer03': [ { u'inner_key01': u'inner value01'},
{ u'inner_key02': u'inner_value02'}]},
u'layer02': { u'key1': u'value01', u'key2': u'value2'},
u'layer03': [ { u'inner_key01': u'inner value01'},
{ u'inner_key02': u'inner_value02'}],
u'surname': u'Required only$uid'}
</code></pre>
| 0 | 2016-08-22T03:16:14Z | 39,136,967 | <p>Your algorithm is really close but there's a few things in it that complicate things unnecessarily. This makes it easy to miss the key line that's causing the problem:</p>
<pre><code>template.update(temp)
</code></pre>
<p>temp is the child-most dictionary of the template but here you set the original template to have all it's children too. Comment this line out and it should work.</p>
<p>Some of the things that I cleaned up to make this line easier to find:</p>
<ul>
<li>Don't hardcode the case where there's only one element in the <code>keys</code> list. The loop can handle it.</li>
<li>In Python, there's a nice shorthand for <code>keys[len(keys)-1]</code>: <code>keys[-1]</code>. See <a href="http://stackoverflow.com/questions/11367902/negative-index-to-python-list">Negative index to Python list</a></li>
<li>Instead of using enumerate and checking if the type of temp is a dict, simply don't loop over the last key (this could change the behaviour a bit for other input)</li>
<li>Using pprint. It pretty prints things like lists and dictionaries.</li>
</ul>
<p>Put together, a simplified version looks like this:</p>
<pre><code>import pprint
def updateTemplate(self, templatename, data):
template = self.getTemplatedata(templatename) # gets the python object with the data from original file
for ref in data:
keys = ref.split(".")
temp = template
for key_part in keys[:-1]:
temp = temp[key_part]
temp[keys[-1]] = data[ref] # Because dictionaries are mutable, this updates template too
pprint.pprint(template)
</code></pre>
<p>Hope this helps.</p>
| 0 | 2016-08-25T04:59:28Z | [
"python",
"json"
] |
Isolating the background of a video with objects of interest present in the initial frame using openCV | 39,070,929 | <p>I'm using OpenCV to locate moving cars from a traffic cam. The video I'm working with starts off with the objects of interest in the initial frame. My question is how would I go about isolating the background without any of the vehicles, to serve as the frame of origin for subsequent motion detection. </p>
<pre><code>camera = cv2.VideoCapture(video)
firstFrame = None
while True:
(grabbed, frame) = camera.read()
if not grabbed:
break
frame = cv2.resize(frame, None, fx=2, fy=2)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (11,11), 0)
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(firstFrame, gray)
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
_, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
if cv2.contourArea(c) < 500:
continue
(x,y,w,h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.imshow('frame', frame)
cv2.imshow('thresh', thresh)
cv2.imshow('frame delta', frameDelta)
if cv2.waitKey(0) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
</code></pre>
<p>Ultimately, first frame will be absent of any vehicles, proceeded by the original frames of the video.</p>
<p>Thanks </p>
| -1 | 2016-08-22T03:17:55Z | 39,091,849 | <p>To solve the problem you described, you should look more into object detection and classification. Locating moving cars is not particularly a background subtraction problem. An example of using Haar Cascades can be found here: <a href="https://github.com/andrewssobral/vehicle_detection_haarcascades" rel="nofollow">https://github.com/andrewssobral/vehicle_detection_haarcascades</a></p>
| 0 | 2016-08-23T03:26:21Z | [
"python",
"opencv"
] |
How to subtract timestamps from two seperate columns, then enter this data into the table | 39,070,975 | <p>I am attempting to create a sign-in, sign-out program using python and mysql on a raspberry pi. I have so far successfully created a system for registering, signing in, and signing out, but am having trouble with the final component. I am trying to subtract the two separate time-stamps (signin, signout) using TIMESTAMPDIFF, and then entering this value into a separate column in the table. However, the statement I am using is not working.</p>
<p>Code:</p>
<pre><code>employee_id = raw_input("Please enter your ID number")
minutes_calc = "INSERT INTO attendance (minutes) WHERE id = %s VALUES (TIMESTAMPDIFF(MINUTE, signin, signout))"
try:
curs.execute(minutes_calc, (employee_id))
db.commit()
except:
db.rollback()
print "Error"
</code></pre>
<p>Table Structure so far (apologies for formatting):</p>
<pre><code>name | id | signin | signout | minutes |
Dr_Kerbal 123 2016-08-21 22:57:25 2016-08-21 22:59:58 NULL
</code></pre>
<p>Please Note that I am in need of a statement that can subtract the timestamps regardless of their value instead of a statement that focuses on the specific timestamps in the example.</p>
<p>Additionally the datatype for the column minutes is decimal (10,0) as I initially intended for it to be in seconds (that was when I encountered other issues which have been solved since), its null status is set to YES, and the default value is NULL.</p>
<p>Thank You for your Assistance</p>
| 0 | 2016-08-22T03:25:27Z | 39,070,997 | <p>You need an <code>update</code> query not <code>INSERT</code></p>
<pre><code>UPDATE attendance
SET `minutes` = TIMESTAMPDIFF(MINUTE, signin, signout);
</code></pre>
| 0 | 2016-08-22T03:28:21Z | [
"python",
"mysql",
"raspberry-pi"
] |
If-statement seemingly ignored by Write operation | 39,071,078 | <p>What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added.
Note that I also have a list Coordinates that stores the same information. The list works as no repeats are added.(By checking) However, the text file has the same coordinates appended over and over again even though it theoretically shouldn't as it is contained within the same if-block as the list.</p>
<pre><code>import requests
pokemon_url = 'https://pogo.appx.hk/top'
while True:
response = requests.get(pokemon_url)
response.raise_for_status()
pokemon = response.json()[0:]
Sighting = 0
Coordinates = [None] * 100
for num in range(len(pokemon)):
if pokemon[num]['pokemon_name'] == 'Aerodactyl':
Lat = pokemon[num]['latitude']
Long = pokemon[num]['longitude']
if (Lat, Long) not in Coordinates:
Coordinates[Sighting] = (Lat, Long)
file = open("aerodactyl.txt", "a")
file.write(str(Lat) + "," + str(Long) + "\n")
file.close
Sighting += 1
</code></pre>
<p>For clarity purposes, this is the output
<a href="http://i.stack.imgur.com/O47r6.png" rel="nofollow"><img src="http://i.stack.imgur.com/O47r6.png" alt="For clarity purposes, this is the output"></a></p>
| -1 | 2016-08-22T03:40:21Z | 39,071,158 | <p>You need to put your <code>Sighting</code> and <code>Coordinates</code> variables outside of the <code>while</code> loop if you do not want them to reset on every iteration.</p>
<p>However, there are a lot more things wrong with the code. Without trying it, here's what I spot:</p>
<ol>
<li>You have no exit condition for the <code>while</code> loop. Please don't do this to the poor website. You'll essentially be spamming requests.</li>
<li><code>file.close</code> should be <code>file.close()</code>, but overall you should only need to open the file once, not on every single iteration of the loop. Open it once, and close once you're done (assuming you will add an exit condition).</li>
<li>Slicing from <code>0</code> (<code>response.json()[0:]</code>) is unnecessary. By default the list starts at index 0. This may be a convoluted way to get a new list, but that seems unnecessary here.</li>
<li><code>Coordinates</code> should not be a hard-coded list of 100 <code>None</code>s. Just use a <a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow"><code>set</code></a> to track existing coordinates.</li>
<li>Get rid of <code>Sighting</code> altogether. It doesn't make sense if you're re-issuing the request over and over again. If you want to iterate through the pokémon from one response, use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> if you need the index.</li>
<li>It's generally good practice to use <a href="https://en.wikipedia.org/wiki/Snake_case" rel="nofollow">snake case</a> for Python variables.</li>
</ol>
| 2 | 2016-08-22T03:51:20Z | [
"python"
] |
If-statement seemingly ignored by Write operation | 39,071,078 | <p>What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added.
Note that I also have a list Coordinates that stores the same information. The list works as no repeats are added.(By checking) However, the text file has the same coordinates appended over and over again even though it theoretically shouldn't as it is contained within the same if-block as the list.</p>
<pre><code>import requests
pokemon_url = 'https://pogo.appx.hk/top'
while True:
response = requests.get(pokemon_url)
response.raise_for_status()
pokemon = response.json()[0:]
Sighting = 0
Coordinates = [None] * 100
for num in range(len(pokemon)):
if pokemon[num]['pokemon_name'] == 'Aerodactyl':
Lat = pokemon[num]['latitude']
Long = pokemon[num]['longitude']
if (Lat, Long) not in Coordinates:
Coordinates[Sighting] = (Lat, Long)
file = open("aerodactyl.txt", "a")
file.write(str(Lat) + "," + str(Long) + "\n")
file.close
Sighting += 1
</code></pre>
<p>For clarity purposes, this is the output
<a href="http://i.stack.imgur.com/O47r6.png" rel="nofollow"><img src="http://i.stack.imgur.com/O47r6.png" alt="For clarity purposes, this is the output"></a></p>
| -1 | 2016-08-22T03:40:21Z | 39,071,393 | <p>Try this:</p>
<pre><code>#!/usr/bin/env python
import urllib2
import json
pokemon_url = 'https://pogo.appx.hk/top'
pokemon = urllib2.urlopen(pokemon_url)
pokeset = json.load(pokemon)
Coordinates = [None] * 100
for num in range(len(pokeset)):
if pokeset[num]['pokemon_name'] == 'Aerodactyl':
Lat = pokeset[num]['latitude']
Long = pokeset[num]['longitude']
if (Lat, Long) not in Coordinates:
Coordinates.append((Lat, Long))
file = open("aerodactyl.txt", "a")
file.write(str(Lat) + "," + str(Long) + "\n")
file.close
</code></pre>
| 0 | 2016-08-22T04:24:38Z | [
"python"
] |
django.db.utils.OperationalError: no such table: auth_user | 39,071,093 | <p>After I install Django-userena,there is an error
my django version :1.9.5
I just install django-userena step by step ,but when i migrate it ,an error happend and I don't how to solve it.</p>
<pre><code> Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
emit_post_migrate_signal(self.verbosity, self.interactive, connection.alias)
File "C:\Python27\lib\site-packages\django\core\management\sql.py", line 50, in emit_post_migrate_signal
using=db)
File "C:\Python27\lib\site-packages\django\dispatch\dispatcher.py", line 192, in send
response = receiver(signal=self, sender=sender, **named)
File "C:\Python27\lib\site-packages\guardian\management\__init__.py", line 33, in create_anonymous_user
User.objects.get(**lookup)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 381, in get
num = len(clone)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 240, in __len__
self._fetch_all()
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 52, in __iter__
results = compiler.execute_sql()
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: auth_user
</code></pre>
<p>apps:</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.sites',
'userena',
'guardian',
'easy_thumbnails',
'accounts',
]
</code></pre>
| 0 | 2016-08-22T03:42:03Z | 39,944,429 | <pre><code>./manage.py migrate
</code></pre>
<p>if your Django version is 1.9 or lower, use</p>
<pre><code>./manage.py syncdb
</code></pre>
<p>then </p>
<pre><code>python manage.py createsuperuser
</code></pre>
<p>more details on <a href="https://github.com/django/django/blob/master/django/contrib/auth/forms.py" rel="nofollow">https://github.com/django/django/blob/master/django/contrib/auth/forms.py</a></p>
<p>May it help</p>
| 0 | 2016-10-09T14:00:04Z | [
"python",
"django",
"django-guardian",
"django-userena"
] |
Upload and rename two different files in two different folders using django? | 39,071,125 | <p>I could upload two different files in the same folder using django. But I have to upload it to two different folders and also rename the files I uploaded as target.{file_extension} and probe.{file_extension}.I have no idea as I am a beginner to django.Could anyone please help me with my issue.
My codes are:</p>
<p>In django model.py</p>
<pre><code>dirname = datetime.now().strftime('%Y.%m.%d.%H.%M.%S')
class Document(models.Model):
docfile = models.FileField(upload_to=dirname)
</code></pre>
<p>In views.py</p>
<pre><code>def test(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
else:
form = DocumentForm() # An empty, unbound form
documents = Document.objects.all()
return render(
request,
'personal/basic.html',
{'documents': documents, 'form': form}
)
</code></pre>
<p>And in my basic.html</p>
<pre><code><form action="/simulation/" method="post" enctype="multipart/form-data" single>
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
<input type="submit" value="Upload" name = "file1"/></p>
</form>
</code></pre>
| 0 | 2016-08-22T03:45:32Z | 39,071,371 | <p>if you check django docs for <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to" rel="nofollow">FileField</a> you see upload_to supports custom method:</p>
<p>(from django docs)</p>
<pre><code>def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
</code></pre>
<p>as you can see in your custom method you have access to current instance which can be used for generating your custom path to save file.</p>
| 2 | 2016-08-22T04:21:18Z | [
"python",
"django"
] |
key error: 'x' --> adding key value pair in for loop, key being char | 39,071,156 | <p>I am a beginner in python and I am trying to solve a coding problem, got this error. Don't understand why ? I went through a couple of Q/A's here but they don't seem to solve my problem. Essentially what I am trying to do is iterate over a string, through its characters and fill these characters in a dictionary. With characters being the keys and values being the number of times these characters appeared. So I'm trying the following: </p>
<pre><code> def myfunc(mystring):
for i in mystring:
if charCounter[i]:
charCounter[i] += 1
charCounter[i] = 1
mystring = "hello! how are you ?"
myfunc(mystring)
</code></pre>
<p>and Im getting following error:</p>
<blockquote>
<p>File "xyq.py", line 3, in myfunc
if CharCounter[i]:
KeyError: 'h'</p>
</blockquote>
<p>Can someone please suggest, where am I going wrong ? And if possible how can I improve the code ?</p>
<p>Thanks</p>
| -3 | 2016-08-22T03:51:02Z | 39,071,226 | <p>You need to check if <code>i</code> is in <code>charCounter</code> before you try to retrieve it:</p>
<pre><code>if i in charCounter:
charCounter[i] += 1
else:
charCounter[i] = 1
</code></pre>
<p>Or alternatively:</p>
<pre><code>if charCounter.get(i):
...
</code></pre>
| 0 | 2016-08-22T04:01:29Z | [
"python",
"dictionary",
"key"
] |
key error: 'x' --> adding key value pair in for loop, key being char | 39,071,156 | <p>I am a beginner in python and I am trying to solve a coding problem, got this error. Don't understand why ? I went through a couple of Q/A's here but they don't seem to solve my problem. Essentially what I am trying to do is iterate over a string, through its characters and fill these characters in a dictionary. With characters being the keys and values being the number of times these characters appeared. So I'm trying the following: </p>
<pre><code> def myfunc(mystring):
for i in mystring:
if charCounter[i]:
charCounter[i] += 1
charCounter[i] = 1
mystring = "hello! how are you ?"
myfunc(mystring)
</code></pre>
<p>and Im getting following error:</p>
<blockquote>
<p>File "xyq.py", line 3, in myfunc
if CharCounter[i]:
KeyError: 'h'</p>
</blockquote>
<p>Can someone please suggest, where am I going wrong ? And if possible how can I improve the code ?</p>
<p>Thanks</p>
| -3 | 2016-08-22T03:51:02Z | 39,071,590 | <pre><code>if charCounter[i]:
</code></pre>
<p>throws <code>KeyError</code> if the key does not exist. What you want to do isuse <code>if i in charCounter:</code> instead:</p>
<pre><code>if i in char_counter:
char_counter[i] += 1
else:
char_counter[i] = 1
</code></pre>
<p>Alternatively you could use <code>get</code> which <em>gets</em> the value if it exists, or returns the second (optional) value if it didn't exist:</p>
<pre><code>char_counter[i] = char_counter.get(i, 0) + 1
</code></pre>
<p>However this counting pattern is so popular that a whole class exists for it: <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>: </p>
<pre><code>from collections import Counter
def my_func(my_string):
return Counter(my_string)
</code></pre>
<p>Example:</p>
<pre><code>>>> counts = my_func('hello! how are you ?')
>>> counts
Counter({' ': 4, 'o': 3, 'h': 2, 'l': 2, 'e': 2, '!': 1, 'r': 1, 'a': 1,
'?': 1, 'w': 1, 'u': 1, 'y': 1})
>>> counts[' ']
4
</code></pre>
<p><code>collections.Counter</code> is a subclass of dictionary, so it would behave in the same way that an ordinary dictionary would do with item access and so forth.</p>
| 0 | 2016-08-22T04:47:32Z | [
"python",
"dictionary",
"key"
] |
OneHotEncoder confusion in scikit learn | 39,071,205 | <p>Using in Python 2.7 (miniconda interpreter). Confused by the example below about <code>OneHotEncoder</code>, confused why <code>enc.n_values_</code> output is <code>[2, 3, 4]</code>? If anyone could help to clarify, it will be great.</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html</a></p>
<pre><code>>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])
OneHotEncoder(categorical_features='all', dtype=<... 'float'>,
handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9])
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]])
</code></pre>
<p>regards,
Lin</p>
| 0 | 2016-08-22T03:58:11Z | 39,071,305 | <p><code>n_values</code> is the number of values per feature.</p>
<p>In this example,</p>
<pre><code>X = 0 0 3
1 1 0
0 2 1
1 0 2
</code></pre>
<p>(X's shape is [n_samples, n_feature])</p>
<p>For the first feature, there are 2 values: 0, 1;</p>
<p>For the second feature, there are 3 values: 0, 1, 2.</p>
<p>For the third feature, there are 4 values: 0, 1, 2, 3.</p>
<p>Therefore, <code>enc.n_values_</code> is <code>[2, 3, 4]</code>.</p>
| 1 | 2016-08-22T04:12:28Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"one-hot-encoding"
] |
Apply a function that manipulates a dataframe to a groupby | 39,071,248 | <p>I have a dataframe that has an index and a couple of other columns. The value in the index are not unique (in fact they repeat many times. Each index can be repeated ~10-20 times). Basically imagine something like this:</p>
<pre><code>import random
random.seed(4)
arr = [[random.randint(1, 4)] + [random.random() for _ in xrange(3)] for i in xrange(5)]
df_ = pd.DataFrame(arr, columns = ['id', 'col1', 'col2', 'col3']).set_index('id')
</code></pre>
<p><a href="http://i.stack.imgur.com/qmq8vm.png" rel="nofollow"><img src="http://i.stack.imgur.com/qmq8vm.png" alt="enter image description here"></a></p>
<p>Now I need to calculate some values based on id. These values are:</p>
<ul>
<li>percentage of 0 in the some particular column</li>
<li>percentage of values that fall into some ranges</li>
<li>something similar to the previous questions</li>
</ul>
<p>Let's for simplicity assume that I need only values in the range <code>[-inf, 0.25], [0.25, 0.75], [0.75, inf]</code> and I will use only <code>col1</code></p>
<p>What I currently have done is:</p>
<p>Created a function that takes a dataframe and returns these 3 numbers.</p>
<pre><code>def f(df):
v1 = len(df[df['col1'] <= 0.25])
v2 = len(df[(df['col1'] >= 0.25) & (df['col1'] <= 0.75)])
v3 = len(df[df['col1'] >= 0.75])
return v1, v2, v3
</code></pre>
<p>Now I am iterating all values in the index, extract data related to this index and applying this function to it. This way I create the new dataframe with the statistics I need.</p>
<pre><code>data = []
for id in set(df_.index.values):
v1, v2, v3 = f(df_.loc[id])
data.append((id, v1, v2, v3))
res_ = pd.DataFrame(data, columns=['id', 'less_25', '25_75', 'more_75'])
</code></pre>
<hr>
<p>Now everything works (I believe correctly), but it is incredibly slow. I need to calculate this data on approximately 1M rows df, where there are ~50k unique ids. My approach will most probably take a day.</p>
<p>I believe that with a smart <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> or may be something else this can be achieved way faster.</p>
| 1 | 2016-08-22T04:04:25Z | 39,073,246 | <p>Let's start by using <code>pd.cut</code> across the entire <code>df_</code> to start.</p>
<pre><code>cat = pd.cut(df_.values.flatten(), [-np.inf, .25, .75, np.inf])
cat_arr = cat.get_values().reshape(df_.shape)
cat_df = pd.DataFrame(cat_arr, df_.index, df_.columns)
</code></pre>
<p><strong><em>Take a look</em></strong></p>
<pre><code>pd.concat([df_, cat_df], axis=1, keys=['df_', 'cat'])
</code></pre>
<p><a href="http://i.stack.imgur.com/SEJf9.png" rel="nofollow"><img src="http://i.stack.imgur.com/SEJf9.png" alt="enter image description here"></a></p>
<p><strong><em>Get Counts of <code>cat</code> per <code>id</code></em></strong></p>
<pre><code>cat_count = cat_df.stack().groupby(level=[0, 1]) \
.value_counts() \
.unstack().fillna(0)
cat_count
</code></pre>
<p><a href="http://i.stack.imgur.com/Dcovo.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dcovo.png" alt="enter image description here"></a></p>
<p><strong><em>Get frequency of <code>cat</code> per <code>id</code></em></strong></p>
<pre><code>cat_count = cat_df.stack().groupby(level=[0, 1])\
.value_counts(normalize=True) \
.unstack().fillna(0)
cat_count
</code></pre>
<p><a href="http://i.stack.imgur.com/rWzmR.png" rel="nofollow"><img src="http://i.stack.imgur.com/rWzmR.png" alt="enter image description here"></a></p>
| 1 | 2016-08-22T07:08:45Z | [
"python",
"pandas"
] |
Apply a function that manipulates a dataframe to a groupby | 39,071,248 | <p>I have a dataframe that has an index and a couple of other columns. The value in the index are not unique (in fact they repeat many times. Each index can be repeated ~10-20 times). Basically imagine something like this:</p>
<pre><code>import random
random.seed(4)
arr = [[random.randint(1, 4)] + [random.random() for _ in xrange(3)] for i in xrange(5)]
df_ = pd.DataFrame(arr, columns = ['id', 'col1', 'col2', 'col3']).set_index('id')
</code></pre>
<p><a href="http://i.stack.imgur.com/qmq8vm.png" rel="nofollow"><img src="http://i.stack.imgur.com/qmq8vm.png" alt="enter image description here"></a></p>
<p>Now I need to calculate some values based on id. These values are:</p>
<ul>
<li>percentage of 0 in the some particular column</li>
<li>percentage of values that fall into some ranges</li>
<li>something similar to the previous questions</li>
</ul>
<p>Let's for simplicity assume that I need only values in the range <code>[-inf, 0.25], [0.25, 0.75], [0.75, inf]</code> and I will use only <code>col1</code></p>
<p>What I currently have done is:</p>
<p>Created a function that takes a dataframe and returns these 3 numbers.</p>
<pre><code>def f(df):
v1 = len(df[df['col1'] <= 0.25])
v2 = len(df[(df['col1'] >= 0.25) & (df['col1'] <= 0.75)])
v3 = len(df[df['col1'] >= 0.75])
return v1, v2, v3
</code></pre>
<p>Now I am iterating all values in the index, extract data related to this index and applying this function to it. This way I create the new dataframe with the statistics I need.</p>
<pre><code>data = []
for id in set(df_.index.values):
v1, v2, v3 = f(df_.loc[id])
data.append((id, v1, v2, v3))
res_ = pd.DataFrame(data, columns=['id', 'less_25', '25_75', 'more_75'])
</code></pre>
<hr>
<p>Now everything works (I believe correctly), but it is incredibly slow. I need to calculate this data on approximately 1M rows df, where there are ~50k unique ids. My approach will most probably take a day.</p>
<p>I believe that with a smart <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> or may be something else this can be achieved way faster.</p>
| 1 | 2016-08-22T04:04:25Z | 39,081,635 | <p>Reposting my comment as answer. It uses group by index with a custom agglomeration function based on numpy.</p>
<pre><code>from __future__ import division
import numpy as np
import pandas as pd
import random
random.seed(4)
arr = [[random.randint(1, 4)] + [random.random() for _ in xrange(3)]\
for i in xrange(10)]
df_ = pd.DataFrame(arr, columns = ['id', 'col1', 'col2','col3']).set_index('id')
# Percentage of zeros in col1
res1 = df_.groupby(df_.index).agg({'col1':lambda x: np.size(x[x==0])/np.size(x)})
# Percentage of values in given range in col1
res2 = df_.groupby(df_.index).agg({'col1':lambda x:\
np.size(x[(x>0.2) & (x<0.5)])/np.size(x)})
</code></pre>
<p>Output:</p>
<pre><code>In [22]: res1
Out[22]:
col1
id
1 0.0
2 0.0
3 0.0
4 0.0
In [23]: res2
Out[23]:
col1
id
1 0.333333
2 0.000000
3 0.000000
4 0.200000
</code></pre>
| 0 | 2016-08-22T14:04:25Z | [
"python",
"pandas"
] |
Parsing tweets' text out of "Status" wrapper in json file | 39,071,262 | <p>I used this tweepy-based <a href="https://gist.github.com/yanofsky/5436496" rel="nofollow">code</a> to pull the tweets of a given user by user_id. I then saved a list of all tweets of a given user (alltweets) to a json file as follows. Note that without "repr", i wasn't able to dump the alltweets list into json file. The code worked as expected</p>
<pre><code>with open(os.path.join(output_file_path,'%s_tweets.json' % user_id), 'a') as f:
json.dump(repr(alltweets), f)
</code></pre>
<p>However, I have a side problem with retrieving the tweets after saving them to the json file. I need to access the text in each tweet, but I'm not sure how to deal with the "Status" wrapper that tweepy uses (See a sample of the json file attached).<a href="http://i.stack.imgur.com/hmzdQ.png" rel="nofollow">sample json file content</a> </p>
<p>I tried to iterate over the lines in the file as follows, but the file is being seen as a single line.</p>
<pre><code>with open(fname, 'r') as f:
for line in f:
tweet = json.loads(line)
</code></pre>
<p>I also tried to iterate over statuses after reading the json file as a string, as follows, but iteration rather takes place on the individual characters in the json file.</p>
<pre><code>with open(fname, 'r') as f:
x = f.read()
for status in x:
"""code"""
</code></pre>
| 0 | 2016-08-22T04:06:50Z | 39,131,778 | <p>Maybe not the prettiest solution but you could just declare <code>Status</code> as a <code>dict</code> and then <code>eval</code> the list (the whole content of the files).</p>
<pre><code>Status = dict
f = open(fname, 'r')
data = eval(f.read())
f.close()
for status in data:
""" do your stuff"""
</code></pre>
| 0 | 2016-08-24T19:39:58Z | [
"python",
"tweepy"
] |
Solving Non-Linear Differential Equation Sympy | 39,071,334 | <p>This code only works for solving the differential equation v_equation if v(t) isn't squared. When I squared it it returned the error PolynomialDivisionFailed. Is there another way of doing this with Sympy or should I find a different python package for doing these sorts of calculations.</p>
<pre><code>from sympy import *
from matplotlib import pyplot as plt
import numpy as np
m = float(raw_input('Mass:\n> '))
g = 9.8
k = float(raw_input('Drag Coefficient:\n> '))
f1 = g * m
t = Symbol('t')
v = Function('v')
v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0)
C1 = Symbol('C1')
C1_ic = solve(v_equation.rhs.subs({t:0}),C1)[0]
v_equation = v_equation.subs({C1:C1_ic})
func = lambdify(t, v_equation.rhs,'numpy')
</code></pre>
| 2 | 2016-08-22T04:16:47Z | 39,073,773 | <p>From my experience with symbolic math packages, I would not recommend performing (symbolic) calculations using floating point constants. It is better to define equations using symbolic constants, perform calculations as far as possible, and then substitute with numerical values. </p>
<p>With this approach, Sympy can provide a solution for this D.E. </p>
<p>First, define symbolic constants. To aid calculations, note that we can provide additional information about these constants (e.g., real, positive, e.t.c)</p>
<pre><code>import sympy as sp
t = sp.symbols('t', real = True)
g, k, m = sp.symbols('g, k, m', real = True, positive = True)
v = sp.Function('v')
</code></pre>
<p>The symbolic solution for the DE can be obtained as follows</p>
<pre><code>f1 = g * m
eq = f1 - k * (v(t) ** 2) - m * sp.Derivative(v(t))
sol = sp.dsolve(eq,v(t)).simplify()
</code></pre>
<p>The solution <code>sol</code> will be a function of <code>k</code>, <code>m</code>, <code>g</code>, and a constant <code>C1</code>. In general, there will be two, complex <code>C1</code> values corresponding to the initial condition. However, both values of <code>C1</code> result in the same (real-valued) solution when substituted in <code>sol</code>.</p>
<p>Note that if you don't need a symbolic solution, a numerical ODE solver, such as Scipy's <code>odeint</code>, may be used. The code would be the following (for an initial condition <code>0</code>):</p>
<pre><code>from scipy.integrate import odeint
def fun(v, t, m, k, g):
return (g*m - k*v**2)/m
tn = np.linspace(0, 10, 101)
soln = odeint(fun, 0, tn, args=(1000, 0.2, 9.8))
</code></pre>
<p><code>soln</code> is an array of samples <code>v(t)</code> corresponding to the <code>tn</code> elements</p>
| 3 | 2016-08-22T07:38:26Z | [
"python",
"numpy",
"sympy"
] |
Get the number of same string in a list | 39,071,351 | <p>I want to get the no. of same string in a list</p>
<p>Example</p>
<pre><code>list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
</code></pre>
<p>Output</p>
<pre><code>2
</code></pre>
<p>I have tried this so far</p>
<pre><code>def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")
</code></pre>
| 0 | 2016-08-22T04:19:15Z | 39,071,441 | <p>There's a built-in method <code>count</code> that does this.</p>
<pre><code>number_of_jeen = list.count('jeen')
</code></pre>
| 6 | 2016-08-22T04:29:59Z | [
"python"
] |
Get the number of same string in a list | 39,071,351 | <p>I want to get the no. of same string in a list</p>
<p>Example</p>
<pre><code>list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
</code></pre>
<p>Output</p>
<pre><code>2
</code></pre>
<p>I have tried this so far</p>
<pre><code>def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")
</code></pre>
| 0 | 2016-08-22T04:19:15Z | 39,071,461 | <p>Try just using a simple counter function. The idea is to loop through the list you have. In each iteration you are checking whether or not the name you are looking at is equal to 'jeen' in this case. If it is increment your counter, otherwise just move onto the next name. Below is an example:</p>
<pre><code>listNames = ['jack','jeen','jeen']
occurrences = 0
for i in listNames:
if(i == 'jeen'):
occurrences += 1
print(occurrences)
</code></pre>
| -2 | 2016-08-22T04:32:07Z | [
"python"
] |
Get the number of same string in a list | 39,071,351 | <p>I want to get the no. of same string in a list</p>
<p>Example</p>
<pre><code>list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
</code></pre>
<p>Output</p>
<pre><code>2
</code></pre>
<p>I have tried this so far</p>
<pre><code>def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")
</code></pre>
| 0 | 2016-08-22T04:19:15Z | 39,071,530 | <p>try this.it will work 100%</p>
<pre><code>list=["jhon","jack","jack"]
def get_count(list,name):
return list.count(name)
length=get_count(list,"jhon")
print length
</code></pre>
| -2 | 2016-08-22T04:40:21Z | [
"python"
] |
Get the number of same string in a list | 39,071,351 | <p>I want to get the no. of same string in a list</p>
<p>Example</p>
<pre><code>list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
</code></pre>
<p>Output</p>
<pre><code>2
</code></pre>
<p>I have tried this so far</p>
<pre><code>def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")
</code></pre>
| 0 | 2016-08-22T04:19:15Z | 39,071,987 | <p>Use <code>Counter</code> from <code>collections</code>:</p>
<pre><code>list = ['jack','jeen','jeen']
count = Counter(list)
print(count['jeen'])
</code></pre>
| 4 | 2016-08-22T05:36:07Z | [
"python"
] |
Python MySQL Bulk Insertion Error with Character Encode | 39,071,397 | <p>I Start new Project in <strong>Python</strong> with <strong>MySQL</strong>.</p>
<p>I just try to insert millions of record from <strong>CSV</strong> to <strong>MySQL</strong> through <strong>MySQLdb</strong> package. </p>
<p><strong>My Code:</strong></p>
<pre><code> import pandas as pd
import MySQLdb
#Connect with MySQL
db = MySQLdb.connect('localhost','root','****','MY_DB')
cur = db.cursor()
#Reading CSV
df = pd.read_csv('/home/shankar/LAB/Python/Rough/******.csv')
for i in df.COMPANY_NAME:
i = i.replace("'","")
i = i.replace("\\","")
#i = i.encode('latin-1', 'ignore')
cur.execute("INSERT INTO polls_company (name) VALUES ('" + i + "')")
db.commit()
</code></pre>
<p>This code working fine in some sort of CSV files, but having issues in few CSV files.</p>
<p><strong>Errors :</strong></p>
<pre><code> ---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-7-aac849862588> in <module>()
13 i = i.replace("\\","")
14 #i = i.encode('latin-1', 'ignore')
---> 15 cur.execute("INSERT INTO polls_company (name) VALUES ('" + i + "')")
16 db.commit()
/home/shankar/.local/lib/python3.5/site-packages/MySQLdb/cursors.py in execute(self, query, args)
211
212 if isinstance(query, unicode):
--> 213 query = query.encode(db.unicode_literal.charset, 'surrogateescape')
214
215 res = None
UnicodeEncodeError: 'latin-1' codec can't encode character '\ufffd' in position 49: ordinal not in range(256)
</code></pre>
<p>Here, this "Character Encoding" issue is occurred in some CSV files only, but i want automatic Insertion with common encoding techniques.</p>
<p>Because CSV Files encoded works with "utf-8", "latin-1" and more...</p>
<p>If i use <strong>utf-8</strong> : then i got error in <strong>latin-1</strong>
and vise versa</p>
<p>So, Is there any ways to operate all kind of CSV file with common encoding </p>
<p>or</p>
<p>any other ways to solve this ?</p>
<p>[Thanks in Advance...]</p>
| 0 | 2016-08-22T04:24:56Z | 39,074,778 | <p>I would let the pandas take care of encoding and you don't need to loop through your DF. Let's do it pandas way:</p>
<pre><code>import pandas as pd
import MySQLdb
#Connect with MySQL
db = MySQLdb.connect('localhost','root','****','MY_DB')
cur = db.cursor()
#Reading CSV
df = pd.read_csv('/home/shankar/LAB/Python/Rough/******.csv')
df.COMPANY_NAME.str.replace(r"['\]*", "").rename(columns={'COMPANY_NAME':'name'}).to_sql('polls_company', db, if_exists='append', index=False)
</code></pre>
| 1 | 2016-08-22T08:36:31Z | [
"python",
"mysql",
"csv",
"pandas",
"mysql-python"
] |
Syntax error when there's a newline after an or operator | 39,071,401 | <p>This is OK:</p>
<pre><code>if 'something' in data['meta']:
<do something>
</code></pre>
<p>This is a syntax error. Why?</p>
<pre><code>if ('something' in data['meta']) or
('something_else' in data['meta']):
<do something>
</code></pre>
<p>The interpreter hands this out:</p>
<pre><code> File "test.py", line 1
if ('something' in data['meta']) or
^
SyntaxError: invalid syntax
</code></pre>
| -3 | 2016-08-22T04:25:24Z | 39,071,436 | <p>Newlines are important. Python needs to know how to parse things. For the second code snippet, you are separating the <code>if</code> into two lines, and Python doesn't like that since it looks like a separate command. Two common ways to span multiple lines is using a backslash or parentheses. For example, both of these are valid syntax:</p>
<pre><code>if ('something' in data['meta']) or \
('something_else' in data['meta']):
<do something>
if (('something' in data['meta']) or
('something_else' in data['meta'])):
<do something>
</code></pre>
<p>You can read about this more in the <a href="https://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP 8 Style Guide</a>.</p>
<p><strong>Small Note</strong>: I add extra indentation on multi-line if statements to easily distinguish when the condition ends and when the subsequent code begins. It's just preference, and PEP8 provides options <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="nofollow">here</a>.</p>
| 8 | 2016-08-22T04:29:43Z | [
"python"
] |
Syntax error when there's a newline after an or operator | 39,071,401 | <p>This is OK:</p>
<pre><code>if 'something' in data['meta']:
<do something>
</code></pre>
<p>This is a syntax error. Why?</p>
<pre><code>if ('something' in data['meta']) or
('something_else' in data['meta']):
<do something>
</code></pre>
<p>The interpreter hands this out:</p>
<pre><code> File "test.py", line 1
if ('something' in data['meta']) or
^
SyntaxError: invalid syntax
</code></pre>
| -3 | 2016-08-22T04:25:24Z | 39,071,449 | <p>That is a syntax error because Python expects your <code>if</code> statement to end on that line, and with <code>:</code>. </p>
<p>However an expression such as this boolean one can continue to another line provided that you either</p>
<ul>
<li>you end the first line in backslash (<code>\</code>) character</li>
<li>you wrap the expression in extra parentheses (preferred).</li>
</ul>
<p>Thus, use either</p>
<pre><code>if ('something' in data['meta']) or \
('something_else' in data['meta']):
<do something>
</code></pre>
<p>or the preferred form</p>
<pre><code>if (('something' in data['meta']) or
('something_else' in data['meta'])):
<do something>
</code></pre>
<hr>
<p><a href="https://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP 8 -- Style Guide for Python Code says</a>:</p>
<blockquote>
<p>The <strong>preferred</strong> way of wrapping long lines is by using <strong>Python's implied line continuation inside parentheses, brackets and braces.</strong> Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. </p>
</blockquote>
| 4 | 2016-08-22T04:30:22Z | [
"python"
] |
Syntax error when there's a newline after an or operator | 39,071,401 | <p>This is OK:</p>
<pre><code>if 'something' in data['meta']:
<do something>
</code></pre>
<p>This is a syntax error. Why?</p>
<pre><code>if ('something' in data['meta']) or
('something_else' in data['meta']):
<do something>
</code></pre>
<p>The interpreter hands this out:</p>
<pre><code> File "test.py", line 1
if ('something' in data['meta']) or
^
SyntaxError: invalid syntax
</code></pre>
| -3 | 2016-08-22T04:25:24Z | 39,071,450 | <p>breaking of line from "or" should be enclosed in brackets like:</p>
<pre><code>if ('something' in data['meta'] or
'something_else' in data['meta']):
<do something>
</code></pre>
| 0 | 2016-08-22T04:30:37Z | [
"python"
] |
Syntax error when there's a newline after an or operator | 39,071,401 | <p>This is OK:</p>
<pre><code>if 'something' in data['meta']:
<do something>
</code></pre>
<p>This is a syntax error. Why?</p>
<pre><code>if ('something' in data['meta']) or
('something_else' in data['meta']):
<do something>
</code></pre>
<p>The interpreter hands this out:</p>
<pre><code> File "test.py", line 1
if ('something' in data['meta']) or
^
SyntaxError: invalid syntax
</code></pre>
| -3 | 2016-08-22T04:25:24Z | 39,071,474 | <p>try code like this:</p>
<pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']):
<do something>
</code></pre>
| -1 | 2016-08-22T04:33:26Z | [
"python"
] |
Rectangle(quadrilateral) Detection by ConvexHull | 39,071,418 | <p>I want to detect the <strong>rectangle</strong> from an image. </p>
<p>I used <code>cv2.findContours()</code> with <code>cv2.convexHull()</code> to filter out the irregular polygon.</p>
<p>Afterwards, I will use the <strong>length of hull</strong> to determine whether the contour is a rectangle or not. </p>
<pre><code>hull = cv2.convexHull(contour,returnPoints = True)
if len(hull) ==4:
return True
</code></pre>
<p>However, sometimes, the <code>convexHull()</code> will return an array with <strong>length 5</strong>.
If I am using the criterion above, I will miss this rectangle.</p>
<p>For example,
<a href="http://i.stack.imgur.com/FNsYr.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/FNsYr.jpg" alt="enter image description here"></a></p>
<p>After using <code>cv2.canny()</code>
<a href="http://i.stack.imgur.com/dMRva.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/dMRva.jpg" alt="enter image description here"></a></p>
<p>By using the methods above, I will get the hull :</p>
<pre><code> [[[819 184]]
[[744 183]]
[[745 145]]
[[787 145]]
[[819 146]]]
</code></pre>
<p><a href="http://i.stack.imgur.com/hkIda.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/hkIda.jpg" alt="enter image description here"></a></p>
<hr>
<p>Here is my question: Given an array (Convex Hull) with length 5, how can I determine whether it is actually referring to a quadrilateral? Thank you.</p>
<p>=====================================================================
updated:</p>
<p>After using Sobel X and Y direction, </p>
<pre><code>sobelxy = cv2.Sobel(img_inversion, cv2.CV_8U, 1, 1, ksize=3)
</code></pre>
<p>I got:
<a href="http://i.stack.imgur.com/MhYZW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/MhYZW.jpg" alt="enter image description here"></a></p>
| 2 | 2016-08-22T04:27:15Z | 39,073,169 | <p>Well,
This is not the right way to extract rectangles. Since we are talking basics here, I would suggest you to take the inversion of the image and apply Sobel in X and Y direction and then run the findcontours function. Then with this you will be able to get lot of rectangles that you can filter out. You will have to apply lot of checks to identify the rectangle having text in it. Also I dont understand why do you want to force select rectangle with length 5. You are limiting the scale. </p>
<p>Secondly, another way is to use the Sobel X and Y image and then apply OpenCVs LineSegmentDetector. Once you get all the line segments you have to apply RANSAC for (Quad fit) so the condition here should be all the angles on a set of randomly chosen intersecting lines should be acute(roughly) and finally filter out the quad roi with text( for this use SWT or other reliable techniques).</p>
<p>As for your query you should select quad with ideally length 4 (points).</p>
<p>Ref: <a href="http://stackoverflow.com/questions/36640801/crop-the-largest-rectangle-using-opencv">Crop the largest rectangle using OpenCV</a></p>
<p>This link will give you the jist of detecting the rectangle in a very simple way. </p>
<p>The images below give you a sort of walkthrough for inversion and sobel of image. Inversion of image eliminates the double boundaries you get from sobel.</p>
<p>For Inversion you use tilde operator.</p>
<p><a href="http://i.stack.imgur.com/ks5MD.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ks5MD.jpg" alt="enter image description here"></a></p>
<p>Also before taking inversion also, its better you suppress the illumination artifacts. This can be done using homomorphic filtering. or taking log of an image.</p>
| 3 | 2016-08-22T07:04:40Z | [
"python",
"opencv",
"image-processing",
"geometry"
] |
Rectangle(quadrilateral) Detection by ConvexHull | 39,071,418 | <p>I want to detect the <strong>rectangle</strong> from an image. </p>
<p>I used <code>cv2.findContours()</code> with <code>cv2.convexHull()</code> to filter out the irregular polygon.</p>
<p>Afterwards, I will use the <strong>length of hull</strong> to determine whether the contour is a rectangle or not. </p>
<pre><code>hull = cv2.convexHull(contour,returnPoints = True)
if len(hull) ==4:
return True
</code></pre>
<p>However, sometimes, the <code>convexHull()</code> will return an array with <strong>length 5</strong>.
If I am using the criterion above, I will miss this rectangle.</p>
<p>For example,
<a href="http://i.stack.imgur.com/FNsYr.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/FNsYr.jpg" alt="enter image description here"></a></p>
<p>After using <code>cv2.canny()</code>
<a href="http://i.stack.imgur.com/dMRva.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/dMRva.jpg" alt="enter image description here"></a></p>
<p>By using the methods above, I will get the hull :</p>
<pre><code> [[[819 184]]
[[744 183]]
[[745 145]]
[[787 145]]
[[819 146]]]
</code></pre>
<p><a href="http://i.stack.imgur.com/hkIda.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/hkIda.jpg" alt="enter image description here"></a></p>
<hr>
<p>Here is my question: Given an array (Convex Hull) with length 5, how can I determine whether it is actually referring to a quadrilateral? Thank you.</p>
<p>=====================================================================
updated:</p>
<p>After using Sobel X and Y direction, </p>
<pre><code>sobelxy = cv2.Sobel(img_inversion, cv2.CV_8U, 1, 1, ksize=3)
</code></pre>
<p>I got:
<a href="http://i.stack.imgur.com/MhYZW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/MhYZW.jpg" alt="enter image description here"></a></p>
| 2 | 2016-08-22T04:27:15Z | 39,107,558 | <p>It isn't so easy to fit a rectangle to a convex polygon.</p>
<p>You can try to find the minimum area or minimum perimeter rectangle by rotating calipers (<a href="https://en.wikipedia.org/wiki/Rotating_calipers" rel="nofollow">https://en.wikipedia.org/wiki/Rotating_calipers</a>).</p>
<p>Then by comparing the areas/perimeters of the hull and the rectangle, you can assess "rectangularity".</p>
| 0 | 2016-08-23T17:38:10Z | [
"python",
"opencv",
"image-processing",
"geometry"
] |
How to get number of rows in a grouped-by category in pandas | 39,071,426 | <p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p>
<pre><code>> print(app_categ_events.label_id.unique().shape)
> print(app_categ_events.category.unique().shape)
Out:
(492,)
(458,)
</code></pre>
<p>I want to look at the <code>label_category</code>âs that have more than one <code>label_id</code> for each (because I thought there was supposed to be a one-to-one mapping).</p>
<p>In Râs <code>data.table</code>, I can do:</p>
<pre><code>app_categ_events[, count_rows := .N, by = list(category, label_id)]
# (or smth of that sort...)
print(app_categ_events[counts_rows > 1])
</code></pre>
<p>Whatâs the best way of doing that in <code>pandas</code>?</p>
| 3 | 2016-08-22T04:28:33Z | 39,071,541 | <p>We <code>transform</code> the dataset to create the 'count_rows' column after grouping by 'category', 'label_id' </p>
<pre><code>app_categ_events['count_rows'] = app_categ_events.groupby(['category',
'label_id'])['label_id'].transform('count')
print(app_categ_events)
# category label_id count_rows
#0 a 1 2
#1 a 1 2
#2 b 2 1
#3 b 3 1
</code></pre>
<p>Now, the equivalent of <code>data.table</code> as showed in the OP's post would be</p>
<pre><code>print(app_categ_events[app_categ_events.count_rows>1])
# category label_id count_rows
#0 a 1 2
#1 a 1 2
</code></pre>
<h3>data</h3>
<pre><code>import pandas as pd;
app_categ_events = pd.DataFrame({'category': ['a', 'a', 'b', 'b'], 'label_id': [1, 1, 2, 3]})
</code></pre>
| 3 | 2016-08-22T04:41:24Z | [
"python",
"pandas"
] |
How to get number of rows in a grouped-by category in pandas | 39,071,426 | <p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p>
<pre><code>> print(app_categ_events.label_id.unique().shape)
> print(app_categ_events.category.unique().shape)
Out:
(492,)
(458,)
</code></pre>
<p>I want to look at the <code>label_category</code>âs that have more than one <code>label_id</code> for each (because I thought there was supposed to be a one-to-one mapping).</p>
<p>In Râs <code>data.table</code>, I can do:</p>
<pre><code>app_categ_events[, count_rows := .N, by = list(category, label_id)]
# (or smth of that sort...)
print(app_categ_events[counts_rows > 1])
</code></pre>
<p>Whatâs the best way of doing that in <code>pandas</code>?</p>
| 3 | 2016-08-22T04:28:33Z | 39,071,587 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow">filtration</a> to return the desired results.</p>
<pre><code>df = pd.DataFrame({'label_id': [1, 1, 2, 3],
'category': ['a', 'b', 'b', 'c']})
df.groupby(['category']).filter(lambda group: len(group) > 1)
category label_id
1 b 1
2 b 2
</code></pre>
| 2 | 2016-08-22T04:47:15Z | [
"python",
"pandas"
] |
How to get number of rows in a grouped-by category in pandas | 39,071,426 | <p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p>
<pre><code>> print(app_categ_events.label_id.unique().shape)
> print(app_categ_events.category.unique().shape)
Out:
(492,)
(458,)
</code></pre>
<p>I want to look at the <code>label_category</code>âs that have more than one <code>label_id</code> for each (because I thought there was supposed to be a one-to-one mapping).</p>
<p>In Râs <code>data.table</code>, I can do:</p>
<pre><code>app_categ_events[, count_rows := .N, by = list(category, label_id)]
# (or smth of that sort...)
print(app_categ_events[counts_rows > 1])
</code></pre>
<p>Whatâs the best way of doing that in <code>pandas</code>?</p>
| 3 | 2016-08-22T04:28:33Z | 39,073,545 | <p><strong><em>Given:</em></strong></p>
<pre><code>app_categ_events = pd.DataFrame({'category': ['a', 'a', 'b', 'b'],
'label_id': [1, 1, 2, 3]})
</code></pre>
<p><strong><em>Solution:</em></strong></p>
<pre><code># identify categories with greater than 1 number of related label_id's
cat_mask = app_categ_events.groupby('category')['label_id'].nunique().gt(1)
cats = cat_mask[cat_mask]
# filter data
app_categ_events[app_categ_events.category.isin(cats.index)]
</code></pre>
<p><a href="http://i.stack.imgur.com/GpZEi.png" rel="nofollow"><img src="http://i.stack.imgur.com/GpZEi.png" alt="enter image description here"></a></p>
| 1 | 2016-08-22T07:26:31Z | [
"python",
"pandas"
] |
regarding a deprecation warning message in Python | 39,071,480 | <p>When running a python program involving the following function, <code>image[x,y] = 0</code> gives the following error message. What does that mean and how to solve it? Thanks.</p>
<p>Warning</p>
<pre><code>VisibleDeprecationWarning: using a non-integer number instead of an integer
will result in an error in the future
image[x,y] = 0
Illegal instruction (core dumped)
</code></pre>
<p>Code</p>
<pre><code>def create_image_and_label(nx,ny):
x = np.floor(np.random.rand(1)[0]*nx)
y = np.floor(np.random.rand(1)[0]*ny)
image = np.ones((nx,ny))
label = np.ones((nx,ny))
image[x,y] = 0
image_distance = ndimage.morphology.distance_transform_edt(image)
r = np.random.rand(1)[0]*(r_max-r_min)+r_min
plateau = np.random.rand(1)[0]*(plateau_max-plateau_min)+plateau_min
label[image_distance <= r] = 0
label[image_distance > r] = 1
label = (1 - label)
image_distance[image_distance <= r] = 0
image_distance[image_distance > r] = 1
image_distance = (1 - image_distance)*plateau
image = image_distance + np.random.randn(nx,ny)/sigma
return image, label[92:nx-92,92:nx-92]
</code></pre>
| 0 | 2016-08-22T04:33:47Z | 39,071,615 | <p>The warning is saying not to use floats to index your array; use <code>np.int</code> instead of <code>np.floor</code></p>
| 0 | 2016-08-22T04:51:09Z | [
"python",
"numpy",
"scipy"
] |
Pika can connect to RabbitMq on ubuntu, but not work on Centos? | 39,071,494 | <p>The same code can work on Ubuntu, not work on Centos! Firewall already closed!</p>
<p>Ubuntu 16.04, python version 3.5.2. </p>
<p>Centos 7,python version 3.5.2.</p>
<p>Ubuntu and centos are the newly installed in virtualbox! RabbitMq config tlsï¼</p>
<p>On Centosï¼ if connect rabbitmq disable ssl is OKï¼ but if connect rabbitmq enable ssl fail.</p>
<p>Can you help me? Thanks very much!</p>
<p>This the rabbitmq config:</p>
<pre><code>rabbit, [
{ loopback_users, [ ] },
{ tcp_listeners, [ 5672 ] },
{ ssl_listeners, [ 5671 ] },
{ ssl_options, [
{ cacertfile, "/ca/private/ca.crt" },
{ certfile, "/ca/server/server.pem" },
{ fail_if_no_peer_cert, false },
{ keyfile, "/ca/server/server.key" },
{ verify, verify_peer }
] },
{ hipe_compile, false }
]
</code></pre>
<p>This the code:</p>
<pre><code>#!/usr/bin/env python3.5
import pika
import ssl
ssl_options = {
"ca_certs":"/root/ca/private/ca.crt",
"certfile": "/root/ca/rbq/client.crt",
"keyfile": "/root/ca/rbq/client.key",
"cert_reqs": ssl.CERT_REQUIRED,
"ssl_version":ssl.PROTOCOL_TLSv1_2
}
credentials = pika.PlainCredentials('ttttt', '123456')
parameters = pika.ConnectionParameters(host='192.168.1.164',
port=5671,
virtual_host='/',
heartbeat_interval = 0,
credentials=credentials,
ssl = True,
ssl_options = ssl_options)
connection = pika.BlockingConnection(parameters)
connection.close()
</code></pre>
<p>This the error msg:</p>
<pre><code>Traceback (most recent call last):
File "./rb.py", line 20, in <module>
connection = pika.BlockingConnection(parameters)
File "/usr/local/lib/python3.5/site-packages/pika/adapters/blocking_connection.py", line 339, in __init__
self._process_io_for_connection_setup()
File "/usr/local/lib/python3.5/site-packages/pika/adapters/blocking_connection.py", line 374, in _process_io_for_connection_setup
self._open_error_result.is_ready)
File "/usr/local/lib/python3.5/site-packages/pika/adapters/blocking_connection.py", line 395, in _flush_output
raise exceptions.ConnectionClosed()
pika.exceptions.ConnectionClosed
</code></pre>
<p>This rabbitmq server log:</p>
<pre><code>[root@master1 rabbitmq]# tail rabbit@master1.log
SSL: certify: ssl_alert.erl:93:Fatal error: decrypt error
=INFO REPORT==== 22-Aug-2016::12:50:48 ===
accepting AMQP connection <0.22118.20> (192.168.1.131:48526 -> 192.168.1.164:5671)
=INFO REPORT==== 22-Aug-2016::12:50:48 ===
closing AMQP connection <0.22118.20> (192.168.1.131:48526 -> 192.168.1.164:5671)
=ERROR REPORT==== 22-Aug-2016::12:54:04 ===
SSL: certify: ssl_alert.erl:93:Fatal error: decrypt error
</code></pre>
| 0 | 2016-08-22T04:35:19Z | 39,120,233 | <p>My server certificate uses md5WithRSAEncryption as the signature algorithm</p>
<p><a href="https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/sec-Using_OpenSSL.html" rel="nofollow">redhat document about openssl</a></p>
<p>I updated algorithm to SHA256. I works OK! :)</p>
<p>Thanks avij!</p>
| 0 | 2016-08-24T10:04:01Z | [
"python",
"ubuntu",
"centos",
"rabbitmq",
"python-pika"
] |
How to convert list [a, b, c] to python slice index[:a, :b :c]? | 39,071,610 | <p>For example, I'm having a group of multi-dimension arrays. I want to write a method to specify the size of the slice for this array such as:</p>
<pre><code>slice = data[:a, :b, :c]
</code></pre>
<p>Because I could only get a list of [a, b, c]. I want to know how can I convert this list to slice index. Or is there a way to connect the list with slice index so as to operate this array as:</p>
<pre><code>list = [a, b, c]
slice = data[list]
</code></pre>
<p>Any reply would be appreciated.</p>
| 3 | 2016-08-22T04:49:57Z | 39,071,627 | <p>Use the <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow">slice()</a> function.</p>
<pre><code>my_list = [a, b, c]
my_slices = tuple(slice(x) for x in my_list)
my_slice = data[my_slices]
</code></pre>
<p>(I updated the variable names to avoid shadowing the builtins by mistake.)</p>
<p><code>slice(x)</code> is equivalent to the slice <code>:x</code>, and <code>slice(x, y, z)</code> is <code>x:y:z</code></p>
| 5 | 2016-08-22T04:53:15Z | [
"python",
"arrays",
"list"
] |
numpy reshape confusion with negative shape values | 39,071,630 | <p>Always confused how numpy reshape handle negative shape parameter, here is an example of code and output, could anyone explain what happens for reshape [-1, 1] here? Thanks.</p>
<p>Related document, using Python 2.7.</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html</a></p>
<pre><code>import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
S = np.array(['box','apple','car'])
le = LabelEncoder()
S = le.fit_transform(S)
print(S)
ohe = OneHotEncoder()
one_hot = ohe.fit_transform(S.reshape(-1,1)).toarray()
print(one_hot)
[1 0 2]
[[ 0. 1. 0.]
[ 1. 0. 0.]
[ 0. 0. 1.]]
</code></pre>
| 0 | 2016-08-22T04:53:24Z | 39,071,682 | <p><code>-1</code> is used to infer one missing length from the other. For example reshaping <code>(3,4,5)</code> to <code>(-1,10)</code> is equivalent to reshaping to <code>(6,10)</code> because <code>6</code> is the only length that makes sense form the other inputs. </p>
| 1 | 2016-08-22T04:59:38Z | [
"python",
"python-2.7",
"numpy",
"machine-learning",
"scikit-learn"
] |
numpy reshape confusion with negative shape values | 39,071,630 | <p>Always confused how numpy reshape handle negative shape parameter, here is an example of code and output, could anyone explain what happens for reshape [-1, 1] here? Thanks.</p>
<p>Related document, using Python 2.7.</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html</a></p>
<pre><code>import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
S = np.array(['box','apple','car'])
le = LabelEncoder()
S = le.fit_transform(S)
print(S)
ohe = OneHotEncoder()
one_hot = ohe.fit_transform(S.reshape(-1,1)).toarray()
print(one_hot)
[1 0 2]
[[ 0. 1. 0.]
[ 1. 0. 0.]
[ 0. 0. 1.]]
</code></pre>
| 0 | 2016-08-22T04:53:24Z | 39,071,706 | <p>From <code>reshape</code> docs:</p>
<blockquote>
<p>One shape dimension can be -1. In this case, the value is inferred
from the length of the array and remaining dimensions.</p>
</blockquote>
<p>In your case it is used for the common task of transforming the (3,) <code>S</code> into a (3,1) array. I think in this particular case using <code>S[:, None]</code> would have the same effect.</p>
| 1 | 2016-08-22T05:03:36Z | [
"python",
"python-2.7",
"numpy",
"machine-learning",
"scikit-learn"
] |
Is it possible to run caffe models on the data-set which is not stored in data-source like LMDB? | 39,071,870 | <p>I have 2 sets of image patches data i.e. training and testing sets. Both of these have been written to LMDB files. I am running convolutional neurall network on this data using Caffe.</p>
<p>The problem is that the data stored on hard disk is occupying considerable amount of space and is hampering my efforts to introduce more training data with deliberate noise addition to make my model more robust. </p>
<p>Is there a way where I can send image patches from my program directly to the CNN (in Caffe) without storing them in LMDB? I am currently using python to generate patches from the images for the training data set. </p>
| 1 | 2016-08-22T05:23:46Z | 39,091,710 | <p>You can write your own python data layer. See discussions <a href="https://groups.google.com/forum/#!topic/caffe-users/aEGXQRFutc8" rel="nofollow">here</a> and implementation for of input data layer for video stream <a href="https://github.com/LisaAnne/lisa-caffe-public/blob/lstm_video_deploy/examples/LRCN_activity_recognition/sequence_input_layer.py" rel="nofollow">here</a>.</p>
<p>Basically you will need add to you network description layer like:</p>
<pre><code>layer {
type: 'Python'
name: 'data'
top: 'data'
top: 'label'
python_param {
# the module name -- usually the filename -- that needs to be in $PYTHONPATH
module: 'filename'
# the layer name -- the class name in the module
layer: 'CustomInputDataLayer'
}
}
</code></pre>
<p>and implement the layer interface in Python:</p>
<pre><code>class CustomInputDataLayer(caffe.Layer):
def setup(self):
...
def reshape(self, bottom, top)
top[0].reshape(BATCH_SIZE, your_data.shape)
top[1].reshape(BATCH_SIZE, your_label.shape)
def forward(self, bottom, top):
# assign output
top[0].data[...] = your_data
top[1].data[...] = your_label
def backward(self, top, propagate_down, bottom):
pass
</code></pre>
| 0 | 2016-08-23T03:09:03Z | [
"python",
"caffe",
"conv-neural-network",
"lmdb"
] |
Is it possible to run caffe models on the data-set which is not stored in data-source like LMDB? | 39,071,870 | <p>I have 2 sets of image patches data i.e. training and testing sets. Both of these have been written to LMDB files. I am running convolutional neurall network on this data using Caffe.</p>
<p>The problem is that the data stored on hard disk is occupying considerable amount of space and is hampering my efforts to introduce more training data with deliberate noise addition to make my model more robust. </p>
<p>Is there a way where I can send image patches from my program directly to the CNN (in Caffe) without storing them in LMDB? I am currently using python to generate patches from the images for the training data set. </p>
| 1 | 2016-08-22T05:23:46Z | 39,097,123 | <p>Other than defining custom python layers, you can use the following options:</p>
<ul>
<li><p>use <code>ImageData</code> layer: it has a source parameter (source: name of a text file, with each line giving an image filename and label)</p></li>
<li><p>use <code>MemoryData</code> layer: using which you can load input images directly from memory to your network using âsetinputarraysâ method in python. Be cautious about using this layer as it only accepts labels which are single values and you cannot use images as labels (e.g. In semantic segmentation)</p></li>
<li><p>use a deploy version of your network like this:</p>
<pre><code>input: "data"
input_shape {
dim: n # batch size
dim: c # number of channels
dim: r # image size1
dim: w # image size2
}
input: "label"
input_shape {
dim: n # batch size
dim: c # number of channels
dim: r # label image size1
dim: w # label image size2
}
... #your other layers to follow
</code></pre></li>
<li><p>use an HDF5 input layer (more or less ine lmdb, but lmdb is more computationally efficient)</p></li>
</ul>
<p>You can find the details of these layers here:
<a href="http://caffe.berkeleyvision.org/tutorial/layers.html" rel="nofollow">http://caffe.berkeleyvision.org/tutorial/layers.html</a></p>
<p>There are examples available online as well. </p>
| 0 | 2016-08-23T09:15:38Z | [
"python",
"caffe",
"conv-neural-network",
"lmdb"
] |
pass the contents of a file as a parameter in python | 39,071,915 | <p>I am trying to download the files based on their ids. How can I download the files if i have their IDS stored in a text file. Here's what I've done so far</p>
<pre><code>import urllib2
#code to read a file comes here
uniprot_url = "http://www.uniprot.org/uniprot/" # constant Uniprot Namespace
def get_fasta(id):
url_with_id = "%s%s%s" %(uniprot_url, id, ".fasta")
file_from_uniprot = urllib2.urlopen(url_with_id)
data = file_from_uniprot.read()
get_only_sequence = data.replace('\n', '').split('SV=')[1]
length_of_sequence = len(get_only_sequence[1:len(get_only_sequence)])
file_output_name = "%s%s%s%s" %(id,"_", length_of_sequence, ".fasta")
with open(file_output_name, "wb") as fasta_file:
fasta_file.write(data)
print "completed"
def main():
# or read from a text file
input_file = open("positive_copy.txt").readlines()
get_fasta(input_file)
if __name__ == '__main__':
main()
</code></pre>
| 3 | 2016-08-22T05:28:35Z | 39,071,945 | <p><a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow"><code>.readlines()</code></a> returns a list of lines in file.
According to an oficial documentation you can also amend it</p>
<blockquote>
<p>For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code.</p>
</blockquote>
<p>So I guess your code may be rewritten in this way</p>
<pre><code>with open("positive_copy.txt") as f:
for id in f:
get_fasta(id.strip())
</code></pre>
<p>You can read more about <code>with</code> keyword in <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow"><code>PEP-343</code></a> page.</p>
| 3 | 2016-08-22T05:31:49Z | [
"python",
"parsing"
] |
PEP 8 E211 issue raised. Not sure why | 39,071,967 | <p>My code:</p>
<pre><code>if 'certainField' in myData['meta']['loc']:
something = myData['meta'] \ <- PEP8 E11 raised for this
['loc'] \ <- PEP8 E11 raised for this
['certainField'] \ <- PEP8 E11 raised for this
['thefield']
</code></pre>
<p>The code works as expected. But PEP 8 E211 is raised for the second, third and fourth line claiming <code>whitespace before '['</code></p>
<p>I don't get it. How can I format this so that PEP 8 is satisfied?</p>
| 3 | 2016-08-22T05:34:05Z | 39,072,055 | <p>You can wrap your statement into parenthesis and remove <kbd>\</kbd></p>
<pre><code>if 'certainField' in myData['meta']['loc']:
something = (myData['meta']
['loc']
['certainField']
['thefield'])
</code></pre>
<p><hr>
Here is an excerpt form <a href="https://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP 8</a> on wrapping long lines:</p>
<blockquote>
<p>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.</p>
<p>Backslashes may still be appropriate at times. For example, long,
multiple with -statements cannot use implicit continuation, so
backslashes are acceptable:</p>
</blockquote>
| 1 | 2016-08-22T05:42:17Z | [
"python"
] |
How to convert a single column Pandas DataFrame into Series | 39,072,010 | <p>I have the following data frame:</p>
<pre><code>import pandas as pd
d = {'gene' : ['foo','bar'],'score' : [4., 3.,]}
df = pd.DataFrame(d)
df.set_index('gene',inplace=True)
</code></pre>
<p>Which make:</p>
<pre><code>In [56]: df
Out[56]:
score
gene
foo 4
bar 3
In [58]: type(df)
Out[58]: pandas.core.frame.DataFrame
</code></pre>
<p>What I want to do is to turn it into a Series.
I expect it to to return:</p>
<pre><code>gene
foo 4
bar 3
#pandas.core.series.Series
</code></pre>
<p>I tried this but it doesn't work:</p>
<pre><code>In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame
In [65]: df.iloc[0:,]
Out[65]:
score
gene
foo 4
bar 3
</code></pre>
<p>What's the right way to do it?</p>
| 2 | 2016-08-22T05:37:38Z | 39,072,042 | <p>Try swapping the indices in the brackets:</p>
<pre><code>df.iloc[:,0]
</code></pre>
<p>This should work.</p>
| 3 | 2016-08-22T05:41:07Z | [
"python",
"pandas"
] |
How to convert a single column Pandas DataFrame into Series | 39,072,010 | <p>I have the following data frame:</p>
<pre><code>import pandas as pd
d = {'gene' : ['foo','bar'],'score' : [4., 3.,]}
df = pd.DataFrame(d)
df.set_index('gene',inplace=True)
</code></pre>
<p>Which make:</p>
<pre><code>In [56]: df
Out[56]:
score
gene
foo 4
bar 3
In [58]: type(df)
Out[58]: pandas.core.frame.DataFrame
</code></pre>
<p>What I want to do is to turn it into a Series.
I expect it to to return:</p>
<pre><code>gene
foo 4
bar 3
#pandas.core.series.Series
</code></pre>
<p>I tried this but it doesn't work:</p>
<pre><code>In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame
In [65]: df.iloc[0:,]
Out[65]:
score
gene
foo 4
bar 3
</code></pre>
<p>What's the right way to do it?</p>
| 2 | 2016-08-22T05:37:38Z | 39,072,156 | <pre><code>s = df.squeeze()
>>> s
gene
foo 4
bar 3
Name: score, dtype: float64
</code></pre>
<p>To get it back to a dataframe:</p>
<pre><code>>>> s.to_frame()
score
gene
foo 4
bar 3
</code></pre>
| 5 | 2016-08-22T05:52:58Z | [
"python",
"pandas"
] |
Adding arbitrary number of arguments to subclass? | 39,072,069 | <pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.name = restaurant_name
self.c_type = cuisine_type
self.number_served = 0
class IceCreamStand(Restaurant):
"""represents aspects of a type of restaurant specifically an IceCreamStand """
def __init__(self, restaurant_name,cuisine_type,flavors):
super().__init__(restaurant_name, cuisine_type,
flavors)
self.flavor = flavors
def display_flavors(self):
print (flavors)
##ICECREAM
dairy_queen = IceCreamStand('dairy queen' , 'ice cream','vanilla' ,'choclate' )
dairy_queen.display_flavors()
</code></pre>
<p>In my assignment I am trying to make class called IceCreamStand that inherits from the Restaraunt class. I want to also add an attribute that stores a list of flavors and call on this method. This is what i have attempted so far but i keep getting an error message saying <strong>init</strong> takes 4 provisional arguments but 5 were given?</p>
| 0 | 2016-08-22T05:43:27Z | 39,072,147 | <p>You can add a <code>*</code> before <code>flavors</code> to get all remaining positional arguments into that list.</p>
<hr>
<p>Actually, I'd recommend that you wouldn't use multiple positional arguments for flavors. Pass a <code>list</code> in instead:</p>
<pre><code>def __init__(self, restaurant_name, cuisine_type, flavors):
...
dairy_queen = IceCreamStand('dairy queen' , 'ice cream', ['vanilla' , 'chocolate'])
</code></pre>
<p>If you use this pattern, you can add another argument with a default value later, and existing code would work without problems:</p>
<pre><code>def __init__(self, restaurant_name, cuisine_type, flavors, organic=False):
...
</code></pre>
| 1 | 2016-08-22T05:51:43Z | [
"python",
"class",
"inheritance"
] |
Position of Matplotlib Pyplot bar chart labels not consistent with nan values | 39,072,221 | <p>I'm plotting bar charts of data that contains missing values (np.nan). It seems as though when the np.nan value appears in the last category, the x-axis ticks are positioned differently than when there are no np.nans or when the NaN values are in a different position.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
years = np.array([2011, 2012, 2013, 2014, 2015])
x = np.arange(len(years))
y1 = np.array([ 29., 10., 16., 29., np.nan])
y2 = np.array([ 29., 10., np.nan, 29., 16.])
y3 = np.array([ np.nan, 29., 29., 10., 16.])
f = plt.figure(figsize=(4,6))
ax = f.add_subplot(311)
ax.bar(x, y1, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
ax = f.add_subplot(312)
ax.bar(x, y2, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
ax = f.add_subplot(313)
ax.bar(x, y3, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/sOM4V.png" rel="nofollow"><img src="http://i.stack.imgur.com/sOM4V.png" alt="Output in jupyter notebook"></a></p>
<p>Ideally, I would like the x-axis labels to be in the same place, regardless of whether there are NaN values in the data.</p>
| 0 | 2016-08-22T05:58:59Z | 39,072,319 | <p>I found one solution:</p>
<p>replace the y1, y2, y3 arrays with <code>np.nan_to_num(y1)</code> ...etc</p>
| 0 | 2016-08-22T06:07:13Z | [
"python",
"matplotlib",
"bar-chart",
"axis-labels"
] |
Position of Matplotlib Pyplot bar chart labels not consistent with nan values | 39,072,221 | <p>I'm plotting bar charts of data that contains missing values (np.nan). It seems as though when the np.nan value appears in the last category, the x-axis ticks are positioned differently than when there are no np.nans or when the NaN values are in a different position.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
years = np.array([2011, 2012, 2013, 2014, 2015])
x = np.arange(len(years))
y1 = np.array([ 29., 10., 16., 29., np.nan])
y2 = np.array([ 29., 10., np.nan, 29., 16.])
y3 = np.array([ np.nan, 29., 29., 10., 16.])
f = plt.figure(figsize=(4,6))
ax = f.add_subplot(311)
ax.bar(x, y1, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
ax = f.add_subplot(312)
ax.bar(x, y2, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
ax = f.add_subplot(313)
ax.bar(x, y3, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/sOM4V.png" rel="nofollow"><img src="http://i.stack.imgur.com/sOM4V.png" alt="Output in jupyter notebook"></a></p>
<p>Ideally, I would like the x-axis labels to be in the same place, regardless of whether there are NaN values in the data.</p>
| 0 | 2016-08-22T05:58:59Z | 39,072,390 | <p>If you need a specific range on the plot, you can just set it explicitly. After each block add, e.g.</p>
<pre><code>ax.set_xlim(-0.5, years.size - 0.5)
</code></pre>
<p><a href="http://i.stack.imgur.com/rpgfZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/rpgfZ.png" alt="enter image description here"></a></p>
| 2 | 2016-08-22T06:12:08Z | [
"python",
"matplotlib",
"bar-chart",
"axis-labels"
] |
Uiautomator for android TV | 39,072,244 | <p>I'm using Uiautomator tool in python for android phone.
But , now I'm interested using it on android TV.</p>
<p>I did the setup for android tv same as that of android phone.
But I found that message_app.click()will not work in TV.</p>
<p>Below is my code snippet</p>
<pre><code>from uiautomator import Device
d = Device('SerialNumberOfDevice')
message_app = d(className=âandroid.widget.TextViewâ, description=âMessagingâ) #initialize message app
message_app.click()
</code></pre>
<p>I suspect that , this is because click() was implemented as "touch events" .
But , In TV we will not use "touch events " instead we use Remote controller.</p>
<p>Is there any way to implement click() for android TV.</p>
<p>Thanks in advance.</p>
| 0 | 2016-08-22T06:00:46Z | 39,402,408 | <p>On Android TV, users primarily use the DPad to navigate and click on elements.</p>
<p>You can use <a href="https://developer.android.com/reference/android/support/test/uiautomator/UiDevice.html#pressDPadDown()" rel="nofollow">UiDevice.pressDPadDown()</a> (or up, left, right, etc) to change focus and <a href="https://developer.android.com/reference/android/support/test/uiautomator/UiDevice.html#pressDPadCenter()" rel="nofollow">UiDevice.pressDPadCenter()</a> to "click".</p>
| 0 | 2016-09-09T01:16:04Z | [
"android",
"python",
"ui-automation",
"android-uiautomator"
] |
How to wrap child methods multiple times in an inheritance tree? | 39,072,269 | <p>In a framework, I often want to provide a base class that the framework user sub classes. The base class provides controlled access to the base class. One way to accomplish this is to provide unimplemented methods with different names, for example by adding an underscore as prefix:</p>
<pre><code>class Base:
def method(self, arg):
# ...
result = self._method(arg)
# ...
return result
def _method(self, arg):
raise NotImplementedError
</code></pre>
<p>However, this scheme only works for one level of inheritance. For more levels, the different method names make it hard to keep an overview of what's going on. Moreover, the framework user has to override different methods depending on the base class he chooses:</p>
<pre><code>class Base:
def method(self, arg):
# ...
result = self._method_sub(arg)
# ...
return result
def _method_sub(self, arg):
raise NotImplementedError
class Intermediate(Base):
def _method_sub(self, arg):
# ...
result = self._method_sub_sub(arg)
# ...
return result
def _method_sub_sub(self, arg):
raise NotImplementedError
</code></pre>
<p>Calling super methods does not help when the base method needs to access return values of the child method. I feel object orientation is slightly flawed, missing a <code>child</code> keyword that allows to forward calls to the child class. What solutions exist to solve this problem?</p>
| 3 | 2016-08-22T06:03:16Z | 39,074,114 | <p>Does this give you what you want?</p>
<pre><code>import abc
class Base(object):
__metaclass__ = abc.ABCMeta
def calculate(self):
result = self.doCalculate()
if 3 < result < 7: # do whatever validation you want
return result
else:
raise ValueError()
@abc.abstractmethod
def doCalculate(self):
pass
class Intermediate(Base):
__metaclass__ = abc.ABCMeta
class Leaf(Intermediate):
def doCalculate(self):
return 5
leaf = Leaf()
print leaf.calculate()
</code></pre>
| 2 | 2016-08-22T07:59:12Z | [
"python",
"python-3.x",
"inheritance",
"design-patterns",
"frameworks"
] |
How to wrap child methods multiple times in an inheritance tree? | 39,072,269 | <p>In a framework, I often want to provide a base class that the framework user sub classes. The base class provides controlled access to the base class. One way to accomplish this is to provide unimplemented methods with different names, for example by adding an underscore as prefix:</p>
<pre><code>class Base:
def method(self, arg):
# ...
result = self._method(arg)
# ...
return result
def _method(self, arg):
raise NotImplementedError
</code></pre>
<p>However, this scheme only works for one level of inheritance. For more levels, the different method names make it hard to keep an overview of what's going on. Moreover, the framework user has to override different methods depending on the base class he chooses:</p>
<pre><code>class Base:
def method(self, arg):
# ...
result = self._method_sub(arg)
# ...
return result
def _method_sub(self, arg):
raise NotImplementedError
class Intermediate(Base):
def _method_sub(self, arg):
# ...
result = self._method_sub_sub(arg)
# ...
return result
def _method_sub_sub(self, arg):
raise NotImplementedError
</code></pre>
<p>Calling super methods does not help when the base method needs to access return values of the child method. I feel object orientation is slightly flawed, missing a <code>child</code> keyword that allows to forward calls to the child class. What solutions exist to solve this problem?</p>
| 3 | 2016-08-22T06:03:16Z | 39,074,497 | <p>I think the question focuses on different points where behavior extension in an intermediate class can happen. The intermediate class obviously shall refine the "<em>control</em>" part here. </p>
<h1>1st Solution</h1>
<p>Mostly this can be done the classical way by just overriding the "safe" method - particularly when "<em>both Base and Intermediate are abstract classes provided by the framework</em>", things can be organized so.
The final "silly" implementation class which does the spade work overrides the unsafe method. </p>
<p>Think of this example:</p>
<pre><code>class DoublePositive:
def double(self, x):
assert x > 0
return self._double(x)
def _double(self, x):
raise NotImplementedError
class DoubleIntPositive(DoublePositive):
def double(self, x):
assert isinstance(x, int)
return DoublePositive.double(self, x)
class DoubleImplementation(DoubleIntPositive):
def _double(self, x):
return 2 * x
</code></pre>
<hr>
<h1>2nd Solution</h1>
<p><strong>Calling virtual child class methods</strong>, thus behavior extension at "inner" execution points in a non-classical manner, could be done by introspection in Python - by stepping down the class <code>__bases__</code> or method resolution order <code>__mro__</code> with a helper function.</p>
<p>Example:</p>
<pre><code>def child_method(cls, meth, _scls=None):
scls = _scls or meth.__self__.__class__
for base in scls.__bases__:
if base is cls:
cmeth = getattr(scls, meth.__name__, None)
if cmeth.__func__ is getattr(cls, meth.__name__, None).__func__:
return child_method(scls, meth) # next child
if cmeth:
return cmeth.__get__(meth.__self__)
for base in scls.__bases__:
r = child_method(cls, meth, base) # next base
if r is not None:
return r
if _scls is None:
raise AttributeError("child method %r missing" % meth.__name__)
return None
class Base(object):
def double(self, x):
assert x > 0
return Base._double(self, x)
def _double(self, x):
return child_method(Base, self._double)(x)
class Inter(Base):
def _double(self, x):
assert isinstance(x, float)
return child_method(Inter, self._double)(x)
class Impl(Inter):
def _double(self, x):
return 2.0 * x
</code></pre>
<p>The helper function <code>child_method()</code> here is thus kind of opposite of Python's <code>super()</code>.</p>
<hr>
<h1>3rd solution</h1>
<p>If calls should be chainable flexibly, things can be organized as a kind of handler chain explicitly. Think of <code>self.addHandler(self.__privmeth)</code> in the <code>__init__()</code> chain - or even via a tricky meta class. Study e.g. the urllib2 handler chains.</p>
| 1 | 2016-08-22T08:21:09Z | [
"python",
"python-3.x",
"inheritance",
"design-patterns",
"frameworks"
] |
Tkinter : How to change position of text on image | 39,072,285 | <p>I have developed some application on my laptop with python and tkinter. Then, I was stuck at some point. Question is : how can I change text position on image.</p>
<pre><code>import tkinter as tk
from PIL import Image, ImageTk
path_to_pic = "....."
root = tk.Tk()
pic = Image.open(path_to_pic)
tkpic = ImageTk.PhotoImage(pic)
tk.Label(root, image = tkpic, text = ".....", compound = tk.CENTER).pack()
root.mainloop()
</code></pre>
<p>This shows that my text appears on the picture, only on the center. I would like to move my text little by little and find best position. Do you know any solution or similar way to achieve this ? </p>
| 0 | 2016-08-22T06:04:16Z | 39,072,871 | <p>You can move text horizontally and vertically by adding spaces and '\n's respectively, to any side(s) of the text you wish:</p>
<pre><code>text = "caption \n\n\n\n\n\n\n"
</code></pre>
<p>This will put "caption" at the top left of the text.</p>
| 0 | 2016-08-22T06:46:50Z | [
"python",
"tkinter"
] |
Implement comparison operator for Enum type in python3 | 39,072,301 | <p>I'm really beginner in Python, so please forgive me if this is something obvious. </p>
<p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p>
<pre><code>import enum
class AB(enum.Enum):
a=1
b=2
c=3
d=4
e=5
@classmethod
def le(cls, a, b):
lst = [cls.a, cls.b, cls.c, cls.d, cls.e]
ia = lst.index(a)
ib = lst.index(b)
return(ia <= ib)
if AB.le(AB.a, AB.b):
print('Do this')
else:
print('Do that')
</code></pre>
<p>Now my question is how to code the comparison operator <code>__le__</code> so that I can run the below code instead? </p>
<pre><code>mem1 = AB.a
mem2 = AB.c
if mem1 <= mem2 :
print('Do this')
else:
print('Do that')
</code></pre>
| 2 | 2016-08-22T06:05:28Z | 39,072,454 | <p>The <code>__le__</code> method should be called as a member function of the LHS operand and takes the RHS operand as its parameter.</p>
<p>However it's not clear from your code which member variables of an <code>AB</code> object should be used in the comparison, so I can't really write the code for you.</p>
<p>Roughly it should look something like:</p>
<pre><code>def __le__(self, b):
return # do something with self and b to figure out which one would be <=
</code></pre>
| 1 | 2016-08-22T06:17:19Z | [
"python",
"python-3.x",
"enums"
] |
Implement comparison operator for Enum type in python3 | 39,072,301 | <p>I'm really beginner in Python, so please forgive me if this is something obvious. </p>
<p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p>
<pre><code>import enum
class AB(enum.Enum):
a=1
b=2
c=3
d=4
e=5
@classmethod
def le(cls, a, b):
lst = [cls.a, cls.b, cls.c, cls.d, cls.e]
ia = lst.index(a)
ib = lst.index(b)
return(ia <= ib)
if AB.le(AB.a, AB.b):
print('Do this')
else:
print('Do that')
</code></pre>
<p>Now my question is how to code the comparison operator <code>__le__</code> so that I can run the below code instead? </p>
<pre><code>mem1 = AB.a
mem2 = AB.c
if mem1 <= mem2 :
print('Do this')
else:
print('Do that')
</code></pre>
| 2 | 2016-08-22T06:05:28Z | 39,072,494 | <p>Thanks to @Rawing and @machine yearning,</p>
<pre><code>import enum
class AB(enum.Enum):
a=1
b=2
c=3
d=4
e=5
def __le__(self, other):
return(self.value <= other.value)
if AB.c <= AB.d:
print('Do this')
else:
print('Do that')
</code></pre>
| 0 | 2016-08-22T06:20:38Z | [
"python",
"python-3.x",
"enums"
] |
Implement comparison operator for Enum type in python3 | 39,072,301 | <p>I'm really beginner in Python, so please forgive me if this is something obvious. </p>
<p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p>
<pre><code>import enum
class AB(enum.Enum):
a=1
b=2
c=3
d=4
e=5
@classmethod
def le(cls, a, b):
lst = [cls.a, cls.b, cls.c, cls.d, cls.e]
ia = lst.index(a)
ib = lst.index(b)
return(ia <= ib)
if AB.le(AB.a, AB.b):
print('Do this')
else:
print('Do that')
</code></pre>
<p>Now my question is how to code the comparison operator <code>__le__</code> so that I can run the below code instead? </p>
<pre><code>mem1 = AB.a
mem2 = AB.c
if mem1 <= mem2 :
print('Do this')
else:
print('Do that')
</code></pre>
| 2 | 2016-08-22T06:05:28Z | 39,072,500 | <p><code>Enum</code> subclasses are somewhat special in that all enumeration values become <em>instances</em> of the class (with a few tweaks). This does mean you can 'just' define a normal method on the <code>Enum</code> subclass and they'll be available on each enumeration value.</p>
<p>This applies to special methods like <code>object.__le__()</code> too; just define it as a regular method, <em>not</em> a <code>classmethod</code>:</p>
<pre><code>class AB(enum.Enum):
def __le__(self, b):
return self.value <= b.value
a = 1
b = 2
c = 3
d = 4
e = 5
</code></pre>
<p>Note that I used the <a href="https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes" rel="nofollow">instance attribute <code>.value</code></a>, just like you can do <code>AB.a.value</code>.</p>
<p>You could also use the <a href="https://docs.python.org/3/library/enum.html#intenum" rel="nofollow"><code>IntEnum</code> class</a>; that makes each enumeration value a subclass of <code>int</code>, and they can be compared <em>naturally</em>:</p>
<pre><code>class AB(enum.IntEnum):
a = 1
b = 2
c = 3
d = 4
e = 5
</code></pre>
<p>Demo:</p>
<pre><code>>>> import enum
>>> class AB(enum.Enum):
... def __le__(self, b):
... return self.value <= b.value
... a = 1
... b = 2
... c = 3
... d = 4
... e = 5
...
>>> AB.a <= AB.b
True
>>> AB.b <= AB.a
False
>>> AB.a < AB.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: AB() < AB()
</code></pre>
<p>and using <code>IntEnum</code> as the base:</p>
<pre><code>>>> class AB(enum.IntEnum):
... a = 1
... b = 2
... c = 3
... d = 4
... e = 5
...
>>> AB.a <= AB.b
True
>>> AB.b >= AB.a
True
>>> AB.b > AB.a
True
>>> AB.a + AB.b
3
</code></pre>
| 3 | 2016-08-22T06:20:47Z | [
"python",
"python-3.x",
"enums"
] |
Display wrong Result in different Excel sheet Python | 39,072,514 | <p>I wish to have 1 python file that can display the results in different Excel sheet, now I able to list out 3 tabs with 3 worksheets,but for/if loop at second sheet that show me empty result. I able to get the results correct in first sheet but not second sheet.</p>
<pre><code>for module in data:
#Go to first sheet
str1 = ''.join(module)
if len(module)<102:
pass
else:
worksheet1.write_row(row, col, module)
row += 1
if str1.isupper():
pass
else:
worksheet1.write_row(row, col, module)
row += 1
#Go to second sheet
#Show empty result in second sheet
MY_MODULE=module[0].split('_') #Module Name
if 1<len(MY_MODULE)<4: #Field Number in Module Name
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
if len(MY_MODULE[0])==3: #Length in Scrum Field
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
if MY_MODULE[0]in ('TPI','SCN','ARR','FUN','MIO','CLK','HTD','SIO','PTH'): #Name in Scrum Field
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
if 2<len(MY_MODULE[1])<9: #Length in Module Name Field
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
</code></pre>
| -9 | 2016-08-22T06:21:46Z | 39,162,563 | <pre><code>if len(MY_MODULE[0])==3: #Length in Scrum Field
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
if MY_MODULE[0]in ('TPI','SCN','ARR','FUN','MIO','CLK','HTD','SIO','PTH'): #Name in Scrum Field
pass
else:
worksheet2.write_row(row, col, MY_MODULE)
row += 1
</code></pre>
<p>Here two if conditions are actually same. Because in last if condition length of all given input string is 3. So you are given two same if conditions and you are printing same result in two times at else condition. </p>
| 1 | 2016-08-26T09:09:14Z | [
"python",
"python-3.x",
"worksheet",
"xlsxwriter"
] |
Sending values from one python script to another from different computer | 39,072,750 | <p>So, I have 2 raspberry pi's. I need to be able to transfer objects (simple single int value) across from one to the other.</p>
<p>The programs are python. One is basically just acting as a controller for the other.</p>
<p>Will the client/ server model work for something like that (from multiprocessing module), or is that only for programs running on the same computer?</p>
<p>Also, I'll end up having the single controller controlling multiple pi's, and the WiFi will perhaps not reach long enough. Is it possible to send like a chain link from the controller to a pi to another pi? I imagine I would just set up a server on the client and pass them that way? (my client/ server knowledge is pretty limited).</p>
<p>Basically, what module/ how do I "trade" object values across python programs on different computers over WiFi?</p>
| -1 | 2016-08-22T06:39:58Z | 39,073,259 | <p>I would suggest you google the python socket module: <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a></p>
<p>I used it t send values from a server to my android device, so I guess it should work with two rasbberries .
There is a good youtube tutorial about socket servers:
<a href="https://www.youtube.com/watch?v=LJTaPaFGmM4" rel="nofollow">https://www.youtube.com/watch?v=LJTaPaFGmM4</a></p>
| 0 | 2016-08-22T07:09:22Z | [
"python",
"raspberry-pi3"
] |
how to draw a font's glyphs using svg? | 39,072,794 | <p>I'm trying to draw all glyphs of a ttf font file.
I have created a XML file using TTX and parsed it with python to write html file and create SVG. but SVG doesn't support curves with more than two control points so the outlines are not what they should be.</p>
<p>How can I fix this? or is there any other way to draw glyph outlines?</p>
<p>this is the html code I use:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<meta charset="UTF-8">
<title>font</title>
</head>
<body>
<svg width="800" height="800" viewbox="0 0 2000 300" overflow="visible">
<g transform="scale(1,-1)">
<path d="M255 168 C221 168,171 176,152 187 Q102 212,102 272 Q102 331,156 385 C204 433,351 493,414 493 C456 493,503 464,503 434 Q503 393,451 352 C431 336,386 310,362 303 L355 303 Q345 303,339 310 Q333 317,332 328 C332 334,340 348,351 350 Q374 356,412 383 Q456 412,456 434 C456 440,440 446,426 446 C412 446,381 442,358 437 C347 435,323 429,311 425 C242 399,149 316,149 272 C149 240,200 215,244 215 Q293 215,359 229 Q397 237,411 240 Q433 246,465 257 C478 260,502 268,524 276 L534 279 Q544 279,551 272 Q556 264,556 255 C556 248,550 238,541 233 L415 188 Q333 156,281 128 Q209 91,172 51 Q139 16,122 -17 Q107 -51,107 -80 Q107 -129,151 -162 Q193 -191,257 -191 L478 -88 Q484 -81,494 -80 C502 -80,519 -95,519 -106 Q519 -114,512 -121 Q460 -179,389 -211 Q326 -239,261 -239 C176 -239,59 -150,59 -80 C59 -44,96 38,137 83 Q159 107,190 128 C202 138,237 159,255 168" stroke="black" fill="transparent"></path>
</svg>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="http://i.stack.imgur.com/L072U.jpg" rel="nofollow">and this is what the glyph outline should look like(from fontLab Studio)</a></p>
| 0 | 2016-08-22T06:43:02Z | 39,085,693 | <p>Truetype fonts don't use cubic beziers. They use quadratic beziers. So if you see a sequence of points: "on, off, off on", that is not a cubic bezier with two end points and two control points. That is actually a quadratic bezier with two endpoints ("on curve" points), two control points ("off curve" points), and a a dropped middle "on" point. i.e.:</p>
<pre><code>on off (on) off on
</code></pre>
<p>To reconstruct the middle on point, you just need to find the midpoint between the two "off" control points.</p>
<p>So, for example, that first "cubic" bezier segment:</p>
<pre><code>C 221,168, 171,176, 152,187
</code></pre>
<p>is probably meant to be two quadratic bezier curves:</p>
<pre><code>Q 221,168, 191,172
Q 171,176, 152,187
</code></pre>
<p>Where the new endpoint ("on curve" point) (191,172) = ((221+171) / 2, (168+176) / 2).</p>
<p><em>Note that I am guessing here, because I don't know what the original coordinates and flags were in the file.</em></p>
<p>If you have a longer sequence of "off curve" points, then you will need to insert extra "on curve" points. For example at one point, I can see a sequence of four off points, so you will need to insert three on points.</p>
<pre><code>on off (on) off (on) off (on) off on
</code></pre>
<p>Again, in each case, just calculate the point halfway between the two neighbouring off points.</p>
<p><strong>Update</strong></p>
<p>So for example, here is the data for a glyph, dumped from a TTF file.</p>
<pre><code> Glyph 54: off = 0x00001E36, len = 210
numberOfContours: 1
xMin: 54
yMin: -12
xMax: 502
yMax: 712
EndPoints
---------
0: 44
Coordinates
-----------
0: Rel ( 431, 578) -> Abs ( 431, 578) on
1: Rel ( -60, 40) -> Abs ( 371, 618)
2: Rel ( -53, 0) -> Abs ( 318, 618) on
3: Rel ( -43, 0) -> Abs ( 275, 618)
4: Rel ( -48, -42) -> Abs ( 227, 576)
5: Rel ( 0, -32) -> Abs ( 227, 544) on
6: Rel ( 0, -22) -> Abs ( 227, 522)
7: Rel ( 31, -42) -> Abs ( 258, 480)
8: Rel ( 23, -20) -> Abs ( 281, 460) on
9: Rel ( 77, -62) -> Abs ( 358, 398) on
10: Rel ( 52, -42) -> Abs ( 410, 356)
11: Rel ( 59, -64) -> Abs ( 469, 292)
12: Rel ( 33, -72) -> Abs ( 502, 220)
13: Rel ( 0, -42) -> Abs ( 502, 178) on
14: Rel ( 0, -44) -> Abs ( 502, 134)
15: Rel ( -58, -90) -> Abs ( 444, 44)
16: Rel ( -109, -56) -> Abs ( 335, -12)
17: Rel ( -75, 0) -> Abs ( 260, -12) on
18: Rel ( -57, 0) -> Abs ( 203, -12)
19: Rel ( -112, 36) -> Abs ( 91, 24)
20: Rel ( -37, 34) -> Abs ( 54, 58) on
21: Rel ( 51, 80) -> Abs ( 105, 138) on
22: Rel ( 33, -24) -> Abs ( 138, 114)
23: Rel ( 69, -32) -> Abs ( 207, 82)
24: Rel ( 41, 0) -> Abs ( 248, 82) on
25: Rel ( 47, 0) -> Abs ( 295, 82)
26: Rel ( 62, 51) -> Abs ( 357, 133)
27: Rel ( 0, 46) -> Abs ( 357, 179) on
28: Rel ( 0, 34) -> Abs ( 357, 213)
29: Rel ( -42, 57) -> Abs ( 315, 270)
30: Rel ( -39, 30) -> Abs ( 276, 300) on
31: Rel ( -69, 51) -> Abs ( 207, 351) on
32: Rel ( -58, 49) -> Abs ( 149, 400) on
33: Rel ( -14, 13) -> Abs ( 135, 413)
34: Rel ( -33, 42) -> Abs ( 102, 455)
35: Rel ( -20, 53) -> Abs ( 82, 508)
36: Rel ( 0, 34) -> Abs ( 82, 542) on
37: Rel ( 0, 45) -> Abs ( 82, 587)
38: Rel ( 42, 59) -> Abs ( 124, 646)
39: Rel ( 41, 32) -> Abs ( 165, 678)
40: Rel ( 78, 34) -> Abs ( 243, 712)
41: Rel ( 61, 0) -> Abs ( 304, 712) on
42: Rel ( 56, 0) -> Abs ( 360, 712)
43: Rel ( 95, -34) -> Abs ( 455, 678)
44: Rel ( 26, -27) -> Abs ( 481, 651) on
</code></pre>
<p>I've added "on" to all the points whose flags (not shown here) indicate that they are meant to be on-curve points.</p>
<p>So if we plot the on-curve points (green) and the off-curve points (red) we get this:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.on {
fill: green;
}
.off {
fill: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- 54,-12 502,712 -->
<svg width="500px" height="500px" viewBox="54 -12 448 724" overflow="visible">
<g transform="translate(0,712) scale(1,-1)">
<g class="points">
<circle cx="431" cy="578" r="5" class="on"/>
<circle cx="371" cy="618" r="5" class="off"/>
<circle cx="318" cy="618" r="5" class="on"/>
<circle cx="275" cy="618" r="5" class="off"/>
<circle cx="227" cy="576" r="5" class="off"/>
<circle cx="227" cy="544" r="5" class="on"/>
<circle cx="227" cy="522" r="5" class="off"/>
<circle cx="258" cy="480" r="5" class="off"/>
<circle cx="281" cy="460" r="5" class="on"/>
<circle cx="358" cy="398" r="5" class="on"/>
<circle cx="410" cy="356" r="5" class="off"/>
<circle cx="469" cy="292" r="5" class="off"/>
<circle cx="502" cy="220" r="5" class="off"/>
<circle cx="502" cy="178" r="5" class="on"/>
<circle cx="502" cy="134" r="5" class="off"/>
<circle cx="444" cy=" 44" r="5" class="off"/>
<circle cx="335" cy="-12" r="5" class="off"/>
<circle cx="260" cy="-12" r="5" class="on"/>
<circle cx="203" cy="-12" r="5" class="off"/>
<circle cx=" 91" cy=" 24" r="5" class="off"/>
<circle cx=" 54" cy=" 58" r="5" class="on"/>
<circle cx="105" cy="138" r="5" class="on"/>
<circle cx="138" cy="114" r="5" class="off"/>
<circle cx="207" cy=" 82" r="5" class="off"/>
<circle cx="248" cy=" 82" r="5" class="on"/>
<circle cx="295" cy=" 82" r="5" class="off"/>
<circle cx="357" cy="133" r="5" class="off"/>
<circle cx="357" cy="179" r="5" class="on"/>
<circle cx="357" cy="213" r="5" class="off"/>
<circle cx="315" cy="270" r="5" class="off"/>
<circle cx="276" cy="300" r="5" class="on"/>
<circle cx="207" cy="351" r="5" class="on"/>
<circle cx="149" cy="400" r="5" class="on"/>
<circle cx="135" cy="413" r="5" class="off"/>
<circle cx="102" cy="455" r="5" class="off"/>
<circle cx=" 82" cy="508" r="5" class="off"/>
<circle cx=" 82" cy="542" r="5" class="on"/>
<circle cx=" 82" cy="587" r="5" class="off"/>
<circle cx="124" cy="646" r="5" class="off"/>
<circle cx="165" cy="678" r="5" class="off"/>
<circle cx="243" cy="712" r="5" class="off"/>
<circle cx="304" cy="712" r="5" class="on"/>
<circle cx="360" cy="712" r="5" class="off"/>
<circle cx="455" cy="678" r="5" class="off"/>
<circle cx="481" cy="651" r="5" class="on"/>
</g>
</g>
</svg></code></pre>
</div>
</div>
</p>
<p>Now to the path. We use quadratic bezier (Q) path commands. As stated above, if we have two adjacent off-curve points, we insert a calculated on-curve point. The inserted point is just the average of the two off-curve points. If there are two adjacent on-curve points, we insert a line (L) instead.</p>
<p>That gives us the following result. The coords in the left column are the original on/off points. And the coords in the right column are the inserted calculated points.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.on {
fill: green;
}
.off {
fill: red;
}
path.outline {
fill: none;
stroke: grey;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- 54,-12 502,712 -->
<svg width="500px" height="500px" viewBox="54 -12 448 724" overflow="visible">
<g transform="translate(0,712) scale(1,-1)">
<path class="outline"
d="M 431, 578
Q 371, 618
318, 618
Q 275, 618 251,597
Q 227, 576
227, 544
Q 227, 522 243.5,501
Q 258, 480
281, 460
L 358, 398
Q 410, 356 439.5,324
Q 469, 292 485.5,256
Q 502, 220
502, 178
Q 502, 134 473,89
Q 444, 44 389.5,16
Q 335, -12
260, -12
Q 203, -12 147,6
Q 91, 24
54, 58
L 105, 138
Q 138, 114 172.5,98
Q 207, 82
248, 82
Q 295, 82 325,107.5
Q 357, 133
357, 179
Q 357, 213 336,240.5
Q 315, 270
276, 300
L 207, 351
L 149, 400
Q 135, 413 118.5,434
Q 102, 455 92,481.5
Q 82, 508
82, 542
Q 82, 587 103,616.5
Q 124, 646 144.5,662
Q 165, 678 204,695
Q 243, 712
304, 712
Q 360, 712 407.5,695
Q 455, 678 468,664.5
L 481, 651
Z"/>
<g class="points">
<circle cx="431" cy="578" r="5" class="on"/>
<circle cx="371" cy="618" r="5" class="off"/>
<circle cx="318" cy="618" r="5" class="on"/>
<circle cx="275" cy="618" r="5" class="off"/>
<circle cx="227" cy="576" r="5" class="off"/>
<circle cx="227" cy="544" r="5" class="on"/>
<circle cx="227" cy="522" r="5" class="off"/>
<circle cx="258" cy="480" r="5" class="off"/>
<circle cx="281" cy="460" r="5" class="on"/>
<circle cx="358" cy="398" r="5" class="on"/>
<circle cx="410" cy="356" r="5" class="off"/>
<circle cx="469" cy="292" r="5" class="off"/>
<circle cx="502" cy="220" r="5" class="off"/>
<circle cx="502" cy="178" r="5" class="on"/>
<circle cx="502" cy="134" r="5" class="off"/>
<circle cx="444" cy=" 44" r="5" class="off"/>
<circle cx="335" cy="-12" r="5" class="off"/>
<circle cx="260" cy="-12" r="5" class="on"/>
<circle cx="203" cy="-12" r="5" class="off"/>
<circle cx=" 91" cy=" 24" r="5" class="off"/>
<circle cx=" 54" cy=" 58" r="5" class="on"/>
<circle cx="105" cy="138" r="5" class="on"/>
<circle cx="138" cy="114" r="5" class="off"/>
<circle cx="207" cy=" 82" r="5" class="off"/>
<circle cx="248" cy=" 82" r="5" class="on"/>
<circle cx="295" cy=" 82" r="5" class="off"/>
<circle cx="357" cy="133" r="5" class="off"/>
<circle cx="357" cy="179" r="5" class="on"/>
<circle cx="357" cy="213" r="5" class="off"/>
<circle cx="315" cy="270" r="5" class="off"/>
<circle cx="276" cy="300" r="5" class="on"/>
<circle cx="207" cy="351" r="5" class="on"/>
<circle cx="149" cy="400" r="5" class="on"/>
<circle cx="135" cy="413" r="5" class="off"/>
<circle cx="102" cy="455" r="5" class="off"/>
<circle cx=" 82" cy="508" r="5" class="off"/>
<circle cx=" 82" cy="542" r="5" class="on"/>
<circle cx=" 82" cy="587" r="5" class="off"/>
<circle cx="124" cy="646" r="5" class="off"/>
<circle cx="165" cy="678" r="5" class="off"/>
<circle cx="243" cy="712" r="5" class="off"/>
<circle cx="304" cy="712" r="5" class="on"/>
<circle cx="360" cy="712" r="5" class="off"/>
<circle cx="455" cy="678" r="5" class="off"/>
<circle cx="481" cy="651" r="5" class="on"/>
</g>
</g>
</svg></code></pre>
</div>
</div>
</p>
<p>If we just draw the shape in black we get a glyph that looks correct.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="100px" height="100px" viewBox="54 -12 448 724" overflow="visible">
<g transform="translate(0,712) scale(1,-1)">
<path d="M 431, 578
Q 371, 618
318, 618
Q 275, 618 251,597
Q 227, 576
227, 544
Q 227, 522 243.5,501
Q 258, 480
281, 460
L 358, 398
Q 410, 356 439.5,324
Q 469, 292 485.5,256
Q 502, 220
502, 178
Q 502, 134 473,89
Q 444, 44 389.5,16
Q 335, -12
260, -12
Q 203, -12 147,6
Q 91, 24
54, 58
L 105, 138
Q 138, 114 172.5,98
Q 207, 82
248, 82
Q 295, 82 325,107.5
Q 357, 133
357, 179
Q 357, 213 336,240.5
Q 315, 270
276, 300
L 207, 351
L 149, 400
Q 135, 413 118.5,434
Q 102, 455 92,481.5
Q 82, 508
82, 542
Q 82, 587 103,616.5
Q 124, 646 144.5,662
Q 165, 678 204,695
Q 243, 712
304, 712
Q 360, 712 407.5,695
Q 455, 678 468,664.5
L 481, 651
Z"/>
</g>
</svg></code></pre>
</div>
</div>
</p>
| 1 | 2016-08-22T17:46:36Z | [
"python",
"html",
"svg",
"fonts",
"bezier-curve"
] |
How to solve " django.db.utils.OperationalError: FATAL: password authentication failed for user "Oeloun-pc" " in Pycharm Windows? | 39,072,802 | <p>Below is my screenshot of PyCharm including settings.py and pg_hba.conf file.</p>
<p>PyCharm with pg_hba.conf screen:</p>
<p><a href="http://i.stack.imgur.com/tM6YQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/tM6YQ.png" alt="enter image description here"></a></p>
| 1 | 2016-08-22T06:43:25Z | 39,073,136 | <p>Use </p>
<pre><code>'USER': 'admin',
</code></pre>
<p>instead of </p>
<pre><code>'USERNAME': 'admin',
</code></pre>
| 0 | 2016-08-22T07:02:48Z | [
"python",
"django",
"postgresql"
] |
Parse out part of URL using regex in Python | 39,073,067 | <p>I want to parse out a part of URL using regex operation. This might be old question. But I am new to regex and searched so much for my requirement and not able to find it. I know ParseURL can be used here. But my URLs are not properly structured to use that. Suppose my URL is as follows,</p>
<pre><code>url = https://www.sitename.com/&q=To+Be+Parsed+out&oq=Dont+Need+to+be+parsed
</code></pre>
<p>Here I want to find out when &q= occurs and parse out until & occurs next. I want to remove + or any special characters in the middle. The output should be,</p>
<pre><code>To Be Parsed out
</code></pre>
<p>Also if there is no match, the original URL should be returned.</p>
<p>I have tried the following,</p>
<pre><code>re.search('q=?([^&]+)&',url).group(0)
</code></pre>
<p>this returns,</p>
<pre><code>&q=To+Be+Parsed+out&oq=Dont+Need+to+be+parsed
</code></pre>
<p>Can anybody help me in parsing this out. Thanks</p>
| 0 | 2016-08-22T06:59:10Z | 39,073,163 | <p>You can use <code>re.search()</code> to get the desired substring and then replace all <code>+</code> with spaces with <code>str.replace()</code>:</p>
<pre><code>re.search(r'/&q=([^&]*)', url).group(1).replace('+', ' ')
</code></pre>
<ul>
<li><code>re.search(r'/&q=([^&]*)', url).group(1)</code> gets the desired portion and <code>replace('+', ' ')</code> does the replaements</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code>In [56]: url
Out[56]: 'https://www.sitename.com/&q=To+Be+Parsed+out&oq=Dont+Need+to+be+parsed'
In [57]: re.search(r'/&q=([^&]*)', url).group(1).replace('+', ' ')
Out[57]: 'To Be Parsed out'
</code></pre>
<hr>
<p>In case when there is no match, catch the <code>AttributeError</code> exception raised by <code>re.search.group()</code> e.g.:</p>
<pre><code>try:
out = re.search(r'/&q=([^&]*)', url).group(1).replace('+', ' ')
except AttributeError:
## No match, do what you want
</code></pre>
| 3 | 2016-08-22T07:04:23Z | [
"python",
"regex",
"python-2.7"
] |
storing and retriving lists from files | 39,073,072 | <p>I have a very big list of lists. One of my programs does this :</p>
<pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form
with open (file_name,'w') as out:
out.write (str(power_time_array))
</code></pre>
<p>Now another independent script need to read this list of lists back.</p>
<p>How do I do this ?</p>
<p>What I have tried :</p>
<pre><code>with open (file_name,'r') as app_trc_file :
power_trace_of_application.append (app_trc_file.read())
</code></pre>
<p>Note : <code>power_trace_application</code> is a list of list of lists.</p>
<p>This stores it as a list with one element as a huge string.</p>
<p><strong>How does one efficiently store and retrieve big lists or list of lists from files in python ?</strong></p>
| 3 | 2016-08-22T06:59:42Z | 39,073,217 | <p>You can serialize your list to json and deserialize it back. This really doesn't change anything in representation, your list is already valid json:</p>
<pre><code>import json
power_time_array = [[1,2,3],[1,2,3]] # In a short form
with open (file_name,'w') as out:
json.dump(power_time_array, out)
</code></pre>
<p>and then just read it back:</p>
<pre><code>with open (file_name,'r') as app_trc_file :
power_trace_of_application = json.load(app_trc_file)
</code></pre>
<p>For speed, you can use a json library with C backend (like <em>ujson</em>). And this works with custom objects too.</p>
| 3 | 2016-08-22T07:07:12Z | [
"python",
"list"
] |
storing and retriving lists from files | 39,073,072 | <p>I have a very big list of lists. One of my programs does this :</p>
<pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form
with open (file_name,'w') as out:
out.write (str(power_time_array))
</code></pre>
<p>Now another independent script need to read this list of lists back.</p>
<p>How do I do this ?</p>
<p>What I have tried :</p>
<pre><code>with open (file_name,'r') as app_trc_file :
power_trace_of_application.append (app_trc_file.read())
</code></pre>
<p>Note : <code>power_trace_application</code> is a list of list of lists.</p>
<p>This stores it as a list with one element as a huge string.</p>
<p><strong>How does one efficiently store and retrieve big lists or list of lists from files in python ?</strong></p>
| 3 | 2016-08-22T06:59:42Z | 39,073,252 | <p>Use <a href="https://docs.python.org/2.7/library/json.html" rel="nofollow">Json</a> library to efficiently read and write structured information (in the form of JSON) to a text file.</p>
<ul>
<li>To write data on the file, use <a href="https://docs.python.org/2.7/library/json.html#json.load" rel="nofollow">json.dump()</a> , and</li>
<li>To retrieve json data from file, use <a href="https://docs.python.org/2.7/library/json.html#json.dump" rel="nofollow">json.load()</a></li>
</ul>
| 3 | 2016-08-22T07:09:02Z | [
"python",
"list"
] |
storing and retriving lists from files | 39,073,072 | <p>I have a very big list of lists. One of my programs does this :</p>
<pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form
with open (file_name,'w') as out:
out.write (str(power_time_array))
</code></pre>
<p>Now another independent script need to read this list of lists back.</p>
<p>How do I do this ?</p>
<p>What I have tried :</p>
<pre><code>with open (file_name,'r') as app_trc_file :
power_trace_of_application.append (app_trc_file.read())
</code></pre>
<p>Note : <code>power_trace_application</code> is a list of list of lists.</p>
<p>This stores it as a list with one element as a huge string.</p>
<p><strong>How does one efficiently store and retrieve big lists or list of lists from files in python ?</strong></p>
| 3 | 2016-08-22T06:59:42Z | 39,073,893 | <p>It will be faster:</p>
<pre><code>from ast import literal_eval
power_time_array = [[1,2,3],[1,2,3]]
with open(file_name, 'w') as out:
out.write(repr(power_time_array))
with open(file_name,'r') as app_trc_file:
power_trace_of_application.append(literal_eval(app_trc_file.read()))
</code></pre>
| 0 | 2016-08-22T07:44:59Z | [
"python",
"list"
] |
How to adress data imported with pandas? | 39,073,123 | <p>I am using pandas to import some .dta file and numpy/sklearn to do some statistics on the set. I call the data <code>sample</code> I do the following: </p>
<pre><code># import neccessary packages
import pandas as pd
import numpy as np
import sklearn as skl
# import data and give a little overview (col = var1-var5, 20 rows)
sample = pd.read_stata('sample_data.dta')
print('variables in dataset')
print(sample.dtypes)
print('first 5 rows and all cols')
print(sample[0:5])
# generate a new var
var6 = sample.var1/sample.var3
</code></pre>
<p>I get an error if I adress a variable by its name directly (<code>var1</code> vs. <code>sample.var1</code>). I find it a little tedious to always include <code>sample.</code>. Is there any nice way to call the variables directly by their name? </p>
| 4 | 2016-08-22T07:01:57Z | 39,073,307 | <p>See this contrived example. Usually I don't like messing with <code>locals()</code> and <code>globals()</code> but I don't see a cleaner way:</p>
<pre><code>class A:
def __init__(self):
self.var1 = 1
self.var2 = 2
obj = A()
locals().update(obj.__dict__)
print(var1)
print(var2)
>> 1
2
</code></pre>
<p>Since you are working with a dataframe you will have to loop through <code>df.columns</code> instead of <code>__dict__</code>. Your code will be something along the lines of:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':[1]})
for col in df.columns:
locals().update({col: df[col]})
print(a)
>> 0 1
Name: a, dtype: int64
</code></pre>
<p>You should be very careful when doing this , as this will overwrite any variable you may have already defined with the same name, eg:</p>
<pre><code>import pandas as pd
a = 7
print(a)
>> 7
df = pd.DataFrame({'a':[1]})
for col in df.columns:
locals().update({col: df[col]})
print(a)
>> 0 1
Name: a, dtype: int64
</code></pre>
| 4 | 2016-08-22T07:12:04Z | [
"python",
"variables",
"pandas",
"error-handling"
] |
python 3.5 tkinter.listbox change size | 39,073,213 | <p>Could anyone advise me what's wrong go with the following code? I try to build a tkinker.listbox with dimensions can be changed with .config command, yet failed. Instead, it produce the error of "AttributeError: 'MovListbox' object has no attribute 'tk'" The code is attached below for your reference. </p>
<p>Many thanks. </p>
<pre><code>import tkinter
def test():
root = tkinter.Tk()
list = [' 1','2',' 3','4','5',' 6','7','8',' 9','10']
a = MovListbox(root, list)
a._setup_style(200, 200, EXTENDED)
class MovListbox(tkinter.Listbox):
def __init__(self, master=None, inputlist=None):
# super(MovListbox, self).__init__()
global NewsClassify_catList
NewsClassify_catList = tkinter.Listbox(master)
NewsClassify_catList.grid(row = 0 , column = 0, columnspan=2, sticky=N)
'''populate the news category onto the listbox'''
for i in range (0, inputlist.__len__()):
NewsClassify_catList.insert(END, inputlist[i])
master.mainloop()
def _setup_style(self, height=100, width=100, mode=EXTENDED):
self.config(height=height, width=width, selectmode=mode)
if __name__ == '__main__':
test()
</code></pre>
| 0 | 2016-08-22T07:07:06Z | 39,074,442 | <p>I've made a few modifications to your code; it's probably not exactly what you want, but you should find it helpful.</p>
<p>The Listbox width and height options are not pixel measurements; they specify dimensions in terms of characters, so <code>height=12</code> makes the Listbox 12 text lines high, and <code>width=40</code> makes the Listbox 40 characters wide. </p>
<pre><code>import tkinter as tk
def test():
root = tk.Tk()
lst = [' 1', '2', ' 3', '4', '5', ' 6', '7', '8', ' 9', '10']
a = MovListbox(root, lst)
a.grid(row=0, column=0, columnspan=2, sticky=tk.N)
a.setup_style(12, 40, tk.EXTENDED)
root.mainloop()
class MovListbox(tk.Listbox):
def __init__(self, master=None, inputlist=None):
super(MovListbox, self).__init__(master=master)
# Populate the news category onto the listbox
for item in inputlist:
self.insert(tk.END, item)
def setup_style(self, height=10, width=20, mode=tk.EXTENDED):
self.config(height=height, width=width, selectmode=mode)
if __name__ == '__main__':
test()
</code></pre>
<p>If you like, you can remove the <code>a.setup_style(12, 40, tk.EXTENDED)</code> call in <code>test()</code> and instead do</p>
<pre><code>self.setup_style(12, 40, tk.EXTENDED)
</code></pre>
<p>at the end of the <code>MovListbox.__init__()</code> method.</p>
<p>I've changed your <code>list</code> variable to <code>lst</code>. <code>list</code> is not a good choice for a variable name as that shadows the built-in <code>list</code> type, which can be confusing, and it can also lead to mysterious bugs.</p>
<hr>
<p>The <code>super</code> built-in function is used to access methods of the parent class. From <a href="https://docs.python.org/3/library/functions.html#super" rel="nofollow">the docs</a>:</p>
<blockquote>
<p><strong>super([type[, object-or-type]])</strong></p>
<p>Return a proxy object that delegates method calls to a parent or
sibling class of type. This is useful for accessing inherited methods
that have been overridden in a class. The search order is the same as that
used by getattr() except that the type itself is skipped. </p>
</blockquote>
<p>Thus</p>
<pre><code>super(MovListbox, self).__init__(master=master)
</code></pre>
<p>says to call the <code>__init__</code> method of the parent class of the MovListbox class, in other words, the <code>tk.Listbox.__init__</code> method. We need to do this because MovListbox is derived from tk.Listbox and we need all the usual Listbox stuff to be set up for our MovListbox instance before we start doing extra stuff with it, like inserting the strings from <code>inputlist</code>.</p>
<p>If a derived class doesn't define its own <code>__init__</code> method then the <code>__init__</code> method from the parent is called automatically when you create an instance of the derived class. But because we've defined an <code>__init__</code> method for MovListbox that new <code>__init__</code> gets called instead. So to get the usual Listbox initialization performed for MovListbox we need to manually call Listbox's <code>__init__</code>, and the customary way to do that gracefully is to use <code>super</code>. </p>
<p>Actually, in Python 3, that <code>super</code> call can be simplified:</p>
<pre><code>super().__init__(master)
</code></pre>
<p>The form I used earlier is necessary in Python 2. However, <code>super</code> only works on new-style classes (the only kind of class that Python 3 supports), but unfortunately Python 2 Tkinter uses the ancient old-style classes for its widgets, and calling <code>super</code> on such classes raises a <code>TypeError</code> exception. :( When working with old-style classes we have to do the call by explicitly specifying the parent class, like this:</p>
<pre><code>tk.Listbox.__init__(self, master)
</code></pre>
<p>That syntax is also valid in Python 3, but it's generally preferred to use <code>super</code> when it's available.</p>
| 1 | 2016-08-22T08:18:02Z | [
"python",
"python-3.x",
"tkinter",
"listbox"
] |
Django/Python: UnboundLocalError. where is my mistake? | 39,073,308 | <p>models.py</p>
<pre><code>class Revistapresei(models.Model):
titlulArticol = models.CharField(max_length=300)
textArticol = models.TextField()
dataArticol = models.DateField(blank=True, null=True)
linkArticol = models.CharField(blank=True, max_length=200)
STIRIINTERNE = 'Interne'
STIRIEXTERNE = 'Externe'
TIP_ARTICOL_CHOICES = (
(STIRIINTERNE, 'Interne'),
(STIRIEXTERNE, 'Externe'),
)
tipArticol = models.CharField(max_length=7, choices=TIP_ARTICOL_CHOICES, default=STIRIINTERNE)
def __str__(self):
return self.titlulArticol
</code></pre>
<p>url.py</p>
<pre><code>from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^revistaPresei/$', views.revistaPresei_list, name='revistaPresei_list'),
url(r'^revistaPresei/(?P<pk>[0-9]+)/$', views.revistaPresei_detail, name='revistaPresei_detail'),
]
</code></pre>
<p>views.py</p>
<pre><code>from django.shortcuts import render, get_object_or_404
from .models import Revistapresei
def index(request):
return render(request, 'blog/index.html', {})
def revistaPresei_list(request):
revistaPreseis = Revistapresei.objects.order_by('-dataArticol')
return render(request, 'blog/revistaPresei_list.html', {'revistaPreseis':revistaPreseis})
def revistaPresei_detail(request, pk):
revistaPresei = get_object_or_404(revistaPresei, pk=pk)
return render(request, 'blog/revistaPresei_detail.html', {'revistaPresei': revistaPresei})
</code></pre>
<p>revistaPresei_list.html</p>
<pre><code><html>
<head>
<title>Revista Presei List</title>
</head>
<body>
{% for revistaPresei in revistaPreseis %}
<div>
<p>{{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }}</p>
<h1><a href="{% url 'revistaPresei_detail' pk=revistaPresei.pk %}">{{ revistaPresei.titlulArticol }}</a></h1>
<p>{{ revistaPresei.textArticol }}</p>
</div>
{% endfor %}
</body>
</code></pre>
<p></p>
<p>revistaPresei_detail.html</p>
<pre><code><html>
<head>
<title>Revista Presei Detail</title>
</head>
<body>
<div>
{% if revistaPresei.titlulArticol %}
<div>
{{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }}
</div>
{% endif %}
<h1>{{ revistaPresei.titlulArticol }}</h1>
<p>{{ revistaPresei.textArticol }}</p>
</div>
</body>
</html>
</code></pre>
<p>In case when I try to select an item in the file - revistaPresei_list.html - I recieve the error :</p>
<p>UnboundLocalError at /revistaPresei/1/<br>
local variable 'revistaPresei' referenced before assignment ...</p>
<p>Tell me the correct answer in code.</p>
| -1 | 2016-08-22T07:12:11Z | 39,073,422 | <p>In your function <code>revistaPresei_detail(request, pk)</code> you have a wrong parameter in the call <code>revistaPresei = get_object_or_404(revistaPresei, pk=pk)</code>.</p>
<p><code>get_object_or_404</code> wants the class name as the first parameter so you have to use <code>revistaPresei = get_object_or_404(Revistapresei, pk=pk)</code> (check the uppercase and lowercase letters).</p>
<p>At the moment you try to use the local variable <code>revistaPresei</code> as a parameter and this value doesn't exist at the time of the call which leads to the <code>UnboundLocalError</code>.</p>
| 1 | 2016-08-22T07:18:43Z | [
"python",
"django",
"view"
] |
Calling a function from another python script with a while loop | 39,073,408 | <p>I have a python script with a function and a while loop and I want to call this function from another python script which also has a while loop. Here is an example script:</p>
<p>script1.py:</p>
<pre><code>global printline
printline = abc
def change(x):
global printline
printline = x
while True:
global printline
print printline
</code></pre>
<p>And this is script2.py:</p>
<pre><code>from script1 import change
change(xyz)
while True:
print hello
</code></pre>
<p>When I run script2.py, it starts to print abc and doesn't go into the while loop in this script.</p>
<p>When I run script1.py, it prints abc.</p>
<p>When I run both together, in different terminals, both print abc.</p>
<p>I need it so that when both scripts are run, script2.py can change the variable printline while going into the while loop.</p>
<p>I don't know if this is the right way to do it as I'm new to python.</p>
<p>Thanks.</p>
| 0 | 2016-08-22T07:18:01Z | 39,073,681 | <p>When you do <code>from script1 import change</code>, it executes all the top-level code in <code>script1.py</code>. So it executes the <code>while True:</code> block, which loops infinitely, and it never returns back to <code>script2.py</code>.</p>
<p>You need to split up <code>script1.py</code> so that you can import the <code>change()</code> function without executing the top-level code.</p>
<p>change.py:</p>
<pre><code>def change(x):
global printline
printline = x
</code></pre>
<p>script1.py:</p>
<pre><code>from change import change
change("abc")
while True:
print printline
</code></pre>
<p>script2.py:</p>
<pre><code>from change import change
change("xyz");
while True:
print printline
</code></pre>
| 1 | 2016-08-22T07:33:14Z | [
"python"
] |
Calling a function from another python script with a while loop | 39,073,408 | <p>I have a python script with a function and a while loop and I want to call this function from another python script which also has a while loop. Here is an example script:</p>
<p>script1.py:</p>
<pre><code>global printline
printline = abc
def change(x):
global printline
printline = x
while True:
global printline
print printline
</code></pre>
<p>And this is script2.py:</p>
<pre><code>from script1 import change
change(xyz)
while True:
print hello
</code></pre>
<p>When I run script2.py, it starts to print abc and doesn't go into the while loop in this script.</p>
<p>When I run script1.py, it prints abc.</p>
<p>When I run both together, in different terminals, both print abc.</p>
<p>I need it so that when both scripts are run, script2.py can change the variable printline while going into the while loop.</p>
<p>I don't know if this is the right way to do it as I'm new to python.</p>
<p>Thanks.</p>
| 0 | 2016-08-22T07:18:01Z | 39,076,946 | <p>Thanks. I'll try that and see if it works.</p>
| 0 | 2016-08-22T10:18:11Z | [
"python"
] |
"python.exe has stopped working" crash, FigureCanvasTkAgg.show() | 39,073,595 | <p>I am running an Anaconda environment with python 3.4, on Windows 7
<code>canvas.show()</code> is causing my python code to crash: </p>
<p><strong>EDIT</strong> : my last example was missing the mainloop() function, so I recreated a better example from sentdex's youtube tutorial <a href="https://www.youtube.com/watch?v=Zw6M-BnAPP0&list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk&index=6" rel="nofollow">here</a></p>
<p>Here is a shorter example of the code:</p>
<pre><code>import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
LARGE_FONT = ("Verdana", 12)
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, GraphPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent) #idk what the parent thing means
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10, padx=10)
page_three_button = tk.Button(self, text="Graph Page",
command=lambda: controller.show_frame(GraphPage))
page_three_button.pack()
class GraphPage(tk.Frame):
def __init__(self, parent, controller):
#initialize the tk.Frame you are about to use
tk.Frame.__init__(self, parent)
#make the label so the user knows what page they are on
label = tk.Label(self, text="Graph Page!", font=LARGE_FONT)
label.pack(pady=10, padx=10)
#keep a way to get back home
home_button = tk.Button(self, text="Home Page",
command=lambda: controller.show_frame(StartPage))
home_button.pack()
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
a.plot([1,2,3,4,5], [5,4,3,2,1])
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
app = SeaofBTCapp()
app.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/uYyLK.png" rel="nofollow"><img src="http://i.stack.imgur.com/uYyLK.png" alt="enter image description here"></a></p>
<p>Unfortunately when I click "check online for solution" nothing pops up.
When i comment out <code>canvas.show()</code>, the program runs and the error message does not pop up.</p>
| 0 | 2016-08-22T07:28:58Z | 39,076,290 | <p>I was able to reproduce the problem after adding <code>from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg</code></p>
<p>After adding <code>root.mainloop()</code> there was no crashing.</p>
| 0 | 2016-08-22T09:47:59Z | [
"python",
"matplotlib",
"tkinter",
"anaconda"
] |
Numpy: Negative Execution Time for exponentiation operation | 39,073,699 | <p>I am multiplying two large matrices, and it turns out the operation is faster when I first perform exponentiation on the first input:</p>
<pre><code>import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np.float32)
start = time.time()
d0 = np.dot(a,b)
print "\nA.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d2 = np.dot(a, np.exp(b))
print "A.exp(B) - {:.2f} seconds".format((time.time()-start))
start = time.time()
d3 = np.dot(np.exp(a), np.exp(b))
print "exp(A).exp(B) - {:.2f} seconds".format((time.time()-start))
</code></pre>
<p>Here are the results:</p>
<pre><code>A.B 1.27 seconds
exp(A).B 1.15 seconds
A.exp(B) 7.31 seconds
exp(A).exp(B) 7.38 seconds
</code></pre>
<p>Can anyone explain what am I doing wrong, or how is this possible? </p>
| 2 | 2016-08-22T07:34:12Z | 39,077,685 | <p>I suspect this to be a matter of memory-caching, since inverting the order of the executions</p>
<pre><code>import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,4000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (4000,20000)), dtype=np.float32)
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d0 = np.dot(a,b)
print "A.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d0 = np.dot(a,b)
print "A.B - {:.2f} seconds".format((time.time()-start))
</code></pre>
<p>will still cause the second statement to be quicker than the first, but second executions of the same statements run also quicker the second time.</p>
<pre><code>exp(A).B - 0.72 seconds
A.B - 0.70 seconds
exp(A).B - 0.70 seconds
A.B - 0.69 seconds
</code></pre>
<p>(I had to reduce the size of the arrays to avoid memory-issues.)</p>
| 1 | 2016-08-22T10:54:21Z | [
"python",
"numpy",
"numeric",
"execution-time",
"exponentiation"
] |
Numpy: Negative Execution Time for exponentiation operation | 39,073,699 | <p>I am multiplying two large matrices, and it turns out the operation is faster when I first perform exponentiation on the first input:</p>
<pre><code>import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np.float32)
start = time.time()
d0 = np.dot(a,b)
print "\nA.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
start = time.time()
d2 = np.dot(a, np.exp(b))
print "A.exp(B) - {:.2f} seconds".format((time.time()-start))
start = time.time()
d3 = np.dot(np.exp(a), np.exp(b))
print "exp(A).exp(B) - {:.2f} seconds".format((time.time()-start))
</code></pre>
<p>Here are the results:</p>
<pre><code>A.B 1.27 seconds
exp(A).B 1.15 seconds
A.exp(B) 7.31 seconds
exp(A).exp(B) 7.38 seconds
</code></pre>
<p>Can anyone explain what am I doing wrong, or how is this possible? </p>
| 2 | 2016-08-22T07:34:12Z | 39,077,915 | <p>What you are seeing is the reason why you would never run an operation only once when you are benchmarking, which is kind of what you are attempting here. Many things will affect the result you are seeing when you're only doing it once. In this case, probably some caching-effect. Also, the b array is so much bigger than the a array that you cannot draw any conclusions with <code>a</code> vs <code>np.exp(a)</code> when doing <code>np.exp(b)</code> unless you're running in a very controlled environment.</p>
<p>To more properly benchmark this, we can cut the two last benchmarks and focus on <code>a</code> vs <code>exp(a)</code>. Also, we repeat the operation 10,000 times and reduce the size of the arrays to avoid having to wait for several minutes:</p>
<pre><code>import time
import numpy as np
a = np.asarray(np.random.uniform(-1,1, (100,400)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (400,2000)), dtype=np.float32)
start = time.time()
for i in xrange(10000):
d0 = np.dot(a,b)
print "\nA.B - {:.2f} seconds".format((time.time()-start))
start = time.time()
for i in xrange(10000):
d0 = np.dot(np.exp(a), b)
print "exp(A).B - {:.2f} seconds".format((time.time()-start))
</code></pre>
<p>This yields the following result on my computer:</p>
<pre><code>A.B - 7.87 seconds
exp(A).B - 13.24 seconds
</code></pre>
<p>As you see, doing <code>np.exp(a)</code> now takes more time than just accessing <code>a</code>, as expected.</p>
| 2 | 2016-08-22T11:04:30Z | [
"python",
"numpy",
"numeric",
"execution-time",
"exponentiation"
] |
Python2 - Summing "for" loop output | 39,073,840 | <p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p>
<p>This is the code so far -</p>
<pre><code>import json
from pprint import pprint
with open('hd-wallet-addrs/addresses.json') as data_file:
data = json.load(data_file)
for balance in data:
print balance['balance']
</code></pre>
<p><br></p>
<p><strong>This is what's in the json file:</strong></p>
<pre><code>[
{
"addr": "1ERDMDducUsmrajDpQjoKxAHCqbTMEU9R6",
"balance": "21.00000000"
},
{
"addr": "1DvmasdbaFD7Tj6diu6D8WVc1Bkbj7jYRM",
"balance": "0.30000000"
},
{
"addr": "18xkkUi7qagUuBAg572UsmDKcZTP5zxaDB",
"balance": "0.80000000"
},
{
"addr": "1MmTDCsySdsWRVbNFwXBy2APW5kGsynkaA3",
"balance": "0.005"
},
]
</code></pre>
<p>The output is like this:</p>
<pre><code>21
0.3
0.8
0.005
</code></pre>
<p>How should I edit my code to add the numbers together?</p>
| 0 | 2016-08-22T07:42:30Z | 39,073,881 | <p>You can use <code>sum</code> function and list comprehension:</p>
<pre><code>sum([float(b['balance']) for b in balance])
</code></pre>
| 0 | 2016-08-22T07:44:33Z | [
"python",
"json",
"python-2.7",
"for-loop"
] |
Python2 - Summing "for" loop output | 39,073,840 | <p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p>
<p>This is the code so far -</p>
<pre><code>import json
from pprint import pprint
with open('hd-wallet-addrs/addresses.json') as data_file:
data = json.load(data_file)
for balance in data:
print balance['balance']
</code></pre>
<p><br></p>
<p><strong>This is what's in the json file:</strong></p>
<pre><code>[
{
"addr": "1ERDMDducUsmrajDpQjoKxAHCqbTMEU9R6",
"balance": "21.00000000"
},
{
"addr": "1DvmasdbaFD7Tj6diu6D8WVc1Bkbj7jYRM",
"balance": "0.30000000"
},
{
"addr": "18xkkUi7qagUuBAg572UsmDKcZTP5zxaDB",
"balance": "0.80000000"
},
{
"addr": "1MmTDCsySdsWRVbNFwXBy2APW5kGsynkaA3",
"balance": "0.005"
},
]
</code></pre>
<p>The output is like this:</p>
<pre><code>21
0.3
0.8
0.005
</code></pre>
<p>How should I edit my code to add the numbers together?</p>
| 0 | 2016-08-22T07:42:30Z | 39,073,905 | <p>Most pythonic way to achieve this will be:</p>
<pre><code>final_balance = sum(map(float, [balance['balance'] for balance in data]))
</code></pre>
<p><a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">map()</a> will convert the list of <code>str</code> numbers to <code>float</code> numbers, and <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow">sum()</a> will add them together.</p>
| 1 | 2016-08-22T07:45:43Z | [
"python",
"json",
"python-2.7",
"for-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.