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 |
---|---|---|---|---|---|---|---|---|---|
Speed up a list operation using threads in python | 39,807,058 | <p>I have a huge list of proxies (70k) and I have this script:</p>
<pre><code>entries = open("proxy.txt").readlines()
proxiesp = [x.strip().split(":") for x in entries]
proxies = []
for x in proxiesp:
x = tuple(x)
proxies.append(x)
set(proxies)
</code></pre>
<p>And the operation of set(proxies) so the duplicates removing, is really slow. Is there a way to speed up this using threads?</p>
| -1 | 2016-10-01T13:13:32Z | 39,807,263 | <p>No, threading won't speed this up, for three reasons:</p>
<ol>
<li><p>The Python GIL prevents Python code from being executed in parallel; threads executing Python code can only be run concurrently. For the same amount of CPU work, the same amount of time or more is required.</p></li>
<li><p>To be able to add to the same datastructure from multiple threads, you'd have to add locking, slowing down threading more.</p></li>
<li><p>Your code is slow because it is wasting cycles, because you are recreating the set object each iteration and then discarding it again. This is sucking up all the time as <code>proxies</code> continues to grow, so in the end you created sets for each size of <code>proxies</code>, from length 1 all the way up to length 70k, approaching 5 million steps to throw away 70k sets.</p></li>
</ol>
<p>You should produce the set <strong>once</strong>. You can do so in a set comprehension:</p>
<pre><code>with open('proxy.txt') as f:
proxies = {tuple(line.strip().split(':')) for line in f}
</code></pre>
| 3 | 2016-10-01T13:34:05Z | [
"python",
"multithreading",
"list",
"python-3.x",
"set"
]
|
Python Selenium CHROMEDRIVER | 39,807,281 | <p>So I'm currently using chromedriver for selenium with Python, responses are quite slow, so I'm trying to reduce how much chromedriver loads..</p>
<p>is there anyway I can remove the address bar, tool bar and most of the gui from chrome its self using chrome arguments?</p>
| 0 | 2016-10-01T13:35:22Z | 39,807,531 | <p>I don't think hiding the address bar and other GUI elements will have any effect. I would like to suggest using PhantomJS, a headless browser without a GUI at all. This will certainly speed up your tests.</p>
| 1 | 2016-10-01T14:02:00Z | [
"python",
"selenium",
"selenium-chromedriver"
]
|
Why tf.Variable is iterable but can't be iterated | 39,807,356 | <p>Why this is true:</p>
<pre><code>from collections import Iterable
import tensorflow as tf
v = tf.Variable(1.0)
print(isinstance(v, Iterable))
True
</code></pre>
<p>while this</p>
<pre><code>iter(v)
</code></pre>
<p>gives</p>
<pre><code>TypeError: 'Variable' object is not iterable.
</code></pre>
| 0 | 2016-10-01T13:44:12Z | 39,808,194 | <p>I found below method in Tensorflow's Variable class: </p>
<pre><code>def __iter__(self):
"""Dummy method to prevent iteration. Do not call.
NOTE(mrry): If we register __getitem__ as an overloaded operator,
Python will valiantly attempt to iterate over the variable's Tensor from 0
to infinity. Declaring this method prevents this unintended behavior.
Raises:
TypeError: when invoked.
"""
raise TypeError("'Variable' object is not iterable.")
</code></pre>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/variables.py#L366" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/variables.py#L366</a></p>
| 2 | 2016-10-01T15:12:57Z | [
"python",
"python-2.7",
"tensorflow",
"iterable"
]
|
Search for the latest rows in terms of timestamp | 39,807,389 | <p>I am looking for how to search for the latest rows in hbase table that is loaded by Nutch 2.3. </p>
<p>I use happybase and thrift, the only example I have found is in this link <a href="https://happybase.readthedocs.io/en/happybase-0.4/tutorial.html#using-table-namespaces" rel="nofollow">https://happybase.readthedocs.io/en/happybase-0.4/tutorial.html#using-table-namespaces</a></p>
| 2 | 2016-10-01T13:47:32Z | 39,807,432 | <p>I dont know python so Im explaining this in hbase shell..
More or less you should be able to do this in python.</p>
<h3>Python way : <a href="http://stackoverflow.com/questions/12458595/convert-timestamp-since-epoch-to-datetime-datetime">Convert timestamp since epoch to datetime.datetime</a></h3>
<blockquote>
<h3>How to get latest timestamp to pass in the filter ?</h3>
<p>LOG data to timestamp
To convert the date '08/08/16 20:56:29' from an hbase log into a
timestamp, do:</p>
</blockquote>
<pre><code> hbase(main):021:0> import java.text.SimpleDateFormat
hbase(main):022:0> import java.text.ParsePosition
hbase(main):023:0> SimpleDateFormat.new("yy/MM/dd HH:mm:ss").parse("08/08/16 20:56:29", ParsePosition.new(0)).getTime()
=> 1218920189000
</code></pre>
<p>after above you can try something like this:</p>
<pre><code>scan 't1', {COLUMNS => 'c1', TIMERANGE => [1303668804, 1303668904]}
hbase(main):001:0> scan
</code></pre>
<p>Here is some help for this command:
Scan a table; pass table name and optionally a dictionary of scanner
specifications. Scanner specifications may include one or more of:
TIMERANGE, FILTER, LIMIT, STARTROW, STOPROW, TIMESTAMP, MAXLENGTH,
or COLUMNS, CACHE</p>
<h3>Some examples:</h3>
<pre><code> hbase> scan '.META.'
hbase> scan '.META.', {COLUMNS => 'info:regioninfo'}
hbase> scan 't1', {COLUMNS => ['c1', 'c2'], LIMIT => 10, STARTROW => 'xyz'}
hbase> scan 't1', {COLUMNS => 'c1', TIMERANGE => [1303668804, 1303668904]}
hbase> scan 't1', {FILTER => "(PrefixFilter ('row2') AND (QualifierFilter (>=, 'binary:xyz'))) AND (TimestampsFilter ( 123, 456))"}
hbase> scan 't1', {FILTER => org.apache.hadoop.hbase.filter.ColumnPaginationFilter.new(1, 0)}
</code></pre>
| 1 | 2016-10-01T13:52:31Z | [
"python",
"hadoop",
"hbase",
"nutch",
"happybase"
]
|
Python Threads, why threads in two dimensions aren't work? | 39,807,458 | <p>I have this script:</p>
<pre><code>import threading
import time
import sys
def threadWait(d1, d2):
global number
time.sleep(1) # My actions
number = number+1 # Count of complete actions +1
sys.stdout.write("\033[K") # Clean line to the end.
sys.stdout.write(str(number)+" (Thread "+str(d1)+", "+str(d2)+") done"+"\r") # Write number and carriage return.
sys.stdout.flush()
number = 0 # Count of complete actions
threadsToJoin = []
dimension1 = [] # Main action task.
for i in range(50): # I have 50 "Main Actions" I need to do in parallel threads.
d1 = i
dimension2 = [] # I need to do each "Main Action" in 10 threads.
for n in range(10):
d2 = n
dimension2.append(threading.Thread(target=threadWait, args=(d1,d2)))
dimension1.append(dimension2)
for item in dimension1:
for items in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
items.start()
threadsToJoin.append(items)
break
else:
continue
for this in threadsToJoin:
this.join()
</code></pre>
<p>But I'm getting an error about "Thread can't be started twice". But when I'm adding all threads in <code>dimension2</code> and running like this:</p>
<pre><code>for item in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
item.start()
break
else:
continue
</code></pre>
<p>Everythin is going good as excpected. What is wrong with the first example and how can I do the whole threading(multithreading) as they do it nowadays?</p>
| 0 | 2016-10-01T13:55:17Z | 39,807,747 | <p>What do you mean here:</p>
<pre><code>for item in dimension1:
for items in dimension2:
</code></pre>
<p>Do you mean:</p>
<pre><code>for item in dimension1:
for items in item:
</code></pre>
<p>I suppose you don't want to run threads in [dimension2] every cycle</p>
| 2 | 2016-10-01T14:25:55Z | [
"python",
"multithreading"
]
|
Python Threads, why threads in two dimensions aren't work? | 39,807,458 | <p>I have this script:</p>
<pre><code>import threading
import time
import sys
def threadWait(d1, d2):
global number
time.sleep(1) # My actions
number = number+1 # Count of complete actions +1
sys.stdout.write("\033[K") # Clean line to the end.
sys.stdout.write(str(number)+" (Thread "+str(d1)+", "+str(d2)+") done"+"\r") # Write number and carriage return.
sys.stdout.flush()
number = 0 # Count of complete actions
threadsToJoin = []
dimension1 = [] # Main action task.
for i in range(50): # I have 50 "Main Actions" I need to do in parallel threads.
d1 = i
dimension2 = [] # I need to do each "Main Action" in 10 threads.
for n in range(10):
d2 = n
dimension2.append(threading.Thread(target=threadWait, args=(d1,d2)))
dimension1.append(dimension2)
for item in dimension1:
for items in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
items.start()
threadsToJoin.append(items)
break
else:
continue
for this in threadsToJoin:
this.join()
</code></pre>
<p>But I'm getting an error about "Thread can't be started twice". But when I'm adding all threads in <code>dimension2</code> and running like this:</p>
<pre><code>for item in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
item.start()
break
else:
continue
</code></pre>
<p>Everythin is going good as excpected. What is wrong with the first example and how can I do the whole threading(multithreading) as they do it nowadays?</p>
| 0 | 2016-10-01T13:55:17Z | 39,807,760 | <p>Your nested loop iterates over something else than you think:</p>
<pre><code>for item in dimension1:
for items in dimension2:
# But I can't do more than 100 Threads at once.
</code></pre>
<p>Ask yourself a question where is <code>dimension2</code> defined?<br>
If you find it hard to figure out, here's the answer:</p>
<pre><code>for i in range(50): # I have 50 "Main Actions" I need to do in parallel threads.
d1 = i
dimension2 = [] # I need to do each "Main Action" in 10 threads.
</code></pre>
<p>After program leaves the first nested loops (those where you create "dimensions" in) variable <code>dimension2</code> holds the value from last iteration of <code>for i in range(50)</code> loop.
Fixing the problem you have involves doing this:</p>
<pre><code>for dimension2 in dimension1:
for items in dimension2:
# But I can't do more than 100 Threads at once.
</code></pre>
<p>The very reason for your problem is trying to reuse variable names in a different context. However the list which you build in <code>dimension2</code> has no notion of variable name where it is stored in. </p>
| 2 | 2016-10-01T14:26:51Z | [
"python",
"multithreading"
]
|
python: check if substring is in tuple of strings | 39,807,545 | <p>Which is the most elegant way to check if there is an occurrence of several substrings in a tuple of strings?</p>
<pre><code>tuple = ('first-second', 'second-third', 'third-first')
substr1 = 'first'
substr2 = 'second'
substr3 = 'third'
#if substr1 in tuple and substr2 in tuple and substr3 in tuple:
# should return True
</code></pre>
| 2 | 2016-10-01T14:02:54Z | 39,807,561 | <pre><code>any(substr in str_ for str_ in tuple_)
</code></pre>
<p>You can start with that and look at <code>all()</code> as well.</p>
| 3 | 2016-10-01T14:04:46Z | [
"python",
"substring",
"tuples"
]
|
python: check if substring is in tuple of strings | 39,807,545 | <p>Which is the most elegant way to check if there is an occurrence of several substrings in a tuple of strings?</p>
<pre><code>tuple = ('first-second', 'second-third', 'third-first')
substr1 = 'first'
substr2 = 'second'
substr3 = 'third'
#if substr1 in tuple and substr2 in tuple and substr3 in tuple:
# should return True
</code></pre>
| 2 | 2016-10-01T14:02:54Z | 39,807,576 | <p>You need to iterate over the tuple for each of the substrings, so using <code>any</code> and <code>all</code>:</p>
<pre><code>all(any(substr in s for s in data) for substr in ['first', 'second', 'third'])
</code></pre>
| 2 | 2016-10-01T14:07:06Z | [
"python",
"substring",
"tuples"
]
|
How to create Python dictionary with multiple 'lists' for each key by reading from .txt file? | 39,807,586 | <p>I have a large text file that looks like:</p>
<pre><code>1 27 21 22
1 151 24 26
1 48 24 31
2 14 6 8
2 98 13 16
.
.
.
</code></pre>
<p>that I want to create a dictionary with. The first number of each list should be the key in the dictionary and should be in this format:</p>
<pre><code>{1: [(27,21,22),(151,24,26),(48,24,31)],
2: [(14,6,8),(98,13,16)]}
</code></pre>
<p>I have the following code (with total points being the largest number in the first column of the text file (ie largest key in dictionary)):</p>
<pre><code>from collections import defaultdict
info = defaultdict(list)
filetxt = 'file.txt'
i = 1
with open(filetxt, 'r') as file:
for i in range(1, num_cities + 1):
info[i] = 0
for line in file:
splitLine = line.split()
if info[int(splitLine[0])] == 0:
info[int(splitLine[0])] = ([",".join(splitLine[1:])])
else:
info[int(splitLine[0])].append((",".join(splitLine[1:])))
</code></pre>
<p>which outputs</p>
<pre><code>{1: ['27,21,22','151,24,26','48,24,31'],
2: ['14,6,8','98,13,16']}
</code></pre>
<p>The reason I want to do this dictionary is because I want to run a for loop through each "inner list" of the dictionary for a given key:</p>
<pre><code>for first, second, third, in dictionary:
....
</code></pre>
<p>I cannot do this with my current code because of the slightly different format of the dictionary (it expects 3 values in the for loop above, but receives more than 3), however it would work with the first dictionary format.</p>
<p>Can anyone suggest anyway to fix this?</p>
| 3 | 2016-10-01T14:08:22Z | 39,807,630 | <pre><code>result = {}
with open(filetxt, 'r') as f:
for line in f:
# split the read line based on whitespace
idx, c1, c2, c3 = line.split()
# setdefault will set default value, if the key doesn't exist and
# return the value corresponding to the key. In this case, it returns a list and
# you append all the three values as a tuple to it
result.setdefault(idx, []).append((int(c1), int(c2), int(c3)))
</code></pre>
<hr>
<p>Edit: Since you want to the key also to be an integer, you can <code>map</code> the <code>int</code> function over the split values, like this</p>
<pre><code> idx, c1, c2, c3 = map(int, line.split())
result.setdefault(idx, []).append((c1, c2, c3))
</code></pre>
| 4 | 2016-10-01T14:12:31Z | [
"python",
"dictionary"
]
|
How to create Python dictionary with multiple 'lists' for each key by reading from .txt file? | 39,807,586 | <p>I have a large text file that looks like:</p>
<pre><code>1 27 21 22
1 151 24 26
1 48 24 31
2 14 6 8
2 98 13 16
.
.
.
</code></pre>
<p>that I want to create a dictionary with. The first number of each list should be the key in the dictionary and should be in this format:</p>
<pre><code>{1: [(27,21,22),(151,24,26),(48,24,31)],
2: [(14,6,8),(98,13,16)]}
</code></pre>
<p>I have the following code (with total points being the largest number in the first column of the text file (ie largest key in dictionary)):</p>
<pre><code>from collections import defaultdict
info = defaultdict(list)
filetxt = 'file.txt'
i = 1
with open(filetxt, 'r') as file:
for i in range(1, num_cities + 1):
info[i] = 0
for line in file:
splitLine = line.split()
if info[int(splitLine[0])] == 0:
info[int(splitLine[0])] = ([",".join(splitLine[1:])])
else:
info[int(splitLine[0])].append((",".join(splitLine[1:])))
</code></pre>
<p>which outputs</p>
<pre><code>{1: ['27,21,22','151,24,26','48,24,31'],
2: ['14,6,8','98,13,16']}
</code></pre>
<p>The reason I want to do this dictionary is because I want to run a for loop through each "inner list" of the dictionary for a given key:</p>
<pre><code>for first, second, third, in dictionary:
....
</code></pre>
<p>I cannot do this with my current code because of the slightly different format of the dictionary (it expects 3 values in the for loop above, but receives more than 3), however it would work with the first dictionary format.</p>
<p>Can anyone suggest anyway to fix this?</p>
| 3 | 2016-10-01T14:08:22Z | 39,808,018 | <p>You are converting your values back to comma separated strings, which you can't use in <code>for first, second, third in data</code> - so just leave them as a list <code>splitLine[1:]</code> (or convert to <code>tuple</code>).<br>
You don't need your initializing <code>for</code> loop with a <code>defaultdict</code>. You also don't need the conditional checks with <code>defaultdict</code> either.</p>
<p>Your code without the superfluous code:</p>
<pre><code>with open(filetxt, 'r') as file:
for line in file:
splitLine = line.split()
info[int(splitLine[0])].append(splitLine[1:])
</code></pre>
<p>One slight difference is if you want to operate on <code>int</code>s I would convert up front:</p>
<pre><code>with open(filetxt, 'r') as file:
for line in file:
splitLine = list(map(int, line.split())) # list wrapper for Py3
info[splitLine[0]].append(splitLine[1:])
</code></pre>
<p>Actually in Py3, I would do:</p>
<pre><code> idx, *cs = map(int, line.split())
info[idx].append(cs)
</code></pre>
| 3 | 2016-10-01T14:54:32Z | [
"python",
"dictionary"
]
|
How to link inputs to new questions in Python (troubleshooting program)? | 39,807,601 | <p>I was programming a troubleshooter on python and I have been finding it really hard to link inputs to new questions:</p>
<pre><code> Question 1
print("Has your car got a flat tyre? 1. Yes 2. No")
choice=input("1/2")
if choice == "1":
goto (Question 2) #How do I link this input
elif choice == "2":
goto (Question 3)
else:
print("Answer not applicable")
Question 2 #Into this question?
print("Have you taken your car to the petrol station? 1. Yes 2. No")
choice=input("1/2")
if choice == "1":
goto (Question 4)
elif choice == "2":
goto (Question 5)
else:
print("Answer not applicable")
Question 3
print("Has your car recently had an MOT? 1. Yes 2. No")
choice=input("1/2")
if choice == "1":
goto (Question 6)
elif choice == "2":
goto (Question 7)
else:
print("Answer not applicable")
</code></pre>
<p>I need to know how to do this before I go further with my project. All help is appreciated.</p>
| 0 | 2016-10-01T14:10:19Z | 39,807,763 | <p>Python does not support labels and goto. What you should be doing is something like the code below.</p>
<pre><code>QUESTION_1 = "Has your car got a flat tyre? 1. Yes 2. No"
QUESTION_2 = "Have you taken your car to the petrol station? 1. Yes 2. No"
QUESTION_3 = "Has your car recently had an MOT? 1. Yes 2. No"
QUESTION_4 = ""
QUESTION_5 = ""
QUESTION_6 = ""
QUESTION_7 = ""
def ask_question(question):
print(question)
answer = input()
return answer
def check_answer(question, answer):
if question == QUESTION_1 and answer == "1":
question = QUESTION_2
elif question == QUESTION_1 and answer == "2":
question = QUESTION_3
elif question == QUESTION_2 and answer == "1":
question = QUESTION_4
elif question == QUESTION_2 and answer == "2":
question = QUESTION_5
elif question == QUESTION_3 and answer == "1":
question = QUESTION_6
elif question == QUESTION_3 and answer == "2":
question = QUESTION_7
else:
print("Answer not applicable")
return question
question = QUESTION_1
while True:
answer = ask_question(question)
question = check_answer(question)
</code></pre>
| 0 | 2016-10-01T14:27:37Z | [
"python",
"design"
]
|
Extract Python dictionary from string | 39,807,724 | <p>I have a string with valid python dictionary inside</p>
<pre><code>data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."
</code></pre>
<p>I need to extract that dict. I tried with regex but for some reason <code>re.search(r"\{(.*?)\}", data)</code> did not work. Is there any better way extract this dict?</p>
| 0 | 2016-10-01T14:22:55Z | 39,807,873 | <p>From @AChampion's suggestion.</p>
<pre><code>>>> import re
>>> import ast
>>> x = ast.literal_eval(re.search('({.+})', data).group(0))
>>> x
{'Bar': 'value', 'Foo': '1002803'}
</code></pre>
<p>so the pattern you're looking for is <code>re.search('({.+})', data)</code></p>
<p>You were supposed to extract the curly braces with the string, so <code>ast.literal_eval</code> can convert the string to a python dictionary . you also don't need the <code>r</code> prefix as <code>{</code> or <code>}</code> in an capturing group <code>()</code> would be matched literally.</p>
| 0 | 2016-10-01T14:40:15Z | [
"python",
"regex",
"django",
"dictionary",
"django-views"
]
|
Extract Python dictionary from string | 39,807,724 | <p>I have a string with valid python dictionary inside</p>
<pre><code>data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."
</code></pre>
<p>I need to extract that dict. I tried with regex but for some reason <code>re.search(r"\{(.*?)\}", data)</code> did not work. Is there any better way extract this dict?</p>
| 0 | 2016-10-01T14:22:55Z | 39,807,934 | <p>Your solution works!</p>
<pre><code>In [1]: import re
In [2]: data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."
In [3]: a = eval(re.search(r"\{(.*?)\}", data).group(0))
In [4]: a
Out[4]: {'Bar': 'value', 'Foo': u'1002803'}
</code></pre>
| 0 | 2016-10-01T14:46:11Z | [
"python",
"regex",
"django",
"dictionary",
"django-views"
]
|
argmin in dataset containing NaN python | 39,807,845 | <pre><code> SGSIN VNVUT CNSHK HKHKG JPOSA
To
MYPKL 1 4 8 9 13
SGSIN NaN 3 7 8 12
VNVUT NaN NaN 3 4 8
CNSHK 1 NaN NaN 1 5
HKHKG NaN NaN NaN NaN 3
</code></pre>
<p>Let say we have the above dataset using pandas. I want to calculate the <code>arg_minimum</code> over the first column and ignoring the <code>NaN</code>. I tried with </p>
<pre><code>df[df[0]].idxmin()
</code></pre>
<p>but it gives </p>
<pre><code>nan
</code></pre>
<p>but I don't get the right result then. Can someone help me? The result I want is (in this case) </p>
<pre><code>[0,3]
</code></pre>
| 2 | 2016-10-01T14:37:04Z | 39,807,996 | <p>You can use numpy's <code>argwhere</code></p>
<pre><code>import numpy as np
np.argwhere(df['SGSIN'].eq(df['SGSIN'].min()))
array([[0],
[3]])
</code></pre>
| 1 | 2016-10-01T14:52:13Z | [
"python",
"pandas",
"machine-learning"
]
|
Startswith with a range of number instead an unit | 39,807,907 | <pre><code>ip = a list of ips
ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip))
</code></pre>
<p>Is is possible to do something like this? I tested it and it doesn't work.
I'd like to delete all ips from "ip" list that start with 256. 257. 258. ecc... to 310.</p>
| -2 | 2016-10-01T14:43:45Z | 39,807,937 | <p>No, <code>str.startswith()</code> doesn't take a range.</p>
<p>You'd have to parse out the first part and test it as an integer; filtering is also easier done with a list comprehension:</p>
<pre><code>[ip for ip in ip_addresses if 257 <= int(ip.partition('.')[0]) <= 310]
</code></pre>
<p>The alternative would be to use the <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow"><code>ipaddress</code> library</a>; it'll reject any invalid address with a <code>ipaddress.AddressValueError</code> exception, and since addresses that start with anything over 255 are invalid, you can easily co-opt that to filter out your invalid addresses:</p>
<pre><code>import ipaddress
def valid_ip(ip):
try:
ipaddress.IPv4Address(ip)
except ipaddress.AddressValueError:
return False
else:
return True
[ip for ip in ip_addresses if valid_ip(ip)]
</code></pre>
| 3 | 2016-10-01T14:46:21Z | [
"python",
"list",
"python-3.x",
"range",
"startswith"
]
|
Arrow keys no longer work in Python shell after upgrading Mac OS to Sierra | 39,807,946 | <p>I'm using zsh, iTerm2 (3.0.9), and pyenv (1.0.2) with pyenv global set to 3.5.2.</p>
<p>In the Python shell, the up and down arrow keys used to work, to access the previous commands in the history. But now after upgrading to OSX 10.12, instead it shows control characters. For example up arrow displays:</p>
<pre><code>^[[A
</code></pre>
<p>I've tried installing readline as suggested in <a href="http://stackoverflow.com/questions/893053/seeing-escape-characters-when-pressing-the-arrow-keys-in-python-shell">Seeing escape characters when pressing the arrow keys in python shell</a> but that didn't help. I don't have the PYTHONSTARTUP variable but didn't used to before, and not sure how that interacts with pyenv.</p>
| -1 | 2016-10-01T14:46:59Z | 39,834,510 | <p>I'm seeing the same thing and the only "fix" I was able to come up with was to not run the <code>pyenv init -</code> command in my .zshrc file. That however will inhibit the functioning of virtual environments.. and so it's not a fix but a workaround to get the python shell history to work again.</p>
<p>I'm continuing to look and see if there is a permanent fix as I'm not nearly as productive without it. </p>
| 0 | 2016-10-03T14:53:49Z | [
"python",
"osx",
"zsh",
"iterm2",
"pyenv"
]
|
Arrow keys no longer work in Python shell after upgrading Mac OS to Sierra | 39,807,946 | <p>I'm using zsh, iTerm2 (3.0.9), and pyenv (1.0.2) with pyenv global set to 3.5.2.</p>
<p>In the Python shell, the up and down arrow keys used to work, to access the previous commands in the history. But now after upgrading to OSX 10.12, instead it shows control characters. For example up arrow displays:</p>
<pre><code>^[[A
</code></pre>
<p>I've tried installing readline as suggested in <a href="http://stackoverflow.com/questions/893053/seeing-escape-characters-when-pressing-the-arrow-keys-in-python-shell">Seeing escape characters when pressing the arrow keys in python shell</a> but that didn't help. I don't have the PYTHONSTARTUP variable but didn't used to before, and not sure how that interacts with pyenv.</p>
| -1 | 2016-10-01T14:46:59Z | 39,906,060 | <p>I had the exact same issue and this command worked for me easy_install -a readline</p>
<p>Full credit here: <a href="http://stackoverflow.com/questions/7375545/ipython-complaining-about-readline">ipython complaining about readline</a></p>
| 1 | 2016-10-06T21:44:27Z | [
"python",
"osx",
"zsh",
"iterm2",
"pyenv"
]
|
Deleting a list after creating an iterator object from it | 39,807,948 | <p>I am trying to understand the concept of iterators in python and tried this in Python 3.5.2.</p>
<pre><code>x = list(range(1000)) # size of x is 9112 bytes
y = iter(x) # size of y is 56 bytes
del x
x = list(y) # size of x is again 9112 bytes
</code></pre>
<p>How does the iterator store the information about the sequence it has to generate?</p>
<p>It does not contain all the elements but even after deleting the original list we are still able to reproduce the original list from the iterator?</p>
<p>If it does not contain all the elements how does it know which is the next element even after deleting <code>x</code>?</p>
| 3 | 2016-10-01T14:47:12Z | 39,808,173 | <p>Because iterators have enough details stored in them to enable them generate the next element of a sequence without having that "next element" in memory.</p>
<p>To understand what is going on let's create our own fake iterator</p>
<pre><code>class Fakeiterator:
def __init__(self, range_list):
self.current = range_list[0]
self.high = range_list[-1]
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
</code></pre>
<p>In our <code>__init__</code> method we've stored enough details (the start point and end point of our iterator) to enable us generate the next element without actually having it in memory. As far as we have this information, even though we're given a list containing 2000 elements we just need to know the start and end point</p>
<p>in our <code>__next__</code> method anytime we ask for the next element in our iterator, The iterator simply increments the current counter and return it back to us.</p>
<p>Lets test our iterator:</p>
<pre><code>>>> x = list(range(5))
>>> y = Fakeiterator(x)
>>> del x
>>> list(y)
[0, 1, 2, 3, 4]
>>>
</code></pre>
<p>The <code>list</code> constructor repeatedly calls <code>__next__</code> until <code>StopIteration</code> is raised by our iterator and that's at the point where the current element is higher than the maximum element we stored at the creation of the iterator.</p>
<p>But in your case calling <code>iter(x)</code> on a list, returns a <code>list_iterator</code> object that <strong>STORES</strong> x internally. <code>x</code> is still stored but not with the name <code>x</code> anymore.</p>
<p>On why <code>getsizeof</code> returns a lower size which as you expected is supposed to be greater or at least equal to the size of the original list. from the docs</p>
<blockquote>
<p>sys.getsizeof(object[, default]) Return the size of an object in
bytes. The object can be any type of object. All built-in objects will
return correct results, but this does not have to hold true for
third-party extensions as it is implementation specific.</p>
<p><strong>Only the memory consumption directly attributed to the object is
accounted for, not the memory consumption of objects it refers to.</strong></p>
<p>If given, default will be returned if the object does not provide
means to retrieve the size. Otherwise a TypeError will be raised.</p>
<p>getsizeof() calls the objectâs <strong>sizeof</strong> method and adds an
additional garbage collector overhead if the object is managed by the
garbage collector.</p>
</blockquote>
<p>To demonstrate that let's write a quick script</p>
<pre><code>import sys
x = [1, 2, 3]
print(sys.getsizeof(x))
class storex():
def __init__(self, param):
self.param = param
y = storex(x)
print(sys.getsizeof(y))
print(y.param, sys.getsizeof(y.param))
</code></pre>
<p>When you run the script. this is the output (on my machine, but it should be the same with yours)</p>
<pre><code>88
56
[1, 2, 3] 88
</code></pre>
<p>even though the list <code>[1, 2, 2]</code> is 88 bytes long, when we store it as an attribute of <code>storex</code> it doesn't automatically make <code>storex</code> become larger than it. because <code>storex</code> refers to it. it's not part of <code>storex</code> directly</p>
<p>But on printing the size of <code>y.param</code>, we can see that it's still the same size as the original <code>[1, 2, 3]</code> list</p>
<p>Also <code>del</code> doesn't delete the object from memory, it simply unbinds the name <code>x</code> so x won't refer to any object in memory. the value of x will only be discarded (garbage collected) when there is no reference to it again</p>
<p>Here is a demonstration of what i mean</p>
<pre><code>>>> x = [1,2,3]
>>> class y: pass
...
>>> y.x = x
>>> id(x), id(y.x)
(140177507371016, 140177507371016)
>>> del x
>>> id(y.x)
140177507371016
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
</code></pre>
<p>deleting <code>x</code> doesn't automatically delete <code>[1,2,3]</code> which <code>y.x</code> points to, even though their id's show that they both pointed to the same object in memory.</p>
| 2 | 2016-10-01T15:10:44Z | [
"python",
"iterator",
"iterable"
]
|
Deleting a list after creating an iterator object from it | 39,807,948 | <p>I am trying to understand the concept of iterators in python and tried this in Python 3.5.2.</p>
<pre><code>x = list(range(1000)) # size of x is 9112 bytes
y = iter(x) # size of y is 56 bytes
del x
x = list(y) # size of x is again 9112 bytes
</code></pre>
<p>How does the iterator store the information about the sequence it has to generate?</p>
<p>It does not contain all the elements but even after deleting the original list we are still able to reproduce the original list from the iterator?</p>
<p>If it does not contain all the elements how does it know which is the next element even after deleting <code>x</code>?</p>
| 3 | 2016-10-01T14:47:12Z | 39,808,275 | <p>According to what I know, del x does not del the value in the memory since your y is still referring it. It is kind of pointer. x and y is referring to the same memory. </p>
<p>when you do del x, python will dereference the x and do garbage collection.</p>
<p>while by doing x=list(y), you are pointing the memory to x again.</p>
| 1 | 2016-10-01T15:21:03Z | [
"python",
"iterator",
"iterable"
]
|
read Chinese character from excel file python3 | 39,807,951 | <p>I have an Excel file that contains two columns, first one in Chinese and the second is just a link.
I tried two methods I found here. but it didn't work and I can't print the value in the console, I changed my encoding variable in settings (pycharm) to U8, still doesn't work.
I used Pandas & xlrd libs, both didn't work while it worked for others who posted.
this is my current code : </p>
<pre><code>from xlrd import open_workbook
class Arm(object):
def __init__(self, id, dsp_name):
self.id = id
self.dsp_name = dsp_name
def __str__(self):
return("Arm object:\n"
" Arm_id = {0}\n"
" DSPName = {1}\n"
.format(self.id, self.dsp_name))
if __name__ == '__main__':
wb = open_workbook('test.xls')
for sheet in wb.sheets():
print(sheet)
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
items = []
rows = []
for row in range(1, number_of_rows):
values = []
for col in range(number_of_columns):
value = str(sheet.cell(row, col).value)
for a in value:
print('\n'.join([a]))
values.append(value)
print(value)
for item in items:
print (item)
print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
print
</code></pre>
<p>obviously it's not working, I was just messing around with it after giving up.
File : <a href="http://www59.zippyshare.com/v/UxITFjis/file.html" rel="nofollow">http://www59.zippyshare.com/v/UxITFjis/file.html</a></p>
| 0 | 2016-10-01T14:47:27Z | 39,813,259 | <p>It's not about encoding, you are not access the right rows.</p>
<p>On the line 24<br>
<code>for row in range(1, number_of_rows):</code></p>
<p>why are you want to start with 1 instead of 0.<br>
try<code>for row in range(number_of_rows):</code></p>
| 1 | 2016-10-02T02:20:52Z | [
"python",
"excel"
]
|
read Chinese character from excel file python3 | 39,807,951 | <p>I have an Excel file that contains two columns, first one in Chinese and the second is just a link.
I tried two methods I found here. but it didn't work and I can't print the value in the console, I changed my encoding variable in settings (pycharm) to U8, still doesn't work.
I used Pandas & xlrd libs, both didn't work while it worked for others who posted.
this is my current code : </p>
<pre><code>from xlrd import open_workbook
class Arm(object):
def __init__(self, id, dsp_name):
self.id = id
self.dsp_name = dsp_name
def __str__(self):
return("Arm object:\n"
" Arm_id = {0}\n"
" DSPName = {1}\n"
.format(self.id, self.dsp_name))
if __name__ == '__main__':
wb = open_workbook('test.xls')
for sheet in wb.sheets():
print(sheet)
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
items = []
rows = []
for row in range(1, number_of_rows):
values = []
for col in range(number_of_columns):
value = str(sheet.cell(row, col).value)
for a in value:
print('\n'.join([a]))
values.append(value)
print(value)
for item in items:
print (item)
print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
print
</code></pre>
<p>obviously it's not working, I was just messing around with it after giving up.
File : <a href="http://www59.zippyshare.com/v/UxITFjis/file.html" rel="nofollow">http://www59.zippyshare.com/v/UxITFjis/file.html</a></p>
| 0 | 2016-10-01T14:47:27Z | 39,815,822 | <p>Well the problem I had wasn't in reading the Chinese characters actually! my problem we're in printing in console.
I thought that the print encoder works fine and I just didn't read it the characters, but this code works fine : </p>
<pre><code>from xlrd import open_workbook
wb = open_workbook('test.xls')
messages = []
links = []
for sheet in wb.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
for row in range(1, number_of_rows):
i = 0
for col in range(number_of_columns):
value = (sheet.cell(row,col).value).encode('gbk')
if i ==0:
messages.append(value)
else:
links.append(value)
i+=1
print(links)
</code></pre>
<p>to check it, I paste the first result in selenium driver (since I was going to use it anyway)</p>
<pre><code>element = driver.find_element_by_class_name('email').send_keys(str(messages[0],'gbk'))
</code></pre>
<p>and it works like a charme!</p>
| 0 | 2016-10-02T09:59:23Z | [
"python",
"excel"
]
|
Python Pandas: Read specific columns from cdv, then reorder | 39,807,953 | <p>I have a csv which I need to manipulated and write back.
I only want specific columns (with header) and re-order them.</p>
<p>I use:</p>
<pre><code>fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname']
df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields, columns='Created', 'Ticket Number', 'Customer Realname', 'CustomerID', 'Closed')
df = df.rename(columns={'Ticket Number': 'CaseNumber', 'Created': 'CreationDate', 'Closed': 'ClosedDate', 'CustomerID': 'EndCustomerEmail', 'Customer Realname': 'EndCustomerName'})
</code></pre>
<p>but it throws a </p>
<blockquote>
<p>SyntaxError: positional argument follows keyword argument</p>
</blockquote>
<p>right after the second line after I expanded it with "column=" to re-order immediately after reading</p>
<p>I'm sure I'm missing something obvious here but can't find it.</p>
| 2 | 2016-10-01T14:47:50Z | 39,808,165 | <p>Try this:</p>
<pre><code># specify your columns in the order you want to have it in the ouptut file
fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname']
df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields)[fields]
df = df.rename(columns={'Ticket Number': 'CaseNumber', 'Created': 'CreationDate', 'Closed': 'ClosedDate', 'CustomerID': 'EndCustomerEmail', 'Customer Realname': 'EndCustomerName'})
</code></pre>
| 2 | 2016-10-01T15:10:13Z | [
"python",
"pandas"
]
|
python write file dealing with encode | 39,807,985 | <p>I'm confused. I need HELP!!!
I'm dealing with a file contains Chinese characters,for instance, let's call it <code>a.TEST</code>, and here is what's inside.</p>
<pre><code>ä½ å¥½ ä¸å½ Hello China 1 2 3
</code></pre>
<p>You don't need to understand what the chinese means.(Actually it's 'hello China')</p>
<pre><code>>>> f=open('wr.TRAIN')
>>> print f.read()
ä½ å¥½ ä¸å½ Hello China 1 2 3
>>> f.seek(0)
>>> content = f.readline()
>>> content
'\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd Hello China 1 2 3\n'
>>> print content
ä½ å¥½ ä¸å½ Hello China 1 2 3
>>> type(content)
<type 'str'>
>>> isinstance(content,unicode)
False
</code></pre>
<p>Here comes the <strong>first Question</strong>: Why python shell give me the <code>utf-8</code>of <code>content</code> when i just type <code>content</code>,meanwhile <code>print content</code> cmd can output the form that I want to see?</p>
<p>The <strong>Second Question</strong>: what's the difference between <code>unicode</code> and <code>str</code>?
Someone told me that <code>encode</code> is convert <code>unicode</code> to <code>str</code>, but what i learned from <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Unicode HowTo</a> tells me <code>encode</code> is convert <code>unicode</code> to <code>utf-8</code></p>
<p>Not over yet! :)</p>
<p>here is <code>test.py</code></p>
<pre><code>#!/usr/bin/python
#-*- coding: utf-8 -*-
fr = open('a.TEST')
fw = open('out.TEST','w')
content = fr.readline()
content_list = content.split()
print content
fw.write('{0}'.format(content_list))
fr.close()
fw.close()
</code></pre>
<p><a href="http://i.stack.imgur.com/4XevK.png" rel="nofollow"><img src="http://i.stack.imgur.com/4XevK.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/Oc52y.png" rel="nofollow"><img src="http://i.stack.imgur.com/Oc52y.png" alt="enter image description here"></a></p>
<p><strong>Third Question</strong>:Why the chinese character turn into utf-8 code when I do <code>.split()</code>?</p>
<p>and I thought <code>fw.write('{0}'.format(content_list).decode('utf-8'))</code> will work, but it doesn't.
I don't want what's written into <code>out.TEST</code> is character encoding form, I want it to be exactly the character that look like originallyï¼ä½ 好ï¼. How to do it?</p>
| 1 | 2016-10-01T14:51:16Z | 39,808,682 | <p>In the beginning, there was just english characters, and people was not satisfied.</p>
<p>Then they want to display every character in the world.But there is problem. One byte can only represent 255 characters. There just simply not enough place to hold them. </p>
<p>Then people decide to use two byte to represent one character.And call it 'utf8'.</p>
<p>No matter what characters you write in, it's all store in byte form.</p>
<p>In Python, there is no such datatype called 'unicode', just 'str'. And 'unicode' is an encoding system of 'str'. </p>
<p>'\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd' is byte form of "ä½ å¥½ ä¸å½".
It can not display without an encoding system specified.</p>
<p>I suppose you could blame linux/unix. Python has no problem to display 'utf-8' characters, while 'cat' cannot.</p>
| 1 | 2016-10-01T16:01:22Z | [
"python",
"unicode",
"encoding",
"utf-8",
"character-encoding"
]
|
python write file dealing with encode | 39,807,985 | <p>I'm confused. I need HELP!!!
I'm dealing with a file contains Chinese characters,for instance, let's call it <code>a.TEST</code>, and here is what's inside.</p>
<pre><code>ä½ å¥½ ä¸å½ Hello China 1 2 3
</code></pre>
<p>You don't need to understand what the chinese means.(Actually it's 'hello China')</p>
<pre><code>>>> f=open('wr.TRAIN')
>>> print f.read()
ä½ å¥½ ä¸å½ Hello China 1 2 3
>>> f.seek(0)
>>> content = f.readline()
>>> content
'\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd Hello China 1 2 3\n'
>>> print content
ä½ å¥½ ä¸å½ Hello China 1 2 3
>>> type(content)
<type 'str'>
>>> isinstance(content,unicode)
False
</code></pre>
<p>Here comes the <strong>first Question</strong>: Why python shell give me the <code>utf-8</code>of <code>content</code> when i just type <code>content</code>,meanwhile <code>print content</code> cmd can output the form that I want to see?</p>
<p>The <strong>Second Question</strong>: what's the difference between <code>unicode</code> and <code>str</code>?
Someone told me that <code>encode</code> is convert <code>unicode</code> to <code>str</code>, but what i learned from <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Unicode HowTo</a> tells me <code>encode</code> is convert <code>unicode</code> to <code>utf-8</code></p>
<p>Not over yet! :)</p>
<p>here is <code>test.py</code></p>
<pre><code>#!/usr/bin/python
#-*- coding: utf-8 -*-
fr = open('a.TEST')
fw = open('out.TEST','w')
content = fr.readline()
content_list = content.split()
print content
fw.write('{0}'.format(content_list))
fr.close()
fw.close()
</code></pre>
<p><a href="http://i.stack.imgur.com/4XevK.png" rel="nofollow"><img src="http://i.stack.imgur.com/4XevK.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/Oc52y.png" rel="nofollow"><img src="http://i.stack.imgur.com/Oc52y.png" alt="enter image description here"></a></p>
<p><strong>Third Question</strong>:Why the chinese character turn into utf-8 code when I do <code>.split()</code>?</p>
<p>and I thought <code>fw.write('{0}'.format(content_list).decode('utf-8'))</code> will work, but it doesn't.
I don't want what's written into <code>out.TEST</code> is character encoding form, I want it to be exactly the character that look like originallyï¼ä½ 好ï¼. How to do it?</p>
| 1 | 2016-10-01T14:51:16Z | 39,808,990 | <h2>What is Encoding</h2>
<p>A file consists of bytes. You can represent each byte with a number between 0 and 255 (or 0x00 and 0xFF in hexadecimal).</p>
<p>Text is also written as bytes. There is an agreement on the way text is written. That is an encoding. The most basic encoding is ASCII and other encodings are usually based on it. For example, ASCII defines that number 65 (0x41) represents 'A', 66 (0x42) represents 'B' etc.</p>
<h2>How are Strings Represented</h2>
<p>In python, you can define a string using numeric values:</p>
<pre><code>>>> '\x41\x42\x43'
'ABC'
</code></pre>
<p><code>'\x41\x42\x43'</code> is exactly the same thing as <code>'ABC'</code>. Python will always represent the string using the more readable textual representation (<code>'ABC'</code>).</p>
<p>However, some numeric values are not printable characters, so they will be represented in numeric form:</p>
<pre><code>>>> '\x00\x01\x02\x03\x04'
'\x00\x01\x02\x03\x04'
</code></pre>
<p>Others characters have aliases to make your job easier:</p>
<pre><code>>>> '\x0a\x0d\x09'
'\n\r\t'
</code></pre>
<h2>Different Encodings</h2>
<p><a href="http://www.asciitable.com/" rel="nofollow">ASCII table</a> defines meaning of numbers 0-127 and includes only the english alphabet. Numbers 128-255 are undefined. So, other encodings define a meaning for 128-255. Yet others change the meaning of the whole range 0-255.</p>
<p>There are many encodings and they define 128-255 differently.</p>
<p>For example, character 185 (0xB9) is <code>Ä
</code> in windows-1250 encoding, but it is <code>Å¡</code> in iso-8859-2 encoding.</p>
<p>So, what happens if you print <code>\xb9</code>? It depends on the encoding used in the console. In my case (my console uses cp852 encoding) it is:</p>
<pre><code>>>> print '\xb9'
â£
</code></pre>
<p>Because of that ambiguity, string <code>'\xb9'</code> will never be <em>represented</em> as <code>'â£'</code> (nor <code>'Ä
'</code>...). That would hide the true value. It will be represented as the numeric value:</p>
<pre><code>>>> '\xb9'
'\xb9'
</code></pre>
<p>Also:</p>
<pre><code>>>> 'â£'
'\xb9'
</code></pre>
<p>See also the string from the question in my console:</p>
<pre><code>>>> content = '\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd Hello China 1 2 3\n'
>>>
>>> content
'\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd Hello China 1 2 3\n'
>>>
>>> print content
ÅŻáÅÄ
Å» ÅÅÅÅŤŻ Hello China 1 2 3
</code></pre>
<p><strong>But what happens if variable is just entered in the console?</strong></p>
<p>When a variable is enteren in cosole without <code>print</code>, its representation is printed. It is the same as the following:</p>
<pre><code>>>> print repr(content)
'\xe4\xbd\xa0\xe5\xa5\xbd \xe4\xb8\xad\xe5\x9b\xbd Hello China 1 2 3\n'
</code></pre>
<h2>What is Unicode?</h2>
<p><a href="http://unicode-table.com/en/#control-character" rel="nofollow">Unicode table</a> aims to define a numeric representation of all characters in the world and more. It can actually do that, because it is not limited to 256 values (or to any other limit actually). This is not an encoding, but a universal mapping of numbers to characters.</p>
<p>For example, unicode defines that number 353 (0x0161) is character <code>Å¡</code>. That is allways true regardless of your locale and encodings you use. That character can be stored in files (or memory) in any encoding which supports <code>Å¡</code>.</p>
<h2>What is UTF-8?</h2>
<p>When encoding a unicode character, one can use any encoding, but not all of them will support all characters.</p>
<p>For example, <code>Å¡</code> (unicode 0x0161) can be encoded in iso-8869-2 as 0xB9, but it cannot be encoded in iso-8869-1 at all.</p>
<p>So, to be able to encode anything, you need an encoding which supports <em>every</em> unicode character. UTF-8 is one of those encodings, but there are others:</p>
<pre><code>>>> u'\u0161'.encode('utf-7')
'+AWE-'
>>> u'\u0161'.encode('utf-8')
'\xc5\xa1'
>>> u'\u0161'.encode('utf-16le')
'a\x01'
>>> u'\u0161'.encode('utf-16be')
'\x01a'
>>> u'\u0161'.encode('utf-32le')
'a\x01\x00\x00'
>>> u'\u0161'.encode('utf-32be')
'\x00\x00\x01a'
</code></pre>
<p>The good thing about utf-8 is that the whole ASCII range is unchanged and as long as only ASCII is used, only one byte is used per character:</p>
<pre><code>>>> u'abcdefg'.encode('utf-8')
'abcdefg'
</code></pre>
<h2>Unicode in Python 2</h2>
<p><strong>Important:</strong> This is really specific to Python 2. Python 3 is different.</p>
<p>Unlike <code>str</code> objects, which are strings of bytes, <code>unicode</code> objects are strings of unicode characters.</p>
<p>They can be encoded into a <code>str</code> in chosen encoding, or decoded from <code>str</code> in chosen encoding.</p>
<p>A unicode string is specified using <code>u</code> before the opening quote. The characters inside are interpreted using current encoding, or they can be specified in numeric format <code>\uHEX</code>:</p>
<pre><code>>>> u'ABCD'
u'ABCD'
>>>
>>> u'\u0041\u0042\u0043'
u'ABC'
>>> u'šâů'
u'\u0161\xe2\u016f'
</code></pre>
<h1>And Now the Answers</h1>
<h2>First Question</h2>
<ul>
<li><code>contents</code> prints <code>repr(contents)</code></li>
<li><code>print contents</code> prints <code>contents</code></li>
</ul>
<h2>Second Question</h2>
<p><strong>UTF-8</strong> strings are byte strings (<code>str</code>). You get them by encoding the <code>unicode</code>:</p>
<pre><code>>>> u'\u0161'.encode('utf-8')
'\xc5\xa1'
>>> '\xc5\xa1'.decode('utf-8')
u'\u0161'
</code></pre>
<p>So yes, <code>encode</code> converts <code>unicode</code> to <code>str</code>. The <code>str</code> can be utf-8, but it does not have to be.</p>
<h2>Third Question</h2>
<p><strong>A)</strong> <em>"Why the chinese character turn into utf-8 code when I do .split()?"</em></p>
<p>They were utf-8 all the time.</p>
<p><strong>B)</strong> <em>"I thought fw.write('{0}'.format(content_list).decode('utf-8')) will work"</em></p>
<p><code>content_list</code> is not a string. It is a list. When a list is converted to a string, it is done using its <code>repr</code>, which also does <code>repr</code> of all of the contents.</p>
<p>For example:</p>
<pre><code>>>> 'a \n a \n a'
'a \n a \n a'
>>> print 'a \n a \n a'
a
a
a
>>> print ['a \n a \n a']
['a \n a \n a']
</code></pre>
<p>The last print printed repr(list) which contains repr(str).</p>
| 3 | 2016-10-01T16:34:19Z | [
"python",
"unicode",
"encoding",
"utf-8",
"character-encoding"
]
|
How to access some widget attribute from another widget in Kivy? | 39,807,997 | <p>Ok let's say I want that label in some widget to use text from label inside another widget:</p>
<pre><code><SubWidget@RelativeLayout>:
Label:
text: str(root.parent.ids.first.text)
<RootWidget>:
Label:
id: first
center_x: 100
text: "text"
SubWidget:
id: second
center_x: 200
</code></pre>
<p>This works but doesn't seem to be nice solution. If I'll place <code>first</code> inside another widget I'll need to change reference to that it everywhere in the code (that can lead to errors).</p>
<p>My first idea was at least to store reference to <code>first</code> at root level and reference to it:</p>
<pre><code><SubWidget@RelativeLayout>:
Label:
text: str(root.parent.l.text)
<RootWidget>:
l: first
Label:
id: first
center_x: 100
text: "text"
SubWidget:
id: second
center_x: 200
</code></pre>
<p>But this leads to exception:</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'text'
</code></pre>
<p>This is confusing since if I'll write something like <code>text: str(root.parent.l)</code> I'll see <code>Label object</code> rather than <code>NoneType</code>.</p>
<p>So I have two questions:</p>
<ol>
<li>Why doesn't second solution works? How it can be fixed?</li>
<li>In general, what's the best way to access some widget attribute from another widget? Can I make it independent of widgets hierarchy?</li>
</ol>
| 0 | 2016-10-01T14:52:14Z | 39,808,691 | <ol>
<li><p>The object property <code>l</code> probably gets populated <strong>after</strong> the first event loop iteration, while you are trying to access it within the first. You could delay it till the second iteration to make it work.</p></li>
<li><p>The most powerful approach is to bind those properties from inside python code, but there are some kv lang tricks to make it simpler. This is my favorite method:</p></li>
</ol>
<pre>BoxLayout
Label
id: label
text: 'hello world'
SubWidget
label_text: label.text
<SubWidget@BoxLayout>
label_text: 'none'
Label
text: root.label_text
</pre>
| 2 | 2016-10-01T16:02:21Z | [
"python",
"kivy",
"kivy-language"
]
|
Click button (python), having problems with both mechanize and selenium | 39,808,006 | <p>I'm trying to click the "Coevolution Scores (TXT)" button that pops up after clicking the "Export..." button, however, using a python script <a href="http://polyview.cchmc.org/cgi-bin/coevolve.cgi?JOB=c8a266e0d7ba7cc" rel="nofollow">here</a>, I could not do it either with mechanize nor selenium, using different selection types.</p>
<p>Is there any other way, or can you possibly figure out what I am doing wrong?</p>
<p>I used this code:</p>
<pre><code>url="http://polyview.cchmc.org/cgi-bin/coevolve.cgi?JOB=c8a266e0d7ba7cc"
driver = webdriver.Chrome(executable_path="C:/ProgramFiles/Google/Chrome/Application/chromedriver.exe")
driver.get(url)
time.sleep(15)
driver.find_element(by=By.XPATH, value="//button[@title='Export...']").click()
</code></pre>
<p>also tried by link_text and by putting <code>find_element_by_link_text</code>, instead of putting the argument inside. Below is the button I try to click.</p>
<pre><code> <form id="downloadMat" target="formTarget" method="POST" action="coeviz_data.pl">
<input name="x" class="idData" type="hidden" value="683436.chi">
<input name="dl" class="dlData" type="hidden" value="683436.chi.wph">
<input name="w" class="weighted" type="hidden" value="wph">
<input name="res" type="hidden" value="scores.txt">
<button onclick="submit()">Coevolution Scores (TXT)</button>
</form>
</code></pre>
| -1 | 2016-10-01T14:53:42Z | 39,808,443 | <p>The code you are trying to select is inside an <code><iframe></code> element. This means that you have to switch frame first before selecting anything that is inside it. This will work:</p>
<pre><code>from selenium import webdriver
import time
from selenium.webdriver.common.by import By
url="http://polyview.cchmc.org/cgi-bin/coevolve.cgi?JOB=c8a266e0d7ba7cc"
driver = webdriver.Chrome(executable_path="C:/ProgramFiles/Google/Chrome/Application/chromedriver.exe")
driver.get(url)
time.sleep(15)
driver.switch_to_frame('ifCoeViz')
driver.find_element(by=By.XPATH, value="//button[@title='Export...']").click()
</code></pre>
| 1 | 2016-10-01T15:37:28Z | [
"python",
"selenium",
"mechanize"
]
|
Is this type of attribute value/function checking, a code smell in Python? | 39,808,072 | <p><em>note</em>: This is <a href="http://codereview.stackexchange.com/questions/142983/is-this-type-of-attribute-value-function-checking-a-code-smell-in-python">crossposted</a> on CodeReview, as per recommendation</p>
<p><strong>Premise</strong>: I have a class hierarchy (Python), where <code>tidy</code> is one of the methods. It removes nodes that are of type <em>ASTIgnore</em>, and rebinds the children of that node to its parent.</p>
<p>The target node cannot delete itself, and doesn't <em>see</em> its parent (for rebinding). Thus, the deletion of the target (of type ASTIgnore) would happen at its parent, where the parent <em>checks the type</em> of its children.</p>
<p><strong>Question</strong>: How would this need to be implemented to reduce the code smell?</p>
<p>Which among these approaches is least bad, or are there other ones (see bottom)?</p>
<pre><code># A)
if child.nodetype == "ASTIgnore":
# B)
if child.isIgnored():
# C)
if child.isIgnoreType:
# D)
if isinstance(child, ASTIgnore):
</code></pre>
<p>Where, the classes and <code>tidy</code> looks like the below. I'll remove the redundancy, based on the cleanest implementation.</p>
<pre><code>class ASTNode(object):
def __init__(self):
self.nodetype = self.__class__.__name__
self.isIgnoreType = False
def isIgnored(self):
return False
def tidy(self):
# Removes "Ignore" type/attribute nodes while maintaining hierarchy
if self.children:
for child in self.children:
child.tidy()
for i, child in reversed(list(enumerate(self.children))):
#--------- Is this Bad? ----------
if child.nodetype == "ASTIgnore":
#------ --------------------------
if not child.children:
# leaf node deletion
self.children.pop(i)
else:
# target node deletion + hierarchy correction
grandkids = child.children
self.children[i:i+1] = grandkids
class ASTIgnore(ASTNode):
def __init__(self):
ASTNode.__init__()
self.isIgnoreType = True
def isIgnored(self):
return True
</code></pre>
<p><strong>On matter of Duck Typing with a Tell-Not-Ask policy</strong>:</p>
<p>I am new to Python, and would like to be a pythonic coder (and a better coder in general). Hence, </p>
<p>How do I <em>Duck Type</em> the above? Would checking the attribute value(<code>igIgnoreType</code>)/function(<code>isIgnored</code>) be considered <em>Duck Typing</em> if the attribute/function is never touched beyond object construction? </p>
<p>I do have another implementation, where <code>tidy</code> is overloaded in <em>Ignore</em> type nodes. <strong>No more type checking</strong>, but the parent still has to remove target child, and rebind grandkids. Here, the Ignore types return their children, which would be <code>[]</code> for leaf nodes. But, there is still a check on if the return was <code>None</code>. I am sure this is certainly <em>Duck Typing</em>, but is checking for <code>None</code> and code-replication, bad code?</p>
<pre class="lang-py prettyprint-override"><code>class ASTNode(object):
def tidy(self):
for i, child in reversed(list(enumerate(self.children))):
grandkids = child.tidy()
if grandkids is not None:
self.children[i:i+1] = grandkids
return None
class ASTIgnore(ASTNode):
def tidy(self):
for i, child in reversed(list(enumerate(self.children))):
grandkids = child.tidy()
if grandkids is not None:
self.children[i:i+1] = grandkids
return self.children
</code></pre>
<p><strong><em>_edit0</em></strong></p>
<p>Based on <a href="http://stackoverflow.com/users/84128/eric-conner">Eric's</a> vote, a <code>isIgnored()</code> function check implementation would look like</p>
<pre class="lang-py prettyprint-override"><code>def tidy(self):
"""
Clean up useless nodes (ASTIgnore), and rebalance the tree
Cleanup is done bottom-top
in reverse order, so that the deletion/insertion doesn't become a pain
"""
if self.children:
# Only work on parents (non-leaf nodes)
for i, child in reversed(list(enumerate(self.children))):
# recurse, so as to ensure the grandkids are clean
child.tidy()
if child.isIgnored():
grandkids = child.children
self.children[i: i + 1] = grandkids
</code></pre>
| 2 | 2016-10-01T15:00:10Z | 39,809,685 | <p>I think using the return value from the <code>tidy</code> method is a good way to pass information between your nodes. You're going to call <code>tidy</code> on each of your children anyway, so getting a return value that tells you what to do with that child makes the whole code simpler.</p>
<p>You can avoid repeating yourself by using <code>super</code> to call the base class's implementation from the derived class, and just changing the return value:</p>
<pre><code>class ASTIgnore(ASTNode):
def tidy(self):
super().tidy() # called for the side-effects, return value is overridden
return self.children
</code></pre>
<p>If you're using Python 2, where <code>super</code> is a little bit less magical than it is in Python 3, you'll need to use <code>super(ASTIgnore, self)</code> instead of <code>super()</code>.</p>
| 1 | 2016-10-01T17:45:53Z | [
"python",
"typechecking",
"duck-typing"
]
|
make bouncing turtle with python | 39,808,240 | <p>i am a beginner with python
I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p>
<pre><code>import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()
</code></pre>
| 2 | 2016-10-01T15:17:26Z | 39,808,329 | <p>You need <code>window_width()/2</code> and <code>window_height()/2</code> to keep inside window.</p>
<p>ie.</p>
<pre><code>if x >= turtle.window_width()/2:
xdir = -1
if x <= -turtle.window_width()/2:
xdir = 1
if y >= turtle.window_height()/2:
ydir = -1
if y <= -turtle.window_height()/2:
ydir = 1
</code></pre>
| 1 | 2016-10-01T15:27:08Z | [
"python",
"turtle-graphics"
]
|
make bouncing turtle with python | 39,808,240 | <p>i am a beginner with python
I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p>
<pre><code>import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()
</code></pre>
| 2 | 2016-10-01T15:17:26Z | 39,808,515 | <p>You should put
turtle.penup()
Before the while loop to make your code better and a little bit faster. It is almost a bug! </p>
| 1 | 2016-10-01T15:44:44Z | [
"python",
"turtle-graphics"
]
|
make bouncing turtle with python | 39,808,240 | <p>i am a beginner with python
I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering</p>
<pre><code>import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()
</code></pre>
| 2 | 2016-10-01T15:17:26Z | 39,809,154 | <p>Although your approach to the problem works (my rework):</p>
<pre><code>import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
while True:
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.mainloop()
</code></pre>
<p>In the long run, it's the wrong approach to take. In this case, due to the infinite loop <code>while True</code>, the <code>mainloop()</code> method is never called so no other turtle event handlers are active. For example, if we wanted to use <code>exitonclick()</code> instead of <code>mainloop()</code>, it wouldn't work. Instead consider:</p>
<pre><code>import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
def move():
global x, y, xdir, ydir
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.ontimer(move, 5)
turtle.ontimer(move, 5)
turtle.exitonclick()
</code></pre>
<p>Here we've turned control back over to the mainloop and the motion is on an event timer. Other turtle events can execute so <code>exitonclick()</code> works. Just something to think about going forward before you program yourself, and your turtle, into a corner.</p>
| 1 | 2016-10-01T16:48:53Z | [
"python",
"turtle-graphics"
]
|
assign value of variables from Matlab matrix | 39,808,429 | <p>Coming from a numpy background I had to use Matlab for a new project started a few days ago.</p>
<p>Switching to Matlab was really straight forward since the syntax is somehow comparable to numpy's syntax. However, there is one thing I was not able to 'convert' in a satisfying way.</p>
<p>In numpy I am able to assign variables based on the rows of a array (or 'matrix' im Matlab terminology) like this:</p>
<pre><code>import numpy as np
arr = np.array([1, 2, 3])
a, b, c = arr
print(a, b, c)
arr = np.array([[1, 2, 3], [11, 22, 33]])
for row in arr:
a, b, c = row
print(a, b, c)
</code></pre>
<p>Which seems to quite elegant. However I did not find a eqivalent way to do this in Matlab without accessing each element of the matrix using index-notation.</p>
<p>Is there a equivalent way to perform variable assignment as shown in the second part of my Python snippet in Matlab or do I have to use the explicit index-notation?</p>
| 2 | 2016-10-01T15:35:47Z | 39,808,466 | <p>The only way to really do this in MATLAB is to use a <a href="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html" rel="nofollow">comma-separated list</a> to "distribute" the contents of a cell array to multiple variables. The down-side is that it requires that you first convert your row (a numeric array) to a cell array using something like <a href="https://www.mathworks.com/help/matlab/ref/num2cell.html" rel="nofollow"><code>num2cell</code></a>.</p>
<pre class="lang-matlab prettyprint-override"><code>% Create an example numeric array
data = [1, 2, 3];
% Convert your data to a cell array
data_as_cell = num2cell(data);
% Use {:} indexing to convert the cell into a comma-separated list
[a, b, c] = data_as_cell{:};
</code></pre>
| 2 | 2016-10-01T15:40:02Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
]
|
Create local files from a Django web | 39,808,462 | <p>I have written a Django web run under Linux server, the web is used to read a</p>
<p>file path and generate some folders and files on the local machine which browse</p>
<p>the web, not sure how to do that, currently it can only generate the files on </p>
<p>the server runs the web locally.</p>
<p>Does it need to use the python package paramikoï¼</p>
<p>Thanks,
Le</p>
| -1 | 2016-10-01T15:39:29Z | 39,808,505 | <p>Django runs on server and every web server has no access to local (user) computer - it can't create folder on local computer (and it can't steal your files). It can only generate file and user can download it.</p>
| 1 | 2016-10-01T15:44:25Z | [
"python",
"django"
]
|
Importing module from string in the Python C API | 39,808,521 | <p>Importing Python modules from files is relatively easy with the Python C API with <code>pyImport_Import()</code> however I would need to use functions stored in strings. Is there a way to import python modules from strings (to clarify: there is no file; the code is in a string) or will I have to save the strings as temp files?</p>
| 0 | 2016-10-01T15:45:06Z | 39,808,548 | <p><s>If my understanding is correct, you could use <a href="https://docs.python.org/3/c-api/import.html#c.PyImport_ImportModule" rel="nofollow"><code>PyImport_ImportModule</code></a> which takes a <code>const char* name</code> to specify the module to be imported.</s></p>
<p>Since my understanding was incorrect:</p>
<p>It would generally be better to dump the contents to a <code>.py</code> file and then execute them with <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.PyRun_File" rel="nofollow"><code>PyRun_File</code></a> but, if you have strings and want to work with those <em>I guess</em> you could use <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.Py_CompileString" rel="nofollow"><code>Py_CompileString</code></a> to compile it to a code object and then feed it to <a href="https://docs.python.org/3/c-api/veryhigh.html?highlight=compile#c.PyEval_EvalCode" rel="nofollow"><code>PyEval_EvalCode</code></a> for evaluation.</p>
| 1 | 2016-10-01T15:47:53Z | [
"python",
"c",
"python-c-api",
"cross-language"
]
|
"Redeclared s defined above without usage" | 39,808,529 | <pre><code>for i in range(10):
s = 5
for j in range(10):
s = min(s)
</code></pre>
<p>The above code gives the title of this question as warning in IntelliJ for the second line.</p>
<p>I'm pretty sure that the warning happens because in the CFG there are possibly two consecutive writes (without read in between) to <code>s</code> because of the nested loops. Until now I have been ignoring the warning but to be on the safe side I'd like to ask for confirmation of my hypothesis.</p>
| 0 | 2016-10-01T15:46:17Z | 39,808,579 | <p>Your hypothesis is nearly correct. The name <code>s</code> was bounded to an integer whose value was never used nor changed in the enclosing loop and yet it is rebounded to another value (<em>although that will raise an error</em>) in the nested loop. Note that the first assignment does not change with any iteration of the outer <code>for</code> loop.</p>
<p>The IDE's warning suggests the first assignment inside the loop is unnecessary as <code>s</code> was never changed. The assignment might as well have been better placed outside the <code>for</code> loop which will prevent a redundant binding and rebinding:</p>
<pre><code>s = 5
for i in range(10):
...
</code></pre>
| 0 | 2016-10-01T15:50:23Z | [
"python",
"intellij-idea"
]
|
implement mat2gray in Opencv with Python | 39,808,545 | <p>I have the same problem with him: <a href="http://http://stackoverflow.com/questions/27483013/scaling-a-matrix-in-opencv" rel="nofollow">Scaling a matrix in OpenCV</a></p>
<p>I got the same problem with him, I have a colored picture, I used matlab to read the picture: <code>Input = imread('input1.jpg');</code>, and the format of the picture is 612x612x3 uint8, I print the 5x5x1 pixel in the picture as below:<code>Input(1:5,1:5,1)</code></p>
<pre><code> 201 201 201 201 201
201 201 201 201 201
202 202 202 202 202
203 203 203 203 203
204 204 204 204 204
</code></pre>
<p>by using the mat2gray function: <code>rgb_out = mat2gray(Input);</code>, these pixels can be transformed to this, they all in the range between 0 and 1: <code>rgb_out(1:5,1:5,1)</code></p>
<pre><code>0.9684 0.9455 0.9266 0.9099 0.9047
0.9657 0.9542 0.9432 0.9354 0.9299
0.9642 0.9571 0.9502 0.9495 0.9456
0.9621 0.9609 0.9562 0.9532 0.9516
0.9673 0.9633 0.9597 0.9580 0.9575
</code></pre>
<p>so the question is how can I implement this in Opencv with Python, I tried the code as below:</p>
<pre><code>print(Input)
rgb_out = np.zeros(Input.shape, np.uint8)
cv2.normalize(Input,rgb_out,1,0,cv2.NORM_MINMAX)
print(rgb_out)
</code></pre>
<p>but the first print is :</p>
<pre><code>[[[205 207 201]
[205 207 201]
[205 207 201]
...,
[232 254 242]
[232 254 242]
[231 253 241]]...
</code></pre>
<p>and the elements in the rgb_out is no more than 1 or 0. please help, thanks.</p>
| 0 | 2016-10-01T15:47:51Z | 39,808,617 | <p>Your input matrix is an integer datatype and your output matrix is defined to be <code>np.uint8</code> (an integer type). By default, <code>cv2.normalize</code> is going to return a result that is the same datatype as the inputs. You'll want to use floating point datatypes if you want output values between <code>0.0</code> and <code>1.0</code>. </p>
<p>One option would be to convert your input and outputs to <code>np.double</code> prior to calling <code>cv2.normalize</code></p>
<pre><code>A = np.double(A)
out = np.zeros(A.shape, np.double)
normalized = cv2.normalize(A, out, 1.0, 0.0, cv2.NORM_MINMAX)
</code></pre>
<p>Alternately, you can specify a floating point datatype to <code>cv2.normalize</code> via the <code>dtype</code> kwarg to force a specific output datatype. </p>
<pre><code>A = np.array([1, 2, 3])
out = np.zeros(A.shape, np.double)
normalized = cv2.normalize(A, out, 1.0, 0.0, cv2.NORM_MINMAX, dtype=cv2.CV_64F)
</code></pre>
| 2 | 2016-10-01T15:54:46Z | [
"python",
"matlab",
"opencv"
]
|
Find all common N-sized tuples in list of tuples | 39,808,550 | <p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p>
<p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p>
<pre><code>(UUID, (tuple of N integers))
</code></pre>
<p>Lets assume that N equals 20 for every k-tuple and that every 20-sized tuple is sorted.
I have saved all my data in a database in the following two forms (2 different tables), so that I can process them more easily:</p>
<ol>
<li>_id, UUID, tuple.as_a_string()</li>
<li>_id, UUID, 1st_elem, 2nd_elem, 3rd_3lem, ... 20th_elem</li>
</ol>
<p>The goal is to find all 10-sized tuples from the list of tuples, such that every one of those tuples to exist in more than one 20-sized tuple.**</p>
<p>For example, if we are given the two following 20-sized tuples:</p>
<pre><code>(1, (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,161,17,18,19,20))
(2, (1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39))
</code></pre>
<p>the common tuple is: (1,3,5,7,9,11,13,15,17,19)</p>
<p>which is a 10-sized tuple, so the result is something like the following:</p>
<pre><code>(1, 2, (1,3,5,7,9,11,13,15,17,19))
</code></pre>
<p>In order to accomplish this, what I am currently doing is (in Python 3):</p>
<ul>
<li>Create a set with the elements of the 20-sized tuple of the 1st row in the database.</li>
<li>Create a set for each row with the elements of the 20-sized tuple of the rest rows in the database.</li>
<li>For each set in the second list of sets, I do the intersection with the first set.</li>
<li>Then I create the combination of the intersection with 10 elements <em>(in Python it is itertools.combinations(new_set, 10) )</em>, which gives me the result that I want.</li>
</ul>
<p>But this procedure is <strong>very slow</strong>. Even using multiprocessing to utilize my 8 CPU cores fully, each computing for a different number, it takes forever. I have the program running for 2 days now and it is only in 20%.</p>
<p>Do you have any ideas on how to optimize the process? Would NumPy arrays help with the speed of execution? Is there any way in SQL to calculate what I want for each row, even one row at a time?</p>
<p>Thanks in advance.</p>
| 2 | 2016-10-01T15:48:06Z | 39,811,749 | <p>It appears that you could put the tuples into the rows of a matrix and make a map from row numbers to UUIDs. Then it's feasible to store all of the tuples in a numpy array since the elements of the tuples are small. numpy has code capable of computing the intersections between rows of such an array. This code generates combinations to process as tuples first, then it makes the comparisons.</p>
<pre><code>from itertools import combinations
import numpy as np
from time import time
minInt=1
maxInt=100
tupleSize=20
intersectionSize=10
K=100
rows=np.zeros((K,tupleSize),dtype=np.int8)
print ('rows uses', rows.nbytes, 'bytes')
for i,c in enumerate(combinations(range(minInt,maxInt),tupleSize)):
if i>=K:
break
for j,_ in enumerate(c):
rows[i,j]=_
t_begin=time()
for i in range(K-1):
for j in range(i+1,K):
intrsect=np.intersect1d(rows[i],rows[j],True)
if intrsect.shape[0]==intersectionSize:
print (i,j,intrsect)
t_finish=time()
print ('K=', K, t_finish-t_begin, 'seconds')
</code></pre>
<p>Here are some sample measurements made on my old two-core P4 clunker at home.</p>
<p>rows uses 200 bytes
K= 10 0.0009770393371582031 seconds</p>
<p>rows uses 1000 bytes
K= 50 0.0410161018371582 seconds</p>
<p>rows uses 2000 bytes
K= 100 0.15625 seconds</p>
<p>rows uses 10000 bytes
K= 500 3.610351085662842 seconds</p>
<p>rows uses 20000 bytes
K= 1000 14.931640863418579 seconds</p>
<p>rows uses 100000 bytes
K= 5000 379.5498049259186 seconds</p>
<p>If you run the code on your machine you can extrapolate. I don't know if it would make your calculation feasible or not.</p>
<p>Maybe I'll just get a bunch of negative votes!</p>
| 3 | 2016-10-01T21:45:08Z | [
"python",
"algorithm",
"sqlite",
"numpy"
]
|
Find all common N-sized tuples in list of tuples | 39,808,550 | <p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p>
<p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p>
<pre><code>(UUID, (tuple of N integers))
</code></pre>
<p>Lets assume that N equals 20 for every k-tuple and that every 20-sized tuple is sorted.
I have saved all my data in a database in the following two forms (2 different tables), so that I can process them more easily:</p>
<ol>
<li>_id, UUID, tuple.as_a_string()</li>
<li>_id, UUID, 1st_elem, 2nd_elem, 3rd_3lem, ... 20th_elem</li>
</ol>
<p>The goal is to find all 10-sized tuples from the list of tuples, such that every one of those tuples to exist in more than one 20-sized tuple.**</p>
<p>For example, if we are given the two following 20-sized tuples:</p>
<pre><code>(1, (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,161,17,18,19,20))
(2, (1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39))
</code></pre>
<p>the common tuple is: (1,3,5,7,9,11,13,15,17,19)</p>
<p>which is a 10-sized tuple, so the result is something like the following:</p>
<pre><code>(1, 2, (1,3,5,7,9,11,13,15,17,19))
</code></pre>
<p>In order to accomplish this, what I am currently doing is (in Python 3):</p>
<ul>
<li>Create a set with the elements of the 20-sized tuple of the 1st row in the database.</li>
<li>Create a set for each row with the elements of the 20-sized tuple of the rest rows in the database.</li>
<li>For each set in the second list of sets, I do the intersection with the first set.</li>
<li>Then I create the combination of the intersection with 10 elements <em>(in Python it is itertools.combinations(new_set, 10) )</em>, which gives me the result that I want.</li>
</ul>
<p>But this procedure is <strong>very slow</strong>. Even using multiprocessing to utilize my 8 CPU cores fully, each computing for a different number, it takes forever. I have the program running for 2 days now and it is only in 20%.</p>
<p>Do you have any ideas on how to optimize the process? Would NumPy arrays help with the speed of execution? Is there any way in SQL to calculate what I want for each row, even one row at a time?</p>
<p>Thanks in advance.</p>
| 2 | 2016-10-01T15:48:06Z | 39,813,183 | <p>Bill, I think this creates a more random mix. Your combinations version steps systematically through the choices. With small K the intersection size is close to <code>tupleSize</code>.</p>
<pre><code>choices = np.arange(minInt, maxInt)
for i in range(K):
rows[i,:] = np.random.choice(choices, tupleSize, replace=False)
</code></pre>
<p>Using <code>sets</code> is about 4x faster than <code>np.intersect1d</code>.</p>
<pre><code>sets = [set(row) for row in rows]
dd = collections.defaultdict(int)
for i in range(K-1):
for j in range(i+1,K):
intrsect=sets[i].intersection(sets[j])
dd[len(intrsect)] += 1
</code></pre>
<p>I switched to collecting the intersection size, as it is more interesting and less sensitive to iteration strategy. </p>
<p>With K=5000:</p>
<pre><code>K= 5000 221.06068444252014 seconds
{0: 77209, 1: 514568, 2: 1524564, 3: 2653485, 4: 3044429, 5: 2436717, 6: 1408293, 7: 596370, 8: 188707, 9: 44262, 10: 7783, 11: 1012, 12: 93, 13: 8}
</code></pre>
<p>The smaller time is just for the <code>sets</code> creation step; that's very fast.</p>
<pre><code>K= 5000 0.058181047439575195 46.79403018951416 seconds
{0: 77209, 1: 514568, 2: 1524564, 3: 2653485, 4: 3044429, 5: 2436717, 6: 1408293, 7: 596370, 8: 188707, 9: 44262, 10: 7783, 11: 1012, 12: 93, 13: 8}
</code></pre>
<p>for larger K</p>
<pre><code>K= 10000 818.3419544696808 seconds
{0: 309241, 1: 2058883, 2: 6096016, 3: 10625523, 4: 12184030, 5: 9749827, 6: 5620209, 7: 2386389, 8: 752233, 9: 176918, 10: 31168, 11: 4136, 12: 407, 13: 18, 14: 2}
K= 10000 0.09764814376831055 151.11484718322754 seconds
</code></pre>
| 2 | 2016-10-02T02:02:59Z | [
"python",
"algorithm",
"sqlite",
"numpy"
]
|
Find all common N-sized tuples in list of tuples | 39,808,550 | <p>I have to create an an application that does the following (I have to parse the data only once and store them in a database):</p>
<p>I am given K tuples (with K over 1000000) and each tuple is in the form of</p>
<pre><code>(UUID, (tuple of N integers))
</code></pre>
<p>Lets assume that N equals 20 for every k-tuple and that every 20-sized tuple is sorted.
I have saved all my data in a database in the following two forms (2 different tables), so that I can process them more easily:</p>
<ol>
<li>_id, UUID, tuple.as_a_string()</li>
<li>_id, UUID, 1st_elem, 2nd_elem, 3rd_3lem, ... 20th_elem</li>
</ol>
<p>The goal is to find all 10-sized tuples from the list of tuples, such that every one of those tuples to exist in more than one 20-sized tuple.**</p>
<p>For example, if we are given the two following 20-sized tuples:</p>
<pre><code>(1, (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,161,17,18,19,20))
(2, (1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39))
</code></pre>
<p>the common tuple is: (1,3,5,7,9,11,13,15,17,19)</p>
<p>which is a 10-sized tuple, so the result is something like the following:</p>
<pre><code>(1, 2, (1,3,5,7,9,11,13,15,17,19))
</code></pre>
<p>In order to accomplish this, what I am currently doing is (in Python 3):</p>
<ul>
<li>Create a set with the elements of the 20-sized tuple of the 1st row in the database.</li>
<li>Create a set for each row with the elements of the 20-sized tuple of the rest rows in the database.</li>
<li>For each set in the second list of sets, I do the intersection with the first set.</li>
<li>Then I create the combination of the intersection with 10 elements <em>(in Python it is itertools.combinations(new_set, 10) )</em>, which gives me the result that I want.</li>
</ul>
<p>But this procedure is <strong>very slow</strong>. Even using multiprocessing to utilize my 8 CPU cores fully, each computing for a different number, it takes forever. I have the program running for 2 days now and it is only in 20%.</p>
<p>Do you have any ideas on how to optimize the process? Would NumPy arrays help with the speed of execution? Is there any way in SQL to calculate what I want for each row, even one row at a time?</p>
<p>Thanks in advance.</p>
| 2 | 2016-10-01T15:48:06Z | 39,813,697 | <p>There doesn't appear to be much hope for this: forgetting the <code>combinations()</code> part, you need to check the intersection of every pair of <code>K</code> tuples. There are <code>choose(K, 2) = K*(K-1)/2</code> pairs, so with a million tuples there are nearly 500 billion pairs.</p>
<p>One low-level trick you can play is to represent a tuple as an integer instead of as a set, where bit <code>2**i</code> is set in the integer when and only when <code>i</code> is in the tuple. Since you said in comments that a tuple contains no duplicates, and each tuple element is in <code>range(1, 100)</code>, 100-bit integers are sufficient (it could be cut to 99 bits, but not worth the bother).</p>
<p>The point is that bitwise "&" of integers goes a lot faster than set intersection. On my box, about 7 times faster. Here's some code to illustrate the concept, and some sloppy timing results (run on a machine doing lots of other stuff simultaneously):</p>
<pre><code>def build(K, values, N):
from random import sample
sets = []
ints = []
for i in range(K):
t = sample(values, N)
sets.append(set(t))
ints.append(sum(1 << i for i in t))
return sets, ints
def run(K, values, N):
from time import time
as_sets, as_ints = build(K, values, N)
for meth, collection in [("sets", as_sets),
("ints", as_ints)]:
s = time()
for i in range(K-1):
base = collection[i]
for j in range(i+1, K):
x = base & collection[j]
t = time()
print("K", K, meth, t-s)
for K in 5000, 10000, 20000:
run(K, range(1, 100), 20)
</code></pre>
<p>And output:</p>
<pre><code>K 5000 sets 7.322501182556152
K 5000 ints 1.0357279777526855
K 10000 sets 30.60071086883545
K 10000 ints 4.150524377822876
K 20000 sets 128.24610686302185
K 20000 ints 15.933331727981567
</code></pre>
<p>Note that, as expected, runtime for either approach is quadratic in K (so doubling K takes about 4 times as long; and making K 10 times larger would increase runtime by a factor of about 10**2 = 100).</p>
<p>While intersection is much faster with ints, determining the cardinality of the result is slower. There are many ways to do that, but "the best" depends on the expected distribution and your tolerance for coding pain ;-) Here's an overview of the <a href="https://en.wikipedia.org/wiki/Hamming_weight" rel="nofollow">major methods</a>.</p>
| 2 | 2016-10-02T03:54:16Z | [
"python",
"algorithm",
"sqlite",
"numpy"
]
|
I would like to remove the first n colors from a colormap without losing the original number of colours | 39,808,565 | <pre><code>from matplotlib import cm
import seaborn as sns
import matplotlib.pyplot as plt
</code></pre>
<p>Here is the original colormap</p>
<pre><code>cmap = [cm.inferno(x)[:3] for x in range(0,256)]
sns.palplot(cmap)
</code></pre>
<p><a href="http://i.stack.imgur.com/VewIo.png" rel="nofollow"><img src="http://i.stack.imgur.com/VewIo.png" alt="enter image description here"></a></p>
<p>My preferred outcome is something along the lines the colormap shown below, <strong>except</strong> with original number of colours </p>
<pre><code>cmap2 = [cm.inferno(x)[:3] for x in range(0,256)][100:]
sns.palplot(cmap2)
</code></pre>
<p><a href="http://i.stack.imgur.com/rg5Mv.png" rel="nofollow"><img src="http://i.stack.imgur.com/rg5Mv.png" alt="enter image description here"></a></p>
| 2 | 2016-10-01T15:49:41Z | 39,808,980 | <p>I believe that by "same resolution" you mean that you want 256 colors in the palette. I would actually think of this as having a different resolution from the original palette in sense that the values are closer together in the color space. In any case, I think you can get what you want by doing:</p>
<pre><code>import numpy as np
import seaborn as sns
from matplotlib import cm
x = np.linspace(.3, 1, 256)
pal = cm.inferno(x)
sns.palplot(pal)
</code></pre>
<p><a href="http://i.stack.imgur.com/LfOoj.png" rel="nofollow"><img src="http://i.stack.imgur.com/LfOoj.png" alt="enter image description here"></a></p>
| 1 | 2016-10-01T16:33:19Z | [
"python",
"matplotlib",
"seaborn",
"colormap"
]
|
Python, Requests, Threading, How fast do python requests close its sockets? | 39,808,573 | <p>I'm trying to make actions with Python requests. Here is my code:</p>
<pre><code>import threading
import resource
import time
import sys
#maximum Open File Limit for thread limiter.
maxOpenFileLimit = resource.getrlimit(resource.RLIMIT_NOFILE)[0] # For example, it shows 50.
# Will use one session for every Thread.
requestSessions = requests.Session()
# Making requests Pool bigger to prevent [Errno -3] when socket stacked in CLOSE_WAIT status.
adapter = requests.adapters.HTTPAdapter(pool_maxsize=(maxOpenFileLimit+100))
requestSessions.mount('http://', adapter)
requestSessions.mount('https://', adapter)
def threadAction(a1, a2):
global number
time.sleep(1) # My actions with Requests for each thread.
print number = number + 1
number = 0 # Count of complete actions
ThreadActions = [] # Action tasks.
for i in range(50): # I have 50 websites I need to do in parallel threads.
a1 = i
for n in range(10): # Every website I need to do in 3 threads
a2 = n
ThreadActions.append(threading.Thread(target=threadAction, args=(a1,a2)))
for item in ThreadActions:
# But I can't do more than 50 Threads at once, because of maxOpenFileLimit.
while True:
# Thread limiter, analogue of BoundedSemaphore.
if (int(threading.activeCount()) < threadLimiter):
item.start()
break
else:
continue
for item in ThreadActions:
item.join()
</code></pre>
<p>But the thing is that after I get 50 Threads up, the <code>Thread limiter</code> starting to wait for some Thread to finish its work. And here is the problem. After scrit went to the Limiter, <code>lsof -i|grep python|wc -l</code> is showing much less than 50 active connections. But before Limiter it has showed all the <= 50 processes. Why is this happening? Or should I use requests.close() instead of requests.session() to prevent it using already oppened sockets?</p>
| 2 | 2016-10-01T15:50:08Z | 39,808,815 | <p>Your limiter is a tight loop that takes up most of your processing time. Use a thread pool to limit the number of workers instead.</p>
<pre><code>import multiprocessing.pool
# Will use one session for every Thread.
requestSessions = requests.Session()
# Making requests Pool bigger to prevent [Errno -3] when socket stacked in CLOSE_WAIT status.
adapter = requests.adapters.HTTPAdapter(pool_maxsize=(maxOpenFileLimit+100))
requestSessions.mount('http://', adapter)
requestSessions.mount('https://', adapter)
def threadAction(a1, a2):
global number
time.sleep(1) # My actions with Requests for each thread.
print number = number + 1 # DEBUG: This doesn't update number and wouldn't be
# thread safe if it did
number = 0 # Count of complete actions
pool = multiprocessing.pool.ThreadPool(50, chunksize=1)
ThreadActions = [] # Action tasks.
for i in range(50): # I have 50 websites I need to do in parallel threads.
a1 = i
for n in range(10): # Every website I need to do in 3 threads
a2 = n
ThreadActions.append((a1,a2))
pool.map(ThreadActons)
pool.close()
</code></pre>
| 1 | 2016-10-01T16:15:50Z | [
"python",
"multithreading",
"sockets",
"python-requests"
]
|
Python | How to parse JSON from results from AWS response? | 39,808,593 | <p>I was trying to get the value of <code>VersionLabel</code> which is <code>php-v1</code> but my code doesn't work properly and I don't know what I'm doing wrong.</p>
<p>Could you please let me know what's wrong and how can I parse the <code>php-v1</code>?</p>
<p>This is my error message.</p>
<p><code>TypeError: the JSON object must be str, not 'dict'</code></p>
<p>This is my code.</p>
<pre><code>#!/usr/bin/env python3
import boto3
import json
def get_label():
try:
env_name = 'my-env'
eb = boto3.client('elasticbeanstalk')
response = eb.describe_instances_health(
EnvironmentName=env_name,
AttributeNames=[
'Deployment'
]
)
#print(response)
data = json.loads(response)
print(data['VersionLabel'])
except:
raise
if __name__ == '__main__':
get_label()
</code></pre>
<p>This is the response I got from AWS when <code>print(response)</code> is invoked.</p>
<pre><code>{
'InstanceHealthList':[
{
'InstanceId':'i-12345678',
'Deployment':{
'DeploymentId':2,
'DeploymentTime':datetime.datetime(2016,
9,
29,
4,
29,
26,
tzinfo=tzutc()),
'Status':'Deployed',
'VersionLabel':'php-v1'
}
}
],
'ResponseMetadata':{
'HTTPStatusCode':200,
'RequestId':'12345678-1234-1234-1234-123456789012',
'RetryAttempts':0,
'HTTPHeaders':{
'content-length':'665',
'content-type':'text/xml',
'date':'Sat, 01 Oct 2016 11:04:56 GMT',
'x-amzn-requestid':'12345678-1234-1234-1234-123456789012'
}
}
}
</code></pre>
<p>Thanks so much!</p>
| 2 | 2016-10-01T15:52:03Z | 39,808,919 | <p>As per the boto3 docs [<a href="http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html?highlight=describe_instances_health#ElasticBeanstalk.Client.describe_instances_health]" rel="nofollow">http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html?highlight=describe_instances_health#ElasticBeanstalk.Client.describe_instances_health]</a>, the describe_instances_health method returns dict and not json. Hence, there is no need for you to do the conversion.
To get VersionLabel from data, use - </p>
<pre><code>data ['InstanceHealthList'][0]['Deployment']['VersionLabel']
</code></pre>
<p>Edit : Note that the above fetches the VersionLabel for the first instance, out of possible multiple instances. In case you have multiple instances and they happen to have different values of VersionLabel, then you would require additional logic to get the one you need.</p>
| 3 | 2016-10-01T16:26:49Z | [
"python",
"json",
"amazon-web-services",
"boto"
]
|
How to save a scraped list in a CSV file? | 39,808,841 | <p>I wrote this code below, which scrapes from the OED.com website words by subject and date and prints them out in a list.</p>
<pre><code>import requests
import re
import urllib2
import os
import csv
year_search = 1550
subject_search = ['Law']
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
request = urllib2.Request('http://www.oed.com/', None, header)
f = opener.open(request)
data = f.read()
f.close()
print 'database first access was successful'
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
outputw = open(resultPath, 'w')
outputh = open(htmlPath, 'w')
request = urllib2.Request(
'http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true'
'&dateFilter='+str(year_search)+'&nearDistance=1&ordered=false&page=1'
'&pageSize=100&scope=ENTRY&sort=entry&subjectClass='
+ str(subject_search) + '&type=dictionarysearch', None, header)
page = opener.open(request)
urlpage = page.read()
outputh.write(urlpage)
new_word = re.findall(
r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print str(new_word)
outputw.write(str(new_word))
page.close()
outputw.close()
</code></pre>
<p>Now I want to print them to a CSV file but in such a way that every year I input will be placed as a row, and the words will all fall in the line of the row.</p>
<p>Sort of like:</p>
<pre><code>1550| word1| word2| etc.|
1551| word1| word2| etc.|
</code></pre>
<p>Does anyone have any ideas?</p>
| 0 | 2016-10-01T16:18:36Z | 39,809,237 | <p>I suggest using the csv.writer method. Here's the sample code:</p>
<p>`</p>
<pre><code>with open('/Applications/Python 3.5/Economic/OED_table.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file)
year = ["1550"]
new_word = ["apple", "banana"]
complete_row = year + new_word
csv_writer.writerow(complete_row)
# writes 1550, apple, banana to OED_table.csv
</code></pre>
<p>`</p>
<p>You can modify it with a for loop to insert multiple rows.</p>
| 1 | 2016-10-01T16:57:54Z | [
"python",
"csv",
"web-scraping"
]
|
How to save a scraped list in a CSV file? | 39,808,841 | <p>I wrote this code below, which scrapes from the OED.com website words by subject and date and prints them out in a list.</p>
<pre><code>import requests
import re
import urllib2
import os
import csv
year_search = 1550
subject_search = ['Law']
path = '/Applications/Python 3.5/Economic'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
header = {'User-Agent':user_agent}
request = urllib2.Request('http://www.oed.com/', None, header)
f = opener.open(request)
data = f.read()
f.close()
print 'database first access was successful'
resultPath = os.path.join(path, 'OED_table.csv')
htmlPath = os.path.join(path, 'OED.html')
outputw = open(resultPath, 'w')
outputh = open(htmlPath, 'w')
request = urllib2.Request(
'http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true'
'&dateFilter='+str(year_search)+'&nearDistance=1&ordered=false&page=1'
'&pageSize=100&scope=ENTRY&sort=entry&subjectClass='
+ str(subject_search) + '&type=dictionarysearch', None, header)
page = opener.open(request)
urlpage = page.read()
outputh.write(urlpage)
new_word = re.findall(
r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage)
print str(new_word)
outputw.write(str(new_word))
page.close()
outputw.close()
</code></pre>
<p>Now I want to print them to a CSV file but in such a way that every year I input will be placed as a row, and the words will all fall in the line of the row.</p>
<p>Sort of like:</p>
<pre><code>1550| word1| word2| etc.|
1551| word1| word2| etc.|
</code></pre>
<p>Does anyone have any ideas?</p>
| 0 | 2016-10-01T16:18:36Z | 39,809,264 | <p>After the line where you define <code>new_word</code> you can do the following:</p>
<pre><code>year_info = [str(year_search)] + new_word
print '|'.join(year_info)
</code></pre>
<p>This will output exactly</p>
<p>1550|word1|word2|etc.|</p>
| 0 | 2016-10-01T17:00:32Z | [
"python",
"csv",
"web-scraping"
]
|
My knapsack code is giving wrong output? | 39,808,872 | <p>I was trying to write a simple 0-1 knapsack problem but am encountering some error. Help would be appreciated.</p>
<pre><code>T = int(input().strip())
def knapsack(n,k,ar):
if n==0 or k==0:
return 0
elif ar[n-1]>k:
return knapsack(n-1,k,ar)
else:
return max(knapsack(n-1,k,ar),ar[n-1] + knapsack(n-1,k-ar[n-1],ar))
for t in range(T):
a = input().strip()
n,k = int(a[0]),int(a[2])
ar = [int(i) for i in input().strip().split(' ')]
print(knapsack(n,k,ar))
</code></pre>
<p>I ran this again an input of </p>
<pre><code>2
3 12
1 6 9
5 9
3 4 4 4 8
</code></pre>
<p>and I am receiving wrong output? I cannot find any error. Thanks in advance</p>
<p>Output</p>
<pre><code>1
8
</code></pre>
| 1 | 2016-10-01T16:21:38Z | 39,809,381 | <p>Your algorithm is fine but your input to the function is wrong. </p>
<p>In the first input, the line <code>n,k = int(a[0]),int(a[2])</code> is taking <code>3</code> and <code>1</code> as an input instead of <code>3</code> and <code>12</code>.<br>
I guess you should use <code>list(map(int, input().split()))</code> instead, and get <code>a[0]</code> and <code>a[1]</code>.</p>
| 2 | 2016-10-01T17:12:13Z | [
"python",
"algorithm",
"python-3.x",
"knapsack-problem"
]
|
Detect If Item is the Last in a List | 39,808,908 | <p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if item != a[-1]:
print(', ')
</code></pre>
<p>And I would like this output:</p>
<pre><code>hello,
9,
3.14,
9
</code></pre>
<p>But I get this output:</p>
<pre><code>hello,
93.14,
9
</code></pre>
<p>I understand why I am getting the output I do not want.
I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)</p>
| 0 | 2016-10-01T16:25:36Z | 39,808,935 | <p>Rather than try and detect if you are at the last item, print the comma and newline <em>when printing the next</em> (which only requires detecting if you are at the first):</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for i, item in enumerate(a):
if i: # print a separator if this isn't the first element
print(',')
print(item, end='')
print() # last newline
</code></pre>
<p>The <code>enumerate()</code> function adds a counter to each element (see <a href="https://stackoverflow.com/questions/22171558/what-does-enumerate-mean">What does enumerate mean?</a>), and <code>if i:</code> is true for all values of the counter except <code>0</code> (the first element).</p>
<p>Or use <code>print()</code> to insert separators:</p>
<pre><code>print(*a, sep=',\n')
</code></pre>
<p>The <code>sep</code> value is inserted between each argument (<code>*a</code> applies all values in <code>a</code> as separate arguments, see <a href="http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters">What does ** (double star) and * (star) do for Python parameters?</a>). This is more efficient than using <code>print(',n'.join(map(str, a)))</code> as this doesn't need to build a whole new string object first.</p>
| 7 | 2016-10-01T16:29:04Z | [
"python",
"list",
"python-3.x"
]
|
Detect If Item is the Last in a List | 39,808,908 | <p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if item != a[-1]:
print(', ')
</code></pre>
<p>And I would like this output:</p>
<pre><code>hello,
9,
3.14,
9
</code></pre>
<p>But I get this output:</p>
<pre><code>hello,
93.14,
9
</code></pre>
<p>I understand why I am getting the output I do not want.
I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)</p>
| 0 | 2016-10-01T16:25:36Z | 39,808,992 | <p>If you really just want to join your elements into a comma+newline-separated string then it's easier to use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join</code></a> method:</p>
<pre><code>elements = ['hello', 9, 3.14, 9]
s = ',\n'.join(str(el) for el in elements)
# And you can do whatever you want with `s` string:
print(s)
</code></pre>
| 3 | 2016-10-01T16:34:20Z | [
"python",
"list",
"python-3.x"
]
|
Detect If Item is the Last in a List | 39,808,908 | <p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if item != a[-1]:
print(', ')
</code></pre>
<p>And I would like this output:</p>
<pre><code>hello,
9,
3.14,
9
</code></pre>
<p>But I get this output:</p>
<pre><code>hello,
93.14,
9
</code></pre>
<p>I understand why I am getting the output I do not want.
I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)</p>
| 0 | 2016-10-01T16:25:36Z | 39,809,104 | <p>If you are just looking to see if the item is last in the (or any item in any list) you could try using a function to check if an item is last in a list.</p>
<pre><code>a = ['hello', 9, 3.14, 9]
def is_last(alist,choice):
if choice == alist[-1]:
print("Item is last in list!")
return True
else:
print("Item is not last")
return False
if is_last(a,9) == True:
<do things>
else:
<do other things>
</code></pre>
| 0 | 2016-10-01T16:44:56Z | [
"python",
"list",
"python-3.x"
]
|
Detect If Item is the Last in a List | 39,808,908 | <p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if item != a[-1]:
print(', ')
</code></pre>
<p>And I would like this output:</p>
<pre><code>hello,
9,
3.14,
9
</code></pre>
<p>But I get this output:</p>
<pre><code>hello,
93.14,
9
</code></pre>
<p>I understand why I am getting the output I do not want.
I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)</p>
| 0 | 2016-10-01T16:25:36Z | 39,809,115 | <p>You are not getting the expected output because in your code you say, "Hey python, print a comma if current element is not equal to last element."</p>
<p>Second element 9 is equal to last element, hence the comma is not printed.</p>
<p>The right way to check for the last element is to check the index of element :</p>
<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if a.index(item) != len(a)-1: #<--------- Checking for last element here
print(', ')
</code></pre>
<p>(Also, this might throw a value error. You should check for that too.)</p>
| 1 | 2016-10-01T16:45:38Z | [
"python",
"list",
"python-3.x"
]
|
Using webbrowser module to use Google Maps | 39,808,974 | <p>i'm just new to python and i want to ask a simple question.<br>
what's the difference between using this code:</p>
<pre><code> import webbrowser, pyperclip, sys
chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe %s"
def location_finder():
output = input('Type the place you want to find!\n')
webbrowser.get(chrome).open('https://www.google.com/maps/place/' + output)
location_finder()
</code></pre>
<p>and this code: </p>
<pre><code> import webbrowser, pyperclip, sys
if len(sys.argv) > 1:
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)
</code></pre>
| -1 | 2016-10-01T16:33:00Z | 39,809,131 | <p>The diffrent is:</p>
<ol>
<li>With the first one, using target browser is <code>chrome.exe</code> and the second is using the default browser.</li>
<li>The first code using import from built in function <code>input</code> and the second code <code>sys.argv</code>is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The <code>sys.argv[1:]</code> get everything after the script name.</li>
</ol>
| 0 | 2016-10-01T16:46:28Z | [
"python",
"module",
"sys",
"pyperclip"
]
|
Python multithreading freeze(?) randomly | 39,809,155 | <p>I'm writing a script that's supposed to get some pictures from a very large amount or websites. First time using multithreading, think it is required here so get an okay runtime. So the Problem: The script runs, but after a seemingly random amount of passed websites it just doesn't continue any more. It doesn't totally freeze tho, the time just goes up from what feels like 1/100 of a sec. to several minutes or so, sometimes so long id just close it instead. Also it doesn't seem like some of the websites are responsible in particular, sometimes it get 970, the only 200 entries. Here the relevant parts of the code:</p>
<pre><code>concurrent = 200
q = Queue(concurrent * 2)
def main(listPath, usagePath, idListPath):
[...]
for i in range(concurrent):
t = Thread(target=work)
t.daemon = True
t.start()
try:
for code in usedIDs:
q.put(code)
q.join()
except KeyboardInterrupt:
sys.exit(1)
def work():
while True:
code = q.get()
picture = getPicture(code)
if picture is None:
pass # todo: find other source or default
if not code in usage.keys():
usage[code] = list()
usage[code].append(picture)
q.task_done()
</code></pre>
<p>Hope i got all the important code there. Thanks in advance! </p>
| 1 | 2016-10-01T16:48:57Z | 39,925,073 | <p>My bad guys, the problem was actually in the getPicture function. Thanks for the answers anyways!</p>
| 0 | 2016-10-07T20:11:42Z | [
"python",
"multithreading",
"freeze"
]
|
Set background and separate foreground color for cell in openpyxl | 39,809,156 | <p>I am using <strong>openpyxl 2.3.5</strong>.</p>
<p>I am writing an Excel sheet from Python and need to set a cell's background color to black and its foreground color (font color?) to white.</p>
<p>I know how to set the background color to white (leaving the foreground/font color):</p>
<pre><code>from openpyxl import Workbook
from openpyxl.styles import PatternFill
wb = Workbook()
ws = wb.create_sheet(title='test')
ws['A1'] = 'hello world'
#define the color:
whiteFill = PatternFill(fgColor='FFFFFF', bgColor='FFFFFF', fill_type='solid')
ws['A1'].fill = whiteFill
</code></pre>
<p>This method "PatternFill" is probably for setting gradients in general. I tried changing fgColor and bgColor to white and black, respectively, but no luck.</p>
<p>I have been looking around for help, but most answers are for earlier versions of openpyxl and apparently a lot has changed in the api.</p>
| 0 | 2016-10-01T16:49:02Z | 39,815,571 | <p>While styles have changed a lot since version 1.x, fills haven't changed that much.</p>
<p>In this case you need to set the foreground to black (<code>000000</code>) and the background doesn't matter because the "pattern" is solid.</p>
| 2 | 2016-10-02T09:21:08Z | [
"python",
"openpyxl"
]
|
kivy python passing parameters to fuction with button click | 39,809,206 | <p>I am having trouble passing parameters to function when calling it with button press. One could do it like this in kivy language:</p>
<pre><code>Button:
on_press: root.my_function('btn1')
</code></pre>
<p>but I would like to do it in python, as I would like to create a larger number of buttons with a loop. Currently I call my function in python like this:</p>
<pre><code>Button(on_press=self.my_function)
</code></pre>
<p>but as I said, if I try to pass a parameter to the function like this, I get an 'AssertionError: None is not callable', like this:</p>
<pre><code>Button(on_press=self.my_function('btn1'))
</code></pre>
| 0 | 2016-10-01T16:53:59Z | 39,809,268 | <pre><code>Button(on_press=self.my_function)
</code></pre>
<p>This is <em>passing</em> the function as an argument.</p>
<pre><code>Button(on_press=self.my_function('btn1'))
</code></pre>
<p>This is <em>calling</em> the function and passing the <em>returned value</em> as the argument to <code>on_press</code>. Since the returned value is None, you get your error.</p>
<p>You instead need to pass a new function that calls your normal function and automatically passes the argument. In general, it's convenient to use <code>functools.partial</code>:</p>
<pre><code>from functools import partial
Button(on_press=partial(self.my_function, 'btn1'))
</code></pre>
<p>You can also use a lambda function:</p>
<pre><code>Button(on_press=lambda *args: self.my_function('btn1', *args))
</code></pre>
| 0 | 2016-10-01T17:01:25Z | [
"python",
"function",
"button",
"kivy"
]
|
Basic Python: Passing a string as an input to a function | 39,809,255 | <p>I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.</p>
<pre><code>f_1 = thresh1[1:mr, 1:mc]
f_2 = thresh1[1:mr, (mc+1):width]
f_3 = thresh1[(mr+1):height, 1:mc]
f_4 = thresh1[(mr+1):height, (mc+1):width]
b_1 = thresh2[1:mr, 1:mc]
b_2 = thresh2[1:mr, (mc+1):width]
b_3 = thresh2[(mr+1):height, 1:mc]
b_4 = thresh2[(mr+1):height, (mc+1):width]
for i in range(1, 5):
n1 = "f_"
n2 = "b_"
num = str(i)
n1 += num
n2 += num
r = cv2.countNonZero((n1)/cv2.countNonZero(n2))
print r
</code></pre>
<p>I want to pass the concatenated strings <code>n1</code> and <code>n2</code> as inputs to the equation <code>cv2.countNonZero((n1)/cv2.countNonZero(n2))</code>.</p>
<p>Here F1 is a binary image (F as in foreground) and B1 is also binary image (B as in Background). I am trying to compute the ratio of non zero pixels in foreground vs background. </p>
<p>r should be calculated for F1/B1 and in the next iteration F2/B2 ... so on</p>
| -1 | 2016-10-01T16:59:56Z | 39,809,501 | <p>You have a problem in that you're trying to use strings to reference variable names. This is considerably difficult to do; you're better off using lists to contain your images. That is, instead of trying to reference <code>f_1</code>, <code>f_2</code>, etc, create a single list called <code>f</code> that contains each of the images.</p>
<p>For instance, instead of the code you have at the top, use:</p>
<pre><code>f = [
thresh1[1:mr, 1:mc],
thresh1[1:mr, (mc+1):width],
thresh1[(mr+1):height, 1:mc],
thresh1[(mr+1):height, (mc+1):width]
]
b = [
thresh2[1:mr, 1:mc],
thresh2[1:mr, (mc+1):width],
thresh2[(mr+1):height, 1:mc],
thresh2[(mr+1):height, (mc+1):width]
]
</code></pre>
<p>Now you can reference what you were calling <code>f_1</code> before with the code <code>f[1]</code>.</p>
<p>Now, inside your loop, you can use:</p>
<pre><code>for i in range(1, 5):
r = cv2.countNonZero(f[i])/cv2.countNonZero(b[i])
print r
</code></pre>
<p>I recommend you look into how to use lists in Python, as this is a fundamental datastructure. Also, there is a difference between <code>"f_1"</code> (which is a string) and <code>f_1</code> (which is a variable named <code>f_1</code>). You can't (easily) go between the two.</p>
| 1 | 2016-10-01T17:24:14Z | [
"python",
"string",
"for-loop"
]
|
Basic Python: Passing a string as an input to a function | 39,809,255 | <p>I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.</p>
<pre><code>f_1 = thresh1[1:mr, 1:mc]
f_2 = thresh1[1:mr, (mc+1):width]
f_3 = thresh1[(mr+1):height, 1:mc]
f_4 = thresh1[(mr+1):height, (mc+1):width]
b_1 = thresh2[1:mr, 1:mc]
b_2 = thresh2[1:mr, (mc+1):width]
b_3 = thresh2[(mr+1):height, 1:mc]
b_4 = thresh2[(mr+1):height, (mc+1):width]
for i in range(1, 5):
n1 = "f_"
n2 = "b_"
num = str(i)
n1 += num
n2 += num
r = cv2.countNonZero((n1)/cv2.countNonZero(n2))
print r
</code></pre>
<p>I want to pass the concatenated strings <code>n1</code> and <code>n2</code> as inputs to the equation <code>cv2.countNonZero((n1)/cv2.countNonZero(n2))</code>.</p>
<p>Here F1 is a binary image (F as in foreground) and B1 is also binary image (B as in Background). I am trying to compute the ratio of non zero pixels in foreground vs background. </p>
<p>r should be calculated for F1/B1 and in the next iteration F2/B2 ... so on</p>
| -1 | 2016-10-01T16:59:56Z | 39,811,400 | <pre><code>f_1_nz = f_1[f_1 != 0].size
# etc.
r_1 = f_1_nz / b_1_nz
# etc.
</code></pre>
<p>Ideally you'd put f_1 etc. into a list and iterate over it, instead of defining new names for each, see the answer by @apnorton.</p>
<p>So, in the end:</p>
<pre><code>for ff, bb in zip(f,b):
f_nz = ff[ff != 0].size
b_nz = bb[bb != 0].size
print f_nz/b_nz
</code></pre>
| 1 | 2016-10-01T20:57:29Z | [
"python",
"string",
"for-loop"
]
|
make a button for animation in matplotlib | 39,809,329 | <p>I just made a simple gui using Qt Designer, the gui has 4 buttons and a widget. The widget will show the animation and the buttons are for pause animation,resume, clean the canvas and start animation. I made this code:</p>
<pre><code>import sys
from PyQt4 import QtGui, uic
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
def start():
def datos(t=0):
while True:
t += 0.1
yield t, np.cos(t)
def init():
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
def run(data):
t,y = data
xdata.append(t)
ydata.append(y)
line.set_data(xdata, ydata)
xmin,xmax =ax.get_xlim()
if t > xmax:
ax.set_xlim(xmin, 1.5*xmax)
ax.figure.canvas.draw()
ani = animation.FuncAnimation(fig, run, datos, blit=False, interval=50,
repeat=False, init_func=init)
def stop():
ani.event_source.stop()
def borr():
plt.clf()
canvas.draw()
def anim():
ani.event_source.start()
window.resume.clicked.connect(anim)
window.pause.clicked.connect(stop)
window.clean.clicked.connect(borr)
return ani
layout=QtGui.QVBoxLayout()
fig=plt.figure()
canvas=FigureCanvas(fig)
layout.addWidget(canvas)
ax = fig.add_subplot(111)
line,=ax.plot([],[],lw=2)
ax.grid()
xdata, ydata = [], []
app = QtGui.QApplication(sys.argv)
window = uic.loadUi("animacion.ui")
window.start.clicked.connect(start)
window.widget.setLayout(layout)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>this shows the grid, but when I press the start button it doesnt show the animation</p>
<p>I also made this code:</p>
<pre><code>import sys
from PyQt4 import QtCore, QtGui, uic
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
def datos(t=0):
while True:
t += 0.1
yield t, np.cos(t)
def init():
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
def run(data):
t,y = data
xdata.append(t)
ydata.append(y)
line.set_data(xdata, ydata)
xmin,xmax =ax.get_xlim()
if t > xmax:
ax.set_xlim(xmin, 1.5*xmax)
ax.figure.canvas.draw()
def start():
window.widget.setLayout(layout)
def stop():
ani.event_source.stop()
def borr():
plt.clf()
canvas.draw()
def anim():
ani.event_source.start()
layout=QtGui.QVBoxLayout()
fig=plt.figure('test')
canvas=FigureCanvas(fig)
layout.addWidget(canvas)
ax = fig.add_subplot(111)
line,=ax.plot([],[],lw=2)
ax.grid()
xdata, ydata = [], []
app = QtGui.QApplication(sys.argv)
window = uic.loadUi("animacion.ui")
window.resume.clicked.connect(anim)
window.pause.clicked.connect(stop)
window.clean.clicked.connect(borr)
window.start.clicked.connect(start)
ani = animation.FuncAnimation(fig, run, datos, blit=False, interval=50,
repeat=False, init_func=init)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>In this case, when I press start the animation begins, I can pause and resume. But when a clean the canvas an press start again it doesnt show the function.</p>
<p>How can I make it works?
thanks!</p>
| 0 | 2016-10-01T17:07:02Z | 39,812,186 | <p>Try to provide minimal <em>working</em> examples. Without animacion.ui we cannot run you code.</p>
<p>Refering to the second code: The problem here seems to be that inside <code>borr()</code> you clear the figure (<code>plt.clf()</code>). If the figure is cleared, where should the animation be drawn to? </p>
| 0 | 2016-10-01T22:50:41Z | [
"python",
"qt",
"animation",
"button",
"matplotlib"
]
|
make a button for animation in matplotlib | 39,809,329 | <p>I just made a simple gui using Qt Designer, the gui has 4 buttons and a widget. The widget will show the animation and the buttons are for pause animation,resume, clean the canvas and start animation. I made this code:</p>
<pre><code>import sys
from PyQt4 import QtGui, uic
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
def start():
def datos(t=0):
while True:
t += 0.1
yield t, np.cos(t)
def init():
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
def run(data):
t,y = data
xdata.append(t)
ydata.append(y)
line.set_data(xdata, ydata)
xmin,xmax =ax.get_xlim()
if t > xmax:
ax.set_xlim(xmin, 1.5*xmax)
ax.figure.canvas.draw()
ani = animation.FuncAnimation(fig, run, datos, blit=False, interval=50,
repeat=False, init_func=init)
def stop():
ani.event_source.stop()
def borr():
plt.clf()
canvas.draw()
def anim():
ani.event_source.start()
window.resume.clicked.connect(anim)
window.pause.clicked.connect(stop)
window.clean.clicked.connect(borr)
return ani
layout=QtGui.QVBoxLayout()
fig=plt.figure()
canvas=FigureCanvas(fig)
layout.addWidget(canvas)
ax = fig.add_subplot(111)
line,=ax.plot([],[],lw=2)
ax.grid()
xdata, ydata = [], []
app = QtGui.QApplication(sys.argv)
window = uic.loadUi("animacion.ui")
window.start.clicked.connect(start)
window.widget.setLayout(layout)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>this shows the grid, but when I press the start button it doesnt show the animation</p>
<p>I also made this code:</p>
<pre><code>import sys
from PyQt4 import QtCore, QtGui, uic
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
def datos(t=0):
while True:
t += 0.1
yield t, np.cos(t)
def init():
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
def run(data):
t,y = data
xdata.append(t)
ydata.append(y)
line.set_data(xdata, ydata)
xmin,xmax =ax.get_xlim()
if t > xmax:
ax.set_xlim(xmin, 1.5*xmax)
ax.figure.canvas.draw()
def start():
window.widget.setLayout(layout)
def stop():
ani.event_source.stop()
def borr():
plt.clf()
canvas.draw()
def anim():
ani.event_source.start()
layout=QtGui.QVBoxLayout()
fig=plt.figure('test')
canvas=FigureCanvas(fig)
layout.addWidget(canvas)
ax = fig.add_subplot(111)
line,=ax.plot([],[],lw=2)
ax.grid()
xdata, ydata = [], []
app = QtGui.QApplication(sys.argv)
window = uic.loadUi("animacion.ui")
window.resume.clicked.connect(anim)
window.pause.clicked.connect(stop)
window.clean.clicked.connect(borr)
window.start.clicked.connect(start)
ani = animation.FuncAnimation(fig, run, datos, blit=False, interval=50,
repeat=False, init_func=init)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>In this case, when I press start the animation begins, I can pause and resume. But when a clean the canvas an press start again it doesnt show the function.</p>
<p>How can I make it works?
thanks!</p>
| 0 | 2016-10-01T17:07:02Z | 39,812,475 | <p>I solved the problem making a function with the animation </p>
<pre><code>import sys
from PyQt4 import QtGui, uic
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
def start():
def datos(t=0):
while True:
t += 0.1
yield t, np.cos(t)
def init():
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
def run(data):
t,y = data
xdata.append(t)
ydata.append(y)
line.set_data(xdata, ydata)
xmin,xmax =ax.get_xlim()
if t > xmax:
ax.set_xlim(xmin, 1.5*xmax)
ax.figure.canvas.draw()
def stop():
ani.event_source.stop()
def borr():
plt.clf()
canvas.draw()
def anim():
ani.event_source.start()
window.resume.clicked.connect(anim)
window.pause.clicked.connect(stop)
window.clean.clicked.connect(borr)
ax = fig.add_subplot(111)
line,=ax.plot([],[],lw=2)
ax.grid()
xdata, ydata = [], []
ani = animation.FuncAnimation(fig, run, datos, blit=False, interval=50,
repeat=False, init_func=init)
canvas.draw()
layout=QtGui.QVBoxLayout()
fig=plt.figure()
canvas=FigureCanvas(fig)
layout.addWidget(canvas)
app = QtGui.QApplication(sys.argv)
window = uic.loadUi("animacion.ui")
window.start.clicked.connect(start)
window.widget.setLayout(layout)
window.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-10-01T23:34:38Z | [
"python",
"qt",
"animation",
"button",
"matplotlib"
]
|
Merge elements in tuples? | 39,809,452 | <p>Here I have a dataset:</p>
<pre><code>rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
</code></pre>
<p>Desired result:</p>
<pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]
</code></pre>
<p>My code:</p>
<pre><code>def rd_edges(f):
allEdges =[]
for line in f.split():
edges =line.split(":")[1].split(';')
for edge in edges:
i =0
j =1
for i in len(edge):
for j in len(edge):
i <j
j +=1
if j >len(edge):
end
i +=1
if i >len(edge)-1:
end
allEdges.append(edge(i),edge(j))
return allEdges
</code></pre>
<p>I know the <code>itertools</code> module can solve this problem, but want to write a function to transfer the data into a tuple without importing any modules. I reviewed some past questions posted on the forum, but am still confused about doing this.</p>
| 2 | 2016-10-01T17:19:17Z | 39,809,593 | <p>The "Roughly equivalent to" code from the docs of the itertools function you have been wisely advised to use shows a correct version that is actually written in Python:</p>
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">https://docs.python.org/3/library/itertools.html#itertools.combinations</a></p>
| 0 | 2016-10-01T17:35:52Z | [
"python",
"tuples"
]
|
Merge elements in tuples? | 39,809,452 | <p>Here I have a dataset:</p>
<pre><code>rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
</code></pre>
<p>Desired result:</p>
<pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]
</code></pre>
<p>My code:</p>
<pre><code>def rd_edges(f):
allEdges =[]
for line in f.split():
edges =line.split(":")[1].split(';')
for edge in edges:
i =0
j =1
for i in len(edge):
for j in len(edge):
i <j
j +=1
if j >len(edge):
end
i +=1
if i >len(edge)-1:
end
allEdges.append(edge(i),edge(j))
return allEdges
</code></pre>
<p>I know the <code>itertools</code> module can solve this problem, but want to write a function to transfer the data into a tuple without importing any modules. I reviewed some past questions posted on the forum, but am still confused about doing this.</p>
| 2 | 2016-10-01T17:19:17Z | 39,809,669 | <pre><code>def find_edges(f):
out = []
for line in f.split():
line = line.split(':')[1]
disjoint = line.split(';')
for d in disjoint:
s = d.split(',')
for i, node in enumerate(s)):
for downnode in s[i+1:]:
out.append((node, downnode))
return out
</code></pre>
<p>This works, but gives out put in a different order. If you care about that, you have to start at the end of the list of nodes and build towards it.</p>
| 0 | 2016-10-01T17:44:10Z | [
"python",
"tuples"
]
|
Merge elements in tuples? | 39,809,452 | <p>Here I have a dataset:</p>
<pre><code>rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
</code></pre>
<p>Desired result:</p>
<pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]
</code></pre>
<p>My code:</p>
<pre><code>def rd_edges(f):
allEdges =[]
for line in f.split():
edges =line.split(":")[1].split(';')
for edge in edges:
i =0
j =1
for i in len(edge):
for j in len(edge):
i <j
j +=1
if j >len(edge):
end
i +=1
if i >len(edge)-1:
end
allEdges.append(edge(i),edge(j))
return allEdges
</code></pre>
<p>I know the <code>itertools</code> module can solve this problem, but want to write a function to transfer the data into a tuple without importing any modules. I reviewed some past questions posted on the forum, but am still confused about doing this.</p>
| 2 | 2016-10-01T17:19:17Z | 39,809,674 | <p>Here is how you could do it without import of itertools:</p>
<pre><code>def rd_edges(f):
allEdges =[]
for line in f.split():
edges = line.split(":")[1].split(';')
for edge in edges:
nodes = edge.split(',')
for i, a in enumerate(nodes):
for b in nodes[i+1:]:
allEdges.append((a,b))
return allEdges
rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
print (rd_edges(rd))
</code></pre>
| 2 | 2016-10-01T17:44:21Z | [
"python",
"tuples"
]
|
Merge elements in tuples? | 39,809,452 | <p>Here I have a dataset:</p>
<pre><code>rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
</code></pre>
<p>Desired result:</p>
<pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]
</code></pre>
<p>My code:</p>
<pre><code>def rd_edges(f):
allEdges =[]
for line in f.split():
edges =line.split(":")[1].split(';')
for edge in edges:
i =0
j =1
for i in len(edge):
for j in len(edge):
i <j
j +=1
if j >len(edge):
end
i +=1
if i >len(edge)-1:
end
allEdges.append(edge(i),edge(j))
return allEdges
</code></pre>
<p>I know the <code>itertools</code> module can solve this problem, but want to write a function to transfer the data into a tuple without importing any modules. I reviewed some past questions posted on the forum, but am still confused about doing this.</p>
| 2 | 2016-10-01T17:19:17Z | 39,809,695 | <p>Below is the simplified solution to achieve it using <a href="https://docs.python.org/2/library/re.html#re.compile" rel="nofollow"><code>re.compile()</code></a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> functions. In order to flatten the list, I am using <a href="https://docs.python.org/2/library/operator.html#operator.add" rel="nofollow"><code>operator.add()</code></a> with <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce()</code></a> function:</p>
<pre><code>import re
from itertools import combinations
from operator import add
rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
my_aplhalist = (re.compile('(\n\d:)').split(rd.rstrip()))[2::2]
my_combinations = [list(combinations(item.split(','), 2)) for item_str in my_aplhalist for item in item_str.split(';')]
my_solution = reduce(add, my_combinations)
# Value of 'my_solution': [('A', 'B'), ('A', 'C'), ('B', 'C'), ('D', 'E'), ('F', 'G'), ('H', 'J'), ('H', 'K'), ('J', 'K')]
</code></pre>
| 1 | 2016-10-01T17:47:14Z | [
"python",
"tuples"
]
|
python webscraping and write data into csv | 39,809,465 | <p>I'm trying to save all the data(i.e all pages) in single csv file but this code only save the final page data.Eg Here url[] contains 2 urls. the final csv only contains the 2nd url data.
I'm clearly doing something wrong in the loop.but i dont know what.
And also this page contains 100 data points. But this code only write first 44 rows.
please help this issue.............</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import csv
url = ["http://sfbay.craigslist.org/search/sfc/npo","http://sfbay.craigslist.org/search/sfc/npo?s=100"]
for ur in url:
r = requests.get(ur)
soup = BeautifulSoup(r.content)
g_data = soup.find_all("a", {"class": "hdrlnk"})
gen_list=[]
for row in g_data:
try:
name = row.text
except:
name=''
try:
link = "http://sfbay.craigslist.org"+row.get("href")
except:
link=''
gen=[name,link]
gen_list.append(gen)
with open ('filename2.csv','wb') as file:
writer=csv.writer(file)
for row in gen_list:
writer.writerow(row)
</code></pre>
| 2 | 2016-10-01T17:20:59Z | 39,809,569 | <p>the gen_list is being initialized again inside your loop that runs over the urls.</p>
<pre><code>gen_list=[]
</code></pre>
<p>Move this line outside the for loop.</p>
<pre><code>...
url = ["http://sfbay.craigslist.org/search/sfc/npo","http://sfbay.craigslist.org/search/sfc/npo?s=100"]
gen_list=[]
for ur in url:
...
</code></pre>
| 3 | 2016-10-01T17:33:31Z | [
"python",
"python-2.7",
"csv",
"web-scraping",
"beautifulsoup"
]
|
Running a command on a remote server to find the uptime in seconds | 39,809,487 | <p>Here's what I have so far:</p>
<pre><code>#!/usr/bin/python
import sys
import os
import subprocess
from subprocess import check_output
import time
import sh
from sh import sshpass
import re
import time, datetime
check_time = 0
with open("log.txt", "a") as f:
while 1:
#out = check_output(["sshpass", "-p", "pass", "ssh",
# "theo@localhost", "\"/usr/bin/cat",
# "/proc/uptime\""])
#print (out)
#out = str(out)
uptime = sh.Command("/usr/bin/sshpass")
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat",
"/proc/uptime\"")
result = str(result)
print (result)
result = result.split(' ', 1)[0]
print (result)
f.write(result)
result_int = int(result)
if result_int > check_time:
print("it rebooted", result_int, "minutes ago")
time.sleep(5)
</code></pre>
<p>Results:</p>
<pre class="lang-none prettyprint-override"><code>checking uptime
Traceback (most recent call last):
File "./uptime.py", line 23, in <module>
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat", "/proc/uptime\"")
File "/usr/lib/python3.5/site-packages/sh.py", line 1021, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/usr/lib/python3.5/site-packages/sh.py", line 486, in __init__
self.wait()
File "/usr/lib/python3.5/site-packages/sh.py", line 500, in wait
self.handle_command_exit_code(exit_code)
File "/usr/lib/python3.5/site-packages/sh.py", line 516, in handle_command_exit_code
raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_127:
RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
STDOUT:
STDERR:
zsh:1: no such file or directory: cat /proc/uptime
</code></pre>
<p>You can see I have two attempts, one using the <code>sh</code> library and one with check_output, both result in the same error about not being able to run <code>/usr/bin/cat /proc/uptime</code>.</p>
<p>However as you can see at the end of the traceback:</p>
<pre><code>RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
</code></pre>
<p>That appears to be a perfectly valid line, and if I copy paste it into a terminal it works.</p>
<p>Any ideas? The command does actually work if I just put in "uptime", but rather than editing the output of that to get the time in seconds, I though it would be easier to do it this way (at least I <em>thought</em> it would be) :)</p>
<p>I'm using python 3.5.2</p>
| 2 | 2016-10-01T17:23:19Z | 39,810,037 | <p>Someone on IRC suggested I use <code>command_string = "cat /proc/cpu/"</code> and</p>
<pre><code>result = uptime("-p", "pass", "ssh", "theo@localhost", command_string)
</code></pre>
<p>Which works!</p>
| 1 | 2016-10-01T18:21:26Z | [
"python",
"linux",
"python-3.x"
]
|
Running a command on a remote server to find the uptime in seconds | 39,809,487 | <p>Here's what I have so far:</p>
<pre><code>#!/usr/bin/python
import sys
import os
import subprocess
from subprocess import check_output
import time
import sh
from sh import sshpass
import re
import time, datetime
check_time = 0
with open("log.txt", "a") as f:
while 1:
#out = check_output(["sshpass", "-p", "pass", "ssh",
# "theo@localhost", "\"/usr/bin/cat",
# "/proc/uptime\""])
#print (out)
#out = str(out)
uptime = sh.Command("/usr/bin/sshpass")
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat",
"/proc/uptime\"")
result = str(result)
print (result)
result = result.split(' ', 1)[0]
print (result)
f.write(result)
result_int = int(result)
if result_int > check_time:
print("it rebooted", result_int, "minutes ago")
time.sleep(5)
</code></pre>
<p>Results:</p>
<pre class="lang-none prettyprint-override"><code>checking uptime
Traceback (most recent call last):
File "./uptime.py", line 23, in <module>
result = uptime("-p", "pass", "ssh", "theo@localhost", "\"cat", "/proc/uptime\"")
File "/usr/lib/python3.5/site-packages/sh.py", line 1021, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/usr/lib/python3.5/site-packages/sh.py", line 486, in __init__
self.wait()
File "/usr/lib/python3.5/site-packages/sh.py", line 500, in wait
self.handle_command_exit_code(exit_code)
File "/usr/lib/python3.5/site-packages/sh.py", line 516, in handle_command_exit_code
raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_127:
RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
STDOUT:
STDERR:
zsh:1: no such file or directory: cat /proc/uptime
</code></pre>
<p>You can see I have two attempts, one using the <code>sh</code> library and one with check_output, both result in the same error about not being able to run <code>/usr/bin/cat /proc/uptime</code>.</p>
<p>However as you can see at the end of the traceback:</p>
<pre><code>RAN: '/usr/bin/sshpass -p pass ssh theo@localhost "cat /proc/uptime"'
</code></pre>
<p>That appears to be a perfectly valid line, and if I copy paste it into a terminal it works.</p>
<p>Any ideas? The command does actually work if I just put in "uptime", but rather than editing the output of that to get the time in seconds, I though it would be easier to do it this way (at least I <em>thought</em> it would be) :)</p>
<p>I'm using python 3.5.2</p>
| 2 | 2016-10-01T17:23:19Z | 39,810,123 | <p>Based on the output, you need to modify your uptime line to look something like this:</p>
<pre><code> result = uptime("-p", "pass", "ssh", "theo@localhost", "cat",
"/proc/uptime")
</code></pre>
<p>It looks like "cat /proc/uptime" is interpreted as one argument by ssh in your original code.</p>
| 2 | 2016-10-01T18:29:24Z | [
"python",
"linux",
"python-3.x"
]
|
How to use standard Linux tools to fix a deadlocked script? | 39,809,554 | <p>I have a script in Python3 and if I use <code>subprocess.Popen.wait()</code> I have problem â my script iterates some Linux command many times and it looks to me like my app is not responding. When I use <code>subprocess.Popen.communicate()</code> my application correctly completes its work in a second.
<strong>What is the right way to solve this problem using Linux?</strong></p>
<p><strong>I think the solution must be somewhere in manipulating with buffer's variable</strong>, but I searched through the entire Internet and could not find anything suitable. May be I don't know enough structure and operation of Linux as a whole.</p>
<p>My question can be reformulated as follows: <strong>What's happened exactly when I use .wait() method? And that leads to failure of it? What is the cause of the so long waiting?</strong> When I aborting running task I see the next log: </p>
<pre><code>Traceback (most recent call last):
File "./test.py", line 6, in <module>
proc.wait()
File "/usr/lib/python3.5/subprocess.py", line 1658, in wait
(pid, sts) = self._try_wait(0)
File "/usr/lib/python3.5/subprocess.py", line 1608, in _try_wait
(pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt
</code></pre>
<p>My files looks approximately like the next things:
script.py:</p>
<pre><code>#!/usr/bin/python3
# -*-coding: utf-8 -*-
import subprocess
proc = subprocess.Popen(['./1.py', '1000000'], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
proc.wait()
out = proc.stdout.read()
# out = proc.communicate()[0]
print(len(out))
</code></pre>
<p>1.py:</p>
<pre><code>#!/usr/bin/python3
# -*-coding: utf-8 -*-
import sys
x = sys.argv[-1]
# print(x, type(x))
for i in range(int(x)):
print(i)
</code></pre>
<p>UPD: As we understand, the problem is a buffer overflow. It turns out the last version of question is, <strong>how to use the Linux possibility to expand buffer or redirect buffer to a file before running the script?</strong></p>
<p>UPD2: I also tried run the script as: $ <strong>python3 -u ./script.py</strong>, but, unfortunally, unbufferring doesn't work as I would like and script is hangs.</p>
| -1 | 2016-10-01T17:31:11Z | 39,810,762 | <p>Your script is sending output to its <code>stdout</code> or <code>stderr</code> pipes. The operating system will buffer some data then block the process forever when the pipe fills. Suppose I have a long winded command like</p>
<p>longwinded.py:</p>
<pre><code>for i in range(100000):
print('a'*1000)
</code></pre>
<p>The following hangs because the stdout pipe fills</p>
<pre><code>import sys
import subprocess as subp
p = subp.Popen([sys.executable, 'longwinded.py'], stdout=subp.PIPE,
stderr=subp.PIPE)
p.wait()
</code></pre>
<p>The next one doesn't hang because <code>communicate</code> reads the stdout and stderr pipes into memory</p>
<pre><code>p = subp.Popen([sys.executable, 'longwinded.py'], stdout=subp.PIPE,
stderr=subp.PIPE)
p.communicate()
</code></pre>
<p>If you don't care what stdout and err are, you can redirect them to the null device</p>
<pre><code>p = subp.Popen([sys.executable, 'longwinded.py'],
stdout=open(os.devnull, 'w'),
stderr=open(os.devnull, 'w'))
p.wait()
</code></pre>
<p>or save them to a file</p>
<pre><code>p = subp.Popen([sys.executable, 'longwinded.py'],
stdout=open('mystdout', 'w'),
stderr=open('mystderr', 'w'))
p.wait()
</code></pre>
| 0 | 2016-10-01T19:41:15Z | [
"python",
"linux",
"subprocess",
"buffer",
"buffer-overflow"
]
|
How do I make a function iterate over a list twice, picking up where it left off? | 39,809,649 | <p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at very busy stops.</p>
<p>I have an <code>if</code> statement in place which only shows the first five results if the stop has more than that, and then passes the results to the bot's <code>send_message</code> function.</p>
<p>I'm looking for a way to get the results from large stop lists in separate chunks of 5, and have the bot pick up where it left off, after sending the first message. My current code is as follows:</p>
<pre><code>if len(info["results"]) > 5:
while i < 5:
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
else:
while i < len(info["results"]):
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return '\n'.join(str(x) for x in n)
</code></pre>
<p>The <code>return</code> statement at the bottom is what is getting passed to the <code>send_message</code> function. Is there any way I can achieve the multiple message method?</p>
| 2 | 2016-10-01T17:41:35Z | 39,809,971 | <p>Here is sample code for how to achieve this with generators and yield keyword -</p>
<pre><code>def splitter(long_mess) :
split_mess = ""
for index in xrange(len(long_mess)) :
if index>0 and index%5==0 :
yield split_mess
split_mess = ""
split_mess += str(long_mess[index]) #replace with the n.append line
yield split_mess
input = "This is a really long message"
ans = splitter(input)
for i in ans :
print i #replace with send_message(i)
</code></pre>
<p>Output : </p>
<pre><code>This
is a
reall
y lon
g mes
sage
</code></pre>
| 1 | 2016-10-01T18:14:40Z | [
"python"
]
|
How do I make a function iterate over a list twice, picking up where it left off? | 39,809,649 | <p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at very busy stops.</p>
<p>I have an <code>if</code> statement in place which only shows the first five results if the stop has more than that, and then passes the results to the bot's <code>send_message</code> function.</p>
<p>I'm looking for a way to get the results from large stop lists in separate chunks of 5, and have the bot pick up where it left off, after sending the first message. My current code is as follows:</p>
<pre><code>if len(info["results"]) > 5:
while i < 5:
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
else:
while i < len(info["results"]):
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return '\n'.join(str(x) for x in n)
</code></pre>
<p>The <code>return</code> statement at the bottom is what is getting passed to the <code>send_message</code> function. Is there any way I can achieve the multiple message method?</p>
| 2 | 2016-10-01T17:41:35Z | 39,810,035 | <p>Here is a sample code which makes a list of lists which contains info about 5 stops. Then, you can call <code>send_message</code> in a loop</p>
<pre><code>def split_into_pairs_of_5(info)
outer = []
inner = []
for x in range(len(info["results"])):
if x % 5 == 0 and inner:
outer.append(inner)
inner = []
inner.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
if inner:
outer.append(inner)
inner = []
return outer
result = split_into_pairs_of_5(info)
for i in info:
send_message('\n'.join(str(x) for x in i))
</code></pre>
| 0 | 2016-10-01T18:20:59Z | [
"python"
]
|
How do I make a function iterate over a list twice, picking up where it left off? | 39,809,649 | <p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at very busy stops.</p>
<p>I have an <code>if</code> statement in place which only shows the first five results if the stop has more than that, and then passes the results to the bot's <code>send_message</code> function.</p>
<p>I'm looking for a way to get the results from large stop lists in separate chunks of 5, and have the bot pick up where it left off, after sending the first message. My current code is as follows:</p>
<pre><code>if len(info["results"]) > 5:
while i < 5:
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
else:
while i < len(info["results"]):
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return '\n'.join(str(x) for x in n)
</code></pre>
<p>The <code>return</code> statement at the bottom is what is getting passed to the <code>send_message</code> function. Is there any way I can achieve the multiple message method?</p>
| 2 | 2016-10-01T17:41:35Z | 39,810,148 | <p>You can do it easily by writing a <a href="https://docs.python.org/2/glossary.html#term-generator" rel="nofollow">generator function</a> like <code>chunks()</code> in the code below:</p>
<pre><code>info = {'results': [
{'route': 1, 'destination': 'DestA', 'duetime': '10'},
{'route': 2, 'destination': 'DestB', 'duetime': '20'},
{'route': 3, 'destination': 'DestC', 'duetime': '30'},
{'route': 4, 'destination': 'DestD', 'duetime': '40'},
{'route': 5, 'destination': 'DestE', 'duetime': '50'},
{'route': 6, 'destination': 'DestF', 'duetime': '60'},
{'route': 7, 'destination': 'DestG', 'duetime': '70'},
{'route': 8, 'destination': 'DestH', 'duetime': '80'},
],
}
def chunks(info, n):
results = info['results']
for i in range(0, len(results), n):
chunk = [
'Route: {} to {}\nDue: {} minutes.\n'.format(
result['route'], result['destination'], result["duetime"])
for result in results[i:i+n]]
yield '\n'.join(chunk)
for i, chunk in enumerate(chunks(info, 5), 1):
print('== CHUNK {} ==\n{}'.format(i, chunk))
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>== CHUNK 1 ==
Route: 1 to DestA
Due: 10 minutes.
Route: 2 to DestB
Due: 20 minutes.
Route: 3 to DestC
Due: 30 minutes.
Route: 4 to DestD
Due: 40 minutes.
Route: 5 to DestE
Due: 50 minutes.
== CHUNK 2 ==
Route: 6 to DestF
Due: 60 minutes.
Route: 7 to DestG
Due: 70 minutes.
Route: 8 to DestH
Due: 80 minutes.
</code></pre>
| 5 | 2016-10-01T18:31:51Z | [
"python"
]
|
How do I make a function iterate over a list twice, picking up where it left off? | 39,809,649 | <p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at very busy stops.</p>
<p>I have an <code>if</code> statement in place which only shows the first five results if the stop has more than that, and then passes the results to the bot's <code>send_message</code> function.</p>
<p>I'm looking for a way to get the results from large stop lists in separate chunks of 5, and have the bot pick up where it left off, after sending the first message. My current code is as follows:</p>
<pre><code>if len(info["results"]) > 5:
while i < 5:
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
else:
while i < len(info["results"]):
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return '\n'.join(str(x) for x in n)
</code></pre>
<p>The <code>return</code> statement at the bottom is what is getting passed to the <code>send_message</code> function. Is there any way I can achieve the multiple message method?</p>
| 2 | 2016-10-01T17:41:35Z | 39,810,465 | <p>My approach uses <code>itertools.groupby()</code> to group the records in chunk of 5 (or any positive number). In your post, you are not showing the name in which <code>send_message</code> calls, so I just name it myself: <code>get_info</code>:</p>
<pre><code>import itertools
def show_rec(rec):
output = 'Route: {route} to {destination}, due in {duetime} minutes'.format(**rec)
return output
def get_info(group_size=5):
# Do something to get info
counter = itertools.count()
for _, group in itertools.groupby(info['results'], key=lambda v: next(counter) // group_size):
yield '\n'.join(show_rec(r) for r in group)
# Here is inside function send_message
for output in get_info(group_size=5):
print output
print
</code></pre>
<h1>Discussion</h1>
<ul>
<li>The first order of business for me is not how to solve this problem, but how to present a record in a nice, clean, and easy-to-understand manner, for that, I created the function <code>show_rec</code> to do the job</li>
<li><code>get_info</code> is really a generator, not a regular function (see the yield keyword)</li>
<li>Inside <code>get_info</code>, I group the records in group of <code>group_size</code> with the help of the <code>itertools.groupby</code> function, which itself is a generator.</li>
<li>Note that <code>counter</code> is a generator object where as <code>next(counter)</code> will yield 0, 1, 2, 3, 4, 5, 6, 7, 8, ... The expression <code>next(counter) // group_size</code> will yield 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, ... for <code>group_size=5</code> and that is what we use to group the records.</li>
</ul>
| 0 | 2016-10-01T19:07:10Z | [
"python"
]
|
How do I make a function iterate over a list twice, picking up where it left off? | 39,809,649 | <p>I'm making a Facebook Messenger bot which returns the times of buses coming to a specified stop. So far, the bot is working fine, but Facebook doesn't allow for messages sent by bots to be over 320 characters. Often, the bot can only display the first 5 or so without going over this limit, which isn't good enough at very busy stops.</p>
<p>I have an <code>if</code> statement in place which only shows the first five results if the stop has more than that, and then passes the results to the bot's <code>send_message</code> function.</p>
<p>I'm looking for a way to get the results from large stop lists in separate chunks of 5, and have the bot pick up where it left off, after sending the first message. My current code is as follows:</p>
<pre><code>if len(info["results"]) > 5:
while i < 5:
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
else:
while i < len(info["results"]):
n.append("Route:" + " " + str(info['results'][i]['route']) + " " + "to" + " " + str(info['results'][i]['destination']) + "\n" + "Due:" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return '\n'.join(str(x) for x in n)
</code></pre>
<p>The <code>return</code> statement at the bottom is what is getting passed to the <code>send_message</code> function. Is there any way I can achieve the multiple message method?</p>
| 2 | 2016-10-01T17:41:35Z | 39,810,877 | <p>You can use a generator function with <code>range</code> (or <code>xrange</code> in Python 2.7), like this:</p>
<pre><code>info = {'results': [
{'route': 1, 'destination': 'DestA', 'duetime': '1'},
{'route': 2, 'destination': 'DestB', 'duetime': '2'},
{'route': 3, 'destination': 'DestC', 'duetime': '3'},
{'route': 4, 'destination': 'DestD', 'duetime': '4'},
{'route': 5, 'destination': 'DestE', 'duetime': '5'},
{'route': 6, 'destination': 'DestF', 'duetime': '6'},
{'route': 7, 'destination': 'DestG', 'duetime': '7'},
{'route': 8, 'destination': 'DestH', 'duetime': '8'},
]}
def iter_with_chunks(seq, chunk_size):
for index in range(0, len(seq), chunk_size):
yield seq[index: index + chunk_size]
for count, chunk in enumerate(iter_with_chunks(info["results"], 5), 1):
print("== CHUNK {count} ==".format(count=count))
for item in chunk:
output = 'Route: {route} to {destination},\n' \
'due in {duetime} minutes\n'.format(**item)
print(output)
</code></pre>
<p>Output:</p>
<pre><code>== CHUNK 1 ==
Route: 1 to DestA,
due in 1 minutes
Route: 2 to DestB,
due in 2 minutes
Route: 3 to DestC,
due in 3 minutes
Route: 4 to DestD,
due in 4 minutes
Route: 5 to DestE,
due in 5 minutes
== CHUNK 2 ==
Route: 6 to DestF,
due in 6 minutes
Route: 7 to DestG,
due in 7 minutes
Route: 8 to DestH,
due in 8 minutes
</code></pre>
| 0 | 2016-10-01T19:54:22Z | [
"python"
]
|
selecting rows in a tuplelist in pandas | 39,809,650 | <p>I have a list of tuples as below in python:</p>
<pre><code> Index Value
0 (1,2,3)
1 (2,5,4)
2 (3,3,3)
</code></pre>
<p>How can I select rows from this in which the second value is less than or equal 2?</p>
<p><strong><em>EDIT:</em></strong></p>
<p>Basically, the data is in the form of <code>[(1,2,3), (2,5,4), (3,3,3)....]</code></p>
| 2 | 2016-10-01T17:41:37Z | 39,809,700 | <p>You could slice the <code>tuple</code> by using <code>apply</code>:</p>
<pre><code>df[df['Value'].apply(lambda x: x[1] <= 2)]
</code></pre>
<p><a href="http://i.stack.imgur.com/MZBwY.png" rel="nofollow"><img src="http://i.stack.imgur.com/MZBwY.png" alt="Image"></a></p>
<hr>
<p>Seems, it was a list of tuples and not a <code>DF</code>:</p>
<p>To return a <code>list</code> back:</p>
<pre><code>data = [item for item in [(1,2,3), (2,5,4), (3,3,3)] if item[1] <= 2]
# [(1, 2, 3)]
</code></pre>
<p>To return a <code>series</code> instead:</p>
<pre><code>pd.Series(data)
#0 (1, 2, 3)
#dtype: object
</code></pre>
| 2 | 2016-10-01T17:47:45Z | [
"python",
"pandas",
"tuples"
]
|
selecting rows in a tuplelist in pandas | 39,809,650 | <p>I have a list of tuples as below in python:</p>
<pre><code> Index Value
0 (1,2,3)
1 (2,5,4)
2 (3,3,3)
</code></pre>
<p>How can I select rows from this in which the second value is less than or equal 2?</p>
<p><strong><em>EDIT:</em></strong></p>
<p>Basically, the data is in the form of <code>[(1,2,3), (2,5,4), (3,3,3)....]</code></p>
| 2 | 2016-10-01T17:41:37Z | 39,809,734 | <pre><code>df[df["Value"].str[1] <= 2]
</code></pre>
<p>You can read this for more details - <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str</a></p>
| 1 | 2016-10-01T17:51:27Z | [
"python",
"pandas",
"tuples"
]
|
selecting rows in a tuplelist in pandas | 39,809,650 | <p>I have a list of tuples as below in python:</p>
<pre><code> Index Value
0 (1,2,3)
1 (2,5,4)
2 (3,3,3)
</code></pre>
<p>How can I select rows from this in which the second value is less than or equal 2?</p>
<p><strong><em>EDIT:</em></strong></p>
<p>Basically, the data is in the form of <code>[(1,2,3), (2,5,4), (3,3,3)....]</code></p>
| 2 | 2016-10-01T17:41:37Z | 39,812,611 | <p>just to put this out there. you should read <a href="http://stackoverflow.com/help/mcve">mcve</a>. your question was/is confusing because it looks as though you've got 2 good answers and your not satisfied. then you edited your question to be clearer, but just barely.</p>
<p>ok, now that i've got my editorial out of the way.</p>
<hr>
<p><strong><em>setup</em></strong><br>
this is what i'm assuming i'm working with</p>
<pre><code># list of tuples
lot = [(1, 2, 3), (2, 5, 4), (3, 3, 3)]
</code></pre>
<p><strong><em>desired output</em></strong><br>
i think. btw, nothing to do with pandas at all</p>
<pre><code>[(a, b, c) for a, b, c in lot if b <= 2]
[(1, 2, 3)]
</code></pre>
<p><strong><em>with pandas</em></strong><br>
however, since you did tag this pandas</p>
<pre><code>s = pd.Series(lot)
</code></pre>
<p>@TrigonaMinima's answer, give them credit if this works for you.</p>
<pre><code>s[s.str[1].le(2)]
0 (1, 2, 3)
dtype: object
</code></pre>
| 0 | 2016-10-01T23:58:32Z | [
"python",
"pandas",
"tuples"
]
|
Python pandas resampling instantaneous hourly data to daily timestep including 00:00 of next day | 39,809,703 | <p>Let's say I have a series of instantaneous temperature measurements (i.e. they capture the temperature at an exact moment in time).</p>
<pre><code>index = pd.date_range('1/1/2000', periods=9, freq='T')
series = pd.Series(range(9), index=index)
series
Out[130]:
2000-01-01 00:00:00 0
2000-01-01 06:00:00 1
2000-01-01 12:00:00 2
2000-01-01 18:00:00 3
2000-01-02 00:00:00 4
2000-01-02 06:00:00 5
2000-01-02 12:00:00 6
2000-01-02 18:00:00 7
2000-01-03 00:00:00 8
Freq: 6H, dtype: int64
</code></pre>
<p>I want to get a average of daily temperature. The problem is that I want to include 00:00:00 from the current day and the next day in the average for the current day. For example I want to average 2000-01-01 00:00:00 to 2000-01-02 00:00:00 inclusive. The pandas resample function will not include 2000-01-02 in the bin because it's a different day.</p>
<p>I would imagine this situation comes up often when dealing with instantaneous measurements that need to be resampled. What's the solution?</p>
| 2 | 2016-10-01T17:48:02Z | 39,812,467 | <p><strong><em>setup</em></strong> </p>
<pre><code>index = pd.date_range('1/1/2000', periods=9, freq='6H')
series = pd.Series(range(9), index=index)
series
2000-01-01 00:00:00 0
2000-01-01 06:00:00 1
2000-01-01 12:00:00 2
2000-01-01 18:00:00 3
2000-01-02 00:00:00 4
2000-01-02 06:00:00 5
2000-01-02 12:00:00 6
2000-01-02 18:00:00 7
2000-01-03 00:00:00 8
Freq: 6H, dtype: int64
</code></pre>
<p><strong><em>solution</em></strong> </p>
<pre><code>series.rolling(5).mean().resample('D').first()
2000-01-01 NaN
2000-01-02 2.0
2000-01-03 6.0
Freq: D, dtype: float64
</code></pre>
| 1 | 2016-10-01T23:33:23Z | [
"python",
"pandas"
]
|
pycrypto: unable to decrypt file | 39,809,743 | <p>I am using PKCS1_OAEP crypto algorithm to encrypt a file. The file is encrypted successfully but unable to decrypt file, getting the error "Ciphertext with incorrect length."</p>
<p>Encryption Algorithm is here: </p>
<pre><code>#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64
fd = open('test.doc', 'rb')
message = fd.read()
fd.close()
print "[*] Original File Size: %d" % len(message)
#message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)
compressed = zlib.compress(message)
print "[*] Compressed File Size: %d" % len(compressed)
chunk_size = 128
ciphertext = ""
offset = 0
while offset < len(compressed):
chunk = compressed[offset:offset+chunk_size]
if len(chunk) % chunk_size != 0:
chunk += " " * (chunk_size - len(chunk)) # Padding with spaces
ciphertext += cipher.encrypt(chunk)
offset += chunk_size
print "[*] Encrypted File Size: %d" % len(ciphertext)
encoded = ciphertext.encode("base64")
print "[*] Encoded file size: %d" % len(encoded)
fd = open("enc.data", 'wb')
fd.write(encoded)
fd.close()
print "[+] File saved successfully!"
</code></pre>
<p>Decryption Algorithm is here:</p>
<pre><code>#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64
key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAEP.new(key)
fd = open('enc.data', 'rb')
encoded = fd.read().strip('\n')
fd.close()
decoded = encoded.decode("base64")
chunk_size = 128
offset = 0
plaintext = ""
while offset < len(decoded):
plaintext += cipher.decrypt(decoded[offset:offset+chunk_size])
offset += chunk_size
#plaintext = cipher.decrypt(decoded)
decompress = zlib.decompress(plaintext)
fd = open('decr.doc', 'wb')
fd.write(decompress)
fd.close()
</code></pre>
<p>Using the following script to generate key</p>
<pre><code>from Crypto.PublicKey import RSA
new_key = RSA.generate(2048, e=65537)
public_key = new_key.publickey().exportKey("PEM")
private_key = new_key.exportKey("PEM")
fileWrite(fileName, data):
fd = open(fileName, 'wb')
fd.write(data)
fd.close()
fileWrite('privkey.der', private_key)
fileWrite('pubkey.der', public_key)
</code></pre>
<p><a href="http://i.stack.imgur.com/NY8ox.png" rel="nofollow">Here is the Error Message</a></p>
| 2 | 2016-10-01T17:52:31Z | 39,811,745 | <p>You encrypt with a <strong>2048 bit RSA key</strong>, which gives encrypted blocks of <strong>2048 bites (256 bytes)</strong>. Your decrypt implementation assumes the encrypted blocks are <strong>128 bytes</strong> where they are actually <strong>256 bytes</strong>, and thus you get the 'incorrect length' error. Notice how your encrypted files size (64512) is more than double of the compressed file size (32223).</p>
<p>In general you would not use <strong>RSA</strong> for <strong>bulk encryption</strong> (as it's quite slow) but would instead combine it with a symmetric encryption like <strong>AES</strong>. You would then encrypt the data with a random <strong>AES</strong> key, and then encrypt the <strong>AES</strong> key with the <strong>RSA</strong> key. This way you get the speed of <strong>AES</strong> and the two keys of <strong>RSA</strong>. This is known as <a href="https://en.wikipedia.org/wiki/Hybrid_cryptosystem" rel="nofollow">Hybrid Encryption</a>.</p>
| 0 | 2016-10-01T21:44:43Z | [
"python",
"encryption",
"cryptography",
"public-key-encryption",
"pycrypto"
]
|
Django: add filtering sidebar to a change list admin view | 39,809,945 | <p>I have a back-end module showing a quite long items listing that looks like this:</p>
<pre><code>ID Label Type
1 Label 1 Type A
2 Label 2 Type B
3 Label 3 Type A
4 Label 4 Type D
5 Label 5 Type C
6 Label 6 Type D
7 Label 7 Type C
</code></pre>
<p>What I want to do is quite simple: I want to add a "filter by" sidebox listing all available types, for example</p>
<pre><code>Available Types
Type A
Type B
Type C
Type D
</code></pre>
<p>If clicked they should enable filtering by single type. For example, if I click on "Type A" only items belonging to that type will be shown. Sidebar's HTML should look like this</p>
<pre><code><ul>
<li><a href="?type=11">Type A</a></li>
<li><a href="?type=12">Type B</a></li>
<li><a href="?type=13">Type C</a></li>
<li><a href="?type=14">Type D</a></li>
</ul>
</code></pre>
<p>How can I implement that? I'm quite confused right now...</p>
<p>Thanx a lot!</p>
| 0 | 2016-10-01T18:12:06Z | 39,810,459 | <p>You can use <code>class based generic views</code></p>
<pre><code>from django.views import generic
class MyListView(generic.ListView):
model = MyModel
template_name = 'my_list.html'
def get_queryset(self):
queryset = super(MyListView, self).get_queryset()
# get query value of query parameter 'type'
type = self.request.GET.get('type', None)
if type:
# if type is given then filter
return queryset.filter(type__exact=type)
# if type is not give then return all
return queryset
</code></pre>
<p>You can refer to docs <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-display/#listview" rel="nofollow">here</a></p>
| 1 | 2016-10-01T19:06:56Z | [
"python",
"django"
]
|
See if user in ManyToManyField | 39,809,984 | <p>I am trying to see if the current user is in the <code>collaborators</code> m2m field, but keep getting an error saying: </p>
<p><code>Cannot query "John Doe": Must be "Company" instance.</code></p>
<p>Could someone help me out with the conditional statement please?</p>
<p><strong>models.py:</strong></p>
<pre><code>class MyUser():
name = ...
email = ...
class Company(models.Model):
user = models.ForeignKey(MyUser, null=True,
related_name='company_owner',
on_delete=models.SET_NULL)
collaborators = models.ManyToManyField(MyUser, blank=True,
related_name='company_collaborators')
name = models.CharField(max_length=120)
</code></pre>
<p><strong>views.py:</strong></p>
<pre><code>def company_dash(request, username):
user = request.user
company = get_object_or_404(
Company, Q(is_active=True), username=username)
# NEED HELP HERE PLEASE
if company.user == user or company.collaborators.filter(company_collaborators=user).exists():
# do something
</code></pre>
| 0 | 2016-10-01T18:15:55Z | 39,810,355 | <p>Full docs is <a href="https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/" rel="nofollow">here</a></p>
<p>You can use</p>
<pre><code>if company.user == user or company.collaborators.filter(collaborators=user):
</code></pre>
<p>or </p>
<pre><code>if company.user == user or company.collaborators.filter(id=user.id):
</code></pre>
<p>I think there is no need to add <code>.exists()</code> due to <code>filter(collaborators=user)</code> returns list that to be evaluated to be <code>False</code> if empty.</p>
| 0 | 2016-10-01T18:54:35Z | [
"python",
"django",
"django-models",
"django-views",
"many-to-many"
]
|
Python - How to plot 'boundary edge' onto a 2D plot | 39,809,997 | <p>The program <strong>pastebinned</strong> below generates a plot that looks like:
<a href="http://i.stack.imgur.com/6pTzP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/6pTzP.jpg" alt="Original plot"></a>
<strong>Pastebin</strong>: <a href="http://pastebin.com/wNgAG6K9" rel="nofollow">http://pastebin.com/wNgAG6K9</a> </p>
<p>Basically, the program solves an equation for AA, and plots the values provided AA>0 and AA=/=0. The data is plotted using <code>pcolormesh</code> from 3 arrays called <code>x</code>, <code>y</code> and <code>z</code> (lines 57 - 59).</p>
<p><strong>What I want to do:</strong></p>
<p>I would like to plot a line around the boundary where the solutions go from zero (black) to non-zero (yellow/green), see plot below. What is the most sensible way to go about this? </p>
<p>I.e. lines in red (done crudely in MS paint)</p>
<p><a href="http://i.stack.imgur.com/qHcFZ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qHcFZ.jpg" alt="enter image description here"></a></p>
<p><strong>Further info: I need to be able to store the red dashed boundary values so that I can plot the red dashed boundary condition to another 2d plot made from real/measured/non-theoretical data.</strong></p>
<p>Feel free to ask for further information.</p>
| 0 | 2016-10-01T18:17:07Z | 39,810,573 | <p>Without seeing your data, I would suggest first trying to work with matplotlib's internal algorithm to plot the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.contour" rel="nofollow"><code>contour</code></a> line corresponding to the zero level. This is simple, but it might happen that the interpolation that is used for this doesn't look good enough (I don't know if it can find that sharp peak in the contour line). The proof of the pudding is in the eating:</p>
<pre><code>plt.contour(x,y,z,[0],colors='r',linewidths=2,linestyles='dashed')
</code></pre>
<p>If that doesn't suffice, you might have to resort to image processing methods to find the boundaries of your data (after turning it into binary).</p>
| 0 | 2016-10-01T19:16:50Z | [
"python",
"matplotlib",
"plot"
]
|
explicitly setting style sheet in python pyqt4? | 39,810,010 | <p>In pyqt standard way for setting style sheet is like this <br><br>
<code>MainWindow.setStyleSheet(_fromUtf8("/*\n"
"gridline-color: rgb(85, 170, 255);\n"
"QToolTip\n"
"{\n"
" border: 1px solid #76797C;\n"
" background-color: rgb(90, 102, 117);;\n"
" color: white;\n"
" padding: 5px;\n"
" opacity: 200;\n"
"}\n"
"#label_3{\n"
" background-color:rgb(90, 102, 117);\n"
" color:white;\n"
" padding-left:20px;\n"
" \n"
"}\n"
"#label_2{\n"
" color:white;\n"
" padding-left:20px;\n"
" \n"
"}\n"</code></p>
<p>But like we link the stylesheet in html
<code><link rel="stylesheet" href="style.css"></code>
.can't we do the same in pyqt?It helps in organizing the things.</p>
| 0 | 2016-10-01T18:18:16Z | 39,838,248 | <p>There are currently only two main ways to set a stylesheet. The first is to use the <code>setStyleSheet</code> method:</p>
<pre><code>widget.setStyleSheet("""
QToolTip {
border: 1px solid #76797C;
background-color: rgb(90, 102, 117);
color: white;
padding: 5px;
opacity: 200;
}
""")
</code></pre>
<p>This will only take a string, so an external resource would need to be explicitly read from a file, or imported from a module.</p>
<p>The second method is to use the <a href="http://doc.qt.io/qt-4.8/qapplication.html#QApplication" rel="nofollow"><code>-stylesheet</code> command-line argument</a>, which allows an external qss resource to be specified as a path:</p>
<pre><code>python myapp.py -stylesheet style.qss
</code></pre>
<p>This opens up the possibility of a tempting hack, since it is easy enough to manipulate the args passed to the <code>QApplication</code> constructor, and explicitly insert a default stylesheet:</p>
<pre><code>import sys
args = list(sys.argv)
args[1:1] = ['-stylesheet', 'style.qss']
app = QtGui.QApplication(args)
</code></pre>
<p>(Inserting the extra arguments at the beginning of the list ensures that it is still possible for the user to override the default with their own stylesheet).</p>
| 2 | 2016-10-03T18:37:28Z | [
"python",
"pyqt",
"pyqt4",
"qss"
]
|
Comparing hundreds of JPEG images taken from multiple angles | 39,810,168 | <p>I am comparing X-ray images to find a specific difference between these images. All images are in jpeg format. Sometimes there are six, or eight different camera angles from which these images are taken. From each angle there are ~ 100 images. I am trying to compare a couple of hundred images to identify a specific difference between these images. </p>
<p>I am using Python and I am relatively new to it. Can Sci-kit image segmentation be used for the following problems? </p>
<ol>
<li>Compensate for the image exposure variations in all images</li>
<li>Compensate for image size variations in all images</li>
</ol>
| 2 | 2016-10-01T18:33:37Z | 39,810,608 | <p>I don't know Sci-kit, but I'm sure <a href="http://docs.opencv.org/2.4/index.html" rel="nofollow">OpenCV</a> can do the job!</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/OpenCV" rel="nofollow">https://en.wikipedia.org/wiki/OpenCV</a></li>
<li><a href="http://docs.opencv.org/2.4/modules/stitching/doc/exposure_compensation.html" rel="nofollow">http://docs.opencv.org/2.4/modules/stitching/doc/exposure_compensation.html</a></li>
<li><a href="http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html" rel="nofollow">http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html</a></li>
</ul>
| 2 | 2016-10-01T19:21:52Z | [
"python",
"jpeg"
]
|
Threading queue hangs in Python | 39,810,172 | <p>I am trying to make a parser multi-threaded via a Queue. It seems to work, but my Queue is hanging. I'd appreciate if someone could tell me how to fix this, since I have rarely written multi-threaded code.</p>
<p>This code reads from the Q:</p>
<pre><code>from silk import *
import json
import datetime
import pandas
import Queue
from threading import Thread
l = []
q = Queue.Queue()
def parse_record():
d = {}
while not q.empty():
rec = q.get()
d['timestamp'] = rec.stime.strftime("%Y-%m-%d %H:%M:%S")
# ... many ops like this
d['dport'] = rec.dport
l.append(d) # l is global
</code></pre>
<p>And this fills the Q:</p>
<pre><code>def parse_records():
ffile = '/tmp/query.rwf'
flows = SilkFile(ffile, READ)
numthreads = 2
# fill queue
for rec in flows:
q.put(rec)
# work on Queue
for i in range(numthreads):
t = Thread(target = parse_record)
t.daemon = True
t.start()
# blocking
q.join()
# never reached
data_df = pandas.DataFrame.from_records(l)
return data_df
</code></pre>
<p>I only call <code>parse_records()</code> in my main. It never terminates.</p>
| 2 | 2016-10-01T18:34:16Z | 39,810,328 | <p>The <a href="https://docs.python.org/3.6/library/queue.html#queue.Queue.empty" rel="nofollow">Queue.empty doc</a> says:</p>
<blockquote>
<p>...if empty() returns False it doesnât guarantee that a subsequent call to get() will not block.</p>
</blockquote>
<p>As a minimum you should use <code>get_nowait</code> or risk data loss. But more importantly, the join will only release when all of the queued items have been marked complete with a <a href="https://docs.python.org/3.6/library/queue.html#queue.Queue.task_done" rel="nofollow">Queue.task_done</a> call:</p>
<blockquote>
<p>If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).</p>
</blockquote>
<p>As a side note, <code>l.append(d)</code> is not atomic and should be protected with a lock.</p>
<pre><code>from silk import *
import json
import datetime
import pandas
import Queue
from threading import Thread, Lock
l = []
l_lock = Lock()
q = Queue.Queue()
def parse_record():
d = {}
while 1:
try:
rec = q.getnowait()
d['timestamp'] = rec.stime.strftime("%Y-%m-%d %H:%M:%S")
# ... many ops like this
d['dport'] = rec.dport
with l_lock():
l.append(d) # l is global
q.task_done()
except Queue.Empty:
return
</code></pre>
<p>You could shorten your code considerably by using a thread pool from the standard libs.</p>
<pre><code>from silk import *
import json
import datetime
import pandas
import multiprocessing.pool
def parse_record(rec):
d = {}
d['timestamp'] = rec.stime.strftime("%Y-%m-%d %H:%M:%S")
# ... many ops like this
d['dport'] = rec.dport
return d
def parse_records():
ffile = '/tmp/query.rwf'
flows = SilkFile(ffile, READ)
pool = multiprocessing.pool.Pool(2)
data_df = pandas.DataFrame.from_records(pool.map(parse_record), flows)
pool.close()
return data_df
</code></pre>
| 2 | 2016-10-01T18:52:09Z | [
"python",
"multithreading",
"queue",
"hang"
]
|
no "\n" but new line being made? | 39,810,199 | <p>There is no <code>\n</code> in my code but when I print out all my variables, it creates a newline meaning my last variable is printed on another line.</p>
<p>my code :</p>
<pre><code>with open("read_it.txt", "r") as text_file:
for items in text_file:
line = items.split(",")
if GTIN in items:
product = line[1]
indprice = line[2]
finprice = float(indprice)* float(Quantity)
print(GTIN,product,Quantity,"£",indprice,"£",finprice)
</code></pre>
<p>current output (wrong) :</p>
<pre><code>086947367 banana 2 £ 0.50
£ 1.0
</code></pre>
<p>I want :</p>
<pre><code>86947367 banana 2 £ 0.50 £ 1.0
</code></pre>
<p>any help appreciated.</p>
| 0 | 2016-10-01T18:37:51Z | 39,810,319 | <p>When you call readline on a file object (which you're doing implicitly in your for loop), it leaves the trailing '\n' and/or '\r' characters. In this case, your indprice variable still contains that trailing '\n'.</p>
<p>Try:</p>
<pre><code>line = items.strip('\r\n').split(',')
</code></pre>
<p>Or, if it's a small text file that you can pull entirely into memory:</p>
<pre><code>for items in text_file.read().split('\n'):
</code></pre>
| 2 | 2016-10-01T18:51:22Z | [
"python",
"python-3.x"
]
|
Django log requests with status 200 to syslog | 39,810,236 | <p>I am writing a Django Application and using basic URL Routing to views. I am trying to implement logging to syslog. I want to log all incoming requests to syslog. My <code>LOGGING</code> dict looks like this:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'verbose': {
'format': '%(process)-5d %(name)s:%(lineno)d %(levelname)s %(message)s'
},
'simple': {
'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s',
'datefmt': '%d/%b/%Y %H:%M:%S'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'syslog': {
'level': 'DEBUG',
'class': 'logging.handlers.SysLogHandler',
'facility': 'local7',
'address': '/dev/log',
'formatter': 'verbose'
},
},
'loggers': {
'django.server': {
'handlers': ['console', 'syslog'],
'level': 'INFO',
'propagate': False
},
'my_project': {
'handlers': ['console', 'syslog'],
'level': 'INFO',
'propagate': False,
},
# root logger
'':{
'handlers': ['console', 'syslog'],
'level': 'INFO',
'disabled': False
},
},
}
</code></pre>
<p>Whenever I hit any URL on the server, the following is logged into the console:</p>
<pre><code>[01/Oct/2016 18:30:34] "POST /api/v1/users/login/ HTTP/1.1" 200 73
</code></pre>
<p>But nothing in my log file.</p>
<p>When I insert a <code>logger.error('Something went wrong!')</code> in my code, it gets logged in my log file.</p>
<p>How do I get the requests log in my log file?</p>
<p>TIA</p>
| 2 | 2016-10-01T18:41:34Z | 39,811,554 | <p>The logging requests from django to syslog depends on several things:</p>
<ul>
<li>Syslog configuration. I assume that your syslog configuration is
correct and syslog does not drop debug messages from local7.</li>
<li>If you run your application with 'runserver', django uses built-in lightweight http server. This server logs request messages. Prior to 1.10 it used to log to <strong>sys.stderr</strong> and it was not possible to configure that via LOGGING dict. In django 1.10 this has changed to use python logging mechanism: <a href="https://docs.djangoproject.com/en/1.10/ref/django-admin/#django-admin-runserver" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/django-admin/#django-admin-runserver</a></li>
<li>If you run your app using nginx+uwsgi for example, logging requests is handled by nginx/uwsgi.</li>
</ul>
| 1 | 2016-10-01T21:17:35Z | [
"python",
"django",
"logging"
]
|
Sending content directly to scrapy pipeline | 39,810,251 | <p>I'm working with scrapy. In my current project I am capturing the text from pdf files. I want to send this to a pipeline for parsing. Right now I have:</p>
<pre><code>def get_pdf_text(self, response):
in_memory_pdf = BytesIO(bytes(response.body))
in_memory_pdf.seek(0)
doc = slate.PDF(in_memory_pdf)
item =OveItem()
item['pdf_text']=doc
return item
</code></pre>
<p>pipelines.py</p>
<pre><code>class OvePipeline(object):
def process_item(self, item, spider):
.......
return item
</code></pre>
<p>This works ,but I think it would be cleaner just to yield the result directly and not have to attach the result to an item to get it to a pipeline, like:</p>
<pre><code>def get_pdf_text(self, response):
in_memory_pdf = BytesIO(bytes(response.body))
in_memory_pdf.seek(0)
yield slate.PDF(in_memory_pdf)
</code></pre>
<p>Is this possible?</p>
| 1 | 2016-10-01T18:43:30Z | 39,810,891 | <p>According to <a href="https://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.parse" rel="nofollow">Scrapy documentation</a>, a spider callback has to either return a <code>Request</code> instance(s), dictionary(ies) or <code>Item</code> instance(s):</p>
<blockquote>
<p>This method, as well as any other Request callback, must return an
iterable of Request and/or dicts or Item objects.</p>
</blockquote>
<p>So, if you don't want to define a special "item" for the pdf content, simply wrap it into a dict:</p>
<pre><code>def get_pdf_text(self, response):
in_memory_pdf = BytesIO(bytes(response.body))
in_memory_pdf.seek(0)
doc = slate.PDF(in_memory_pdf)
return {'pdf_text': doc}
</code></pre>
| 1 | 2016-10-01T19:56:01Z | [
"python",
"scrapy"
]
|
Using the click package: Making an option be a choice of `int` | 39,810,313 | <p>I'm trying to make a <code>click.option</code> be a choice between the numbers <code>0</code>, <code>1</code> and <code>2</code>. I tried this: </p>
<pre><code>@click.Option('--verbosity', default=1, type=click.Choice([0, 1, 2]))
def f():
# ...
pass
</code></pre>
<p>But I get the exception <code>TypeError: sequence item 0: expected str instance, int found</code>. I guess <code>click</code> expects only strings in <code>click.Choice</code>. Any way to get it to accept ints? I know I can convert to int manually after it's received, but if there's an idiomatic way to receive an <code>int</code> choice, that'll be better.</p>
| 2 | 2016-10-01T18:50:41Z | 39,810,394 | <p>You can use <code>IntRange(min=0, max=2)</code>:</p>
<blockquote>
<p><code>class click.IntRange(min=None, max=None, clamp=False)</code> </p>
<p>A parameter
that works similar to click.INT but restricts the value to fit into a
range. The default behavior is to fail if the value falls outside the
range, but it can also be silently clamped between the two edges.</p>
</blockquote>
<p><a href="http://click.pocoo.org/5/api/#click.IntRange" rel="nofollow">From the docs.</a></p>
| 2 | 2016-10-01T19:00:08Z | [
"python",
"click"
]
|
Shut down server in TensorFlow | 39,810,356 | <p>When we want to use distributed TensorFlow, we will create a parameter server using</p>
<pre><code>tf.train.Server.join()
</code></pre>
<p>However, I can't find any way to shut down the server except killing the processing. The TensorFlow documentation for join() is</p>
<pre><code>Blocks until the server has shut down.
This method currently blocks forever.
</code></pre>
<p>This is quite bothering to me because I would like to create many servers for computation and shut them down when everything finishes.</p>
<p>Is there possible solutions for this.</p>
<p>Thanks</p>
| 0 | 2016-10-01T18:54:36Z | 39,812,053 | <p>There's currently no clean way to shut down a TensorFlow gRPC server. It <em>is</em> possible to <a href="http://stackoverflow.com/a/35708349/3574081">shut down a gRPC server</a>, but doing it safely requires additional memory management for all of the in-flight request and response buffers, which would require a lot of additional plumbing (of the worst kind: asynchronous shared memory management...) for a feature that nobody had requested—until now!</p>
<p>In practice you should be able to use the same <code>tf.train.Server</code> object for many different computations. If this doesn't work for your use case, please feel free to <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow">open an GitHub issue</a> and tell us more about your use case.</p>
| 0 | 2016-10-01T22:30:13Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning",
"grpc"
]
|
python 'string index out of range' error | 39,810,553 | <p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems.
my code is:</p>
<pre><code>a = input('word ->')
b = []
count = 0
while count < 5:
b.append(a[count])
count +=1
print(b)
</code></pre>
<p>it would be great if someone could help. thanks</p>
| 0 | 2016-10-01T19:14:55Z | 39,810,584 | <p>The problem is that your "count" will increase each loop until it reaches 5. If the string in the input is shorter than 5, you will get index error.</p>
| 0 | 2016-10-01T19:18:33Z | [
"python",
"indexing",
"syntax",
"range"
]
|
python 'string index out of range' error | 39,810,553 | <p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems.
my code is:</p>
<pre><code>a = input('word ->')
b = []
count = 0
while count < 5:
b.append(a[count])
count +=1
print(b)
</code></pre>
<p>it would be great if someone could help. thanks</p>
| 0 | 2016-10-01T19:14:55Z | 39,810,611 | <p>Because when you give input smaller than 5 a[count] is out of index.
So try this one:</p>
<pre><code>a = input('word ->')
b = []
count = 0
while count < len(a):
b.append(a[count])
count +=1
print(b)
</code></pre>
| 1 | 2016-10-01T19:22:14Z | [
"python",
"indexing",
"syntax",
"range"
]
|
python 'string index out of range' error | 39,810,553 | <p>I'm trying to code a word scrambler but when I try to append letters from my word, using index, I get the error 'String index out of range'. I have tried this without the 'input' but once I added it in I started getting problems.
my code is:</p>
<pre><code>a = input('word ->')
b = []
count = 0
while count < 5:
b.append(a[count])
count +=1
print(b)
</code></pre>
<p>it would be great if someone could help. thanks</p>
| 0 | 2016-10-01T19:14:55Z | 39,810,645 | <p>I'm not sure what you are trying to achieve here, but look at this:</p>
<pre><code>word = input('word -> ')
b1 = []
# Iterate over letters in a word:
for letter in word:
b1.append(letter)
print(b1)
b2 = []
# Use `enumerate` if you need to have an index:
for i, letter in enumerate(word):
# `i` here is your `count` basically
b2.append(letter)
print(b2)
# Make a list of letters using `list` constructor:
b3 = list(word)
print(b3)
assert b1 == b2 == b3
</code></pre>
| 2 | 2016-10-01T19:26:50Z | [
"python",
"indexing",
"syntax",
"range"
]
|
Executeable Tkinter plus selenium | 39,810,918 | <p>WEll , i am getting hard to make this works, i have tried Cx_freeze</p>
<p>but its showing this:</p>
<p><a href="http://i.stack.imgur.com/8zXWE.png" rel="nofollow"><img src="http://i.stack.imgur.com/8zXWE.png" alt="With Cx_freeze"></a></p>
<p>This is the Setup:</p>
<pre><code>import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter","schedule","selenium"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "Yad2AutoAd",
version = "0.1",
description = "Auto Jumper for Yad2 Advertises",
options = {"build_exe": build_exe_options},
executables = [Executable("Yad2Ads.py", base=base)])
</code></pre>
<p>and with pyinstaller its showing this:</p>
<pre><code> Traceback (most recent call last):
File "site-packages\selenium\webdriver\common\service.py", line 64, in start
File "subprocess.py", line 859, in __init__
File "subprocess.py", line 1114, in _execute_child
FileNotFoundError: [WinError 2] \u200f\u200f××ער×ת ××× ×פשר×ת ××תר ×ת ××§×××¥ שצ××
×
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Yad2Adv.py", line 9, in <module>
File "site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __ini
t__
File "site-packages\selenium\webdriver\common\service.py", line 71, in start
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executabl
e needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chrome
driver/home
Failed to execute script Yad2Adv
Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.chrom
e.service.Service object at 0x0000000002C3D668>>
Traceback (most recent call last):
File "site-packages\selenium\webdriver\common\service.py", line 163, in __del_
_
File "site-packages\selenium\webdriver\common\service.py", line 135, in stop
AttributeError: 'Service' object has no attribute 'process'
</code></pre>
<p>Well its kind a the same error i think , what should i do i tried to insert the selenium folder into the same folder with the exe file.
I think this post is pretty detailed, and sorry if looks like a long script.
just want to make sure you guys understand this problem.
Thanks in advance!
P.S
The Code for Initialise webdriver:</p>
<pre><code>driver = webdriver.PhantomJS()
</code></pre>
<p>and the PhantomJs.exe is in the same folder as the project.</p>
| 0 | 2016-10-01T19:58:35Z | 39,823,365 | <p>Well after Saurabh Gaur told me if i was initialising the web driver, have re-thinking about it again and search for it , well you have to make executeable-path
for you webdriver for example:</p>
<pre><code>phantomdriver = r"C:\Users\Bar\PycharmProjects\Yad2FinalFix\phantomjs.exe"
driver = webdriver.PhantomJS(executable_path=phantomdriver)
</code></pre>
<p>this solved my problem, thank you Saurabh Gaur you have saved me many times!</p>
| 0 | 2016-10-03T01:19:06Z | [
"python",
"selenium",
"executable",
"pyinstaller",
"cx-freeze"
]
|
behavior of machine epsilon in simple arithmetic | 39,811,087 | <p>*using python x2</p>
<p>my homework asks me to set: eps = 2.**-52
the output of eps then becomes: 2.2204e-16</p>
<p>(1. + eps - 1. = 2.2204e-16) # expected</p>
<p>(1. + eps/2. - 1. = 0.0) # what?</p>
<p>My homework simply asks me what happened in the second equation. I've experimented with different sigfigs for the floats and reviewed resources but still don't understand. Any help much appreciated!</p>
| -3 | 2016-10-01T20:20:14Z | 39,811,170 | <p><code>(1 + eps/2.0) - 1 = 0.0</code> because <code>eps/2.0</code> is too small to be properly represented alongside 1 (it as called <em>absorption</em> or <em>cancellation</em>)</p>
<p>On a typical machine running Python, there are 53 bits of precision available for a Python float. If you try to go further, Python will eliminate the smallest part so the number can be properly represented.</p>
<p>In that case, 1 "wins" (1 "absorbs" <code>eps/2</code>), then substract to 1 and you get 0.</p>
| 0 | 2016-10-01T20:30:25Z | [
"python",
"python-2.7",
"floating-point"
]
|
issues importing a script | 39,811,120 | <p>Hello i have been working on this simple script and i have run into some rather annoying problems that i can not fix myself with the def. and import function it just won't work. here is the main script </p>
<pre><code>import time # This part import the time module
import script2 # This part imports the second script
def main():
print("This program is a calaulater have fun using it")
name = input("What is your name? ")
print("Hello",name)
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
script2 test()
if q1 == "no":
print("That is fine",name,"Hope to see you soon bye")
time.sleep(2)
if __name__ == '__main__':
try:
main()
except Exception as e:
time.sleep(10)
</code></pre>
<p>And then the second script is called script2 here is that script as well
import time</p>
<pre><code>def test():
print("You would like to do some maths i hear.")
print("you have some truely wonderfull option please chooice form the list below.")
</code></pre>
<p>That is my script currently but it deos not work please help me.</p>
| -1 | 2016-10-01T20:24:40Z | 39,811,224 | <p>This is an error:</p>
<pre><code>def main():
#...
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
# ...
</code></pre>
<p>Firstly, the <code>q1</code> in <code>main()</code> and the <code>q1</code> outside are not the same variable.</p>
<p>Secondly, <code>if q1 == "yes":</code> is executed before <code>q1 = input(...)</code>, because <code>main()</code> was not called yet.</p>
<p>The solution would be to return the <code>q1</code> value from main and only then use it:</p>
<pre><code>def main():
# ...
return q1
if __name__ == '__main__':
# ...
result_from_main = main()
if result_from_main == "yes":
# ...
</code></pre>
<p>Of course, the all names are completely messed up now, but that is a different problem...</p>
| 0 | 2016-10-01T20:37:29Z | [
"python",
"function",
"python-import"
]
|
issues importing a script | 39,811,120 | <p>Hello i have been working on this simple script and i have run into some rather annoying problems that i can not fix myself with the def. and import function it just won't work. here is the main script </p>
<pre><code>import time # This part import the time module
import script2 # This part imports the second script
def main():
print("This program is a calaulater have fun using it")
name = input("What is your name? ")
print("Hello",name)
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
script2 test()
if q1 == "no":
print("That is fine",name,"Hope to see you soon bye")
time.sleep(2)
if __name__ == '__main__':
try:
main()
except Exception as e:
time.sleep(10)
</code></pre>
<p>And then the second script is called script2 here is that script as well
import time</p>
<pre><code>def test():
print("You would like to do some maths i hear.")
print("you have some truely wonderfull option please chooice form the list below.")
</code></pre>
<p>That is my script currently but it deos not work please help me.</p>
| -1 | 2016-10-01T20:24:40Z | 39,811,267 | <p>Firstly your indentation doesn't seems to be right. As zvone stated. Secondly you should use script2.test() instead of script2 test(). A functional code is</p>
<pre><code>import time # This part import the time module
import script2 # This part imports the second script
def main():
print("This program is a calaulater have fun using it")
name = input("What is your name? ")
print("Hello",name)
q1 = input("Would you like to some maths today? ")
if q1 == "yes":
script2.test()
if q1 == "no":
print("That is fine",name,"Hope to see you soon bye")
time.sleep(2)
if __name__ == '__main__':
try:
main()
except Exception as e:
time.sleep(10)
</code></pre>
| 0 | 2016-10-01T20:41:42Z | [
"python",
"function",
"python-import"
]
|
How to add url file to zip | 39,811,192 | <p>I have a zip file with the following structure:</p>
<pre><code>my_zip.zip
|-file1.txt
|-folder1/
|-file2.txt
</code></pre>
<p>I want to add <code>some_file</code> <strong>from url</strong> to the <code>folder1</code>. I know that I can do something like:</p>
<pre><code>>>> import zipfile
>>> z = zipfile.ZipFile("my_zip.zip", "w")
>>> z.write("some_file")
</code></pre>
<p>But, there are two issues:</p>
<ul>
<li>How to add the <code>some_file</code> to that specific <code>folder1</code>?</li>
<li>Should I download the <code>some_file</code> to my PC and next use <code>z.write('path/to_my/local/some_file')</code>? There is no way to do it directly from url to the zip?</li>
</ul>
| 0 | 2016-10-01T20:33:42Z | 39,811,408 | <p>Use <a href="https://docs.python.org/3.7/library/zipfile.html#zipfile.ZipFile.writestr" rel="nofollow"><code>ZipFile.writestr(<em>arcname</em>, <em>data</em>)</code></a>.</p>
<p>To write to a folder in the zipfile, you just write the foldername as if you were writing to a folder in a folder (So <code>folder1/some_file</code>).</p>
<pre><code>import urllib.request
import zipfile
z = zipfile.ZipFile("my_zip.zip", "w")
page = urllib.request.urlopen('http://example.com/') # Change to website
z.writestr('folder1/some_file', page.read())
</code></pre>
| 1 | 2016-10-01T20:58:06Z | [
"python",
"python-3.x",
"url",
"zip"
]
|
KNeighborsClassifier .predict() function doesn't work | 39,811,270 | <p>i am working with KNeighborsClassifier algorithm from scikit-learn library in Python. I followed basic instructions e.g. split my data and labels into training and test data, then trained my model on a training data. Now I am trying to predict accuracy of testing data but get an error. Here is my code:</p>
<pre><code>from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
data_train, data_test, label_train, label_test = train_test_split(df, labels,
test_size=0.2,
random_state=7)
mod = KNeighborsClassifier(n_neighbors=4)
mod.fit(data_train, label_train)
predictions = mod.predict(data_test)
print accuracy_score(label_train, predictions)
</code></pre>
<p>The error I get:</p>
<pre><code>ValueError: Found arrays with inconsistent numbers of samples: [140 558]
</code></pre>
<p>140 is the portion of training data and 558 is the test data based on the test_size=0.2 (my data set is 698 samples). I verified that labels and data sets are of the same size 698. However, I get this error which is basically trying to compare test data and training data sets.</p>
<p>Does anyone knows what is wrong here? What should I use to train my model against to and what should I use to predict the score?</p>
<p>Thanks!</p>
| 1 | 2016-10-01T20:42:00Z | 39,811,525 | <p>Did you tried to solve your issue via the following question ?</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/30813044/sklearn-found-arrays-with-inconsistent-numbers-of-samples-when-calling-linearre">sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()</a></p>
</blockquote>
| 1 | 2016-10-01T21:13:34Z | [
"python",
"pandas",
"machine-learning"
]
|
KNeighborsClassifier .predict() function doesn't work | 39,811,270 | <p>i am working with KNeighborsClassifier algorithm from scikit-learn library in Python. I followed basic instructions e.g. split my data and labels into training and test data, then trained my model on a training data. Now I am trying to predict accuracy of testing data but get an error. Here is my code:</p>
<pre><code>from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
data_train, data_test, label_train, label_test = train_test_split(df, labels,
test_size=0.2,
random_state=7)
mod = KNeighborsClassifier(n_neighbors=4)
mod.fit(data_train, label_train)
predictions = mod.predict(data_test)
print accuracy_score(label_train, predictions)
</code></pre>
<p>The error I get:</p>
<pre><code>ValueError: Found arrays with inconsistent numbers of samples: [140 558]
</code></pre>
<p>140 is the portion of training data and 558 is the test data based on the test_size=0.2 (my data set is 698 samples). I verified that labels and data sets are of the same size 698. However, I get this error which is basically trying to compare test data and training data sets.</p>
<p>Does anyone knows what is wrong here? What should I use to train my model against to and what should I use to predict the score?</p>
<p>Thanks!</p>
| 1 | 2016-10-01T20:42:00Z | 39,812,834 | <p>You should calculate the <code>accuracy_score</code> with <code>label_test</code>, not <code>label_train</code>. You want to compare the actual labels of the test set, <code>label_test</code>, to the predictions from your model, <code>predictions</code>, for the test set.</p>
| 1 | 2016-10-02T00:44:02Z | [
"python",
"pandas",
"machine-learning"
]
|
Python alphabet shifting string | 39,811,337 | <p>i have tried but can't seem to find my mistake in my code.
My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p>
<p>Could anyone tell me what i have done wrong or have forgotten?</p>
<pre><code>letter = input("type something")
shift = int(input("type how many shifts"))
if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
a = ord(letter) + shift
b = chr(a)
print(b)
else:
print(letter)
</code></pre>
<p>EDIT: thanks for the == replacement for in! Does someone know why using more than one character in letter gives the same print?(Desired output: when i put in abc and 1 i want it to print bcd)</p>
| 0 | 2016-10-01T20:48:41Z | 39,811,383 | <p>I suppose you want to shift the letters so if the input letter is 'a' and shift is 3, then the output should be 'd'.</p>
<p>In that case replace</p>
<pre><code>if letter == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
</code></pre>
<p>with</p>
<pre><code>if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
</code></pre>
<p>Or better yet as Tempux suggested you can use </p>
<pre><code>if letter.isalpha()
</code></pre>
<p>If you want to shift multple letters you need to loop across each character. Try the following code for multiple letters</p>
<pre><code>letter = input("type something")
shift = int(input("type how many shifts"))
s = ""
for l in letter:
if l.isalpha():
a = ord(l) + shift
s += chr(a)
else:
s += l
print(s)
</code></pre>
| 0 | 2016-10-01T20:54:53Z | [
"python",
"algorithm"
]
|
Python alphabet shifting string | 39,811,337 | <p>i have tried but can't seem to find my mistake in my code.
My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p>
<p>Could anyone tell me what i have done wrong or have forgotten?</p>
<pre><code>letter = input("type something")
shift = int(input("type how many shifts"))
if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
a = ord(letter) + shift
b = chr(a)
print(b)
else:
print(letter)
</code></pre>
<p>EDIT: thanks for the == replacement for in! Does someone know why using more than one character in letter gives the same print?(Desired output: when i put in abc and 1 i want it to print bcd)</p>
| 0 | 2016-10-01T20:48:41Z | 39,811,389 | <p>You compare letter with list, but i think you want to check for contain letter in list, so you should just replace <code>==</code> to <code>in</code></p>
| 0 | 2016-10-01T20:55:50Z | [
"python",
"algorithm"
]
|
Python alphabet shifting string | 39,811,337 | <p>i have tried but can't seem to find my mistake in my code.
My code is suppose to switch all the alphabetic characters (like a/aa/A/AA) and do nothing with the rest but when i run the code it doesn't give an error yet do what i want.</p>
<p>Could anyone tell me what i have done wrong or have forgotten?</p>
<pre><code>letter = input("type something")
shift = int(input("type how many shifts"))
if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
a = ord(letter) + shift
b = chr(a)
print(b)
else:
print(letter)
</code></pre>
<p>EDIT: thanks for the == replacement for in! Does someone know why using more than one character in letter gives the same print?(Desired output: when i put in abc and 1 i want it to print bcd)</p>
| 0 | 2016-10-01T20:48:41Z | 39,811,481 | <p>From the looks of it, I'd say you're more after something like this:</p>
<pre><code>import string
text = input("type something> ")
shift = int(input("enter number of shifts> "))
for letter in text:
index = ord(letter) - ord('a') + shift
print(string.ascii_letters[index % len(string.ascii_letters)])
</code></pre>
| 0 | 2016-10-01T21:06:38Z | [
"python",
"algorithm"
]
|
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other | 39,811,423 | <p>So I have this homework assignment and seem to be stuck on this question.</p>
<p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p>
<p>Example:</p>
<pre><code>>>>threePairs([5, 6, 3, 2, 1, 4])
False
>>>threePairs([1, 1, 2, 2, 2, 2])
True
</code></pre>
<p>I've tried using indexes and I don't really know how to slice so I'm stuck in figuring out how I make those pairs equal to each other in the condition so it is True.</p>
<p>This is what I had previous to deleting it and trying again.</p>
<pre><code>def threePairs(aList):
if [0] == [1] and [2] == [3] and [4] == [5]:
return True
else:
return False
</code></pre>
| 0 | 2016-10-01T20:59:26Z | 39,811,465 | <p>You could <code>zip</code> the a sliced list with itself one position ahead, with steps equal to <code>2</code> to get adjacent elements. Then feed that to <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> with the condition you need:</p>
<pre><code>def threePairs(l):
return all(i == j for i,j in zip(l[::2], l[1::2]))
</code></pre>
<p><a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> simply takes an element from each of the iterables supplied and returns it as a tuple until one of the sequences is exhausted. </p>
<p>So, for example, if <code>l = [5, 6, 3, 2, 1, 4]</code> and <code>zip</code> is used with <code>zip(l[::2], l[1::2])</code> you'd have:</p>
<pre><code># l[::2] = [5, 3, 1]
# l[1::2] = [6, 2, 4]
print(list(zip(l[::2], l[1::2])))
[(5, 6), (3, 2), (1, 4)]
</code></pre>
| 2 | 2016-10-01T21:04:31Z | [
"python",
"list",
"python-3.x",
"pair"
]
|
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other | 39,811,423 | <p>So I have this homework assignment and seem to be stuck on this question.</p>
<p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p>
<p>Example:</p>
<pre><code>>>>threePairs([5, 6, 3, 2, 1, 4])
False
>>>threePairs([1, 1, 2, 2, 2, 2])
True
</code></pre>
<p>I've tried using indexes and I don't really know how to slice so I'm stuck in figuring out how I make those pairs equal to each other in the condition so it is True.</p>
<p>This is what I had previous to deleting it and trying again.</p>
<pre><code>def threePairs(aList):
if [0] == [1] and [2] == [3] and [4] == [5]:
return True
else:
return False
</code></pre>
| 0 | 2016-10-01T20:59:26Z | 39,811,471 | <p>How about making a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter()</code></a> and check how many "pairs" you've got:</p>
<pre><code>In [1]: from collections import Counter
In [2]: def has_pairs(l, n):
return sum(value / 2 for value in Counter(l).values()
if value % 2 == 0) == n
In [3]: has_pairs([5, 6, 3, 2, 1, 4], 3)
Out[3]: False
In [4]: has_pairs([1, 1, 2, 2, 2, 2], 3)
Out[4]: True
</code></pre>
<p>Works for a list with any length and any input number of pairs.</p>
<p>Instead of using a <code>sum()</code> to count all the pairs, you can iterate over the counter one value at a time and have an <em>early exit</em> if number of pairs reaches or exceeds the input number of pairs.</p>
| 2 | 2016-10-01T21:05:05Z | [
"python",
"list",
"python-3.x",
"pair"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.