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 |
---|---|---|---|---|---|---|---|---|---|
Clean from .txt, write new variable as a csv delimited string (not list) into a csv file | 39,934,531 | <p>my .txt file looks like the following:</p>
<pre><code>Page 1 of 49
<="">
View Full Profile
S.S. Anne
Oil Tanker
42 miles offshore
Anchor length is 50 feet
<="">
View Full Profile
S.S. Minnow
Passenger Ship
1502.2 miles offshore
Anchor length is 12 feet
<="">
View Full Profile
S.S. Virginia
Passenger Ship
2 km offshore
Anchor length is 25 feet
<="">
View Full Profile
S.S. Chesapeake
Naval Ship
10 miles offshore
Anchor length is 75 feet
<="">
</code></pre>
<p>I've worked out the cleaning part so that following 'View Full Profile' I take the next 4 line items and put them into their own new line item, I do this for each instance of 'View Full Profile'.</p>
<p>Code:</p>
<pre><code>import csv
data = []
with open('ship.txt','r',encoding='utf8') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if 'View Full Profile' in line:
x = [lines[i+1],lines[i+2],lines[i+3],lines[i+4]]
data.append(x)
for line in data:
y = line
print(y)
with open('ship_test.csv', 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
</code></pre>
<p>And the output of printing y to see what will be written into the new file is:</p>
<pre><code>['S.S. Anne\n', 'Oil Tanker\n', '42 miles offshore\n', 'Anchor length is 50 feet\n']
['S.S. Minnow\n', 'Passenger Ship\n', '1502.2 miles offshore\n', 'Anchor length is 12 feet\n']
['S.S. Virginia\n', 'Passenger Ship\n', '2 km offshore\n', 'Anchor length is 25 feet\n']
['S.S. Chesapeake\n', 'Naval Ship\n', '10 miles offshore\n', 'Anchor length is 75 feet\n']
[Finished in 0.1s]
</code></pre>
<p>When it copies into the new file I get the following:</p>
<pre><code>"S.S. Anne
","Oil Tanker
","42 miles offshore
","Anchor length is 50 feet
"
"S.S. Minnow
","Passenger Ship
","1502.2 miles offshore
","Anchor length is 12 feet
"
"S.S. Virginia
","Passenger Ship
","2 km offshore
","Anchor length is 25 feet
"
"S.S. Chesapeake
","Naval Ship
","10 miles offshore
","Anchor length is 75 feet
"
</code></pre>
<p>I am looking to write into the new file the output of y. I believe it writes each item as its own line due to the '/n' attached to each element of x. How do I remove this (I tried splitting and received an error) so that x is written as a single line item in the new file as a csv string?</p>
| 0 | 2016-10-08T16:11:37Z | 39,934,573 | <pre><code>line = line.replace('\n', '')
</code></pre>
<p>Use the replace method</p>
<p>If there is a list of strings:</p>
<pre><code>line = [l.replace('\n', '') for l in line]
</code></pre>
| 0 | 2016-10-08T16:15:57Z | [
"python",
"csv"
] |
Clean from .txt, write new variable as a csv delimited string (not list) into a csv file | 39,934,531 | <p>my .txt file looks like the following:</p>
<pre><code>Page 1 of 49
<="">
View Full Profile
S.S. Anne
Oil Tanker
42 miles offshore
Anchor length is 50 feet
<="">
View Full Profile
S.S. Minnow
Passenger Ship
1502.2 miles offshore
Anchor length is 12 feet
<="">
View Full Profile
S.S. Virginia
Passenger Ship
2 km offshore
Anchor length is 25 feet
<="">
View Full Profile
S.S. Chesapeake
Naval Ship
10 miles offshore
Anchor length is 75 feet
<="">
</code></pre>
<p>I've worked out the cleaning part so that following 'View Full Profile' I take the next 4 line items and put them into their own new line item, I do this for each instance of 'View Full Profile'.</p>
<p>Code:</p>
<pre><code>import csv
data = []
with open('ship.txt','r',encoding='utf8') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if 'View Full Profile' in line:
x = [lines[i+1],lines[i+2],lines[i+3],lines[i+4]]
data.append(x)
for line in data:
y = line
print(y)
with open('ship_test.csv', 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
</code></pre>
<p>And the output of printing y to see what will be written into the new file is:</p>
<pre><code>['S.S. Anne\n', 'Oil Tanker\n', '42 miles offshore\n', 'Anchor length is 50 feet\n']
['S.S. Minnow\n', 'Passenger Ship\n', '1502.2 miles offshore\n', 'Anchor length is 12 feet\n']
['S.S. Virginia\n', 'Passenger Ship\n', '2 km offshore\n', 'Anchor length is 25 feet\n']
['S.S. Chesapeake\n', 'Naval Ship\n', '10 miles offshore\n', 'Anchor length is 75 feet\n']
[Finished in 0.1s]
</code></pre>
<p>When it copies into the new file I get the following:</p>
<pre><code>"S.S. Anne
","Oil Tanker
","42 miles offshore
","Anchor length is 50 feet
"
"S.S. Minnow
","Passenger Ship
","1502.2 miles offshore
","Anchor length is 12 feet
"
"S.S. Virginia
","Passenger Ship
","2 km offshore
","Anchor length is 25 feet
"
"S.S. Chesapeake
","Naval Ship
","10 miles offshore
","Anchor length is 75 feet
"
</code></pre>
<p>I am looking to write into the new file the output of y. I believe it writes each item as its own line due to the '/n' attached to each element of x. How do I remove this (I tried splitting and received an error) so that x is written as a single line item in the new file as a csv string?</p>
| 0 | 2016-10-08T16:11:37Z | 39,934,760 | <p>You should strip the terminating newline as soon as you read the line. The first part of your code could become:</p>
<pre><code>data = []
with open('ship.txt','r',encoding='utf8') as f:
for line in lines:
if 'View Full Profile' in line:
x = [ next(f).strip(), next(f).strip(),
next(f).strip(), next(f).strip() ]
data.append(x)
</code></pre>
<p>You could even write the csv file on the fly:</p>
<pre><code>with open('ship.txt','r',encoding='utf8') as f, open('ship_test.csv', 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in f:
if 'View Full Profile' in line:
x = [ next(f).strip(), next(f).strip(),
next(f).strip(), next(f).strip() ]
writer.writerow(x)
</code></pre>
| 0 | 2016-10-08T16:34:35Z | [
"python",
"csv"
] |
How to read files with separators in Python and append characters at the end? | 39,934,586 | <p>I have a file format that looks like this</p>
<pre><code> >1ATGC>2TTTT>3ATGC>$$$>B1ATCG>B2TT-G>3TTCG>B4TT-G>B5TTCG>B6TTCG$$$>C1TTTT>C2ATGC
</code></pre>
<p>Note: "$$$" divides the file, such that anything before $$$ is Set 1 and after $$$ is Set 2 and after the next $$$ Set3 etc.</p>
<p>I have to do the following:</p>
<p>a. Concatenate the sequences following ">". So, I have to join "ATGC" "TTTT" "ATGC" and store in (1) and I have to concatenate "ATCG" "TT-G" "TTCG" "TT-G" "TTCG""TTCG" and store as (2)... concatenate again and store in (3)</p>
<p>The output should be a list that looks like:</p>
<pre><code>("ATGCTTTTATGC","ATCGTT-GTTCGTT-GTTCGTTCG","TTTTATGC")
</code></pre>
<p>(2) Then, I find the the Set that has the maximum length => here Set(2)</p>
<p>(3) If length of Set i is not equal to Set (2), then I add "Z" at the end Set i, such that length of Set i is now equal to length of Set (2)</p>
<p>(4) I replace all "-" with "Z"</p>
<p>The output should look like:</p>
<pre><code> ("ATGCTTTTATGCZZZZZZZZZZZZ",
"ATCGTTZGTTCGTTZGTTCGTTCG",
"TTTTATGCZZZZZZZZZZZZZZZZ")
</code></pre>
<p>Here is the code, I have attempted:</p>
<pre><code>in_file = open('c:/test.txt','r')
org = []
seqlist = []
seqstring = ""
for line in in_file:
if line.startswith("$$$"):
if seqstring!= "":
seqlist.append(seqstring)
seqstring = ""
org.append(line.rstrip("\n"))
elif line.startswith(">"):
seqstring += line.rstrip("\n")
seqlist.append(seqstring)
setdraft = seqlist
maxsetlength = max(len(seqlist))
setdraft2 =[]
for i in setdraft:
if len(i) != maxsetlength:
setdraft2 = i.append("Z")
setfinal =[]
for j in setdraft2:
if j in setdraft2 =="-":
setfinal = j.insert ("Z")
</code></pre>
<p>The above script does not work. It gives me multiple errors.
Eg. When I print <code>setdraft</code> it gives me the output</p>
<pre><code>['>1ATGC>2TTTT>3ATGC>$$$>B1ATCG>B2TT-G>3TTCG>B4TT-G>B5TTCG>Bââ6TTCG$$$>C1TTTT>C2ATââGC']
</code></pre>
<p>which is the same as the input </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/ACER/Desktop/trial.py", line 25, in <module>
maxsetlength = max(len(seqlist))
TypeError: 'int' object is not iterable
</code></pre>
| 1 | 2016-10-08T16:17:12Z | 39,934,848 | <p>It's unclear how fragile your data set is, but if it follows the pattern above (namely the last 4 characters are the ones you are looking for) then you can use a couple of <code>split()</code>s and <code>itertools.zip_longest</code> and <code>zip</code> it back to append the <code>Z</code></p>
<pre><code>>>> import itertools as it
>>> import string
>>> def digit_index(s):
... for i, c in enumerate(s):
... if c in string.digits:
... return i
... return 0
...
>>> s = '>1ATGC>2TTTT>3ATGC>$$$>B1ATCG>B2TT-G>3TTCG>B4TT-G>B5TTCG>B6TTCG$$$>C1TTTT>C2ATGC'
>>> parsed = [''.join(y[digit_index(y)+1:].replace('-', 'Z') for y in x.split('>')) for x in s.split('$$$')]
>>> parsed
['ATGCTTTTATGC', 'ATCGTTZGTTCGTTZGTTCGTTCG', 'TTTTATGC']
>>> [''.join(x) for x in zip(*it.zip_longest(*parsed, fillvalue='Z'))]
['ATGCTTTTATGCZZZZZZZZZZZZ',
'ATCGTTZGTTCGTTZGTTCGTTCG',
'TTTTATGCZZZZZZZZZZZZZZZZ']
</code></pre>
<p>If you don't mind it as a list then you can avoid <code>join()</code>ing it back to a string:</p>
<pre><code>>>> list(zip(*it.zip_longest(*parsed, fillvalue='Z')))
[('A', 'T', 'G', 'C', 'T', 'T', 'T', 'T', 'A', 'T', 'G', 'C', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z'),
('A', 'T', 'C', 'G', 'T', 'T', 'Z', 'G', 'T', 'T', 'C', 'G', 'T', 'T', 'Z', 'G', 'T', 'T', 'C', 'G', 'T', 'T', 'C', 'G'),
('T', 'T', 'T', 'T', 'A', 'T', 'G', 'C', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'Z')]
</code></pre>
| 1 | 2016-10-08T16:44:38Z | [
"python",
"append",
"startswith"
] |
Google Vision API Error Code | 39,934,619 | <p>I am trying the example code in
<a href="https://googlecloudplatform.github.io/google-cloud-python/stable/vision-usage.html" rel="nofollow">https://googlecloudplatform.github.io/google-cloud-python/stable/vision-usage.html</a></p>
<pre><code>from google.cloud import vision
client = vision.Client()
image = client.image('./image.jpg')
safe_search = image.detect_safe_search()
</code></pre>
<p>image.detect_safe_search throws a key error for the result returned from api. On printing the result dict, I found the it didn't have the expected key because it gave error response. The response returned from google api is</p>
<pre><code>{u'error': {u'message': u'image-annotator::error(12): Image processing error!', u'code': 13}}
</code></pre>
<p>I could not find any references for the error code in the documentation of api. What am I missing?</p>
| 0 | 2016-10-08T16:19:53Z | 40,089,669 | <p><a href="https://code.google.com/p/google-cloud-platform/issues/detail?id=123" rel="nofollow">Here's an issue</a> which also mentions the error. That issue has been forwarded to the Google engineering team.</p>
<p>Could you perhaps try re-encoding your image? Save it as a png or resave to jpg to see if maybe it's corrupted or anything?</p>
| 0 | 2016-10-17T14:57:06Z | [
"python",
"google-cloud-vision",
"google-cloud-python"
] |
Python - While-Loop until list is empty | 39,934,635 | <p>I'm working with Django and I have a queryset of objects that has been converted to a list (<code>unpaid_sales</code>). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (<code>bucket</code>) reaches zero.</p>
<p>This is how I set it up:</p>
<pre><code>while unpaid_sales:
while bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
...do stuff
</code></pre>
<p>In some cases, I am getting the following error: </p>
<blockquote>
<p>pop from empty list</p>
</blockquote>
<p>What's wrong with my logic?</p>
| 0 | 2016-10-08T16:21:32Z | 39,934,670 | <p>Do not use separate <code>while</code>loops. Do as follows :</p>
<pre><code>while unpaid_sales and bucket > 0 :
unpaid_sale = unpaid_sales.pop(0)
...do stuff
</code></pre>
| 3 | 2016-10-08T16:25:30Z | [
"python"
] |
Python - While-Loop until list is empty | 39,934,635 | <p>I'm working with Django and I have a queryset of objects that has been converted to a list (<code>unpaid_sales</code>). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (<code>bucket</code>) reaches zero.</p>
<p>This is how I set it up:</p>
<pre><code>while unpaid_sales:
while bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
...do stuff
</code></pre>
<p>In some cases, I am getting the following error: </p>
<blockquote>
<p>pop from empty list</p>
</blockquote>
<p>What's wrong with my logic?</p>
| 0 | 2016-10-08T16:21:32Z | 39,934,680 | <p>You should do a single loop: <code>while bucket>0 and unpaid_sales</code>. Here, you are popping elements in the <code>bucket</code> loop, and then just just check that <code>bucket</code> is positive, but you do not check that <code>element_sales</code> still has elements in it.</p>
| 2 | 2016-10-08T16:26:24Z | [
"python"
] |
Python - While-Loop until list is empty | 39,934,635 | <p>I'm working with Django and I have a queryset of objects that has been converted to a list (<code>unpaid_sales</code>). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (<code>bucket</code>) reaches zero.</p>
<p>This is how I set it up:</p>
<pre><code>while unpaid_sales:
while bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
...do stuff
</code></pre>
<p>In some cases, I am getting the following error: </p>
<blockquote>
<p>pop from empty list</p>
</blockquote>
<p>What's wrong with my logic?</p>
| 0 | 2016-10-08T16:21:32Z | 39,934,685 | <p>Your end criteria must be formulated a little differently: loop while there are items and the <code>bucket</code> is positive. <code>or</code> is not the right operation here.</p>
<pre><code>while unpaid_sales and bucket > 0
unpaid_sale = unpaid_sales.pop(0)
#do stuff
</code></pre>
| 3 | 2016-10-08T16:27:19Z | [
"python"
] |
Find out all the punctuations in a sentence that has been put into a list | 39,934,679 | <p>I have this variable:</p>
<pre><code>Words = ["Hi",".","how","are","you","?","I","feel","like","I","could",",","do","better"]
</code></pre>
<p>From this I want a variable that finds all the punctuations and puts it into a list as well. Like this:</p>
<pre><code>Punctuations = [".","?",","]
</code></pre>
| 1 | 2016-10-08T16:26:24Z | 39,934,787 | <p>You can use <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> to identify punctuation marks:</p>
<pre><code>from string import punctuation
punctuations = [w for w in words if w in punctuation]
</code></pre>
| 1 | 2016-10-08T16:37:57Z | [
"python",
"list",
"punctuation"
] |
Find out all the punctuations in a sentence that has been put into a list | 39,934,679 | <p>I have this variable:</p>
<pre><code>Words = ["Hi",".","how","are","you","?","I","feel","like","I","could",",","do","better"]
</code></pre>
<p>From this I want a variable that finds all the punctuations and puts it into a list as well. Like this:</p>
<pre><code>Punctuations = [".","?",","]
</code></pre>
| 1 | 2016-10-08T16:26:24Z | 39,934,966 | <p>The solution using <code>re.findall</code> function:</p>
<pre><code>import re
Words = ["Hi",".","how","are","you","?","I","feel","like","I","could",",","do","better"]
Punctuations = re.findall("[^\w\s]+", ''.join(Words))
print(Punctuations) # ['.', '?', ',']
</code></pre>
| 0 | 2016-10-08T16:57:29Z | [
"python",
"list",
"punctuation"
] |
Invalid format specifier for thousands place | 39,934,706 | <p>I am trying to make a simple chart like output. Here are strings that I want to display:</p>
<p>a = "name", b = "10000.00", c = "code", d = "45.60", e = "30.00"</p>
<pre><code>print("{0:20}${1:,20}{2:20}${3:,20}${4:,<5}".format(a,b,c,d,e),file=outfile)
</code></pre>
<p>I put "," to indicate thousands place in each format specifier in which I want them to be output as currency. It reports the error:</p>
<pre><code>print("{0:20}${1:,20}{2:20}${3:20}${4:<5}".format(a,b,c,d,e),file=outfile)
ValueError: Invalid format specifier
</code></pre>
<p>What did I do wrong?</p>
| 1 | 2016-10-08T16:29:13Z | 39,934,825 | <p>As per the <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">docs</a>, width has to go after comma. Moreover, your <code>b</code> variable has to be a number (and not a string, as in your MWE):</p>
<pre><code>>>> x = 10000.0
>>> '{0:20,}'.format(x)
' 10,000.0'
</code></pre>
| 0 | 2016-10-08T16:42:24Z | [
"python"
] |
Lowest common ancestor in python's NetworkX | 39,934,721 | <p>Using NetworkX</p>
<p>I want to get lowest common ancestor from node1 and node11 in DiGraph.</p>
<p>The following is the code.</p>
<pre><code>import networkx as nx
G = nx.DiGraph() #Directed graph
G.add_nodes_from([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
G.add_edges_from([(2,1),(3,1),(4,1),(5,2),(6,2),(7,3),(8,3),(9,3),(10,4),(10,12),(14,9),(15,8),(12,11),(13,11),(14,12),(15,13)])
ancestors1 = nx.ancestors(G, 1)
ancestors2 = nx.ancestors(G, 11)
src_set = set(ancestors1)
tag_set = set(ancestors2)
matched_list = list(src_set & tag_set)
dic = {}
for elem in matched_list:
print elem
length1 = nx.dijkstra_path_length(G, elem, 1)
path1 = nx.dijkstra_path(G, elem, 1)
dist1 = len(path1)
length2 = nx.dijkstra_path_length(G, elem, 11)
path2 = nx.dijkstra_path(G, elem, 11)
dist2 = len(path2)
dist_sum = dist1 + dist2
dic[elem] = dist_sum
min_num = min(dic.values())
for k, v in sorted(dic.items(), key=lambda x:x[1]):
if v != min_num:
break
else:
print k, v
</code></pre>
<p>I have a problem with a execution speed, so I want faster execution speed.</p>
<p>If you have any good idea or algorithm, please tell me the idea.</p>
<p>Sorry for the poor English.</p>
| 2 | 2016-10-08T16:30:27Z | 39,935,416 | <p>Rerunning Dijkstra in a loop indeed seems like an overkill.</p>
<p>Say we build the digraph obtained by <em>reversing</em> the edges:</p>
<pre><code>import networkx as nx
G = nx.DiGraph() #Directed graph
G.add_nodes_from([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
edges = [(2,1),(3,1),(4,1),(5,2),(6,2),(7,3),(8,3),(9,3),(10,4),(10,12),(14,9),(15,8),(12,11),(13,11),(14,12),(15,13)]
G.add_edges_from([(e[1], e[0]) for e in edges])
</code></pre>
<p>Now we run BFS from each of the two nodes:</p>
<pre><code>preds_1 = nx.bfs_predecessors(G, 1)
preds_2 = nx.bfs_predecessors(G, 11)
</code></pre>
<p>Finding the common vertices reachable from both nodes in the reversed graph is easy:</p>
<pre><code>common_preds = set([n for n in preds_1]).intersection(set([n for n in preds_2]))
</code></pre>
<p>Now you can query the above easily. For example, to find the common vertex reachable from both, closest to 1, is:</p>
<pre><code>>>> min(common_preds, key=lambda n: preds_1[n])
10
</code></pre>
| 3 | 2016-10-08T17:42:12Z | [
"python",
"algorithm",
"networkx",
"lowest-common-ancestor"
] |
How to access re-raised exception in Python 3? | 39,934,738 | <p>In Python 3, there's a <a href="https://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/" rel="nofollow">useful <code>raise ... from ...</code> feature</a> to re-raise an exception. That said, how do you find the original (/ re-raised) exception from the raised exception? Here's a (silly) example with comments to demonstrate what I mean--</p>
<pre><code>def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err
try:
some_func()
except as err:
# how can I access the original exception (TypeError)?
</code></pre>
| 2 | 2016-10-08T16:32:29Z | 39,934,807 | <p>It's in the <code>__cause__</code> attribute of the raised exception. Taken from the <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="nofollow">docs on the <code>raise</code> statement</a> it says regarding <code>raise ... from ...</code>:</p>
<blockquote>
<p>The <code>from</code> clause is used for exception chaining: if given, the second expression must be another exception class or instance, <em>which will then be attached to the raised exception as the <code>__cause__</code> attribute</em> (which is writable). If the raised exception is not handled, both exceptions will be printed.</p>
</blockquote>
<p>So, in your given scenario, <code>repr</code>ing the <code>__cause__</code> attribute:</p>
<pre><code>def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except TypeError as err:
raise Exception("blah") from err
try:
some_func()
except Exception as er:
print(repr(er.__cause__))
</code></pre>
<p>Will print out:</p>
<pre><code>TypeError("'NoneType' object is not callable",)
</code></pre>
| 3 | 2016-10-08T16:40:39Z | [
"python",
"python-3.x",
"exception",
"exception-handling"
] |
How to access re-raised exception in Python 3? | 39,934,738 | <p>In Python 3, there's a <a href="https://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/" rel="nofollow">useful <code>raise ... from ...</code> feature</a> to re-raise an exception. That said, how do you find the original (/ re-raised) exception from the raised exception? Here's a (silly) example with comments to demonstrate what I mean--</p>
<pre><code>def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err
try:
some_func()
except as err:
# how can I access the original exception (TypeError)?
</code></pre>
| 2 | 2016-10-08T16:32:29Z | 39,934,808 | <p>Whenever an exception is raised from an exception handler (the <code>except</code> clause), the original exception will bestored in new exception's <code>__context__</code>.</p>
<p>Whenever an exception is raised using <code>from</code> syntax, the exception specified in <code>from</code> will be saved in the <code>__cause__</code> attribute of the new exception.</p>
<p>In the usual use case, that amounts to both <code>__cause__</code> and <code>__context__</code> containing the original exception:</p>
<pre><code>def f():
try:
raise Exception('first exception')
except Exception as e:
raise Exception('second exception') from e
try:
f()
except Exception as e:
print('This exception', e)
print('Original exception', e.__context__)
print('Also original exception', e.__cause__)
</code></pre>
<p>Here is also an example of when <code>__context__</code> is set:</p>
<pre><code>try:
raise Exception('first exception')
except Exception as e:
raise Exception('second exception')
</code></pre>
<p>and an example of when <code>__cause__</code> is set:</p>
<pre><code>e = Exception('first exception')
raise Exception('second exception') from e
</code></pre>
| 1 | 2016-10-08T16:40:55Z | [
"python",
"python-3.x",
"exception",
"exception-handling"
] |
merge two lists of dictionaries in python? | 39,934,750 | <p>I have two lists of dictionaries:</p>
<pre><code>old = [{'a':'1','b':'2'},{'a':'2','b':'3'},{'a':'3','b':'4'},{'a':'4','b':'5'}]
new = [{'a':'1','b':'100'},{'a':'2','b':'100'},{'a':'5','b':'6'}]
</code></pre>
<p>How can I merge two lists of dictionaries to get:</p>
<pre><code>update = [{'a':'1','b':'2,100'},{'a':'2','b':'3,100'},{'a':'3','b':'4'},{'a':'4','b':'5'},{'a':'5','b':'6'}]
</code></pre>
<p>the idea is if new 'a' is not in the old, add it and if new 'a' is in the old, update 'b' and if old 'a' is not in the new, keep it.</p>
| 0 | 2016-10-08T16:33:36Z | 39,935,532 | <p>If 'a' is the real key here and b is the value, imo it would be easier to convert the list of dicts into one dict, process the merge and then convert it back. This way you can use the standard functions.</p>
<p>Convert into one dict where a is the key:</p>
<pre><code>def intoRealDict(listOfDicts):
values = []
for item in listOfDicts:
values.append((item.get('a'), item.get('b')))
return dict(values) #Use Dict Constructur ('3', '4) -> {'3': '4'}
</code></pre>
<p>Convert into the data structure again:</p>
<pre><code>def intoTheDataStructure(realDict):
res = []
for i in realDict:
res.append(dict([('a', i), ('b', realDict[i])]))
return res
</code></pre>
<p>Easy Merge of your two lists: </p>
<pre><code>def merge(l1, l2):
d1, d2 = intoRealDict(l1), intoRealDict(l2)
for i in d2:
if i in d1:
#extend "b"
d1[i] = d1[i] + ", " + d2[i]
else:
#append value of key i
d1[i] = d2[i]
return intoTheDataStructure(d1)
</code></pre>
<p>Working Code with bad performance</p>
| 0 | 2016-10-08T17:54:39Z | [
"python",
"list",
"dictionary"
] |
Get intellij python to autocomplete on tab instead of space (and tab) which is does now | 39,934,771 | <p>Is there a way to prevent intelli(Idea) pycharm plugin from not autocompleting on space; I want autocomplete only when I hit the tab.
Space to me means I want to continue typing without being bothered.</p>
<p>E.g. I'm trying to say something like d = 0.
Idea forces me to escape. A space will autocomplete to delattr.</p>
<p><a href="http://i.stack.imgur.com/smEky.png" rel="nofollow"><img src="http://i.stack.imgur.com/smEky.png" alt="Intellij autocomplete"></a></p>
| 0 | 2016-10-08T16:36:02Z | 39,935,108 | <p>You can disable "Settings | Editor | General | Code Completion | Insert selected variant by typing dot, space, etc", then only Enter and Tab will choose the selected item in autopopup completion.</p>
| 2 | 2016-10-08T17:13:06Z | [
"python",
"intellij-idea",
"autocomplete"
] |
make a list from string json? python | 39,934,782 | <p>I have a json string i get it from json array below i have given it </p>
<pre><code>annotation = sentence["annotation"]
text = sentence["text"]
#ioblist = [annotation]
ioblist=[[x[0], x[4]] for x in annotation] #nothing
</code></pre>
<p>the proram did not convert here is my string in list at index 0 </p>
<pre><code> {u'1': [u'Bill', u'bill', u'NNP', u'B-PERSON'],
u'3': [u'born', u'bear', u'VBN', u'O'],
u'2': [u'was', u'be', u'VBD', u'O'],
u'5': [u'.', u'.', u'.', u'O'],
u'4': [u'1986', u'BIL', u'CD', u'B-DATE']}
</code></pre>
<p><strong>update 1:</strong></p>
<p>I am making list as </p>
<pre><code> ioblist=[[x[0], x[4]] for x in annotation]
</code></pre>
| -1 | 2016-10-08T16:37:04Z | 39,934,804 | <p><code>range()</code> gives you a iterable of integers, but your dictionary keys are <code>u'...'</code>, i.e. unicode strings. Hence, the lookup <code>ioblist[0]</code> must fail, since <code>0 != u'0'</code> (Python isn't PHP, thankfully).</p>
| 0 | 2016-10-08T16:40:30Z | [
"python"
] |
Popen in a function is blocking that function from being executed in a separate thread | 39,934,799 | <p>I'm trying to execute a binary from a python program (under Linux) and would like to dedicate this to a separate thread. Edit: The binary will run for quite a while and write data to disk. It would be nice if I could retreive stdout and stderr in python so that I can write this to a log. It would also be nice if I could evaluate the return value of the binary to make sure that it succeeds. </p>
<p>However, as soon as the function that I start with the thread contains the Popen statement, the thread doesn't seem to start at all :-( Is that a weird thing about thread safety that I don't understand? As soon as I comment out the part where the external command is called, the function is called fine....</p>
<p>Here is a minimum version of my code, I'm using python 2.7.9:</p>
<pre><code>from subprocess import Popen, PIPE
import subprocess
import sys
from threading import Thread
def record ( _command):
print "Starting function"
print "Now executing the following command: " + _command
sys.stdout.flush()
#Here starts the interesting part. As long as this parts is part of the function, the function is not started at all.
#Not even the two lines before are executed :-(
#If I comment out the following lines, at least the print statements work
process = Popen([_command], stdout=PIPE, stderr=PIPE, shell=True)
stdout_lines = iter(process.stdout.readline, "")
for stdout_line in stdout_lines:
yield stdout_line
process.stdout.close()
return_code = process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(return_code, _command)
###########################
#Main function starts here#
###########################
threads=[]
for i in range (0,5):
t=Thread(target=record,args=('ls',))
threads.append(t)
t.start()
# wait for all threads to finish
for t in threads:
t.join()
print "Exiting skript"
</code></pre>
<p>This code just prints out:</p>
<pre><code>Exiting skript
</code></pre>
<p>As soon as I comment out the Popen part, I get:</p>
<pre><code>Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
</code></pre>
<p>Starting function
Now executing the following command: ls</p>
<pre><code>Exiting skript
</code></pre>
| 0 | 2016-10-08T16:39:31Z | 39,936,769 | <p>Your <code>record</code> function doesn't work as intended not because of the <code>Popen</code> call but because it's a generator function (because it contains a <code>yield</code> statement). Generator functions don't actually run their code when you call them. Instead, they return a generator object immediately, and the code in the function is run only when the generator object is iterated on.</p>
<p>I don't think there's any useful way to call a generator function directly as the target of a thread. Instead, you might want the thread to target some other function that consumes a generator object. Or you could restructure your current function to not be a generator (it's not obvious what the purpose of the <code>yield</code> statements was).</p>
| 1 | 2016-10-08T19:57:35Z | [
"python",
"multithreading"
] |
Popen in a function is blocking that function from being executed in a separate thread | 39,934,799 | <p>I'm trying to execute a binary from a python program (under Linux) and would like to dedicate this to a separate thread. Edit: The binary will run for quite a while and write data to disk. It would be nice if I could retreive stdout and stderr in python so that I can write this to a log. It would also be nice if I could evaluate the return value of the binary to make sure that it succeeds. </p>
<p>However, as soon as the function that I start with the thread contains the Popen statement, the thread doesn't seem to start at all :-( Is that a weird thing about thread safety that I don't understand? As soon as I comment out the part where the external command is called, the function is called fine....</p>
<p>Here is a minimum version of my code, I'm using python 2.7.9:</p>
<pre><code>from subprocess import Popen, PIPE
import subprocess
import sys
from threading import Thread
def record ( _command):
print "Starting function"
print "Now executing the following command: " + _command
sys.stdout.flush()
#Here starts the interesting part. As long as this parts is part of the function, the function is not started at all.
#Not even the two lines before are executed :-(
#If I comment out the following lines, at least the print statements work
process = Popen([_command], stdout=PIPE, stderr=PIPE, shell=True)
stdout_lines = iter(process.stdout.readline, "")
for stdout_line in stdout_lines:
yield stdout_line
process.stdout.close()
return_code = process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(return_code, _command)
###########################
#Main function starts here#
###########################
threads=[]
for i in range (0,5):
t=Thread(target=record,args=('ls',))
threads.append(t)
t.start()
# wait for all threads to finish
for t in threads:
t.join()
print "Exiting skript"
</code></pre>
<p>This code just prints out:</p>
<pre><code>Exiting skript
</code></pre>
<p>As soon as I comment out the Popen part, I get:</p>
<pre><code>Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
Starting function
Now executing the following command: ls
</code></pre>
<p>Starting function
Now executing the following command: ls</p>
<pre><code>Exiting skript
</code></pre>
| 0 | 2016-10-08T16:39:31Z | 39,937,315 | <p>With some small fixes, your code runs:</p>
<ul>
<li>got rid of the generator function, doesn't make sense with threads</li>
<li>simplified the way to get output from the process, but still read line by line (reading the final output with <code>communicate</code> would work but you seem to require having the lines printed immediately to have an idea of the current progress)</li>
<li>protected output using a <code>Lock</code> or it would be mixed up between threads</li>
<li>merged stdout and stderr in pipe to avoid deadlocks</li>
</ul>
<p>fixed code:</p>
<pre><code>from subprocess import Popen, PIPE, STDOUT
import subprocess
import sys
from threading import Thread,Lock
lck = Lock()
def record ( _command):
lck.acquire()
print("Starting function")
print("Now executing the following command: " + _command)
lck.release()
process = Popen([_command], stdout=PIPE, stderr=STDOUT, shell=True)
while True:
line = process.stdout.readline()
if len(line)==0:
break
lck.acquire()
sys.stdout.write(line)
lck.release()
process.wait()
return_code = process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(return_code, _command)
# main program
threads=[]
for i in range (0,5):
t=Thread(target=record,args=('ls',))
threads.append(t)
t.start()
# wait for all threads to finish
for t in threads:
t.join()
print("Exiting skript")
</code></pre>
| 1 | 2016-10-08T20:59:59Z | [
"python",
"multithreading"
] |
Is pandas read_csv really slow compared to python open? | 39,934,801 | <p>my requirement is to remove duplicate rows from csv file, but the size of the file is 11.3GB. So I bench marked the pandas and python file generator.</p>
<p><strong>Python File Generator:</strong></p>
<pre><code>def fileTestInPy():
with open(r'D:\my-file.csv') as fp, open(r'D:\mining.csv', 'w') as mg:
dups = set()
for i, line in enumerate(fp):
if i == 0:
continue
cols = line.split(',')
if cols[0] in dups:
continue
dups.add(cols[0])
mg.write(line)
mg.write('\n')
</code></pre>
<p><a href="http://i.stack.imgur.com/0HLDH.png" rel="nofollow"><img src="http://i.stack.imgur.com/0HLDH.png" alt="Python File Generator"></a> </p>
<p><strong>Using Pandas read_csv:</strong></p>
<pre><code>import pandas as pd
df = pd.read_csv(r'D:\my-file.csv', sep=',', iterator=True, chunksize=1024*128)
def fileInPandas():
for d in df:
d_clean = d.drop_duplicates('NPI')
d_clean.to_csv(r'D:\mining1.csv', mode='a')
</code></pre>
<p><a href="http://i.stack.imgur.com/Pvu3I.png" rel="nofollow"><img src="http://i.stack.imgur.com/Pvu3I.png" alt="Pandas read_csv"></a></p>
<p><strong>Details:</strong>
Size: 11.3 GB
rows: 100 million, but in this 50 million are duplicate
Python Version: 3.5.2
Pandas Version: 0.19.0
RAM: 8GB
CPU: Core-i5 2.60GHz</p>
<p>What I'm observed here, 643 sec took when I use the python file generator, but 1756 took when I use the pandas.</p>
<p>Even my system was not hanged when I used the python file generator, but when I used the pandas my system was hanged.</p>
<p>Am I using correct way in pandas ?
Even I want to do sorting on 11.3GB file, how to do that ?</p>
| 0 | 2016-10-08T16:39:52Z | 39,934,895 | <p>Pandas is not a good choice for this task. It reads the entire 11.3G file into memory and does string-to-int conversions on all of the columns. I'm not surprised that your machine bogged down!</p>
<p>The line-by-line version is much leaner. It doesn't do any conversions, doesn't bother looking at unimportant columns and doesn't keep a large dataset in memory. It is the better tool for the job.</p>
<pre><code>def fileTestInPy():
with open(r'D:\my-file.csv') as fp, open(r'D:\mining.csv', 'w') as mg:
dups = set()
next(fp) # <-- advance fp so you don't need to check each line
# or use enumerate
for line in fp:
col = line.split(',', 1)[0] # <-- only split what you need
if col in dups:
continue
dups.add(col)
mg.write(line)
# mg.write('\n') # <-- line still has its \n, did you
# want another?
</code></pre>
<p>Also, if this is python 3.x and you know your file is ascii or UTF-8, you could open both files in binary mode and save a conversion.</p>
| 1 | 2016-10-08T16:50:21Z | [
"python",
"windows",
"python-3.x",
"pandas",
"python-3.5"
] |
Dictionary counter | 39,934,806 | <p>Let's say I have a sequence "ADFG"
The script should see if it's in the list (A,T,G,C) and then if it is, get the key from the dictionary and add 1.
So, for the sequence "ADFG", it would add 1 to variable "a" and to variable "g", and add 2 to variable "error".
However, while the script isn't returning an error, the dicio[i]+=1 line isn't adding up anything.... Any ideas?
I know there are simpler ways to do this but I would like to use a dictionary.</p>
<pre><code>seq= input ("dna seq:").upper()
a,t,g,c,error=0,0,0,0,0
dicio= {"A":a,"T":t,"G":g,"C":c}
for i in seq:
if i in ("A","T","G","C"):
dicio[i]+=1
a+=1
else:
error+=1
print("A={:.2f} %".format(a/len(seq)*100))
print("T={:.2f} %".format(t/len(seq)*100))
print("G={:.2f} %".format(g/len(seq)*100))
print("C={:.2f} %".format(c/len(seq)*100))
print("Da sequencia,{:.2f} % sao erros".format(error/len(seq)*100))
</code></pre>
| 0 | 2016-10-08T16:40:39Z | 39,934,875 | <p>you mean that t,g,c are unaffected by the adding in <code>dicio</code></p>
<p>That's normal: dictionary has not taken the references of the variables, but just copied the initial values. You're not updating them when you add 1 to the values of the dictionary.
(<code>a</code> is a special case in your code, it gets updated in all cases, but maybe it's a bug, at least not logical compared to the rest of the code).</p>
<p>To do what you want, you need to forget about your <code>t,g</code> ... variables and just use <code>dicio</code> to display the results:</p>
<pre><code>for i in ("A","T","G","C"):
print("{}={:.2f} %".format(i,dicio[i]/len(seq)*100))
</code></pre>
<p>(as a bonus you'll save a lot of copy/paste :))</p>
<p>BTW: If you want to initialize the dictionary and keep keys ordered you need <code>ordereddict</code>:</p>
<pre><code>from Collections import ordereddict
dicio = ordereddict()
for k in ("A","T","G","C"):
dicio[k] = 0
</code></pre>
| 0 | 2016-10-08T16:48:02Z | [
"python",
"python-3.x",
"dictionary",
"count"
] |
Dictionary counter | 39,934,806 | <p>Let's say I have a sequence "ADFG"
The script should see if it's in the list (A,T,G,C) and then if it is, get the key from the dictionary and add 1.
So, for the sequence "ADFG", it would add 1 to variable "a" and to variable "g", and add 2 to variable "error".
However, while the script isn't returning an error, the dicio[i]+=1 line isn't adding up anything.... Any ideas?
I know there are simpler ways to do this but I would like to use a dictionary.</p>
<pre><code>seq= input ("dna seq:").upper()
a,t,g,c,error=0,0,0,0,0
dicio= {"A":a,"T":t,"G":g,"C":c}
for i in seq:
if i in ("A","T","G","C"):
dicio[i]+=1
a+=1
else:
error+=1
print("A={:.2f} %".format(a/len(seq)*100))
print("T={:.2f} %".format(t/len(seq)*100))
print("G={:.2f} %".format(g/len(seq)*100))
print("C={:.2f} %".format(c/len(seq)*100))
print("Da sequencia,{:.2f} % sao erros".format(error/len(seq)*100))
</code></pre>
| 0 | 2016-10-08T16:40:39Z | 39,935,152 | <p>I think you're trying to use dictionaries to store the values instead of having <code>a,t,g,c</code> be connected to it and updated at the same time. Here's some code that uses some dictionary features to make it a little more concise: </p>
<pre><code>seq= input ("dna seq:").upper()
a,t,g,c,error=0,0,0,0,0
dicio= {"A":a,"T":t,"G":g,"C":c}
for i in seq:
if i in dicio.keys():
dicio[i]+=1
else:
error+=1
for key,value in dicio.items():
print("{}={:.2f} %".format(key,value/len(seq)*100))
print("Da sequencia,{:.2f} % sao erros".format(error/len(seq)*100))
</code></pre>
| 0 | 2016-10-08T17:17:22Z | [
"python",
"python-3.x",
"dictionary",
"count"
] |
How to only make a variable decrease once before a while loop repeats (Python) | 39,934,847 | <p>At school I have to do a mini homework of programming a quiz. In this quiz, a user has to input the answer. If they're right, they move straight onto the next question, if they're wrong, then the attempts they have left decrease by 1.
I'm using a while loop to make sure that while the amount of attempts there are left are greater than 0, every time that the user answers incorrectly, it will take off 1 attempt. However, every time I run this command, it loops completely out of control, and ends up subtracting all of the attempts left 1 by 1.
Here's what I have in one question:</p>
<pre><code>answer1 = int(input("What is 420 X 15?\n"))
while trys != 0:
if answer1 == 420*15:
print("Correct!")
trys = 0 #To move straight onto the next question, sets to 0
elif answer1 != 420*15:
trys = trys - 1
print("Incorrect, "+str(trys)+" attempts left")
</code></pre>
<p>Running this in Python 3.5.2 Shell results in this outcome:</p>
<pre><code>What is 420 X 15?
1
Incorrect, 2 attempts left
Incorrect, 1 attempts left
Incorrect, 0 attempts left
</code></pre>
<p>Then it moves onto the next question.</p>
<p>The '1' on line 2 is what I answered purposefully to get the answer wrong. I assume this error definitely has something to do with the loop repeating the <code>trys = trys - 1</code> part of the code on line 7. When the user get's the answer right, there's no problem with the code and it moves onto the next question as I hoped for. When the user is incorrect, it just loops out of control.</p>
<p>Any help would be greatly appreciated, or a redirection to another thread with the answer I'm looking for :)</p>
| 0 | 2016-10-08T16:44:26Z | 39,934,872 | <p>You should move the <code>input</code> inside the loop:</p>
<pre><code>while trys != 0:
answer1 = int(input("What is 420 X 15?\n"))
# ...
</code></pre>
| 1 | 2016-10-08T16:47:51Z | [
"python",
"while-loop"
] |
How to only make a variable decrease once before a while loop repeats (Python) | 39,934,847 | <p>At school I have to do a mini homework of programming a quiz. In this quiz, a user has to input the answer. If they're right, they move straight onto the next question, if they're wrong, then the attempts they have left decrease by 1.
I'm using a while loop to make sure that while the amount of attempts there are left are greater than 0, every time that the user answers incorrectly, it will take off 1 attempt. However, every time I run this command, it loops completely out of control, and ends up subtracting all of the attempts left 1 by 1.
Here's what I have in one question:</p>
<pre><code>answer1 = int(input("What is 420 X 15?\n"))
while trys != 0:
if answer1 == 420*15:
print("Correct!")
trys = 0 #To move straight onto the next question, sets to 0
elif answer1 != 420*15:
trys = trys - 1
print("Incorrect, "+str(trys)+" attempts left")
</code></pre>
<p>Running this in Python 3.5.2 Shell results in this outcome:</p>
<pre><code>What is 420 X 15?
1
Incorrect, 2 attempts left
Incorrect, 1 attempts left
Incorrect, 0 attempts left
</code></pre>
<p>Then it moves onto the next question.</p>
<p>The '1' on line 2 is what I answered purposefully to get the answer wrong. I assume this error definitely has something to do with the loop repeating the <code>trys = trys - 1</code> part of the code on line 7. When the user get's the answer right, there's no problem with the code and it moves onto the next question as I hoped for. When the user is incorrect, it just loops out of control.</p>
<p>Any help would be greatly appreciated, or a redirection to another thread with the answer I'm looking for :)</p>
| 0 | 2016-10-08T16:44:26Z | 39,934,954 | <p>You should make your input inside the loop so each time it take from the user the input and check if trys reach zero so the work code should be like this for the question <br></p>
<pre><code>trys = 3
while trys != 0:
answer1 = int(input("What is 420 X 15?\n"))
if answer1 == 420*15:
print("Correct!")
trys = 0 #To move straight onto the next question, sets to 0
elif answer1 != 420*15:
trys = trys - 1
print("Incorrect, "+str(trys)+" attempts left")
</code></pre>
| 1 | 2016-10-08T16:56:42Z | [
"python",
"while-loop"
] |
Combination of PyCharm and ipython fails to import qt5 or Qt5Agg | 39,934,861 | <p>I have installed elementary os and Pycharm and the whole python stack via <code>conda</code>, and now have troubles starting interactive matplotlib in the <code>ipython</code> sesssion.</p>
<p>Here's pycharm's ipython session:</p>
<pre><code>/home/foo/.conda/envs/myenv3/bin/python3.5 /opt/pycharm-2016.2.3/helpers/pydev/pydevconsole.py 41070 33134
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
PyDev console: using IPython 5.0.0
import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
</code></pre>
<p>And here is what happens if I try to import <code>pyplot</code>:</p>
<pre><code>In[4]: import matplotlib.pyplot as plt
Traceback (most recent call last):
File "/opt/pycharm-2016.2.3/helpers/pydev/pydev_ipython/inputhook.py", line 502, in enable_gui
gui_hook = guis[gui]
KeyError: 'qt5'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/pycharm-2016.2.3/helpers/pydev/_pydev_bundle/pydev_ipython_console_011.py", line 123, in enable_gui
return real_enable_gui(gui, app)
File "/opt/pycharm-2016.2.3/helpers/pydev/pydev_ipython/inputhook.py", line 508, in enable_gui
raise ValueError(e)
ValueError: Invalid GUI request 'qt5', valid ones are:dict_keys(['gtk3', 'wx', 'qt', 'osx', 'pyglet', 'glut', 'tk', 'gtk', 'none', 'qt4'])
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/foo/.conda/envs/myenv3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2869, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-eff513f636fd>", line 1, in <module>
import matplotlib.pyplot as plt
</code></pre>
<ul>
<li>This problem only happens when <code>ipython</code> is installed. <strong>When I don't select ipython, however, I only get an irresponsive black screen when I <code>plt.figure()</code></strong>.</li>
<li>This problem does not happen when I start <code>ipython</code> manually from the terminal (outside of pycharm). Also, if I do <code>matplotlib.use('Qt5Agg')</code> before importing <code>pyplot</code>, the error persists in pycharm, but does not appear in the ipython console in my terminal.</li>
<li>Installing on a new conda environment following <code>conda create -n test python=3.5 ; conda install ipython matplotlib scipy -n test</code> and loading the new environment in pycharm did not help</li>
<li>Reinstalling pycharm 2.3 or Invalidate Caches + Restart did not help</li>
<li>Installing pycharm educational 3.0 did not help</li>
</ul>
<p>How can I get this to work?</p>
| 0 | 2016-10-08T16:46:05Z | 39,944,039 | <p>Pycharm appears to not fully support <code>qt5</code>, the issue is <a href="https://youtrack.jetbrains.com/issue/PY-20981" rel="nofollow">open</a>. Downgrading it is the fastest workaround. </p>
<p>With conda the following will perform a downgrade to the last stable version:</p>
<pre><code>conda install pyqt=4.11.4
</code></pre>
| 1 | 2016-10-09T13:15:17Z | [
"python",
"matplotlib",
"pyqt",
"ipython",
"pycharm"
] |
Deploying Flask Application with pandas to Elastic Beanstalk | 39,934,889 | <p>I a new to AWS. Trying to deploy a simple flask application to AWS. I had no problem until I included pandas package. </p>
<p>No even with the simplest application I get errors such as "your requirements.txt file is invalid". </p>
<p>My test application is very simple:
There are only two files in the folder
application.py and requirements.txt. </p>
<h2>Application.py is basic:</h2>
<pre><code>from flask import Flask
from pandas import DataFrame
application = Flask(__name__)
@application.route("/")
def home():
return "hello pandas "
if __name__ == '__main__':
application.run()
</code></pre>
<hr>
<p>Requirements file was created with pip freeze
boto3==1.4.1
botocore==1.4.60
click==6.6
docutils==0.12
Flask==0.11.1
itsdangerous==0.24
Jinja2==2.8
jmespath==0.9.0
MarkupSafe==0.23
numpy==1.11.2
pandas==0.19.0
python-dateutil==2.5.3
pytz==2016.7
s3transfer==0.1.7
six==1.10.0</p>
<h2> Werkzeug==0.11.11</h2>
<p>I have seen posts recommending choosing a bigger instance type than t1.micro that is default. I have done that as follows:</p>
<pre><code> eb create -i m4.large --timeout 100
</code></pre>
<p>but still no luck. </p>
<p>If anyone has deployed flask application that uses pandas to AWS successfully please advise on the best way to do that.
Thank you.</p>
| 1 | 2016-10-08T16:49:40Z | 39,935,606 | <p>I have had the same problem deploying a django app to EBS with pandas, and the issue was that there are certain C libraries that need to be installed first. Just add this in your .ebextensions folder:</p>
<pre><code>commands:
install_devtools:
command: yum -y groupinstall 'Development tools'
</code></pre>
<p>Heads up, I believe that this will only work on sizes T2 small and above.</p>
| 0 | 2016-10-08T18:02:29Z | [
"python",
"amazon-web-services",
"pandas",
"flask",
"elastic-beanstalk"
] |
Python: selenium select | 39,934,896 | <p>I have a website with some different prices currencies you can select in a <code><select></code> with <code><option></code>, it looks like this:</p>
<pre><code><div class="menu" style="display: none;">
<p class="current-country">
<span class="flag store-7"></span>
Italia
</p>
<div class="currency-list">
<label for="currencyList">Cambia valuta:</label>
<select name="currency-list" id="currencyList" data-bind="valueFromOptions: currencies, value: selectedCurrencyId">
<option value="1" data-label="GBP">£ GBP</option>
<option value="2" data-label="USD">$ USD</option>
<option value="3" data-label="CAD">C$ CAD</option>
<option value="8" data-label="SEK">kr SEK</option>
<option value="9" data-label="NOK">kr NOK</option>
<option value="10" data-label="DKK">kr DKK</option>
<option value="14" data-label="CHF">⣠CHF</option>
<option value="19" data-label="EUR"> ⬠EUR</option>
<option value="21" data-label="AUD">$ AUD</option>
<option value="10021" data-label="RMB">Â¥ RMB</option>
<option value="10042" data-label="HKD">$ HKD</option>
<option value="10064" data-label="NZD">$ NZD</option>
<option value="10078" data-label="SGD">$ SGD</option>
<option value="10085" data-label="TWD">NT$ TWD</option>
<option value="10123" data-label="RUB">ÑÑб. RUB</option>
</select>
</div>
</div>
</code></pre>
<p>I want to iterate between the options available and each time print the price of the item, however, in this website, everytime you change the currency it reloads the page, so the code is not working for me, here is my code:</p>
<pre><code>driver.get(root_url[i] + str(num)) # open the page
el = driver.find_element_by_name('currency-list') # find the <select>
for option in el.find_elements_by_tag_name('option'): # for options inside
div = driver.find_element_by_class_name('menu')
driver.execute_script("document.getElementsByClassName('menu')[0].style.display = 'block';") # make the div containing the <select> visible
option.click()
elem = driver.find_element_by_class_name('current-price') # find the price element and print it
print(elem.get_attribute('innerHTML'), root_url[i] + str(num), option.get_attribute('innerHTML'))
driver.close()
</code></pre>
<p>I get an error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/dodob/PycharmProjects/Learning/Asosly.py", line 17, in <module>
print(elem.get_attribute('innerHTML'), root_url[i] + str(num), option.get_attribute('innerHTML'))
File "C:\Users\dodob\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 111, in get_attribute
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
File "C:\Users\dodob\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 461, in _execute
return self._parent.execute(command, params)
File "C:\Users\dodob\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "C:\Users\dodob\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
Stacktrace:
at fxdriver.cache.getElementAt (resource://fxdriver/modules/web-element-cache.js:9454)
at Utils.getElementAt (file:///C:/Users/dodob/AppData/Local/Temp/tmpb9cwfwq1/extensions/fxdriver@googlecode.com/components/command-processor.js:9039)
at WebElement.getElementAttribute (file:///C:/Users/dodob/AppData/Local/Temp/tmpb9cwfwq1/extensions/fxdriver@googlecode.com/components/command-processor.js:12146)
at DelayedCommand.prototype.executeInternal_/h (file:///C:/Users/dodob/AppData/Local/Temp/tmpb9cwfwq1/extensions/fxdriver@googlecode.com/components/command-processor.js:12661)
at DelayedCommand.prototype.executeInternal_ (file:///C:/Users/dodob/AppData/Local/Temp/tmpb9cwfwq1/extensions/fxdriver@googlecode.com/components/command-processor.js:12666)
at DelayedCommand.prototype.execute/< (file:///C:/Users/dodob/AppData/Local/Temp/tmpb9cwfwq1/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)
</code></pre>
<p>I am sorry for my English, but anyway, what can I do to wait till the page reloads because I think it makes the issue.</p>
<p>If needed, I am trying to scrape some info from ASOS, example link <a href="http://www.asos.com/it/asos/asos-jeans-skinny-alla-caviglia-kaki/prd/6759361" rel="nofollow">here</a></p>
| 0 | 2016-10-08T16:50:25Z | 39,950,929 | <pre><code># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome(\Path to chrome driver\)
driver.maximize_window()
baseurl = "http://www.asos.com/it/asos/asos-jeans-skinny-alla-caviglia-kaki/prd/6759361"
driver.get(baseurl)
def Getprice():
selected_currency = driver.find_element(By.CSS_SELECTOR,".selected-currency")
currentprice = driver.find_element(By.CSS_SELECTOR,".current-price")
print "The price for selected current currency " + selected_currency.text + " is " +currentprice.text
def Setcurrency(text):
one = driver.find_element(By.CLASS_NAME, "selected-currency")
one.click()
currentselection = driver.find_element_by_id("currencyList")
select = Select(currentselection)
select.select_by_visible_text(text)
def getallcurrencies():
one = driver.find_element(By.CLASS_NAME, "selected-currency")
one.click()
el = driver.find_element_by_id("currencyList")
currency =[]
for option in el.find_elements_by_tag_name('option'):
currency.append((option.text).encode('utf8'))
return currency
list_of_currencies = getallcurrencies()
for currency in list_of_currencies:
currentvalue= currency.decode('utf8')
try:
Setcurrency(currentvalue)
time.sleep(2)
element_present = EC.presence_of_element_located((By.CSS_SELECTOR,".current-price"))
WebDriverWait(driver, 10).until(element_present)
Getprice()
except TimeoutException:
print "Timed out waiting for page to load"
</code></pre>
<p>This program will first get all the avaiable currencies & then print all the prices :</p>
<pre><code>The price for selected current currency £ GBP is £ 25,49
The price for selected current currency $ USD is $ 41,10
The price for selected current currency C$ CAD is C$ 50,85
The price for selected current currency kr SEK is SEK 318,66
The price for selected current currency kr NOK is NOK 326,83
The price for selected current currency kr DKK is DKK 254,93
The price for selected current currency ⣠CHF is CHF 38,95
The price for selected current currency ⬠EUR is ⬠33,99
The price for selected current currency $ AUD is $ 54,94
The price for selected current currency ¥ RMB is ¥ 245,12
The price for selected current currency $ HKD is HKD$ 310,89
The price for selected current currency $ NZD is NZD$ 62,13
The price for selected current currency $ SGD is SGD$ 55,41
The price for selected current currency NT$ TWD is NT$ 1.274,65
The price for selected current currency ÑÑб. RUB is ÑÑб. 2.338,81
</code></pre>
<p>Hope this will help in resolving your problem</p>
| 1 | 2016-10-10T03:32:00Z | [
"python",
"selenium"
] |
Storing updated variables in a loop? | 39,934,898 | <p>I have written this program which asks the user about how many rectangles they wants to print out. It also asks for the width and height of each, and prints the triangles. After asking the height and width of each, it moves onto the next rectangle and so on. </p>
<p>This all works fine using the program I've made but at the end I want to print out the total area of all the rectangles that the user has created. How can I update my code and achieve this? How is it possible to store the area of the first rectangle and add the area of the second to this first area and so on?
Here is the code:</p>
<pre><code>size = input("How many rectangles?" ) #asks the number of rectangles
i=1
n = 1
while i <= size:
w = input("Width "+str(n)+"? ") #asks for width of each rectangle
h = input("Height "+str(n)+"? ") #asks for height of each rectangle
n=n+1
h1=1
w1=1
z = ""
while w1 <= w:
z=z+"*"
w1+=1
while h1<=h:
print z
h1+=1
i+=1
</code></pre>
| 0 | 2016-10-08T16:50:51Z | 39,934,946 | <p>How about you just accumulate the total area?</p>
<p>Above your loop, do:</p>
<pre><code>area = 0
</code></pre>
<p>Then, somewhere inside your loop, after you've got <code>w</code> and <code>h</code> from the user, just do</p>
<pre><code>area += w * h
</code></pre>
<p>When you finish looping, <code>area</code> will contain the total area.</p>
| 3 | 2016-10-08T16:56:11Z | [
"python",
"python-2.7"
] |
Storing updated variables in a loop? | 39,934,898 | <p>I have written this program which asks the user about how many rectangles they wants to print out. It also asks for the width and height of each, and prints the triangles. After asking the height and width of each, it moves onto the next rectangle and so on. </p>
<p>This all works fine using the program I've made but at the end I want to print out the total area of all the rectangles that the user has created. How can I update my code and achieve this? How is it possible to store the area of the first rectangle and add the area of the second to this first area and so on?
Here is the code:</p>
<pre><code>size = input("How many rectangles?" ) #asks the number of rectangles
i=1
n = 1
while i <= size:
w = input("Width "+str(n)+"? ") #asks for width of each rectangle
h = input("Height "+str(n)+"? ") #asks for height of each rectangle
n=n+1
h1=1
w1=1
z = ""
while w1 <= w:
z=z+"*"
w1+=1
while h1<=h:
print z
h1+=1
i+=1
</code></pre>
| 0 | 2016-10-08T16:50:51Z | 39,935,049 | <p>This code should really use a for loop instead of a while loop to keep track of counters, keep numbers in variables instead of just "*" strings, and use += instead of x=x+1 in a few places, among other things, but here's a minimal step to solve the total area problem you specifically asked about:</p>
<pre><code>size = input("How many rectangles?" ) #asks the number of rectangles
i=1
n = 1
area = 0
while i <= int(size):
w = float(input("Width "+str(n)+"? ")) #asks for width of each rectangle
h = float(input("Height "+str(n)+"? ")) #asks for height of each rectangle
n+=1
h1=1
w1=1
z = ""
while w1 <= w:
z=z+"*"
w1+=1
while h1<=h:
print(z)
h1+=1
area += len(z)
i+=1
print('total area = ',area)
</code></pre>
| 2 | 2016-10-08T17:06:01Z | [
"python",
"python-2.7"
] |
Installed Virtualenv and activating virtualenv doesn't work | 39,934,906 | <p>I cloned my Django Project from Github Account and activated the virtualenv using famous command <code>source nameofenv/bin/activate</code>
And when I run <code>python manage.py runserver</code> </p>
<p>It gives me an error saying:</p>
<blockquote>
<p>ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?</p>
</blockquote>
| 0 | 2016-10-08T16:51:48Z | 39,935,137 | <p>on ubuntu version</p>
<pre><code>#install python pip
sudo apt-get install python-pip
#install python virtualenv
sudo apt-get install python-virtualenv
# create virtual env
virtualenv myenv
#activate the virtualenv
. myenv/bin/activate
#install django inside virtualenv
pip install django
#create a new django project
django-admin.py startproject mysite
#enter to the folder of the new django project
cd mysite
#run the django project
python manage.py runserver
</code></pre>
| 1 | 2016-10-08T17:15:36Z | [
"python",
"django",
"virtualenv"
] |
Installed Virtualenv and activating virtualenv doesn't work | 39,934,906 | <p>I cloned my Django Project from Github Account and activated the virtualenv using famous command <code>source nameofenv/bin/activate</code>
And when I run <code>python manage.py runserver</code> </p>
<p>It gives me an error saying:</p>
<blockquote>
<p>ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?</p>
</blockquote>
| 0 | 2016-10-08T16:51:48Z | 39,936,492 | <blockquote>
<p>I was thinking that every and each dependency I need, might be present inside virtualenv.</p>
</blockquote>
<p>Well, no. By default, a newly created virtualenv comes empty, that is, with no third-party library. (Optionaly, you may allow a virtualenv to access libraries installed system-wide, but that's another story.)</p>
<p>Once the virtualenv is created, you need to install the dependencies you need.</p>
<p>(How could virtualenv know what dependencies you need?)</p>
<p>The procedure is to install the virtualenv, activate it, and then install the libraries needed for the project (in you case Django and perhaps others).</p>
<p>If you project has a requirements.txt, you may install every required dependency with the command:</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>If your project has a setup.py, you may also execute </p>
<pre><code>pip install -e path/to/your/project/clone/.
</code></pre>
<p>to install the project in the virtualenv. This should install the dependencies.</p>
<p>Of course, if the only dependency is Django, you can just type</p>
<pre><code>pip install django
</code></pre>
| 1 | 2016-10-08T19:28:22Z | [
"python",
"django",
"virtualenv"
] |
Installed Virtualenv and activating virtualenv doesn't work | 39,934,906 | <p>I cloned my Django Project from Github Account and activated the virtualenv using famous command <code>source nameofenv/bin/activate</code>
And when I run <code>python manage.py runserver</code> </p>
<p>It gives me an error saying:</p>
<blockquote>
<p>ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?</p>
</blockquote>
| 0 | 2016-10-08T16:51:48Z | 39,936,515 | <p>I'm guessing you also upload the virtual environment from your other pc. And you hope that only activating that will works, bzz.</p>
<p>It's not recommended to upload the virtualenv files to your git repository, as @Alain says it's a good practice to have a <code>requirements.txt</code> file containing the project dependencies. You can use <code>pip freeze > requirements.txt</code> (when the environment is activated) to generate the project requirements file. </p>
<p>By doing so, when you clone the repository from another computer, you need to create a new virtualenv by issuing the command:</p>
<pre><code>virtualenv nameofenv
</code></pre>
<p>then activating it</p>
<pre><code>source naveofenv/bin/activate
</code></pre>
<p>and finally use the requirements file to install the requirements for your project using</p>
<pre><code>pip install -r requirements.txt
</code></pre>
| 0 | 2016-10-08T19:30:50Z | [
"python",
"django",
"virtualenv"
] |
Python version/import confusion | 39,934,909 | <p>I'm trying to get this Python 2.7 code to work.</p>
<p><a href="https://github.com/slanglab/phrasemachine" rel="nofollow">https://github.com/slanglab/phrasemachine</a></p>
<p>I've downloaded and unzipped the repo from github. Here's what happens when I try to run the code.</p>
<pre><code>phrasemachine$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import phrasemachine
>>> text = "Barack Obama supports expanding social security."
>>> print phrasemachine.get_phrases(text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "phrasemachine.py", line 253, in get_phrases
tagger = TAGGER_NAMES[tagger]()
File "phrasemachine.py", line 166, in get_stdeng_nltk_tagger
tagger = NLTKTagger()
File "phrasemachine.py", line 133, in __init__
import nltk
</code></pre>
<p>ImportError: No module named nltk</p>
<p>So, I need the nltk module. I have that installed here:</p>
<p>Sure enough, Python 2 doesn't know about nltk.</p>
<pre><code>phrasemachine$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named nltk
</code></pre>
<p>But, Python 3 does.</p>
<pre><code>phrasemachine$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import nltk
>>>
</code></pre>
<p>Pip tells me that nltk is already installed, but for 3.5.</p>
<pre><code>$ sudo pip install -U nltk
Requirement already up-to-date: nltk in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/nltk-3.2.1-py3.5.egg
</code></pre>
<p>Update 10/10/16: I installed the 2.7 version of Python via brew, which give me the 2.7 pip.</p>
<pre><code>$ /usr/local/bin/pip --version
pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7)
</code></pre>
<p>Then I installed nltk with that pip:</p>
<pre><code>$ sudo /usr/local/bin/pip install -U nltk
Password:
The directory '/Users/me/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/me/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting nltk
Downloading nltk-3.2.1.tar.gz (1.1MB)
100% |ââââââââââââââââââââââââââââââââ| 1.1MB 683kB/s
Installing collected packages: nltk
Running setup.py install for nltk ... done
Successfully installed nltk-3.2.1
</code></pre>
<p>It says it installed nltk but the warnings are concerning. And, Python 2.7 still fails to import nltk.</p>
<pre><code>$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import phrasemachine
>>> text = "Barack Obama supports expanding social security."
>>> print phrasemachine.get_phrases(text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "phrasemachine.py", line 253, in get_phrases
tagger = TAGGER_NAMES[tagger]()
File "phrasemachine.py", line 166, in get_stdeng_nltk_tagger
tagger = NLTKTagger()
File "phrasemachine.py", line 133, in __init__
import nltk
ImportError: No module named nltk
>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named nltk
</code></pre>
<p>Final update! I pointed Python 2.7 to the site packages directory where Homebrew installs stuff and I'm now good!</p>
<pre><code>>>> import sys
>>> sys.path.append('/usr/local/lib/python2.7/site-packages')
</code></pre>
| 0 | 2016-10-08T16:52:02Z | 39,937,305 | <p>Since you have two python distributions, you also need two versions of <code>pip</code>. Find out where your <code>pip</code> executables are with <code>which -a pip</code>, and install <code>pip</code> for your Python 2.7 distribution if necessary. Then tell the <code>pip</code> that goes with Python 2.7 (perhaps <code>/usr/local/bin/pip</code>) to install the <code>nltk</code>.</p>
<p>(Edit: Pip must be able to find the proper Python on its PATH. I hadn't thought to go into this.)</p>
| 1 | 2016-10-08T20:58:57Z | [
"python",
"osx",
"python-3.x",
"pip",
"nltk"
] |
Retrieve Tkinter Checkbutton Status : TclError: can't read "PY_VAR": no such variable | 39,934,913 | <p>I am using <code>Tkinter</code> in a basic Python 2.7 GUI application and I would like to retrieve the <code>Checkbutton</code> widget status (checked/unchecked) by using a <code>IntVar</code> but I am getting the following error. </p>
<pre><code>TclError: can't read "PY_VAR": no such variable
</code></pre>
<p>I have followed the example on <a href="http://effbot.org/tkinterbook/checkbutton.htm" rel="nofollow">effbot about the Checkbutton Widget</a> and I am using a different <code>IntVar</code> for each button and using a <code>callback</code> function to print the variable by calling the <code>getvar</code> function on the buttons.</p>
<p>My only goal is to view a status of the <code>Checkbutton</code> widget. </p>
<p>I am using the Tkinter Grid Geometry manger to place the widgets on the GUI. Here is a <a href="http://stackoverflow.com/help/mcve">MCVE</a> example that produces the error.</p>
<pre><code>#!/usr/bin/env python
import Tkinter as tk
class Frame(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.buttons = dict() #number to button widget
self.createWidgets(master)
def printvar(self, button_number):
print self.buttons[button_number].getvar()
def createWidgets(self,master):
for n in range(0,4):
var = tk.IntVar()
button = tk.Checkbutton(
master,
variable=var,
command=lambda bn=n: self.printvar(bn)
)
button.grid(row=0, column=n)
self.buttons[n] = button
window = Frame(tk.Tk())
window.mainloop()
</code></pre>
<p>The code makes four numbered buttons passing the number to a <code>lambda</code> function which looks up the button in a <code>dict</code> and calls its corresponding <code>getvar</code> function.</p>
<p>If you run the example code it will produce the following error when you check any of the four buttons. It is in a file named <code>tktest.py</code></p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "./tktest.py", line 20, in <lambda>
command=lambda bn=n: self.printvar(bn)
File "./tktest.py", line 12, in printvar
print self.buttons[button_number].getvar()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 513, in getvar
return self.tk.getvar(name)
TclError: can't read "PY_VAR": no such variable
</code></pre>
<p>There is no <code>var</code> variable for each button and I am therefore calling the <code>getvar</code> method.</p>
<p>Any alternative methodology for checking each individual <code>Checkbutton</code> widget status would also be acceptable. </p>
| 0 | 2016-10-08T16:52:14Z | 39,935,242 | <p>EDIT: First create n number of var for use and than asign for each button and save in a list.</p>
<pre><code>def createWidgets(self,master):
self.vars=[]
for n in range(0,4):
var = tk.IntVar()
self.vars.append(var)
for n in range(0,4):
button = tk.Checkbutton(
master,
variable=self.vars[n],
command=lambda bn=n: self.printvar(bn)
)
button.grid(row=0, column=n)
self.buttons[n] = button
</code></pre>
<p>and then you can change your method to this for call the var for the number</p>
<pre><code>def printvar(self, button_number):
print "The button:{} is {}".format(button_number,self.vars[button_number].get())
</code></pre>
<p>The output for example is:</p>
<pre><code>The button:2 is 0
The button:2 is 1
</code></pre>
<p>when 0 is unchecked and 1 checked</p>
| 2 | 2016-10-08T17:25:21Z | [
"python",
"python-2.7",
"user-interface",
"tkinter"
] |
Checking if input's characters match the ones given in Python | 39,935,019 | <p>I'm in a Python course for beginners.
We have to create a code that turns input of maximum 6 words into an acronym. </p>
<p>Before creating an acronym, it has to check if the words contain only characters from given set, but I can't just check if it's in alphabet as we are using our local alphabet that has special characters (õ, ä, ö, ü).</p>
<pre><code>def main():
nr_of_words_limit = 6
chars = "abcdefghijklmnopqrstuvwõäöüxyz"
def not_allowed_characters_check(text, chars):
"""This checks if all words in text only include characters from chars"""
def acronym(text, chars, nr_of_words_limit):
"""Creates acronym after checking for not allowed characters"""
</code></pre>
<p>So, in this case:</p>
<pre><code>text = "Hello World!"
</code></pre>
<p>It would just say that text contains not allowed characters due to the exclamation mark.</p>
<p>How would I go about comparing if every letter in every word in text matches chars then?</p>
<p>Thanks for any help, really appreciate it.</p>
| 0 | 2016-10-08T17:02:47Z | 39,935,060 | <p>Simplest way is to check if the set of characters in the word is a subset of the alphabet using <code>set(word).issubset(alphabet)</code>. For example:</p>
<pre><code>alpha_set = set("best")
print set("test").issubset(alpha_set)
print set("testa").issubset(alpha_set)
</code></pre>
<p>prints:</p>
<pre><code>True
False
</code></pre>
<p><a href="https://ideone.com/kEz0IV" rel="nofollow">Example here</a></p>
| 1 | 2016-10-08T17:07:28Z | [
"python",
"acronym"
] |
Checking if input's characters match the ones given in Python | 39,935,019 | <p>I'm in a Python course for beginners.
We have to create a code that turns input of maximum 6 words into an acronym. </p>
<p>Before creating an acronym, it has to check if the words contain only characters from given set, but I can't just check if it's in alphabet as we are using our local alphabet that has special characters (õ, ä, ö, ü).</p>
<pre><code>def main():
nr_of_words_limit = 6
chars = "abcdefghijklmnopqrstuvwõäöüxyz"
def not_allowed_characters_check(text, chars):
"""This checks if all words in text only include characters from chars"""
def acronym(text, chars, nr_of_words_limit):
"""Creates acronym after checking for not allowed characters"""
</code></pre>
<p>So, in this case:</p>
<pre><code>text = "Hello World!"
</code></pre>
<p>It would just say that text contains not allowed characters due to the exclamation mark.</p>
<p>How would I go about comparing if every letter in every word in text matches chars then?</p>
<p>Thanks for any help, really appreciate it.</p>
| 0 | 2016-10-08T17:02:47Z | 39,937,024 | <p>You can use <a href="https://docs.python.org/3.4/howto/regex.html#regex-howto" rel="nofollow">regular expressions</a> to check if every word in your text matches a certain pattern. The pattern in your case is that all characters in a word should be letters of the alphabet : uppercase <strong>A-Z</strong> as well as lowercase <strong>a-z</strong> (i assume from your example) and the letters <strong>õäöü</strong> ).</p>
<p>Learning how to use regular expressions might seem daunting for beginners but with a bit of practice you will find them very useful and efficient.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
def check_allowed_chars(text):
"""
"""
pattern = re.compile('[a-zA-Zõäöü]+$')
words = text.split()
for word in words:
if not pattern.match(word):
print('The text contains not allowed characters!')
return
</code></pre>
| 0 | 2016-10-08T20:26:40Z | [
"python",
"acronym"
] |
How does 'range()' work internally? | 39,935,042 | <p>How does the range() differentiate the call being made in this case?</p>
<p><strong>Example:</strong></p>
<pre><code>def ex():
list = [1,2,3,4]
for val in range(len(list)):
print(val)
break
for val in range(len(list)):
print(val)
break
</code></pre>
<p><strong>Output -</strong> </p>
<pre><code>0
0
</code></pre>
<p>In short, my question is why doesn't the output yield this way?</p>
<pre><code>0
1
</code></pre>
<p>During the first call to the range() in the 'first for loop' , the call is 'range(len(list))',
and in the first call to the range() in the 'second for loop', the call is 'range(len(list))' which the equivalent to the second call to the range() in the 'first for loop'. How does range() know if the call was from 'second for loop' and not 'first for loop'?</p>
| 0 | 2016-10-08T17:05:25Z | 39,935,074 | <p>I'm not sure why you expect <code>range</code> <em>would</em> remember that it had been called previously. The class does not maintain any state about previous calls; it simply does what you ask. Each call to <code>range(x)</code> returns a new <code>range</code> object that provides numbers from 0 to <code>x-1</code> as you iterate over it. Each call is independent of any previous calls.</p>
<p>To get the behavior you are describing, you need to reuse the <em>same</em> <em>iterator</em> for the <code>range</code> object in each loop.</p>
<pre><code>Python 3.5.1 (default, Apr 18 2016, 11:46:32)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3,4]
>>> r = range(len(l))
>>> for val in r:
... print(val)
... break
...
0
>>> for val in r:
... print(val)
... break
...
0
>>> i = iter(r)
>>> for val in i:
... print(val)
... break
...
0
>>> for val in i:
... print(val)
... break
...
1
</code></pre>
<hr>
<p>You can image that something like</p>
<pre><code>for x in xs:
do_something(x)
</code></pre>
<p>is short for</p>
<pre><code>i = iter(xs)
while True:
try:
x = next(i)
except StopIteration:
break
do_something(x)
</code></pre>
<p><code>iter</code> returns its argument if it is already, in fact, an iterator, so every <code>for</code> loop returns a fresh, start-at-the-beginning iterator when you attempt to iterate over a non-iterator iterable.</p>
| 6 | 2016-10-08T17:08:47Z | [
"python",
"range"
] |
How should a Python module be structured? | 39,935,054 | <p>This is my first time posting on stack overflow, so I apologize if I do something wrong.</p>
<p>I am trying to understand the best way to structure a Python module. As an example, I made a backup module that syncs the source and destination, only copying files if there are differences between source and destination. The backup module contains only a class named Backup.</p>
<p>Now I was taught that OOP is the greatest thing ever, but this seems wrong. After looking through some of the standard library source, I see that most everything isn't broken out into a class. I tried to do some research on this to determine when I should use a class and when I should just have functions and I got varying info. I guess my main question is, should the following code be left as a class or should it just be a module with functions. It is very simple currently, but I may want to add more in the future.</p>
<pre><code>"""Class that represents a backup event."""
import hashlib
import os
import shutil
class Backup:
def __init__(self, source, destination):
self.source = source
self.destination = destination
def sync(self):
"""Synchronizes root of source and destination paths."""
sroot = os.path.normpath(self.source)
droot = os.path.normpath(self.destination) + '/' + os.path.basename(sroot)
if os.path.isdir(sroot) and os.path.isdir(droot):
Backup.sync_helper(sroot, droot)
elif os.path.isfile(sroot) and os.path.isfile(droot):
if not Backup.compare(sroot, droot):
Backup.copy(sroot, droot)
else:
Backup.copy(sroot, droot)
def sync_helper(source, destination):
"""Synchronizes source and destination."""
slist = os.listdir(source)
dlist = os.listdir(destination)
for s in slist:
scurr = source + '/' + s
dcurr = destination + '/' + s
if os.path.isdir(scurr) and os.path.isdir(dcurr):
Backup.sync_helper(scurr, dcurr)
elif os.path.isfile(scurr) and os.path.isfile(dcurr):
if not Backup.compare(scurr, dcurr):
Backup.copy(scurr, dcurr)
else:
Backup.copy(scurr, dcurr)
for d in dlist:
if d not in slist:
Backup.remove(destination + '/' + d)
def copy(source, destination):
"""Copies source file, directory, or symlink to destination"""
if os.path.isdir(source):
shutil.copytree(source, destination, symlinks=True)
else:
shutil.copy2(source, destination)
def remove(path):
"""Removes file, directory, or symlink located at path"""
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.unlink(path)
def compare(source, destination):
"""Compares the SHA512 hash of source and destination."""
blocksize = 65536
shasher = hashlib.sha512()
dhasher = hashlib.sha512()
while open(source, 'rb') as sfile:
buf = sfile.read(blocksize)
while len(buf) > 0:
shasher.update(buf)
buf = sfile.read(blocksize)
while open(destination, 'rb') as dfile:
buf = dfile.read(blocksize)
while len(buf) > 0:
dhasher.update(buf)
buf = dfile.read(blocksize)
if shasher.digest() == dhasher.digest():
return True
else:
return False
</code></pre>
<p>I guess it doesn't really make sense as a class, since the only method is sync. On the other hand a backup is a real world object. This really confuses me.</p>
<p>As some side questions. My sync method and sync_helper function seem very similar and it is probably possible to collapse the two somehow (I will leave that as an exercise for myself), but is this generally how this is done when using a recursive function that needs a certain initial state. Meaning, is it ok to do some stuff in one function to reach a certain state and then call the recursive function that does the actual thing. This seems messy.</p>
<p>Finally, I have a bunch of utility functions that aren't actually part of the object, but are used by sync. Would it make more sense to break these out into like a utility submodule or something as to not cause confusion?</p>
<p>Structuring my programs is the most confusing thing to me right now, any help would be greatly appreciated.</p>
| 1 | 2016-10-08T17:06:33Z | 39,936,521 | <p>This method (and several others) is wrong:</p>
<pre><code>def copy(source, destination):
"""Copies source file, directory, or symlink to destination"""
</code></pre>
<p>It works the way it was used (<code>Backup.copy(scurr, dcurr)</code>), but it does not work when used on an instance.</p>
<p>All methods in Python should take <code>self</code> as the first positional argument: <code>def copy(self, source, destination)</code>, or should be turned into <code>staticmethod</code> (or moved out of the class).</p>
<p>A static method is declared using the <code>staticmethod</code> decorator:</p>
<pre><code>@staticmethod
def copy(source, destination):
"""Copies source file, directory, or symlink to destination"""
</code></pre>
<p>But in this case, <code>source</code> and <code>destination</code> are actually attributes of <code>Backup</code> instances, so probably it should be modified to use attributes:</p>
<pre><code>def copy(self):
# use self.source and self.destination
</code></pre>
| 0 | 2016-10-08T19:31:18Z | [
"python"
] |
return multiple values from scipy root finding / optimization function | 39,935,131 | <p>I'm trying to return multiple values that are obtained inside a scipy root finding function (scipy.optimize.root).</p>
<p>For example:</p>
<pre><code>B = 1
def testfun(x, B):
B = x + 7
return B**2 + 9/18 - x
y = scipy.optimize.root(testfun, 7, (B))
</code></pre>
<p>Is there any way to return the value of B without using globals? </p>
| 1 | 2016-10-08T17:15:17Z | 39,936,198 | <p>I'm not aware of anything SciPy specific, but how about a simple closure:</p>
<pre><code>from scipy import optimize
def testfun_factory():
params = {}
def testfun(x, B):
params['B'] = x + 7
return params['B']**2 + 9/18 - x
return params, testfun
params, testfun = testfun_factory()
y = optimize.root(testfun, 7, 1)
print(params['B'])
</code></pre>
<p>Alternatively, an instance of a class with <a href="https://docs.python.org/3/reference/datamodel.html#object.__call__" rel="nofollow"><code>__call__</code></a> could also be passed as the callable.</p>
| 1 | 2016-10-08T18:59:03Z | [
"python",
"function",
"optimization",
"scipy"
] |
Mine Tweets between two dates in Python | 39,935,150 | <p>I would like to mine tweets for two keywords for a specific period of time. I currently have the code below, but how do I add so it only mine tweets between two dates? (10/03/2016 - 10/07/2016) Thank you!</p>
<pre><code>#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['python', 'javascript', 'ruby'])
</code></pre>
| 0 | 2016-10-08T17:17:02Z | 39,935,340 | <p>You can't. Have a look at <a href="http://stackoverflow.com/questions/26205102/making-very-specific-time-requests-to-the-second-on-twitter-api-using-python">this question</a>, that is the closest you can get.</p>
<p>The Twitter API does not allow to search by time. Trivially, what you can do is fetching tweets and looking at their timestamps afterwards in Python, but that is highly inefficient.</p>
| 1 | 2016-10-08T17:35:21Z | [
"python",
"twitter"
] |
Dividing a Pandas series with the same series shifted one place | 39,935,169 | <p>I have a Pandas series, a time and a value.
I would like to calculate the changes between each value.
Like this: current value / previous value.</p>
<p>When I run this code:</p>
<pre><code>print now.head(n=3)
print before.head(n=3)
delta = now.divide(before)
print delta.iloc[1]
print now.iloc[1] / before.iloc[1]
</code></pre>
<p>I get this result:</p>
<pre><code>DateTime
2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
2014-01-08 09:32:00 623.53846
Name: close, dtype: float64
DateTime
2014-01-08 09:26:00 624.01000
2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
Name: close, dtype: float64
1.0
1.00000368863
</code></pre>
<p>What am I missing since the last two numbers are not the same?</p>
<p>The series now and before are the same series, only shifted one place. </p>
<p><strong>Update</strong>: The problem was the indexes which pandas matches when dividing. Luckily pandas has the built-in function called .pct_change() that does exactly what I want. Thank you Steven G. for showing me that.</p>
| 0 | 2016-10-08T17:18:48Z | 39,935,230 | <p>the problem is that when you do <code>delta = now.divide(before)</code>it will match indexes. so delta.iloc[1] will be <code>623.53836 / 623.53836</code> representing the division on <code>2014-01-08 09:27:00</code> index</p>
<p>when you use integer location <code>now.iloc[1] / before.iloc[1]</code> it doesn't care about the index so it does <code>623.54066 / 623.53836</code> </p>
<p>remember that <code>.iloc[1]</code> is the second row and <code>.iloc[0]</code> is the first row</p>
| 0 | 2016-10-08T17:24:18Z | [
"python",
"pandas"
] |
Dividing a Pandas series with the same series shifted one place | 39,935,169 | <p>I have a Pandas series, a time and a value.
I would like to calculate the changes between each value.
Like this: current value / previous value.</p>
<p>When I run this code:</p>
<pre><code>print now.head(n=3)
print before.head(n=3)
delta = now.divide(before)
print delta.iloc[1]
print now.iloc[1] / before.iloc[1]
</code></pre>
<p>I get this result:</p>
<pre><code>DateTime
2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
2014-01-08 09:32:00 623.53846
Name: close, dtype: float64
DateTime
2014-01-08 09:26:00 624.01000
2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
Name: close, dtype: float64
1.0
1.00000368863
</code></pre>
<p>What am I missing since the last two numbers are not the same?</p>
<p>The series now and before are the same series, only shifted one place. </p>
<p><strong>Update</strong>: The problem was the indexes which pandas matches when dividing. Luckily pandas has the built-in function called .pct_change() that does exactly what I want. Thank you Steven G. for showing me that.</p>
| 0 | 2016-10-08T17:18:48Z | 39,935,513 | <p>You could divide by the values:</p>
<pre><code>now['delta'] = now.values / before.values
</code></pre>
<p>This will add a new column to your now dataframe of course. </p>
<p>Alternately, if you want this in its own dataframe you could write:</p>
<pre><code>delta = now.copy()
delta['delta'] = now.close.values / before.close.values
delta.drop('close', 1, inplace=True)
</code></pre>
| 0 | 2016-10-08T17:52:49Z | [
"python",
"pandas"
] |
Create nested list using list comprehension | 39,935,226 | <p>I have two lists:</p>
<pre><code>L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]
</code></pre>
<p>And I need to create sub-list for each item in L2 that is smaller than 4, add it to all the numbers in L1 that are smaller than 4.
I tried doing this:</p>
<pre><code>result = [(x+y) for x in L2 if x < 4 for y in L1 if y < 4]
</code></pre>
<p>But it resulted me this:</p>
<pre><code>[4, 4, 6, 6, 6, 6]
</code></pre>
<p>While the outcome should look like this:</p>
<pre><code>[[4, 4], [6, 6], [6, 6]]
</code></pre>
<p>any idea on how should I nest it in the right way?</p>
| 1 | 2016-10-08T17:24:06Z | 39,935,260 | <p>Create a nested list comprehension </p>
<pre><code>>>> [[(x+y) for y in L1 if y < 4] for x in L2 if x < 4]
[[4, 4], [6, 6], [6, 6]]
</code></pre>
<p>Here the inner list comprehension creates the inner lists which are then appended to a single list by the outer comprehension. </p>
| 6 | 2016-10-08T17:26:54Z | [
"python",
"list",
"list-comprehension",
"nested-lists"
] |
Create nested list using list comprehension | 39,935,226 | <p>I have two lists:</p>
<pre><code>L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]
</code></pre>
<p>And I need to create sub-list for each item in L2 that is smaller than 4, add it to all the numbers in L1 that are smaller than 4.
I tried doing this:</p>
<pre><code>result = [(x+y) for x in L2 if x < 4 for y in L1 if y < 4]
</code></pre>
<p>But it resulted me this:</p>
<pre><code>[4, 4, 6, 6, 6, 6]
</code></pre>
<p>While the outcome should look like this:</p>
<pre><code>[[4, 4], [6, 6], [6, 6]]
</code></pre>
<p>any idea on how should I nest it in the right way?</p>
| 1 | 2016-10-08T17:24:06Z | 39,935,277 | <p>The numbers below 4 in L1 are:</p>
<pre><code>L1_below_4 = [x for x in L1 if x < 4]
</code></pre>
<p>And for L2:</p>
<pre><code>L2_below_4 = [y for y in L2 if y < 4]
</code></pre>
<p>Now it's easy:</p>
<pre><code>[[x + y for x in L1_below_4] for y in L2_below_4]
</code></pre>
<p>Or as a one-liner:</p>
<pre><code>[[x + y for x in L1 if x < 4] for y in L2 if y < 4]
</code></pre>
| 1 | 2016-10-08T17:28:48Z | [
"python",
"list",
"list-comprehension",
"nested-lists"
] |
Self learning url filter | 39,935,279 | <p>I need to classify given urls as porn or non porn via python script (not by visiting them in person and watching videos) and I thought about calculating porn probability for each url by classifying words it contains, e.g. if url contains words 'bang' and '18' there is high probability its porn site, I tried implementing it, but it isnt very accurate, are there any python libraries than can help me classify those urls? I'm looking for libraries which can learn from test data, like smart anti-spam filters, like:</p>
<pre><code> data = {
'google.com':0,
'superxxx.com':1,
'bigbangtheory.com':0,
'hot18bangbang.com':1,
...
...
}
</code></pre>
<p>and so on, I've pretty big collection of 'bad' urls, so I think I could train some AI classifier. If this is bad idea, could you recommend me any way of filtering out 'bad' urls from 'good' urls?</p>
| 0 | 2016-10-08T17:28:49Z | 39,935,826 | <p>This is a good use case for logistic regression, but it's not a very good question for Stack Overflow. If you already have the training data, go find a tool (or implement this yourself because it wouldn't be that difficult) and then ask a question about the troubles you're having getting it to work. Stack Overflow is not the place to as for recommendations on tools to use.</p>
| 1 | 2016-10-08T18:24:02Z | [
"python",
"machine-learning",
"artificial-intelligence"
] |
Self learning url filter | 39,935,279 | <p>I need to classify given urls as porn or non porn via python script (not by visiting them in person and watching videos) and I thought about calculating porn probability for each url by classifying words it contains, e.g. if url contains words 'bang' and '18' there is high probability its porn site, I tried implementing it, but it isnt very accurate, are there any python libraries than can help me classify those urls? I'm looking for libraries which can learn from test data, like smart anti-spam filters, like:</p>
<pre><code> data = {
'google.com':0,
'superxxx.com':1,
'bigbangtheory.com':0,
'hot18bangbang.com':1,
...
...
}
</code></pre>
<p>and so on, I've pretty big collection of 'bad' urls, so I think I could train some AI classifier. If this is bad idea, could you recommend me any way of filtering out 'bad' urls from 'good' urls?</p>
| 0 | 2016-10-08T17:28:49Z | 39,935,832 | <p>The modern approach to do this is to use a character level LSTM sequence classifier. It requires a fairly large amount of data though, but it shouldn't be too hard to find, by getting examples of family filter black lists for example. </p>
<p>Here are some examples of the concept: </p>
<ul>
<li>I would start here, a cool article on character level LSTMs: <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/" rel="nofollow">The Unreasonable Effectiveness of Recurrent Neural Networks
</a> </li>
<li><a href="https://cs224d.stanford.edu/reports/EugeneLouis.pdf" rel="nofollow">Making a Manageable Email Experience with Deep
Learning</a> </li>
<li><a href="http://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/" rel="nofollow">Sequence Classification with LSTM Recurrent Neural Networks in Python with Keras
</a></li>
</ul>
<p>Recurrent neural networks are neural networks that take their own output as input for the next step, or that learn to output state vectors that are passed to their own cell at the next step to represent short term memory.</p>
<p>Basically, your features are sequences of sub sequences of letters (aka, friendship becomes <code>[frie, frien, riend, iends, endsh, ...]</code> in one hot representation), and you have a neural net that has a state that evolves with subsequence it sees, and gives you a judgement at the end.</p>
| 1 | 2016-10-08T18:24:29Z | [
"python",
"machine-learning",
"artificial-intelligence"
] |
Safely using for-loop variables outside the loop | 39,935,281 | <p><a href="http://stackoverflow.com/a/3611987/336527">Most arguments</a> about why the design decision was made to make for-loop variables <em>not</em> local to the loop suggest that there are popular use cases.</p>
<p>The obvious use case is this:</p>
<pre><code>x = default_value
for x in iterator:
# do stuff
# do something with x here
</code></pre>
<p>Unfortunately, often the first line is forgotten:</p>
<pre><code># should have set default value for x here
# but forgot
for x in iterator:
# do stuff
# do something with x here
</code></pre>
<p>So when iterator is empty, they raise <code>NameError</code> if <code>x</code> was not defined earlier.</p>
<p>This mistake gets worse with nested loops:</p>
<pre><code>for y in outer_iterator:
# should have set default value for x here
# but forgot
for x in inner_iterator(y):
# do stuff
# do something with x
</code></pre>
<p>Here forgetting the <code>x = default_value</code> results in a silent error instead of an exception if <code>inner_iterator(y)</code> is empty on the second or later iteration through the outer loop.</p>
<p>Testing these situations is tough, because <code>inner_iterator(y)</code> is not an outside argument, so unless the test is lucky enough to somehow recreate the case when it's empty, the bug won't be detected.</p>
<p>Are all use cases fragile or is there a safe way to rely on the scoping rule of the for-loop variables? </p>
| 1 | 2016-10-08T17:28:54Z | 39,935,817 | <p>There is no 100% safe way to rely on a variable being set inside a for-loop unless you can be 100% sure that the iterator is never empty. To achieve the 100% assurance, you could do something like <code>for x in iterator or [None]:</code>, but this poses a similar "remembering to do it" problem. It is probably more "pythonic" than setting defaults, but defaults may provide more clarity. The whole relying on for-loop scoping is similar to something like <code>if (condition): x = something</code> and then contemplating about what if I call x when condition is false? You probably would not write code like that anyway so why do it for for-loops? I like to make it a habit of declaring all variables that will be used outside upfront (e.g., setting all variables to None or some other default at the beginning of a function), but it just comes down to preference.</p>
| 0 | 2016-10-08T18:23:28Z | [
"python",
"python-3.x",
"scope"
] |
Safely using for-loop variables outside the loop | 39,935,281 | <p><a href="http://stackoverflow.com/a/3611987/336527">Most arguments</a> about why the design decision was made to make for-loop variables <em>not</em> local to the loop suggest that there are popular use cases.</p>
<p>The obvious use case is this:</p>
<pre><code>x = default_value
for x in iterator:
# do stuff
# do something with x here
</code></pre>
<p>Unfortunately, often the first line is forgotten:</p>
<pre><code># should have set default value for x here
# but forgot
for x in iterator:
# do stuff
# do something with x here
</code></pre>
<p>So when iterator is empty, they raise <code>NameError</code> if <code>x</code> was not defined earlier.</p>
<p>This mistake gets worse with nested loops:</p>
<pre><code>for y in outer_iterator:
# should have set default value for x here
# but forgot
for x in inner_iterator(y):
# do stuff
# do something with x
</code></pre>
<p>Here forgetting the <code>x = default_value</code> results in a silent error instead of an exception if <code>inner_iterator(y)</code> is empty on the second or later iteration through the outer loop.</p>
<p>Testing these situations is tough, because <code>inner_iterator(y)</code> is not an outside argument, so unless the test is lucky enough to somehow recreate the case when it's empty, the bug won't be detected.</p>
<p>Are all use cases fragile or is there a safe way to rely on the scoping rule of the for-loop variables? </p>
| 1 | 2016-10-08T17:28:54Z | 39,935,819 | <p>I agree that the most obvious reason for loops not to have their own scope, is the complications that would introduce when assigning values to variables in the outer scope.</p>
<p>But that does not necessarily mean the iterated value. Consider the following:</p>
<pre><code>total = 0
for item in some_list:
total += item
</code></pre>
<p>If the loop had its own variable scope, implementing this would be a nightmare.</p>
<p>One of the onsequences is that the <code>item</code> is also avaialable out of the loop, but that does not really mean there is a nice way (or as you say <em>"safe"</em> way) to use it.</p>
<p>You can use it, but then you have to be careful.</p>
| 0 | 2016-10-08T18:23:33Z | [
"python",
"python-3.x",
"scope"
] |
Python Get Variable Name Inside Class | 39,935,305 | <p>In Python 3, if you have a class, like this:</p>
<pre><code>LETTERS = list('abcdefghijklmnopqrstuvwxyz')
class letter:
def __init__(self, name):
self.number = LETTERS.index(name)
self.nextLetter = LETTERS[self.number+1]
self.previousLetter = LETTERS[self.number-1]
</code></pre>
<p>and you create an instance of letter, myLetter, like this:</p>
<p><code>myLetter = letter('c')</code></p>
<p>In letter, how do I get the variable name? (myLetter in this case)</p>
| 0 | 2016-10-08T17:31:01Z | 39,935,801 | <p>Think of <code>myLetter</code> as a pointer to the class instance of <code>letter</code>. For example, if you have:</p>
<pre><code>LETTERS = list('abcdefghijklmnopqrstuvwxyz')
class letter:
def __init__(self, name):
self.number = LETTERS.index(name)
self.nextLetter = LETTERS[self.number+1]
self.previousLetter = LETTERS[self.number-1]
myLetter = letter('c')
myLetter2 = myLetter
</code></pre>
<p>Both myLetter and myLetter2 are aliases for the exact same myLetter instance. For example:</p>
<pre><code>myLetter.number = 50
print(myLetter2.number)
>>> 50
</code></pre>
<p>So finding something to return the name of the <code>letter</code> instance within the <code>letter</code> class is ambiguous.</p>
| 2 | 2016-10-08T18:22:19Z | [
"python",
"class",
"python-3.x"
] |
pip install bs4 giving _socketobject error | 39,935,335 | <p>I am trying to install BeautifulSoup4 using the command <code>pip install BeautifulSoup4</code>, as per the bs documentation here:</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/#Download">https://www.crummy.com/software/BeautifulSoup/#Download</a></p>
<p>I am using Mac OS X 10.7.5, and python 2.7.12</p>
<p>When I run the command in Terminal I get the error:</p>
<pre><code>AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
</code></pre>
<p>Can anyone suggest what I'm doing wrong? Thanks in advance.</p>
<p>EDIT:
In light of comments I have tried to run <code>sudo pip install pyopenssl</code> however I get the same 'socketobject' error.</p>
| 7 | 2016-10-08T17:34:30Z | 40,023,593 | <p>From what I understand, the <em><code>pyopenssl</code> package version installed system-wide is not up-to-date</em>. Upgrade it:</p>
<pre><code>sudo pip install --upgrade pyopenssl
</code></pre>
<p>Or, remove it and install the latest in your virtual environment:</p>
<pre><code>$ sudo pip uninstall pyopenssl
$ # activate virtual environment
(myvirtualenv) $ pip install --upgrade pyopenssl
</code></pre>
| 1 | 2016-10-13T14:18:29Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
pip install bs4 giving _socketobject error | 39,935,335 | <p>I am trying to install BeautifulSoup4 using the command <code>pip install BeautifulSoup4</code>, as per the bs documentation here:</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/#Download">https://www.crummy.com/software/BeautifulSoup/#Download</a></p>
<p>I am using Mac OS X 10.7.5, and python 2.7.12</p>
<p>When I run the command in Terminal I get the error:</p>
<pre><code>AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
</code></pre>
<p>Can anyone suggest what I'm doing wrong? Thanks in advance.</p>
<p>EDIT:
In light of comments I have tried to run <code>sudo pip install pyopenssl</code> however I get the same 'socketobject' error.</p>
| 7 | 2016-10-08T17:34:30Z | 40,042,425 | <p>Alternatively, you can install Anaconda Python from: <a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a></p>
<p>This installation includes BS out of the box as most of the common libraries you will use. Plus it makes library installation quite easy.</p>
| 0 | 2016-10-14T11:47:07Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
pip install bs4 giving _socketobject error | 39,935,335 | <p>I am trying to install BeautifulSoup4 using the command <code>pip install BeautifulSoup4</code>, as per the bs documentation here:</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/#Download">https://www.crummy.com/software/BeautifulSoup/#Download</a></p>
<p>I am using Mac OS X 10.7.5, and python 2.7.12</p>
<p>When I run the command in Terminal I get the error:</p>
<pre><code>AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
</code></pre>
<p>Can anyone suggest what I'm doing wrong? Thanks in advance.</p>
<p>EDIT:
In light of comments I have tried to run <code>sudo pip install pyopenssl</code> however I get the same 'socketobject' error.</p>
| 7 | 2016-10-08T17:34:30Z | 40,078,202 | <p>I'm using <code>OS X 10.12</code> and <code>python 2.7.10</code></p>
<pre><code>sudo easy_install BeautifulSoup4
sudo easy_install pyopenssl
</code></pre>
<p>They all worked fine.</p>
| 0 | 2016-10-17T03:46:11Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
pip install bs4 giving _socketobject error | 39,935,335 | <p>I am trying to install BeautifulSoup4 using the command <code>pip install BeautifulSoup4</code>, as per the bs documentation here:</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/#Download">https://www.crummy.com/software/BeautifulSoup/#Download</a></p>
<p>I am using Mac OS X 10.7.5, and python 2.7.12</p>
<p>When I run the command in Terminal I get the error:</p>
<pre><code>AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
</code></pre>
<p>Can anyone suggest what I'm doing wrong? Thanks in advance.</p>
<p>EDIT:
In light of comments I have tried to run <code>sudo pip install pyopenssl</code> however I get the same 'socketobject' error.</p>
| 7 | 2016-10-08T17:34:30Z | 40,095,393 | <p>See <a href="http://stackoverflow.com/a/31576259/3579910">http://stackoverflow.com/a/31576259/3579910</a>:</p>
<p>Try:</p>
<pre><code>sudo apt-get purge python-openssl
sudo apt-get install libffi-dev
sudo pip install pyopenssl
</code></pre>
<p>Apparently you can't vote duplicate if there is an open bounty.</p>
<p>Background:</p>
<blockquote>
<p>That happend because Ubuntu 12.04 (that is my server's OS) has old
pyOpenSSL library which not accept attribute 'set_tlsext_host_name'.
For fix that, you need to add dependence pyOpenSSL >= 0.13. On Ubuntu
for update pyOpenSSL use pip, you also need to install libffi-dev and
remove python-openssl by apt.</p>
</blockquote>
<p><a href="https://github.com/passslot/passslot-python-sdk/issues/1" rel="nofollow">Source</a></p>
<hr>
<p>On Mac, you can get homebrew to replace the apt-get calls: follow the instructions for installing <a href="http://stackoverflow.com/a/19688479/3579910">homebrew</a>.</p>
| 0 | 2016-10-17T20:47:34Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
pip install bs4 giving _socketobject error | 39,935,335 | <p>I am trying to install BeautifulSoup4 using the command <code>pip install BeautifulSoup4</code>, as per the bs documentation here:</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/#Download">https://www.crummy.com/software/BeautifulSoup/#Download</a></p>
<p>I am using Mac OS X 10.7.5, and python 2.7.12</p>
<p>When I run the command in Terminal I get the error:</p>
<pre><code>AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'
</code></pre>
<p>Can anyone suggest what I'm doing wrong? Thanks in advance.</p>
<p>EDIT:
In light of comments I have tried to run <code>sudo pip install pyopenssl</code> however I get the same 'socketobject' error.</p>
| 7 | 2016-10-08T17:34:30Z | 40,100,036 | <p>"That happend because your OS has old pyOpenSSL library which is does not an accept attribute 'set_tlsext_host_name'.
To fix this, you need to add dependence pyOpenSSL >= 0.13.</p>
<pre><code>$ brew purge python-openssl
$ brew install libffi-dev
$ brew install pyOpenSSL
</code></pre>
<p>Let me know if this is unclear or if it doesn't work for you.</p>
| 1 | 2016-10-18T05:14:31Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
Multiple regression output nodes in tensorflow learn | 39,935,394 | <p>I am relatively new to tensorflow and want to use the DNNRegressor from tf.contrib.learn for a regression task. But instead of one output node, I would like to have several (let's say ten for example). </p>
<p>How can I configure my regressor to adjust many output nodes to fit my needs? </p>
<p>My question is related to the following ones already asked on SO, but there seems to be no working answer (I am using TensorFlow version 0.11)</p>
<p><a href="http://stackoverflow.com/questions/34224826/skflow-regression-predict-multiple-values?rq=1">skflow regression predict multiple values</a></p>
<p><a href="http://stackoverflow.com/questions/39192107/multiple-target-columns-with-skflow-tensorflowdnnregressor">Multiple target columns with SkFlow TensorFlowDNNRegressor</a></p>
| 1 | 2016-10-08T17:39:37Z | 40,039,971 | <p>It seems using tflearn will be the other choice.</p>
<p>Update: I realize we should use Keras as an well developed API for tensorflow+ theano .</p>
| 1 | 2016-10-14T09:41:51Z | [
"python",
"tensorflow",
"skflow"
] |
python3 exception invalid syntax error | 39,935,486 | <p>I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:</p>
<pre><code>Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list
</code></pre>
<p>and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.</p>
<pre><code>line = line.split()
if line.index("create"):
print("basd");
except ValueError:
print("123");
</code></pre>
<p>But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.</p>
| -2 | 2016-10-08T17:49:48Z | 39,935,502 | <p>You need to add <code>try</code> before the <code>if</code> statement:</p>
<pre><code>line = line.split()
try: # added 'try'
if line.index("create"):
print("basd");
except ValueError:
print("123");
</code></pre>
<p>Also note, you don't need the semicolons at the end of statements, and it is generally frowned upon when they are used in that way.</p>
<p>As an alterintave to @Rosemans solution, you can do that all on one line:</p>
<pre><code>print('basd') if "create" in line else print("123")
</code></pre>
| 0 | 2016-10-08T17:51:54Z | [
"python",
"exception"
] |
python3 exception invalid syntax error | 39,935,486 | <p>I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:</p>
<pre><code>Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list
</code></pre>
<p>and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.</p>
<pre><code>line = line.split()
if line.index("create"):
print("basd");
except ValueError:
print("123");
</code></pre>
<p>But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.</p>
| -2 | 2016-10-08T17:49:48Z | 39,935,531 | <p>if/except is not a valid construct. Use try/except:</p>
<pre><code>line = line.split()
try:
if line.index('create'):
print('basd')
except ValueError:
print("123")
</code></pre>
<p>Alternatively, you could avoid the exception and the try/except altogether:</p>
<pre><code>line = line.split()
if 'create' in line:
print('basd')
else:
print("123")
</code></pre>
| 1 | 2016-10-08T17:54:34Z | [
"python",
"exception"
] |
python3 exception invalid syntax error | 39,935,486 | <p>I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:</p>
<pre><code>Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list
</code></pre>
<p>and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.</p>
<pre><code>line = line.split()
if line.index("create"):
print("basd");
except ValueError:
print("123");
</code></pre>
<p>But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.</p>
| -2 | 2016-10-08T17:49:48Z | 39,935,543 | <p>Rather than using <code>index</code>, you should just be using the <code>in</code> operator, which returns a simple boolean:</p>
<pre><code>if "create" in line:
print("basd")
else:
print("123")
</code></pre>
<p>This will not raise an exception so there is no need for try/except.</p>
| 4 | 2016-10-08T17:55:55Z | [
"python",
"exception"
] |
python3 exception invalid syntax error | 39,935,486 | <p>I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:</p>
<pre><code>Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list
</code></pre>
<p>and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.</p>
<pre><code>line = line.split()
if line.index("create"):
print("basd");
except ValueError:
print("123");
</code></pre>
<p>But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.</p>
| -2 | 2016-10-08T17:49:48Z | 39,935,564 | <pre><code>#use try block..
line = line.split()
try:
if line.index("create"):
print("basd")
except ValueError:
print("123")
</code></pre>
| -1 | 2016-10-08T17:58:38Z | [
"python",
"exception"
] |
Intellisense in visual studio for app engine python project | 39,935,497 | <p>I am trying to have intellisense support for my python app engine project in visual studio 2015(community edition ptvs installed)</p>
<p>How I could achive this?</p>
<p>What I have tried is: </p>
<p>I installed <code>ndb</code> for <code>from google.appengine.ext import ndb</code> with pip which seems ok for intellisense:</p>
<p><code>from google.appengine.ext.ndb import msgprop</code><br>
becomes<br>
<code>from ndb import msgprop</code></p>
<p>and </p>
<p><code>D:\Python27\Lib\site-packages</code> has <code>ndb</code> and <code>ndb-1.0.13b1.dist-info</code> </p>
<p>I don't think when I upload to app engine this will work </p>
| 0 | 2016-10-08T17:50:54Z | 39,954,367 | <p>Add folder: C:\Program Files (x86)\Google\google_appengine resolves issue:</p>
<p><a href="http://i.stack.imgur.com/iUkWy.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/iUkWy.jpg" alt="enter image description here"></a></p>
<p>and project looks like</p>
<p><a href="http://i.stack.imgur.com/1W1NW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/1W1NW.jpg" alt="enter image description here"></a></p>
<p>Do not forget restart VS 2015 to get intellisense.</p>
<p>Then in order to void upload this folder to app engine in app.yaml add section: </p>
<pre><code>skip_files:
- ^(google)
</code></pre>
| 0 | 2016-10-10T08:39:24Z | [
"python",
"visual-studio",
"google-app-engine",
"visual-studio-2015-comm"
] |
Invalid block tag : 'endblock'. Did you forget to register or load this tag? | 39,935,578 | <p>l get stuck in this error. l'm fresh user of <code>Django</code> and l m learning it by following steps on Youtube channel. l did everything same but l got this block tag error.
here is layout1 html content:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{ % block title %}{% endblock %}</title>
</head>
<body>
{ % block content %} {% endblock %}
</body>
</html>
</code></pre>
<p>index html content:</p>
<pre><code>{% extends "layout/layout1.html"%}
{% block title %}The Video page{% endblock %}
{ % block content %}
<h1>This is a html</h1>
<p>This is a p tag</p>
<a href="http://www.noobmovies.com">Click me!</a>
<img src="https://upload.wikimedia.org/wikipedia/en/7/72/Anthony_Raneri.jpg"/>
{% endblock % }
</code></pre>
<p>views.py content:</p>
<pre><code>from django.template.response import TemplateResponse
# Create your views here.
def video(request):
return TemplateResponse (request,"video/index.html",{})
</code></pre>
<p>how can l handle this problem? as l did double-check to make sure everything is typed same like Youtube channel and normally ,l did not get where l did a mistake.</p>
| -1 | 2016-10-08T17:59:55Z | 39,935,688 | <p>Django didn't recognise your starting block tag, because you have a space between the <code>{</code> and the <code>%</code>.</p>
<p>You also have the same error in both start and end tags in the other template file.</p>
| 1 | 2016-10-08T18:10:38Z | [
"python",
"html",
"django"
] |
Invalid block tag : 'endblock'. Did you forget to register or load this tag? | 39,935,578 | <p>l get stuck in this error. l'm fresh user of <code>Django</code> and l m learning it by following steps on Youtube channel. l did everything same but l got this block tag error.
here is layout1 html content:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{ % block title %}{% endblock %}</title>
</head>
<body>
{ % block content %} {% endblock %}
</body>
</html>
</code></pre>
<p>index html content:</p>
<pre><code>{% extends "layout/layout1.html"%}
{% block title %}The Video page{% endblock %}
{ % block content %}
<h1>This is a html</h1>
<p>This is a p tag</p>
<a href="http://www.noobmovies.com">Click me!</a>
<img src="https://upload.wikimedia.org/wikipedia/en/7/72/Anthony_Raneri.jpg"/>
{% endblock % }
</code></pre>
<p>views.py content:</p>
<pre><code>from django.template.response import TemplateResponse
# Create your views here.
def video(request):
return TemplateResponse (request,"video/index.html",{})
</code></pre>
<p>how can l handle this problem? as l did double-check to make sure everything is typed same like Youtube channel and normally ,l did not get where l did a mistake.</p>
| -1 | 2016-10-08T17:59:55Z | 39,935,696 | <p>You simply have typos.</p>
<p>You should have <code>{%</code> not <code>{ %</code>, and you got those typos in both of templates.</p>
<p>So you need to have </p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
</code></pre>
<p>and </p>
<pre><code>{% extends "layout/layout1.html"%}
{% block title %}The Video page{% endblock %}
{% block content %}
<h1>This is a html</h1>
<p>This is a p tag</p>
<a href="http://www.noobmovies.com">Click me!</a>
<img src="https://upload.wikimedia.org/wikipedia/en/7/72/Anthony_Raneri.jpg"/>
{% endblock %}
</code></pre>
<p>NOTE: don't forget about identations in <em>html</em> files, it makes code more readable.</p>
| 1 | 2016-10-08T18:11:10Z | [
"python",
"html",
"django"
] |
Python code: explain please | 39,935,607 | <pre><code>first_num = raw input ("Please input first number. ")
sec_num = raw input (" Please input second number:")
answer = into( first_num) +into( sec_num)
print " Now I will add your two numbers : ", answer
print " Pretty cool. huh ?
print " Now I'll count backwards from ",answer
counter = answer
while (counter >=0):
print counter
counter = counter-1
print " All done !"
</code></pre>
<p>I think the first half in a command to add first and second numbers to get sum and the second half is a command to return to start or zero out. I don't know python language.</p>
| -5 | 2016-10-08T18:02:42Z | 39,936,178 | <p>You should probably try to run the code first and play with it to understand it. The code is simple; the first half take two user inputs and add them to each other then it displays the result. </p>
<pre><code>first_num = input("Please input first number:") # get first number input
sec_num = input("Please input second number:") # get second number input
answer = int(first_num) +int(sec_num) # add up int values of the numbers
print(" Now I will add your two numbers : ", answer) # display answer
</code></pre>
<p>As for the second half it takes a number from which it counters downward till zero</p>
<pre><code>print("Now I'll count backwards from ", answer)
counter = answer # set counter start value
while(counter >=0):
print(counter) # display counter value on each iteration
counter = counter-1 # decrement counter value on each iteration
print(" All done !)
</code></pre>
<p>I changed your code cause your lines were a bit messy and some incorrect. This version by me works on python3 and <strong>NOT</strong> python2.7. If you want to learn python I advise you to start with <a href="https://www.codecademy.com/learn/python" rel="nofollow">code academy python tutorial</a></p>
| 1 | 2016-10-08T18:57:57Z | [
"python"
] |
Flask application not reflecting new JS changes | 39,935,655 | <p>I have the following code in my Flask server:</p>
<pre><code> res = Response(resp, mimetype='text/plain')
res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
res.headers["Pragma"] = "no-cache"
res.headers["Expires"] = "0"
return res
</code></pre>
<p>On the client side I have some javascript code (in folder static/JS/) that I am constantly editing while fixing bugs and so on. However the changes I make to the javascript code (example adding an alert or debug statement) do not execute when I refresh the page in a regular chrome window (even when I kill the browser and restart it). This means it continues to run an older (cached copy). The refresh works properly when I use an incognito window. Is there a way so that even the regular browser window can always fetch the latest code? I am concerned that in a production environment the browser will used cached copies and cause an issue.</p>
| 0 | 2016-10-08T18:06:58Z | 39,936,150 | <p>One trick for making sure the browser does not cache a file is to change the url when the file changes. That can be done without changing the filename, by appending a query:</p>
<pre><code><script src="myscript.js?version=7">
</code></pre>
<p>Or, even better:</p>
<pre><code><script src="myscript.js?timestamp=2837482.2456">
</code></pre>
<p>You can make a function which generates the URL with the file's actual timestamp. That way, browser will cache it as long as it does not change.</p>
<p>If you are wondering... the query will be ignored. It does not affect static files.</p>
| 0 | 2016-10-08T18:55:08Z | [
"javascript",
"python",
"caching",
"flask"
] |
Wrangling a data frame in Pandas (Python) | 39,935,744 | <p>I have the following data in a csv file:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
the_data = """
ABC,2016-6-9 0:00,95,{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}
ABC,2016-6-10 0:00,0,{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}
ABC,2016-6-11 0:00,0,{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}
ABC,2016-6-12 0:00,0,{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}
ABC,2016-6-13 0:00,0,{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}
DEF,2016-6-16 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}
DEF,2016-6-17 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}
DEF,2016-6-18 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}
DEF,2016-6-19 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}
DEF,2016-6-20 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}
"""
</code></pre>
<p>I read the data into a Pandas data frame, as follows:</p>
<pre><code>df = pd.read_csv(StringIO(the_data), sep=',', header=None)
</code></pre>
<p>The 'Company' and 'Date' fields will never change.</p>
<p>However, the 'keys' inside the curly braces (e.g. <code>"//PurpleCar"</code>, <code>"//YellowCar"</code>, <code>"//BlueCar"</code>, <code>"//WhiteCar"</code>, <code>"//BlackCar"</code>, <code>"//BlackCar"</code>and <code>"NPO-GreenCar"</code>) are <strong>not static</strong>. They can (and will) change frequently.</p>
<p>(note: another script that I have outputs a dictionary and 'creates' this text file, hence this data structure)</p>
<p>I'd like to get the data frame to appear as follows so that I can use Matplotlib to create visualizations:</p>
<pre><code> Company Date Purple Yellow Blue White-XYZ Black Pink NPO-Green
0 ABC 2016-6-9 115 403 16 0 0 0 0
1 ABC 2016-6-10 219 381 90 0 0 0 0
2 ABC 2016-6-11 817 21 31 0 0 0 0
3 ABC 2016-6-12 80 2011 8888 0 0 0 0
4 ABC 2016-6-13 32 15 4 0 0 0 0
5 DEF 2016-6-16 32 0 0 0 15 4 3
6 DEF 2016-6-17 32 0 0 0 15 4 0
7 DEF 2016-6-18 32 0 0 0 15 4 7
8 DEF 2016-6-19 32 0 0 0 15 4 14
9 DEF 2016-6-20 32 0 0 0 15 4 21
</code></pre>
<p>The problems that I'm facing are:</p>
<p>a) moving the 'key' values up to the column headers</p>
<p>b) allowing the 'key' values to be dynamic (again, they can and will change)</p>
<p>c) removing the square braces (<code>'['</code> and <code>']'</code>)</p>
<p>d) removing the double slashes (<code>'//'</code>) </p>
<p>e) removing the "L" following the numerical value</p>
<p>Points 'c', 'd' and 'e' above can be addressed with the following issue (which is related):</p>
<p><a href="http://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a></p>
<p>It's points 'a' and 'b' that are the ones I'm struggling with.</p>
<p>Does anyone see a way to address these?</p>
<p>Thanks!</p>
<p><strong>* UPDATE *</strong></p>
<p>The data originally posted had a small mistake. Here is the data:</p>
<pre><code>the_data = """
ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}"
ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}"
ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}"
ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}"
ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}"
DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}"
DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}"
DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}"
DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}"
DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}"
"""
</code></pre>
<p>The difference between this data and the original data is the apostrophes <code>(")</code> before the opening curly brace (<code>"{"</code>) and after the closing curly brace (<code>"}"</code>).</p>
| 0 | 2016-10-08T18:16:48Z | 39,937,012 | <p>I really don't think this pandas can do much for you here. You're data is very obtuse and seems to me to be best dealt with using regular expressions. Here's my solution: </p>
<pre><code>import re
static_cols = []
dynamic_cols = []
for line in the_data.splitlines():
if line == '':
continue
# deal with static columns
x = line.split(',')
company, date, other = x[0:3]
keys = ['Company', 'Date', 'Other']
values = [company, date, other]
d = {i: j for i, j in zip(keys, values)}
static_cols.append(d)
# deal with dynamic columns
keys = re.findall(r'(?<=//)[^\']*', line)
values = re.findall(r'\d+(?=L)', line)
d = {i: j for i, j in zip(keys, values)}
dynamic_cols.append(d)
df1 = pd.DataFrame(static_cols)
df2 = pd.DataFrame(dynamic_cols)
df = pd.concat([df1, df2], axis=1)
</code></pre>
<p>And the output: </p>
<p><a href="http://i.stack.imgur.com/0i4f8.png" rel="nofollow"><img src="http://i.stack.imgur.com/0i4f8.png" alt="enter image description here"></a> </p>
<p>Also, your data had an extra column after the date I wasn't sure how to deal with so I just called it 'Other'. It wasn't included in your output, so you can easily remove it if you want as well. </p>
| 0 | 2016-10-08T20:25:03Z | [
"python",
"regex",
"pandas"
] |
Wrangling a data frame in Pandas (Python) | 39,935,744 | <p>I have the following data in a csv file:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
the_data = """
ABC,2016-6-9 0:00,95,{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}
ABC,2016-6-10 0:00,0,{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}
ABC,2016-6-11 0:00,0,{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}
ABC,2016-6-12 0:00,0,{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}
ABC,2016-6-13 0:00,0,{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}
DEF,2016-6-16 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}
DEF,2016-6-17 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}
DEF,2016-6-18 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}
DEF,2016-6-19 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}
DEF,2016-6-20 0:00,0,{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}
"""
</code></pre>
<p>I read the data into a Pandas data frame, as follows:</p>
<pre><code>df = pd.read_csv(StringIO(the_data), sep=',', header=None)
</code></pre>
<p>The 'Company' and 'Date' fields will never change.</p>
<p>However, the 'keys' inside the curly braces (e.g. <code>"//PurpleCar"</code>, <code>"//YellowCar"</code>, <code>"//BlueCar"</code>, <code>"//WhiteCar"</code>, <code>"//BlackCar"</code>, <code>"//BlackCar"</code>and <code>"NPO-GreenCar"</code>) are <strong>not static</strong>. They can (and will) change frequently.</p>
<p>(note: another script that I have outputs a dictionary and 'creates' this text file, hence this data structure)</p>
<p>I'd like to get the data frame to appear as follows so that I can use Matplotlib to create visualizations:</p>
<pre><code> Company Date Purple Yellow Blue White-XYZ Black Pink NPO-Green
0 ABC 2016-6-9 115 403 16 0 0 0 0
1 ABC 2016-6-10 219 381 90 0 0 0 0
2 ABC 2016-6-11 817 21 31 0 0 0 0
3 ABC 2016-6-12 80 2011 8888 0 0 0 0
4 ABC 2016-6-13 32 15 4 0 0 0 0
5 DEF 2016-6-16 32 0 0 0 15 4 3
6 DEF 2016-6-17 32 0 0 0 15 4 0
7 DEF 2016-6-18 32 0 0 0 15 4 7
8 DEF 2016-6-19 32 0 0 0 15 4 14
9 DEF 2016-6-20 32 0 0 0 15 4 21
</code></pre>
<p>The problems that I'm facing are:</p>
<p>a) moving the 'key' values up to the column headers</p>
<p>b) allowing the 'key' values to be dynamic (again, they can and will change)</p>
<p>c) removing the square braces (<code>'['</code> and <code>']'</code>)</p>
<p>d) removing the double slashes (<code>'//'</code>) </p>
<p>e) removing the "L" following the numerical value</p>
<p>Points 'c', 'd' and 'e' above can be addressed with the following issue (which is related):</p>
<p><a href="http://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a></p>
<p>It's points 'a' and 'b' that are the ones I'm struggling with.</p>
<p>Does anyone see a way to address these?</p>
<p>Thanks!</p>
<p><strong>* UPDATE *</strong></p>
<p>The data originally posted had a small mistake. Here is the data:</p>
<pre><code>the_data = """
ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}"
ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}"
ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}"
ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}"
ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}"
DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}"
DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}"
DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}"
DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}"
DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}"
"""
</code></pre>
<p>The difference between this data and the original data is the apostrophes <code>(")</code> before the opening curly brace (<code>"{"</code>) and after the closing curly brace (<code>"}"</code>).</p>
| 0 | 2016-10-08T18:16:48Z | 39,938,209 | <p>Consider converting the dictionary column values as Python dictionaries using <a href="https://docs.python.org/2/library/ast.html" rel="nofollow"><code>ast.literal_eval()</code></a> and then cast them as individual dataframes for final merge with original dataframe:</p>
<pre><code>from io import StringIO
import pandas as pd
import ast
...
df = pd.read_csv(StringIO(the_data), header=None,
names=['Company', 'Date', 'Value', 'Dicts'])
dfList = []
for i in df['Dicts'].tolist():
result = ast.literal_eval(i.replace('L]', ']'))
result = {k.replace('//',''):v for k,v in result.items()}
temp = pd.DataFrame(result)
dfList.append(temp)
dictdf = pd.concat(dfList).reset_index(drop=True)
df = pd.merge(df, dictdf, left_index=True, right_index=True).drop(['Dicts'], axis=1)
print(df)
# Company Date Value Black Blue NPO-Green Pink Purple White-XYZ Yellow
# 0 ABC 2016-6-9 0:00 95 NaN 16.0 NaN NaN 115 0.0 403.0
# 1 ABC 2016-6-10 0:00 0 NaN 90.0 NaN NaN 219 0.0 381.0
# 2 ABC 2016-6-11 0:00 0 NaN 31.0 NaN NaN 817 0.0 21.0
# 3 ABC 2016-6-12 0:00 0 NaN 8888.0 NaN NaN 80 0.0 2011.0
# 4 ABC 2016-6-13 0:00 0 NaN 4.0 NaN NaN 32 0.0 15.0
# 5 DEF 2016-6-16 0:00 0 15.0 NaN 3.0 4.0 32 NaN NaN
# 6 DEF 2016-6-17 0:00 0 15.0 NaN 0.0 4.0 32 NaN NaN
# 7 DEF 2016-6-18 0:00 0 15.0 NaN 7.0 4.0 32 NaN NaN
# 8 DEF 2016-6-19 0:00 0 15.0 NaN 14.0 4.0 32 NaN NaN
# 9 DEF 2016-6-20 0:00 0 15.0 NaN 21.0 4.0 32 NaN NaN
</code></pre>
| 0 | 2016-10-08T22:54:19Z | [
"python",
"regex",
"pandas"
] |
Rasterio Geotiff Coordinate Translation | 39,935,789 | <p>I have some geotiff files but the coordinates are slightly off. I want to use rasterio's API (or other python geo API like pygdal) to geometrically translate (shift) the image. For example, how do I move the image's coordinates 'north' by a single pixel width.</p>
<p>When displayed with a tool like qgis the image should be exactly the same but shifted up a few pixels.</p>
| 0 | 2016-10-08T18:21:23Z | 39,948,444 | <p>Modifying the georeference of a geotiff is a really simple task. I will show how to do it using the <code>gdal</code> python module. First, you should have a look at the <a href="http://www.gdal.org/gdal_datamodel.html" rel="nofollow">GDAL data model</a> with particular focus on the '<strong>affine geotransform</strong>'.</p>
<p>I will assume that your raster is not skewed or rotated, so that your geotransform looks something like</p>
<pre><code>gt = (X_topleft, X_resolution, 0, Y_topleft, 0, Y_resolution)
</code></pre>
<p>With this geotransform, the raster coordinate <code>(0,0)</code> has a top-left corner at <code>(X_topleft, Y_topleft)</code>.</p>
<p>To shift the raster position, you need to change <code>X_topleft</code> and <code>Y_topleft</code>.</p>
<pre><code>import gdal
# open dataset with update permission
ds = gdal.Open('myraster.tif', gdal.GA_Update)
# get the geotransform as a tuple of 6
gt = ds.GetGeoTransform()
# unpack geotransform into variables
x_tl, x_res, dx_dy, y_tl, dy_dx, y_res = gt
# compute shift of 1 pixel RIGHT in X direction
shift_x = 1 * x_res
# compute shift of 2 pixels UP in Y direction
# y_res likely negative, because Y decreases with increasing Y index
shift_y = -2 * y_res
# make new geotransform
gt_update = (x_tl + shift_x, x_res, dx_dy, y_tl + shift_y, dy_dx, y_res)
# assign new geotransform to raster
ds.SetGeoTransform(gt_update)
# ensure changes are committed
ds.FlushCache()
ds = None
</code></pre>
| 1 | 2016-10-09T20:56:33Z | [
"python",
"gdal",
"geotiff",
"rasterio"
] |
python os.system from input nor working | 39,935,808 | <pre><code>#!/usr/bin/env python
import os
import subprocess
mail=raw_input("")
os.system("mail" + mail + "<<<test")
</code></pre>
<p>When I run this program I`ve got error :sh: 1: Syntax error: redirection unexpected.</p>
<p>The script must send mail using mailutilis</p>
| 0 | 2016-10-08T18:23:01Z | 39,936,033 | <p>Don't use <code>os.system</code>. Replace it with <code>subprocess.Popen</code>:</p>
<pre><code>address = raw_input()
with open('test') as text:
subprocess.Popen(["mail", address], stdin=text).wait()
</code></pre>
| 0 | 2016-10-08T18:43:20Z | [
"python",
"os.system"
] |
How can I print a euro (â¬) symbol in Python? | 39,935,857 | <p>I'm teaching myself Python using the command-line interpreter (v3.5 for Windows).</p>
<p><strong>All I want to do is output some text that includes the euro (â¬) symbol</strong> which I understand to be code 80h (128 dec).</p>
<pre><code>#!
# -*- coding: utf-8 -*-
mytext = 'Please pay \x8035.'
print(mytext)
</code></pre>
<p>It falls over on the last line:</p>
<pre><code>UnicodeEncodeError: 'charmap' codec can't encode character '\x80' in position 11: character maps to <undefined>
</code></pre>
<p>I've done lots of googling (re encodings etc) and I've a rough idea why the print command fails. Tinkering with the above code shows that ASCII codes up to \x7f work fine, as one might expect.</p>
<p>But I can't figure out how to display the <strong>â¬</strong>, and I'm finding the information on encodings overwhelming and impenetrable. (Remember I'm just a noob!)</p>
<ul>
<li>I've tried prefixing the text string with <em>u</em> to create a unicode string in the first place.</li>
<li>I've tried creating an intermediate object <em>outputtext = mytext.encode('utf-8')</em> but outputting this with <em>print</em> expands the string into an even more cryptic form: <em>b'Please pay \xc2\x8035.'</em></li>
<li>I've tried to find a different function instead of <em>print</em> to output this intermediate string, but nothing has worked yet.</li>
</ul>
<p>Please can someone show me some code that <strong>just works</strong>, so I can study it and work backwards from there. Thanks!</p>
| 0 | 2016-10-08T18:26:54Z | 39,935,897 | <p>You can use this:</p>
<pre><code>mytext = 'Please pay \u20ac.'
print(mytext)
</code></pre>
<p>... based on <a href="http://www.fileformat.info/info/unicode/char/20ac/index.htm" rel="nofollow">Unicode Character 'EURO SIGN'</a>.</p>
| 2 | 2016-10-08T18:30:49Z | [
"python",
"utf-8",
"character-encoding"
] |
How can I print a euro (â¬) symbol in Python? | 39,935,857 | <p>I'm teaching myself Python using the command-line interpreter (v3.5 for Windows).</p>
<p><strong>All I want to do is output some text that includes the euro (â¬) symbol</strong> which I understand to be code 80h (128 dec).</p>
<pre><code>#!
# -*- coding: utf-8 -*-
mytext = 'Please pay \x8035.'
print(mytext)
</code></pre>
<p>It falls over on the last line:</p>
<pre><code>UnicodeEncodeError: 'charmap' codec can't encode character '\x80' in position 11: character maps to <undefined>
</code></pre>
<p>I've done lots of googling (re encodings etc) and I've a rough idea why the print command fails. Tinkering with the above code shows that ASCII codes up to \x7f work fine, as one might expect.</p>
<p>But I can't figure out how to display the <strong>â¬</strong>, and I'm finding the information on encodings overwhelming and impenetrable. (Remember I'm just a noob!)</p>
<ul>
<li>I've tried prefixing the text string with <em>u</em> to create a unicode string in the first place.</li>
<li>I've tried creating an intermediate object <em>outputtext = mytext.encode('utf-8')</em> but outputting this with <em>print</em> expands the string into an even more cryptic form: <em>b'Please pay \xc2\x8035.'</em></li>
<li>I've tried to find a different function instead of <em>print</em> to output this intermediate string, but nothing has worked yet.</li>
</ul>
<p>Please can someone show me some code that <strong>just works</strong>, so I can study it and work backwards from there. Thanks!</p>
| 0 | 2016-10-08T18:26:54Z | 39,935,957 | <p>In Python 3, you can simply copy and paste the ⬠character directly into a UTF-8 encoded text file (no need for codes):</p>
<pre><code>mytext = 'Please pay â¬.'
print(mytext)
</code></pre>
| 0 | 2016-10-08T18:35:12Z | [
"python",
"utf-8",
"character-encoding"
] |
How can I print a euro (â¬) symbol in Python? | 39,935,857 | <p>I'm teaching myself Python using the command-line interpreter (v3.5 for Windows).</p>
<p><strong>All I want to do is output some text that includes the euro (â¬) symbol</strong> which I understand to be code 80h (128 dec).</p>
<pre><code>#!
# -*- coding: utf-8 -*-
mytext = 'Please pay \x8035.'
print(mytext)
</code></pre>
<p>It falls over on the last line:</p>
<pre><code>UnicodeEncodeError: 'charmap' codec can't encode character '\x80' in position 11: character maps to <undefined>
</code></pre>
<p>I've done lots of googling (re encodings etc) and I've a rough idea why the print command fails. Tinkering with the above code shows that ASCII codes up to \x7f work fine, as one might expect.</p>
<p>But I can't figure out how to display the <strong>â¬</strong>, and I'm finding the information on encodings overwhelming and impenetrable. (Remember I'm just a noob!)</p>
<ul>
<li>I've tried prefixing the text string with <em>u</em> to create a unicode string in the first place.</li>
<li>I've tried creating an intermediate object <em>outputtext = mytext.encode('utf-8')</em> but outputting this with <em>print</em> expands the string into an even more cryptic form: <em>b'Please pay \xc2\x8035.'</em></li>
<li>I've tried to find a different function instead of <em>print</em> to output this intermediate string, but nothing has worked yet.</li>
</ul>
<p>Please can someone show me some code that <strong>just works</strong>, so I can study it and work backwards from there. Thanks!</p>
| 0 | 2016-10-08T18:26:54Z | 39,935,969 | <p>From <a href="http://www.python-forum.org/viewtopic.php?f=6&t=13995" rel="nofollow">http://www.python-forum.org/viewtopic.php?f=6&t=13995</a> :</p>
<p>This is behavior of python 2,Python 3 dos not do this.</p>
<p>Python 2.7:</p>
<pre><code>>>> s = "â¬"
>>> s
'\xe2\x82\xac'
>>> print s
ââ¬
>>> s = u"â¬"
>>> s
u'\u20ac'
>>> print s
â¬
>>> print('\xe2\x82\xac'.decode('utf8'))
â¬
</code></pre>
<p>Python 3.4</p>
<pre><code>>>> s = 'â¬'
>>> s
'â¬'
>>> print(s)
â¬
>>>
>>> print(repr(s))
'â¬'
</code></pre>
| 0 | 2016-10-08T18:37:03Z | [
"python",
"utf-8",
"character-encoding"
] |
How can I print a euro (â¬) symbol in Python? | 39,935,857 | <p>I'm teaching myself Python using the command-line interpreter (v3.5 for Windows).</p>
<p><strong>All I want to do is output some text that includes the euro (â¬) symbol</strong> which I understand to be code 80h (128 dec).</p>
<pre><code>#!
# -*- coding: utf-8 -*-
mytext = 'Please pay \x8035.'
print(mytext)
</code></pre>
<p>It falls over on the last line:</p>
<pre><code>UnicodeEncodeError: 'charmap' codec can't encode character '\x80' in position 11: character maps to <undefined>
</code></pre>
<p>I've done lots of googling (re encodings etc) and I've a rough idea why the print command fails. Tinkering with the above code shows that ASCII codes up to \x7f work fine, as one might expect.</p>
<p>But I can't figure out how to display the <strong>â¬</strong>, and I'm finding the information on encodings overwhelming and impenetrable. (Remember I'm just a noob!)</p>
<ul>
<li>I've tried prefixing the text string with <em>u</em> to create a unicode string in the first place.</li>
<li>I've tried creating an intermediate object <em>outputtext = mytext.encode('utf-8')</em> but outputting this with <em>print</em> expands the string into an even more cryptic form: <em>b'Please pay \xc2\x8035.'</em></li>
<li>I've tried to find a different function instead of <em>print</em> to output this intermediate string, but nothing has worked yet.</li>
</ul>
<p>Please can someone show me some code that <strong>just works</strong>, so I can study it and work backwards from there. Thanks!</p>
| 0 | 2016-10-08T18:26:54Z | 39,936,499 | <p>Here are four ways of printing a string with the Euro symbol in Python 3.x, in increasing order of obscurity.</p>
<p><strong>1. Direct input</strong></p>
<p>Use your keyboard to enter the symbol, or copy and paste it from somewhere else:</p>
<pre class="lang-py prettyprint-override"><code>mytext = "Please pay â¬35."
print(mytext)
</code></pre>
<p><strong>2. Use Unicode glyph number</strong></p>
<p>Look up the Unicode glyph number, for example from the very useful page <a href="http://www.fileformat.info/info/unicode/" rel="nofollow">http://www.fileformat.info/info/unicode/</a>, and use that code in your string:</p>
<pre class="lang-py prettyprint-override"><code>mytext = "Please pay \u20ac35."
print(mytext)
</code></pre>
<p><strong>3. Use glyph name</strong></p>
<p>You can use <a href="https://docs.python.org/3.5/library/unicodedata.html" rel="nofollow"><code>lookup()</code></a> from the <code>unicodedata</code> module to access Unicode glyphs by name. Again <a href="http://www.fileformat.info/info/unicode/" rel="nofollow">http://www.fileformat.info/info/unicode/</a> will help you find the glyph name:</p>
<pre class="lang-py prettyprint-override"><code>import unicodedata
mytext = "Please pay {}35.".format(unicodedata.lookup("EURO SIGN"))
print(mytext)
</code></pre>
<p><strong>4. Use Windows-1252 codepage</strong></p>
<p>If you really want to use the <code>\x80</code> byte code, you can do that, because it represents the Euro symbol in the Windows-1252 codepage. What you need to do is first create a byte string containing that byte code, and then decoding that byte string so that the byte code is translated to the Euro symbol entry in the Windows-1252 codepage:</p>
<pre class="lang-py prettyprint-override"><code>mytext = b"Please pay \x8035.".decode("windows-1252")
print(mytext)
</code></pre>
| 0 | 2016-10-08T19:28:51Z | [
"python",
"utf-8",
"character-encoding"
] |
Why is this regex expression not working? | 39,935,867 | <p>I want to separate out the links from the string which don't have ':' in between and do not end with '.jpg' or '.svg', and also start with '/wiki/'.</p>
<p>So these are wrong - </p>
<pre><code>"https://boomerrang.com"
"/wiki/sbsbs:kjanw"
"/wiki/aswaa:asawsa.jpg"
"/wiki/awssa.random.jpg"
"/wiki/boom.jpg"
</code></pre>
<p>How the final result should look like - </p>
<pre><code>"/wiki/justthis"
</code></pre>
<p><strong>What I tried -</strong> </p>
<pre><code>r'^/wiki/.*[^:](?!jpg|svg)$'
</code></pre>
<p>But its not evaluating properly, infact its giving all the result which I do not want... I'm kind of new to regex, so please tell me why this is not working, and how should I correct it.</p>
<p>Thanks</p>
| 2 | 2016-10-08T18:27:39Z | 39,935,972 | <p>Why your pattern doesn't work:</p>
<p><code>.*[^:]</code> doesn't prevent a <code>:</code> to be present in the string since <code>.*</code> can match it.</p>
<p><code>(?!jpg|svg)$</code> doesn't make sense since it says that the end of the string isn't followed by "jpg" or "svg". Obviously the end of the string isn't followed by anything since it's the end of the string. Keep in mind that a lookaround (lookahead or lookbehind), anchors like <code>^</code>, <code>$</code> or a word-boundary <code>\b</code> are <em>zero-width assertions</em> and don't consume characters, so <code>(?!jpg|svg)</code> and <code>$</code> are tested from the same position in the string.</p>
<p>You can try that:</p>
<pre><code>r'^/wiki/[^:]*(?<!\.jpg)(?<!\.svg)$'
</code></pre>
<p>The two negative lookbehinds at the end ensure that the string doesn't end with <code>.svg</code> or <code>.jpg</code>.</p>
<p><code>[^:]*</code> avoids any <code>:</code> in the string.</p>
| 3 | 2016-10-08T18:37:34Z | [
"python",
"regex"
] |
passing the return of a function into another function in python | 39,935,988 | <p>I am absolutely overlooking something basic here... I'm trying to pass the return of a function (a list of lists) into another function as an argument. When i compile i get the error that the gameGridWords variable is not defined. </p>
<p>Any help would be greatly appreciated!</p>
<p>This is the function that returns gameGridWords:</p>
<pre><code># Populates the tile grid with random word pairs
###########################################################################
def gridWords():
# Picks 18 random words from text file to a list, doubles list and shuffles it, returns a list with 18 pairs of words
words = [line.strip() for line in open("words.txt", 'r')]
randomWords=[]
for i in range(0, 18):
element=random.randint(0, len(words)-1)
randomWords.append(words[element])
randomWords.extend(randomWords)
randomWordPairs=randomWords
random.shuffle(randomWordPairs)
# Populates the game grid with word pairs
gameGridWords=[]
for row in range(6):
columnls=[]
for column in range(6):
columnls.append(randomWordPairs[0])
del randomWordPairs[0]
gameGridWords.append(columnls)
#print (gameGridWords)
return gameGridWords
</code></pre>
<p>This is the function that generates the error:</p>
<pre><code># Draws the game grid and fills it with 18 pairs of random words
###########################################################################
def drawGrid(gameGridWords, revealed=True):
# Background color
gameDisplay.fill(BLACK)
# Draws the grid with gray tiles and populates it with random word pairs
for row in range(6):
for column in range(6):
if not revealed:
color = GRAY
pygame.draw.rect(gameDisplay,color,[(MARGIN + WIDTH) * column + MARGIN,(MARGIN + HEIGHT) * row + MARGIN,WIDTH,HEIGHT])
else:
word_display(gameGridWords[row][column], BLACK, row, column)
"""
# Fills tiles with blue
for row in range(6):
for column in range(6):
if grid[row][column] == 1:
color = BLUE
pygame.draw.rect(gameDisplay,color,[(MARGIN + WIDTH) * column + MARGIN,(MARGIN + HEIGHT) * row + MARGIN,WIDTH,HEIGHT])
"""
timer()
tryCounter()
#pygame.display.update()
</code></pre>
<p>I call gridWords() inside my gameLoop() function outside my actual while loop.</p>
<p>I call drawGrid() in my gameLoop() inside the while loop with : drawGrid(gameGridWords, True) The error i get is as follows:</p>
<p>Traceback (most recent call last): File "C:\Users\Mileta Nikoletic\OneDrive\Eclipse workspace\Python\P-UPPGIFT DD1316\Memory\test6.py", line 440, in gameIntro()</p>
<p>File "C:\Users\Mileta Nikoletic\OneDrive\Eclipse workspace\Python\P-UPPGIFT DD1316\Memory\test6.py", line 192, in gameIntro button("Play (space bar)", 150,400,250,50, GRAY, BLUE, action="play")</p>
<p>File "C:\Users\Mileta Nikoletic\OneDrive\Eclipse workspace\Python\P-UPPGIFT DD1316\Memory\test6.py", line 154, in button gameLoop()</p>
<p>File "C:\Users\Mileta Nikoletic\OneDrive\Eclipse workspace\Python\P-UPPGIFT DD1316\Memory\test6.py", line 423, in gameLoop</p>
<p>drawGrid(gameGridWords, True)
NameError: name 'gameGridWords' is not defined</p>
<p>If i passed gameGridWords into drawGrid, than i assume that gameGridWords would be defined? </p>
<p>Thanks for your patience!</p>
| 1 | 2016-10-08T18:38:29Z | 39,948,473 | <p>You have to assign data returned by first function to variable ie.</p>
<pre><code>result = gridWords()
</code></pre>
<p>and later use this data with second function.</p>
<pre><code>drawGrid(result)
</code></pre>
<p>(btw. name <code>result</code> doesn't matter, you can use different name)</p>
<p>if second function isn't in the same function but in subfunction then you have to send <code>result</code> to this subfunction and this subfunction has to send it to your function</p>
<pre><code>result = gridWords()
subfunction(result)
def subfunction(data):
drawGrid(data)
</code></pre>
| 0 | 2016-10-09T20:59:17Z | [
"python",
"pygame"
] |
Why is this condition-based list comprehension not working? | 39,936,092 | <p>I want to create a list from an existing list after removing all duplicates.
Program works if I use a "for loop" but nothing happens if I use a list comprehension.</p>
<pre><code>#use for loop
l=[1,2,2,3,1,1,2]
j=[]
for i in l:
if i not in j:
j.append(i)
print l
print j
#using list
l1=[1,2,2,3,1,1,2]
j1=[]
j1=[i for i in l1 if i not in j1]
print l1
print j1
</code></pre>
| 0 | 2016-10-08T18:49:05Z | 39,936,121 | <p>The expression <code>[i for i in l1 if i not in j1]</code> is evaluated and then assigned to <em>j1</em>. So during the evaluation <em>j1</em> stays empty.</p>
<p>BTW: An easy was of removing duplicates is to pass the list to the <a href="https://docs.python.org/3/library/functions.html#func-set" rel="nofollow">set</a> function and then to the <a href="https://docs.python.org/3/library/functions.html#func-list" rel="nofollow">list</a> function if you need a list:</p>
<pre><code>j1=list(set(l1))
</code></pre>
| 3 | 2016-10-08T18:52:18Z | [
"python",
"list",
"python-2.7",
"list-comprehension"
] |
Why is this condition-based list comprehension not working? | 39,936,092 | <p>I want to create a list from an existing list after removing all duplicates.
Program works if I use a "for loop" but nothing happens if I use a list comprehension.</p>
<pre><code>#use for loop
l=[1,2,2,3,1,1,2]
j=[]
for i in l:
if i not in j:
j.append(i)
print l
print j
#using list
l1=[1,2,2,3,1,1,2]
j1=[]
j1=[i for i in l1 if i not in j1]
print l1
print j1
</code></pre>
| 0 | 2016-10-08T18:49:05Z | 39,936,145 | <p><code>j1</code> is <code>[]</code> at the start and isn't updated at intermediate points within the list comprehension. Could do this instead of list comprehension though:</p>
<pre><code>l1=[1,2,2,3,1,1,2]
j1=list(set(l1))
print l1
print j1
</code></pre>
| 0 | 2016-10-08T18:54:40Z | [
"python",
"list",
"python-2.7",
"list-comprehension"
] |
In python, how to import just words but not any punctuation from a .txt file? | 39,936,157 | <p>For example ,I have a txt file which content is:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>star, year, op, ed
ad, ed, offer, year
</code></pre>
<blockquote>
<p>Blockquote</p>
</blockquote>
<p>I want to import them and form a list which have each line as a sublist:
[['star','year','op','ed'],['ad','ed','offer','year']]
So I use the command below:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>list = []
with open ("file_name", 'r') as f:
for line in f:
split_line = line.split()
list.append(split_line)
f.close()
</code></pre>
<p>But when I print the list, the result is:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>[['star,','year,','op,','ed'],['ad,','ed,','offer,','year']]
</code></pre>
<p>So how can I get a list with only words but not any punctuations?</p>
| 1 | 2016-10-08T18:55:25Z | 39,936,192 | <p>All you need is splitting with comma and space:</p>
<pre><code>with open ("file_name") as f:
result = [line.split(', ') for line in f]
</code></pre>
<p>And note that you don't need to close the file manually when you are using <code>whith</code> statement. That's exactly what the <code>with</code> does at the end of the block. And another note, don't name your variable names with python built-in names.</p>
<p>As another alternative (and more pythonic approach) for this task you can use <code>csv</code> module which will split your lines automatically with a delimiter (by default the comma).</p>
<pre><code>import csv
with open ("file_name") as f:
spam_reader = csv.reader(f) # you can pass the delimiter to reader function (if its something else rather than comma)
rows = list(spam_reader)
</code></pre>
| 0 | 2016-10-08T18:58:32Z | [
"python",
"python-3.x",
"split"
] |
In python, how to import just words but not any punctuation from a .txt file? | 39,936,157 | <p>For example ,I have a txt file which content is:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>star, year, op, ed
ad, ed, offer, year
</code></pre>
<blockquote>
<p>Blockquote</p>
</blockquote>
<p>I want to import them and form a list which have each line as a sublist:
[['star','year','op','ed'],['ad','ed','offer','year']]
So I use the command below:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>list = []
with open ("file_name", 'r') as f:
for line in f:
split_line = line.split()
list.append(split_line)
f.close()
</code></pre>
<p>But when I print the list, the result is:</p>
<blockquote>
<p>Blockquote</p>
</blockquote>
<pre><code>[['star,','year,','op,','ed'],['ad,','ed,','offer,','year']]
</code></pre>
<p>So how can I get a list with only words but not any punctuations?</p>
| 1 | 2016-10-08T18:55:25Z | 39,936,433 | <p>in split function try to give ", " as argument like this.</p>
<pre><code>split_line = line[:-2].split(", ")
</code></pre>
<p>Hope this helps.</p>
| 0 | 2016-10-08T19:22:20Z | [
"python",
"python-3.x",
"split"
] |
Accessing global from within lambda | 39,936,195 | <p>I never access globals from within functions, instead I pass them in as arguments. Therefore the following code feels weird to me, where I am accessing a global object directly from within the function: </p>
<pre><code>ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))
</code></pre>
<p>How should I be doing this?</p>
| 0 | 2016-10-08T18:58:52Z | 39,936,258 | <p>What's wrong with what you've written? It's not necessarily accessing the global scope, it's really accessing the local scope (and if it doesn't find the variable uses the global scope). Just as an example this is perfectly fine:</p>
<pre><code>def func():
ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))
</code></pre>
<p>Because of this I think of it more as a closure than accessing globals. If you didn't do this with a <code>lambda</code> here's how you could do it:</p>
<pre><code>def wrapper(url):
ws = WebSocket(url)
def send(msg):
return ws.send(msg)
return send
sch.on_receive(wrapper(url))
</code></pre>
<p>Or more tersely:</p>
<pre><code>wrapper = lambda url: Websocket(url).send
sch.on_receive(wrapper(url))
</code></pre>
<p>But this is really just the equivalent of:</p>
<pre><code>sch.on_recieve(WebSocket(url).send)
</code></pre>
| 0 | 2016-10-08T19:04:47Z | [
"python"
] |
Accessing global from within lambda | 39,936,195 | <p>I never access globals from within functions, instead I pass them in as arguments. Therefore the following code feels weird to me, where I am accessing a global object directly from within the function: </p>
<pre><code>ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))
</code></pre>
<p>How should I be doing this?</p>
| 0 | 2016-10-08T18:58:52Z | 39,936,261 | <p>There is no problem with <strong>accessing</strong> global variables from functions (including lambdas), without using <code>global</code>:</p>
<pre><code>>>> a = 1
>>> b = list()
>>>
>>> def f():
... b.append(a)
...
>>> f()
>>> print(b)
[1]
</code></pre>
<p>As you can see above, a global variable can be read and the object in the variable can be used without any restrictions.</p>
<p>What can not be done without a <code>global</code> is <strong>assigning</strong> an object to a global variable. That is because an assignment automatically creates a local variable.</p>
<pre><code>def f():
a = 4 # this is a new local variable a, regardless of whether there is a global 'a'
</code></pre>
<p>Hence, the following is fine:</p>
<pre><code>ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))
</code></pre>
<p>On the other hand, if you really wanted to assign value to a global variable, that would be impossible within a lambda (other than by hacks, such as accessing the globals directory...)</p>
| 1 | 2016-10-08T19:04:59Z | [
"python"
] |
How to make sure the sting appear in somewhere in the list | 39,936,199 | <p><a href="http://i.stack.imgur.com/VJH9R.jpg" rel="nofollow">enter image description here</a>Write a function that takes,as an argument,a list and a string, and returns a Boolean based on whether or not all of the letters in the string appear somewhere in the list.
For question 3</p>
<p>def findLetters(myList,myString):
for i in myList:
if i==myString:
return True
return False
That is what did in python, but if I run python shell it constantly give False.</p>
| -1 | 2016-10-08T18:59:07Z | 39,936,586 | <p>Looks like homework task. It is fairly simple so try it yourself.
Use operator <code>in</code> to check if letter is in string.</p>
<pre><code>if c in string:
print(c, 'is in', string)
</code></pre>
| 0 | 2016-10-08T19:37:23Z | [
"python"
] |
Is it safe and pythonic to consume the iterator in the body of a for loop? | 39,936,220 | <p>Is it safe in Python to do something like this (say, in a parser)?</p>
<pre><code>iterator = iter(some_iterable)
for x in iterator:
# do stuff with x
if some_condition(x):
y = next(iterator)
# do stuff with y
</code></pre>
<p>I've tested in Python 2 and 3 and it does what I expect, but I wonder whether it's really safe and whether it's idiomatic. The above code should be equivalent to the following rather more verbose alternative:</p>
<pre><code>iterator = iter(some_iterable)
while True:
try:
x = next(iterator)
except StopIteration:
break
# do stuff with x
if some_condition(x):
y = next(iterator)
# do stuff with y
</code></pre>
| 3 | 2016-10-08T19:00:51Z | 39,936,333 | <p>Basically it's always better to keep track of your exceptions and handle them properly. But regarding the difference between the <code>while</code> and <code>for</code> loops in this case when you are calling a <code>next()</code> function within a <code>while</code> loop it's always possible to raise an StopIteration exception, but when you are using a <code>for</code> loop based on the number of <code>next()</code> calls and your iteration it may be different.</p>
<p>For example in this case for even number of iteration it doesn't raise an exception but for odds it does. And the reason is that in even iteration numbers your next is always one item in front of the for loop, while for odds it's not like so.</p>
<pre><code>In [1]: it = iter(range(4))
In [2]: for x in it:
...: print(x)
...: next(it)
...:
0
2
In [3]: it = iter(range(3))
In [4]: for x in it:
print(x)
next(it)
...:
0
2
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-4-1b3db7079e29> in <module>()
1 for x in it:
2 print(x)
----> 3 next(it)
4
StopIteration:
</code></pre>
| 1 | 2016-10-08T19:11:21Z | [
"python"
] |
Looking for a regular expression used on variable string | 39,936,275 | <p>I have a string that can vary slightly:</p>
<pre><code>str1 = "[X] text [Y] abc123"
str1 = "(X ) text [y ] abc123"
str1 = "(x) text (Y) abc123"
str1 = "(X ) text (Y) abc123"
str1 = "(X ) text [Y ] abc123"
str1 = "[X] text333 [y] abc123222"
</code></pre>
<p>so basically X and Y are static and they can either be between <code>()</code> or <code>[]</code>. My problem is, that there can be some white spaces as well. X and Y with bracket can be assumed as delimiter to capture group 1. I am currently asking myself how to parse "text" and "abc123" in the most reliable way. How would you do it? "text" and "abc123" are variable strings. I want to use them further</p>
| 0 | 2016-10-08T19:06:09Z | 39,936,426 | <p>How about this? </p>
<pre><code>chars='[]()'
x,text,y,abc123 = ''.join([x for x in str1 if x not in chars]).split()
print(x,text,y,abc123)
</code></pre>
| 0 | 2016-10-08T19:21:21Z | [
"python",
"regex"
] |
Looking for a regular expression used on variable string | 39,936,275 | <p>I have a string that can vary slightly:</p>
<pre><code>str1 = "[X] text [Y] abc123"
str1 = "(X ) text [y ] abc123"
str1 = "(x) text (Y) abc123"
str1 = "(X ) text (Y) abc123"
str1 = "(X ) text [Y ] abc123"
str1 = "[X] text333 [y] abc123222"
</code></pre>
<p>so basically X and Y are static and they can either be between <code>()</code> or <code>[]</code>. My problem is, that there can be some white spaces as well. X and Y with bracket can be assumed as delimiter to capture group 1. I am currently asking myself how to parse "text" and "abc123" in the most reliable way. How would you do it? "text" and "abc123" are variable strings. I want to use them further</p>
| 0 | 2016-10-08T19:06:09Z | 39,936,742 | <p>How about:</p>
<pre><code>[\[)]X[\])]\s*(.+?)\s*[\[(]Y[\])]\s*(.+)
</code></pre>
<p><code>text</code> will be in group 1 and <code>abc123</code> in group 2</p>
<p><strong>Explanation:</strong></p>
<pre><code>[\[)] : character class `[` or `(`
X : whatever X stands for
[\])] : character class `]` or `)`
\s* : 0 or more space character
(.+?) : 1 or more any character non greedy, captured in group 1
\s* : 0 or more space character
[\[(] : character class `[` or `(`
Y : whatever X stands for
[\])] : character class `]` or `)`
\s* : 0 or more space character
(.+) : 1 or more any character, captured in group 2
</code></pre>
| 0 | 2016-10-08T19:54:46Z | [
"python",
"regex"
] |
Looking for a regular expression used on variable string | 39,936,275 | <p>I have a string that can vary slightly:</p>
<pre><code>str1 = "[X] text [Y] abc123"
str1 = "(X ) text [y ] abc123"
str1 = "(x) text (Y) abc123"
str1 = "(X ) text (Y) abc123"
str1 = "(X ) text [Y ] abc123"
str1 = "[X] text333 [y] abc123222"
</code></pre>
<p>so basically X and Y are static and they can either be between <code>()</code> or <code>[]</code>. My problem is, that there can be some white spaces as well. X and Y with bracket can be assumed as delimiter to capture group 1. I am currently asking myself how to parse "text" and "abc123" in the most reliable way. How would you do it? "text" and "abc123" are variable strings. I want to use them further</p>
| 0 | 2016-10-08T19:06:09Z | 39,936,902 | <p>The regex you want could be <code>r'(?i)\s*(?:\[\s*(?:X|Y)\s*\]|\(\s*(?:X|Y)\s*\))\s*'</code>
This assumes that <code>[]</code> or <code>()</code> pairs must match, and that (as you show in your example) X and Y can be either upper or lower case (or mixed case, if <code>X</code> or <code>Y</code> is a longer token). It does not require that <code>[X]</code> preceed <code>[Y]</code>.</p>
<p>If you use this regex to split any of your <code>str1</code> values, you'll get an array of 3 elements (<code>['', 'text', 'abc123']</code>).</p>
<pre><code>strs = [ "[X] text [Y] abc123",
"(X ) text [y ] abc123",
"(x) text (Y) abc123",
"(X ) text (Y) abc123",
"(X ) text [Y ] abc123",
"[X] text333 [y] abc123222", ]
for s in strs:
print(re.split(r'(?i)\s*(?:\[\s*(?:X|Y)\s*\]|\(\s*(?:X|Y)\s*\))\s*', s))
</code></pre>
<p>prints</p>
<pre><code>['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text', 'abc123']
['', 'text333', 'abc123222']
</code></pre>
| 0 | 2016-10-08T20:12:57Z | [
"python",
"regex"
] |
Looking for a regular expression used on variable string | 39,936,275 | <p>I have a string that can vary slightly:</p>
<pre><code>str1 = "[X] text [Y] abc123"
str1 = "(X ) text [y ] abc123"
str1 = "(x) text (Y) abc123"
str1 = "(X ) text (Y) abc123"
str1 = "(X ) text [Y ] abc123"
str1 = "[X] text333 [y] abc123222"
</code></pre>
<p>so basically X and Y are static and they can either be between <code>()</code> or <code>[]</code>. My problem is, that there can be some white spaces as well. X and Y with bracket can be assumed as delimiter to capture group 1. I am currently asking myself how to parse "text" and "abc123" in the most reliable way. How would you do it? "text" and "abc123" are variable strings. I want to use them further</p>
| 0 | 2016-10-08T19:06:09Z | 39,937,036 | <pre class="lang-python prettyprint-override"><code>import re
str1 = "( X ) text [Y] abc 123 xyz"
m = re.match( r'^[\(\[][xX ]+[\]\)]\s*(\S*)\s*[\(\[][yY ]+[\]\)]\s*(.*)$', str1)
if m:
str1text = m.group(1)
str1moretext = m.group(2)
print str1text
print str1moretext
else:
print "No match!!"
</code></pre>
| 0 | 2016-10-08T20:27:22Z | [
"python",
"regex"
] |
Import Error When Adding a Database to a Flask App | 39,936,287 | <p>I'm following this <a href="http://blog.toast38coza.me/adding-a-database-to-a-flask-app/" rel="nofollow">tutorial</a> and when running <code>$ nosetests</code> in Step 2, I'm getting the following import errors:</p>
<pre><code>EE
======================================================================
ERROR: Failure: ImportError (No module named flask_sqlalchemy)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/path/to/project/app/__init__.py", line 4, in <module>
from flask_sqlalchemy import SQLAlchemy
ImportError: No module named flask_sqlalchemy
======================================================================
ERROR: Failure: ImportError (No module named flask_testing)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/path/to/project/tests.py", line 3, in <module>
from flask_testing import TestCase
ImportError: No module named flask_testing
----------------------------------------------------------------------
Ran 2 tests in 0.150s
FAILED (errors=2)
</code></pre>
<p>With the help of <a href="http://stackoverflow.com/questions/18157494/python3-virtual-environment-and-pip">these</a> <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">two</a> links, I'm running the following commands:</p>
<pre><code>// Set up virtual environment
$ cd project
$ python3 -m venv flask
$ source flask/bin/activate
$ (flask)$
// Install
$ (flask)$ curl https://bootstrap.pypa.io/get-pip.py | python3
// Deactivate then reactivate virtual environment
(flask)$ deactivate
$ source flask/bin/activate
// Current status
(flask)$ pip -V
# pip 8.1.2 from /project/flask/lib/python3.5/site-packages (python 3.5)
(flask)$ python -V
# Python 3.5.2
// install modules
$ flask/bin/pip3 install flask
$ flask/bin/pip3 install flask-sqlalchemy
$ flask/bin/pip3 install flask-testing
// Updated status
(flask)$ pip list
# click (6.6)
# Flask (0.11.1)
# Flask-SQLAlchemy (2.1)
# Flask-Testing (0.6.1)
# itsdangerous (0.24)
# Jinja2 (2.8)
# MarkupSafe (0.23)
# pip (8.1.2)
# setuptools (20.10.1)
# SQLAlchemy (1.1.1)
# Werkzeug (0.11.11)
# wheel (0.29.0)
</code></pre>
<p>And have set up the following files:</p>
<pre><code>// tests.py
from flask_testing import TestCase
from app import db, app
TEST_SQLALCHEMY_DATABASE_URI = "sqlite:///test.sqlite"
class MyTest(TestCase):
def create_app(self):
app.config['SQLALCHEMY_DATABASE_URI'] = TEST_SQLALCHEMY_DATABASE_URI
return app
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
// __init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
// run.py
#!flask/bin/python3
from app import app
app.run(debug=True)
</code></pre>
<p>I'm trying to use python3 for everything and it seems it's looking in 2.7 for the modules. Can you tell me what I'm doing wrong? Thanks.</p>
| 0 | 2016-10-08T19:07:08Z | 39,937,672 | <p>In Flask, usually the import errors of modules (though installed), directed to the way you are running the application. When you run the run.py, please check the interpreter path. I have seen some times, running ./run.py would not work since the libraries are under flask/* directories.
You can either run ~/flask/bin/python run.py or add flask/bin/python to LD_LIBRARY_PATH</p>
| 0 | 2016-10-08T21:42:41Z | [
"python",
"flask",
"flask-sqlalchemy"
] |
Permutations of 2 characters in Python into fixed length string with equal numbers of each character | 39,936,344 | <p>I've looked through the 2 questions below, which seem closest to what I am asking, but don't get me to the answer to my question.</p>
<p><a href="http://stackoverflow.com/questions/36517439/permutation-of-x-length-of-2-characters">Permutation of x length of 2 characters</a></p>
<p><a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>
<p>I am trying to find a way to take 2 characters, say 'A' and 'B', and find all unique permutations of those characters into a 40 character string. Additionally - I need each character to be represented 20 times in the string. So all resulting strings each have 20 'A's and 20 'B's.</p>
<p>Like this:</p>
<pre><code>'AAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAAABABBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAABAABBBBBBBBBBBBBBBBBBB'
</code></pre>
<p>etc...</p>
<p>All I really need is the count of unique combinations that follow these rules. </p>
<pre><code>y=['A','A','A','A','B','B','B','B']
comb = set(itertools.permutations(y))
print("Combinations Found: {:,}".format(len(comb)))
</code></pre>
<p>This works, but it doesn't scale well to an input string of 20 'A's and 20 'B's. The above code takes 90 seconds to execute. Even just scaling up to 10 'A's and 10 'B's ran for 20 minutes before I killed it.</p>
<p>Is there more efficient way to approach this given the parameters I've described?</p>
| 2 | 2016-10-08T19:12:10Z | 39,936,670 | <p>If all you need is the count, this can be generalized to <a href="https://en.wikipedia.org/wiki/Binomial_coefficient" rel="nofollow"><code>n</code> choose <code>k</code></a>. Your total size is <code>n</code> and the number of elements of <code>"A"</code> is <code>k</code>. So, your answer would be:</p>
<p>(n choose k) = (40 choose 20) = <a href="http://www.wolframalpha.com/input/?i=40+choose+20" rel="nofollow">137846528820</a></p>
| 0 | 2016-10-08T19:46:48Z | [
"python",
"string",
"algorithm",
"permutation"
] |
Providing visibility of periodic changes to a database | 39,936,352 | <p>This is quite a general question, though Iâll give the specific use case for context.</p>
<p>I'm using a FileMaker Pro database to record personal bird observations. For each bird on the national list, I have extracted quite a lot of base data by website scraping in Python, for example conservation status, geographical range, scientific name and so on. In day-to-day use of the database, this base data remains fixed and unchanging. However, once a year or so I will want to re-scrape the base data to pick up the most recent published information on status, range, and even changes in scientific name (that happens).</p>
<p>I know there are options such as PyFilemaker or bBox which should allow me to write to the FileMaker database from Python, so the update mechanism itself shouldn't be a problem.</p>
<p>It would be rather dangerous simply to overwrite all of last yearâs base data with the newly scraped data, and I'm looking for general advice as to how best to provide visibility for the changes before manually importing them. What I have in mind is to use pandas to generate a spreadsheet using the base data, and to highlight the changed cells. Does that sound a sensible way of doing it? I suspect that this may be a very standard requirement, and if anybody could help out with comments on an approach which is straightforward to implement in Python that would be most helpful. </p>
| 0 | 2016-10-08T19:12:50Z | 39,941,551 | <p>This is not a standard requirement and there is no easy way of doing this. The best way to track changes is a Source Control system like git, but it is not applicable to FileMaker Pro as the files are binary.</p>
<p>You can try your approach, or you can try to add the new records in FileMaker instead of updating them and flag them as current or use only the last record</p>
<p>There are some amazing guys here, but you might want to take it to one of the FileMAker forums as the FIleMAker audience there is much larger then in SO</p>
| 1 | 2016-10-09T08:28:58Z | [
"python",
"filemaker"
] |
Pandas: Get datetime index value from row | 39,936,434 | <p>I have a dataframe with datetime type column set to index.
I want to process the data per row with apply function. how can I access the index value of the current row?</p>
<pre><code> hid lat lon
2016-08-11 10:56:00 549 40.639504 -79.996961
2016-08-11 10:57:00 639 40.539504 -79.993981
2016-08-11 10:58:00 749 40.438842 -79.924733
def f(row):
# I want to access row idx value here
df['new'] = df.apply(lambda row: f(row), axis=1)
</code></pre>
| 0 | 2016-10-08T19:22:27Z | 39,936,584 | <p>Since apply will return a Series you could call the name of that Series which represent the index such has:</p>
<pre><code>df['new'] = df.apply(lambda row: row.name, axis=1)
</code></pre>
| 1 | 2016-10-08T19:37:13Z | [
"python",
"datetime",
"pandas"
] |
Secure alternatives to DiD or the UNIX socket? | 39,936,449 | <p>I'm trying to learn more about Docker, what it's for, and how it functions. To that end, I've set up two containers using <code>docker-compose</code>: </p>
<ul>
<li>One container, based on Docker's <code>python:3</code> image, runs some service </li>
<li>The other container, also based on Dockers's <code>python:3</code> image, contains a Django app.<br>
The reason for using Docker is that it seemed like a great way to ensure functionality across different systems. </li>
</ul>
<p>My purpose is to have an HTTP-served interface (the Django app), to manage the other container. I seek to be able to issue commands to the service container, through the Django app. Usually, this would be done through <code>docker exec $container_ID <command></code>. However, the Django app is of course not able to call the <code>docker</code> command just like that, given it's in a container itself. All of this is served on my LAN, not exposed to the web.</p>
<p>Right now, from what I understand, I have these options to give Django <code>docker exec</code> privilege/functionality on the other container: </p>
<ul>
<li><strong>Use Docker-in-Docker:</strong> However, from what I gather, even the author of DiD recommends <a href="https://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/" rel="nofollow">against using DiD</a>, unless you have a very specific, suitable purpose. Instead, he recommends you use: </li>
<li><strong>The Docker UNIX socket,</strong> using something like <a href="https://docker-py.readthedocs.io/en/stable/" rel="nofollow">docker-py</a> to do the magic. However, a cursory search shows that this is also iffy: any container having access to the socket effectively has root access to the host file system <a href="https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container.html" rel="nofollow">[1]</a> <a href="https://www.ctl.io/developers/blog/post/tutorial-understanding-the-security-risks-of-running-docker-containers" rel="nofollow">[2]</a>, if I understood correctly (which I'm not entirely sure of). I'm not expecting malware on my LAN anytime soon (knock on virtual wood), but the matter still bugs me: if an attacker finds a way to gain control of the Django container, they effectively have a free privilege escalation to the host system. There's a <a href="https://integratedcode.us/2016/04/20/sharing-the-docker-unix-socket-with-unprivileged-containers-redux/" rel="nofollow">Docker post</a> showing how you could deal with this, but it does not seem to be a full-fledged Docker functionality (yet?). The explanation is relatively technical and I am not yet quite at that level of expertise to fully grasp it. </li>
<li><strong>Hackity hack</strong> using shared volumes. Basically the Django container writes the commands to a shared file, and the service container periodically reads that file and executes the commands it finds inside. I'm not sure whether this is realistic, or whether I will end up in networking hell though, I just came up with it.</li>
</ul>
<p>Is there another Docker functionality that I missed that allows me to fulfil my inter-container-management needs?</p>
| 1 | 2016-10-08T19:24:25Z | 39,943,864 | <p>You can do what you want (of course if I understood well) like this:</p>
<p><code>
docker run -d -v /var/run/docker.socket:/var/run/docker.socket -v $(which docker):/usr/bin/docker manager-app:latest
</code></p>
<p>Then you can use docker binary to access the other containers on the host and manage your service containers.</p>
<hr>
<p>Since you asked for other ways, I can propose two:</p>
<ul>
<li>Use Docker TCP socker instead and set DOCEKR_HOST env in your container to docker host IP then you don't need socker anymore (it's less secure, make sure you have proper firewall to protect you docker from outside world or use a network which is not routerd/nat) </li>
</ul>
<p>Or</p>
<ul>
<li>Embed a small API in your service containers to run the command on your behalf, this way you don't need docker functionality all all.</li>
</ul>
| 0 | 2016-10-09T12:55:29Z | [
"python",
"docker",
"docker-compose"
] |
python multiprocessing, cpu-s and cpu cores | 39,936,480 | <p>I was trying out <code>python3</code> <code>multiprocessing</code> on a machine that has 8 cpu-s and each cpu has four cores (information is from <code>/proc/cpuinfo</code>). I wrote a little script with a useless function and I use <code>time</code> to see how long it takes for it to finish.</p>
<pre><code>from multiprocessing import Pool,cpu_count
def f(x):
for i in range(100000000):
x*x
return x*x
with Pool(8) as p:
a = p.map(f,[x for x in range(8)])
#~ f(5)
</code></pre>
<p>Calling <code>f()</code> without multiprocessing takes about 7s (<code>time</code>'s "real" output). Calling <code>f()</code> 8 times with a pool of 8 as seen above, takes around 7s again. If I call it 8 times with a pool of 4 I get around 13.5s, so there's some overhead in starting the script, but it runs twice as long. So far so good. Now here comes the part that I do not understand. If there are 8 cpu-s each with 4 cores, if I call it 32 times with a pool of 32, as far as I see it should run for around 7s again, but it takes 32s which is actually slightly longer than running <code>f()</code> 32 times on a pool of 8.</p>
<p>So my question is <code>multiprocessing</code> not able to make use of cores or I don't understand something about cores or is it something else?</p>
| 0 | 2016-10-08T19:27:14Z | 39,938,798 | <p>Simplified and short.. Cpu-s and cores are hardware that your computer have. On this hardware there is a operating system, the middleman between hardware and the programs running on the computer. The programs running on the computer are allotted cpu time. One of these programs is the python interpetar, which runs all the programs that has the endswith .py. So of the cpu time on your computer, time is allotted to python3.* which in turn allot time to the program you are running. This speed will depend on what hardware you have, what operation you are running, and how cpu-time is allotted between all these instances. </p>
<p><strong>How is cpu-time allotted?</strong> It is an like an while loop, the OS is distributing incremental between programs, and the python interpreter is incremental distributing it's distribution time to programs runned by the python interpretor. This is the reason the entire computer halts when a program misbehaves.</p>
<p><strong>Many processes does not equal</strong> more access to hardware. It does equal more allotted cpu-time from the python interpretor allotted time. Since you increase the number of programs under the python interpretor which do work for your application. </p>
<p><strong>Many processes does equal</strong> more work horses. </p>
<hr>
<p>You see this in practice in your code. You increase the number of workhorses to the point where the python interpreters allotted cpu-time is divided up between so many processes that all of them slows down. </p>
| 0 | 2016-10-09T00:31:53Z | [
"python",
"multiprocessing"
] |
Using GET and POST to add data to a database in Django | 39,936,494 | <p>I am working on a project that will have a raspberry PI collect data from a set of sensors and then send the data to a django server.</p>
<p>I need the server to then take that data and add it to a database and perform ARIMA time series forecasting on the updated dataset every x seconds after a number of new entries are added. </p>
<p>Can I use POST in the raspberry PI program to <strong>send</strong> the data to that url, and then use GET in a django view to <strong>add</strong> the incoming data into a database? </p>
| 0 | 2016-10-08T19:28:27Z | 39,936,550 | <p>you can use <strong>urllib</strong> module or <strong>requests</strong> module in python to send POST request to your Django server. </p>
<p>And you can have Django view to respond to that POST request. Inside this view, you can have method to add the data which sent from your Raspberry Pi program into your database which is at the Django server side.</p>
<p>Therefore you don't need another GET method to deal with adding data into the database in this case. </p>
| 0 | 2016-10-08T19:33:54Z | [
"python",
"django",
"raspberry-pi"
] |
Implementing HTTP/2 client using python 3.5 hyper library | 39,936,497 | <p>Im trying to implement my own HTTP/2 client using python3.5 hyper library. Everything seems to work fine until I request objects larger than 64Kb.</p>
<p>I've already set the <code>network_buffer_size</code> in larger values than the default which is actually 64K, even set the library code to set the network_buffer_size big enough so it could process the response but still the amount of data received from server is 64K no matter how big the file is. </p>
<pre><code>conn = hyper.HTTP20Connection(SERVER, int(sys.argv[2]), True, window_manager=FlowControlManagerUs, enable_push=False, ssl_context=ssl_context)
conn.network_buffer_size = 256000
conn.connect()
</code></pre>
<p>And here's where I get the request:</p>
<p>resp = conn.get_response(strid)</p>
<p>data = resp.read()</p>
<p>I've implemented the FlowControlManager just setting initial_window_size to large value.</p>
<p>Thanks</p>
| 1 | 2016-10-08T19:28:38Z | 39,939,871 | <p>Flow-control in HTTP/2 is implemented via two type of flow control windows: one for the connection, and one for each stream, in the words of <a href="https://tools.ietf.org/html/rfc7540#section-5.2" rel="nofollow">RFC 7540, 5.2 Flow control</a>: </p>
<blockquote>
<p>A flow-control scheme ensures that streams on the same connection do
not destructively interfere with each other. Flow control is used for
both individual streams and for the connection as a whole.</p>
</blockquote>
<p>hyper allows to implement your own flow control policy by sub classing <code>hyper.http20.window.BaseFlowControlManager</code>. By setting <code>initial_window_size</code> to large value, you've set the <strong>connection window</strong> to a large value. The stream window however is left unchanged, and it turns out that the default value for the stream window <em>is</em> 64 kb, from section <a href="https://tools.ietf.org/html/rfc7540#section-5.2.1" rel="nofollow">5.2.1 Flow-Control Principles</a>:</p>
<blockquote>
<ol start="4">
<li>The initial value for the flow-control window is 65,535 octets
for both new streams and the overall connection.</li>
</ol>
</blockquote>
<p>In order to increase the window for the stream, you'll have to also implement the <code>increase_window_size</code> method of the flow-control manager.</p>
| 0 | 2016-10-09T03:54:54Z | [
"python",
"http2",
"hyper"
] |
Shortest way to run seven if statements in Python | 39,936,512 | <p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>
<p><strong>code:</strong></p>
<pre><code>def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'
</code></pre>
<p>The question may appear subjective but I think there should be a <strong>pythonic</strong> and better and shorter and cleaner way of writing this.</p>
| 1 | 2016-10-08T19:30:39Z | 39,936,534 | <p>You could use a <strong><a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a></strong> aka map and simply put in multiple keys for the same values. </p>
<p>Then you only need to ask that dictionary for the value matching the current <em>day</em> key.</p>
| 1 | 2016-10-08T19:32:44Z | [
"python"
] |
Shortest way to run seven if statements in Python | 39,936,512 | <p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>
<p><strong>code:</strong></p>
<pre><code>def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'
</code></pre>
<p>The question may appear subjective but I think there should be a <strong>pythonic</strong> and better and shorter and cleaner way of writing this.</p>
| 1 | 2016-10-08T19:30:39Z | 39,936,548 | <p>A generic solution would be:</p>
<pre><code>def get_day_name(day):
return {
'1': 'Monday',
'2': 'Tuesday',
'3': 'Wednesday',
'4': 'Thursday',
'5': 'Friday',
'6': 'Saturday',
'7': 'Sunday'
}.get(str(day), 'Invalid day selected')
</code></pre>
<p>Several things are done here:</p>
<ol>
<li>to get rid of checking both strings <code>'2'</code> and integers <code>2</code>, convert all to strings: <code>str(day)</code></li>
<li>there is a mapping (<code>dict</code>) from all allowed strings (<code>'1'</code> - <code>'7'</code>) to the results</li>
<li>instead of just taking the result with <code>{...}[day]</code>, dictionary provides methog <code>get</code> which accepts the <em>default</em> argument to be returned if the key is not found (<code>'Invalid day selected'</code>).</li>
</ol>
<hr>
<p>But then again, since those are just numbers, this can be simplified using a list instead of a dictionary:</p>
<pre><code>def get_day_name(day):
day = int(day)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
if 1 <= day <= 7:
return days[day-1]
else:
return 'Invalid day selected'
</code></pre>
<p>In this case, strings are first converted to integers and then the integers are used to get a value from the list.
This, of course, won't work if <code>day = 'something that isnt int'</code>. This would raise an exception which could be handled, but if that has to be handled, the solution with dict is nicer.</p>
| 1 | 2016-10-08T19:33:48Z | [
"python"
] |
Shortest way to run seven if statements in Python | 39,936,512 | <p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>
<p><strong>code:</strong></p>
<pre><code>def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'
</code></pre>
<p>The question may appear subjective but I think there should be a <strong>pythonic</strong> and better and shorter and cleaner way of writing this.</p>
| 1 | 2016-10-08T19:30:39Z | 39,936,562 | <p>You could use a dictionary. The <code>get</code> method of the dictionary returns the default <code>'Invalid day selected'</code> when the given <code>day</code> is not in the dictionary:</p>
<pre><code>days_in_week = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'}
def func(day):
return days_in_week.get(int(day), 'Invalid day selected')
</code></pre>
<p>The cast to integer using <code>int</code> allows the function to take both strings and integer <code>day</code> parameter.</p>
| 1 | 2016-10-08T19:34:19Z | [
"python"
] |
Shortest way to run seven if statements in Python | 39,936,512 | <p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>
<p><strong>code:</strong></p>
<pre><code>def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'
</code></pre>
<p>The question may appear subjective but I think there should be a <strong>pythonic</strong> and better and shorter and cleaner way of writing this.</p>
| 1 | 2016-10-08T19:30:39Z | 39,936,571 | <p>What I would do instead, is create a dictionary, and cast your <code>day</code> to a single type, and then look that up in your dictionary. This significantly minimizes your code: </p>
<pre><code>def get_weekday(day):
days_dict = {
'1': 'Monday',
'2': 'Tuesday',
'3': 'Wednesday',
'4': 'Thursday',
'5': 'Friday',
'6': 'Saturday',
'7': 'Sunday'
}
return days_dict.get(str(day), 'Invalid day selected')
</code></pre>
<p>So, what is happening in the above function, is you are passing your <code>day</code>, it doesn't matter whether you pass it as a string or an int, the casting is made as an <code>str</code> already. Your dictionary now holds the mapping for you, and lookup will cost you O(1). </p>
<p>The <code>get</code> method will return <code>None</code> if it does not find an entry in your dictionary. However, per your requirement, you are looking to return <code>Invalid day selected</code> for invalid entries. <code>get</code> will take an extra argument that will be returned in the event an invalid key is provided.</p>
<p>Here is a demo of the different cases that can come up and how the function behaves:</p>
<pre><code>>>> print(get_weekday(2))
Tuesday
>>> print(get_weekday('5'))
Friday
>>> print(get_weekday("invalid_thing"))
Invalid day selected
</code></pre>
| 4 | 2016-10-08T19:35:20Z | [
"python"
] |
Shortest way to run seven if statements in Python | 39,936,512 | <p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>
<p><strong>code:</strong></p>
<pre><code>def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'
</code></pre>
<p>The question may appear subjective but I think there should be a <strong>pythonic</strong> and better and shorter and cleaner way of writing this.</p>
| 1 | 2016-10-08T19:30:39Z | 39,936,744 | <p>I would rather use the <code>get</code> method of a dictionary instead of writing multiple <code>elif</code>s:</p>
<pre><code>def get_weekday(day):
WEEK = {"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday",
"7": "Sunday"}
return WEEK.get(str(day), "Invalid day selected!")
</code></pre>
<p>Converting the day argument explicitly to <code>str</code> ensures both string and integer arguments would work.</p>
| -1 | 2016-10-08T19:55:04Z | [
"python"
] |
python removing references from a scientific paper | 39,936,527 | <p>NOTE: I am inexperienced with regular expressions.</p>
<p>I want to be able to convert scientific articles into iTunes tracks. To do this I copy and paste the text in txt files and convert them to spoken tracks. However when I do this the references are included and the computer's voice reads them aloud e.g. "(Smith J. et al. 2016)" and this is annoying as I'd like it to skip anything in brackets containing a reference.
Hence I want to make a python script that removes all of these references from the txt file before converting it to a spoken track.
I reckon that I could do this with something like the following code:</p>
<pre><code>start_ref=find("(")
finish_ref=find(")", start_ref)
# then remove all pieces of the string between each start and finish
</code></pre>
<p>But this is not accurate enough. Instead I would like to somehow use regular expressions.</p>
<p>can someone show me some example code as to how I would iterative remove the references from the following text (while accounting for different referencing styles e.g. Harvard vs APA etc.):</p>
<blockquote>
<p>"This method has been shown to outperform previously discussed methods
(Smith, J. et al., 2014) and while it has its draw-backs, it is clear
that the benefits outweigh the disadvantages (Jones, A. & Karver, B.,
2009, Lubber, H. et al., 2013)."</p>
</blockquote>
<p>Can anyone provide some sample code?</p>
| 0 | 2016-10-08T19:31:59Z | 39,936,761 | <p>This should do the trick:</p>
<pre><code>import re
a = "This method has been shown to outperform previously discussed methods (Smith, J. et al., 2014) and while it has its draw-backs, it is clear that the benefits outweigh the disadvantages (Jones, A. & Karver, B., 2009, Lubber, H. et al., 2013)."
a = re.sub(r"\s\([A-Z][a-z]+,\s[A-Z][a-z]?\.[^\)]*,\s\d{4}\)", "", a)
</code></pre>
<p>It replaces by "" (ie nothing) every string made of a space, <code>(</code>, one uppercase letter followed by one or more lowercase letters (ie a name), a comma, a space, one capital letter and a point (optionally separated by a lowercase letter for names like Christine that would be abridged to <code>Ch.</code>), then anything but a closing parenthesis until we reach a comma, a space, four digits and a closing parenthesis. To summarize, it assumes that everything that looks like <code>(Azdfs, E. stuff 2343)</code> should be deleted. I think that should be enough not to get overdetection.</p>
<p>The output I get with my code is <code>This method has been shown to outperform previously discussed methods and while it has its draw-backs, it is clear that the benefits outweigh the disadvantages.</code></p>
| 1 | 2016-10-08T19:56:36Z | [
"python",
"string"
] |
python removing references from a scientific paper | 39,936,527 | <p>NOTE: I am inexperienced with regular expressions.</p>
<p>I want to be able to convert scientific articles into iTunes tracks. To do this I copy and paste the text in txt files and convert them to spoken tracks. However when I do this the references are included and the computer's voice reads them aloud e.g. "(Smith J. et al. 2016)" and this is annoying as I'd like it to skip anything in brackets containing a reference.
Hence I want to make a python script that removes all of these references from the txt file before converting it to a spoken track.
I reckon that I could do this with something like the following code:</p>
<pre><code>start_ref=find("(")
finish_ref=find(")", start_ref)
# then remove all pieces of the string between each start and finish
</code></pre>
<p>But this is not accurate enough. Instead I would like to somehow use regular expressions.</p>
<p>can someone show me some example code as to how I would iterative remove the references from the following text (while accounting for different referencing styles e.g. Harvard vs APA etc.):</p>
<blockquote>
<p>"This method has been shown to outperform previously discussed methods
(Smith, J. et al., 2014) and while it has its draw-backs, it is clear
that the benefits outweigh the disadvantages (Jones, A. & Karver, B.,
2009, Lubber, H. et al., 2013)."</p>
</blockquote>
<p>Can anyone provide some sample code?</p>
| 0 | 2016-10-08T19:31:59Z | 39,936,783 | <p>something like</p>
<pre><code> import re
text = ...
re.sub(r'\((?:[\w \.&]+\, )+[0-9]{4}\)', text)
</code></pre>
<p>seems to do it.
You can use <a href="https://www.debuggex.com/" rel="nofollow">Debuggex</a> to train yourself in regex.</p>
| 2 | 2016-10-08T19:58:46Z | [
"python",
"string"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.