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 |
---|---|---|---|---|---|---|---|---|---|
recursion Think Python 2 exercise 5.5 | 39,814,341 | <p>This question regarding exercise 5.5 from Think Python 2 has been <a href="https://stackoverflow.com/questions/21048933/understanding-recursion-in-python-2-think-python-exercise-5">asked and answered already</a>, but I still don't understand how this function works. Here's the function in question:</p>
<pre><code>def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
t.rt(2*angle)
draw(t, length, n-1)
t.lt(angle)
t.bk(length*n)
</code></pre>
<p>I see a recursive loop here:</p>
<pre><code>def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
</code></pre>
<p>After the function calls itself a sufficient number of times to cause n == 0, how does it move on to the next step, namely t.rt(2*angle)? Once n == 0, shouldn't the function return None and simply end? If not, where is returning to? The same thing happens again the next time it calls itself, and then the function continues to perform work long after the state n == 0 has been satisfied (twice!). I'm obviously missing a key concept here and would appreciate any light anyone can shed on this topic. Thanks in advance~</p>
| 1 | 2016-10-02T06:07:51Z | 39,975,543 | <p>I've posted a picture explaining this in the following <a href="https://stackoverflow.com/questions/21048933/understanding-recursion-in-python-2-think-python-exercise-5/39974778#39974778">question</a> , for a fast navigation here's my picture : </p>
<p><a href="http://i.stack.imgur.com/rIfDL.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/rIfDL.jpg" alt="Explanation"></a></p>
| 1 | 2016-10-11T10:44:24Z | [
"python",
"python-3.x",
"recursion"
]
|
Why is this python web scraping code using requests package not working? | 39,814,352 | <pre><code>import lxml.html
import requests
l1=[]
headers= {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
r = requests.get('http://www.naukri.com/jobs-by-location', headers=headers)
html = r.content
root = lxml.html.fromstring(html)
urls = root.xpath('//div[4]/div/div[1]/div/a/@href') #This xpath should give the list of cities(their links)
l1.extend(urls)
</code></pre>
<p>This python code is meant to scrape the list of job cities(their 'a href' tags) and store it in list l1. But here I am getting a blank list. The same xpath is working on Chrome console but it's not working in this code. Due to that I added headers to make my code act as a browser but still it's not working.. </p>
<p><a href="http://i.stack.imgur.com/Xx1xW.jpg" rel="nofollow">http://i.stack.imgur.com/Xx1xW.jpg</a></p>
| -2 | 2016-10-02T06:09:16Z | 39,819,409 | <p>I tried to achieve the same using Selenium WebDriver, and this also succeeds. When this succeeds from your computer, it might be a problem in one of the used libraries.</p>
<pre><code>import selenium.webdriver as driver
browser = driver.Chrome()
browser.get("http://www.naukri.com/jobs-by-location")
links = browser.find_elements_by_xpath("//div[4]/div/div[1]/div/a")
for link in links:
href = link.get_attribute("href")
print(href)
browser.quit()
</code></pre>
| -1 | 2016-10-02T16:57:27Z | [
"python",
"python-2.7",
"web-scraping",
"python-requests"
]
|
Saving full array as txt in python | 39,814,403 | <p>I at the moment trying to sample an audio files and store the information from the sampling into to txt file. </p>
<p>The sampling is done using the <a href="https://github.com/librosa/librosa" rel="nofollow">librosa</a>. </p>
<p>The problem occurs when i save it to a file...
The array doesn't get fully saved, I am only able to view a few of the sampling point, and the rest is dotted. </p>
<p>example: </p>
<pre><code>22050.000
[ -8.61534572e-05 -1.64340396e-04 -8.03423245e-05 ..., -1.40137578e-04
-3.71412549e-04 -5.04361582e-04]
</code></pre>
<p>This is how i am doing it:</p>
<pre><code>import tensorflow as tf
import numpy as np
import librosa
from os import listdir
from os.path import isfile, join
import os
path_train = "/home/k/kaldi-trunk/egs/start/s5/data/train"
path_test = "/home/k/kaldi-trunk/egs/start/s5/data/test"
dnn_train = "/home/k/kaldi-trunk/dnn/train/"
dnn_test = "/home/k/kaldi-trunk/dnn/test/"
dnn = "/home/k/kaldi-trunk/dnn/"
path = "/home/k/kaldi-trunk/egs/start/s5/data/"
train_filelist = path_train+"/wav_train.txt"
test_filelist = path_test+"/wav_test.txt"
files_train = [f for f in listdir(dnn_train) if isfile(join(dnn_train, f))]
files_test = [f for f in listdir(dnn_test) if isfile(join(dnn_test, f))]
os.chdir(dnn_train)
train = []
test = []
for line in files_train:
#print dnn_train+line
y,sr=librosa.core.load(dnn_train+line)
train.append(y.tolist())
print "Train done!"
for line in files_test:
x,sr=librosa.core.load(dnn_test+line)
test.append(x.tolist())
print "Test done!"
os.chdir(dnn)
with open('sample_test.txt','wb') as f:
np.savetxt(f,test)
with open('sample_train.txt','wb') as f:
np.savetxt(f,train)
</code></pre>
<p>anything that could explain why i can't save all the sample point rather than a few?</p>
<p>desired output is two seperate files [sample_test,sample_train]
in which each line contain a list.
each entry in the list should contain as many decimals, which is why either it would be appreciated having it stored as either float or double. </p>
| 1 | 2016-10-02T06:17:45Z | 39,817,377 | <p>The argument to <code>np.savetxt</code> should be an array.</p>
<p>Add <code>test = np.array(test)</code> before saving the data.</p>
<ol>
<li>This will give an error if the data can not be converted to an array.</li>
<li>You can print, for diagnosis, the shape of the array: <code>print test.shape</code></li>
</ol>
<p>Your output suggests that you have a float and then a list in your data, that are printed instead of the content of a NumPy array.</p>
| 0 | 2016-10-02T13:12:18Z | [
"python",
"numpy",
"librosa"
]
|
pandas, apply with args which are dataframe row entries | 39,814,416 | <p>I have a pandas dataframe 'df' with two columns 'A' and 'B', I have a function with two arguments</p>
<pre><code>def myfunction(B, A):
# do something here to get the result
return result
</code></pre>
<p>and I would like to apply it row-by-row to df using the 'apply' function</p>
<pre><code>df['C'] = df['B'].apply(myfunction, args=(df['A'],))
</code></pre>
<p>but I get the error</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>whats happening here, it seems it takes df['A'] as the whole series! not just the row entry from that series as required.</p>
| 2 | 2016-10-02T06:19:35Z | 39,814,457 | <p>I think you need:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6]})
print (df)
A B
0 1 4
1 2 5
2 3 6
def myfunction(B, A):
#some staff
result = B + A
# do something here to get the result
return result
df['C'] = df.apply(lambda x: myfunction(x.B, x.A), axis=1)
print (df)
A B C
0 1 4 5
1 2 5 7
2 3 6 9
</code></pre>
<p>Or:</p>
<pre><code>def myfunction(x):
result = x.B + x.A
# do something here to get the result
return result
df['C'] = df.apply(myfunction, axis=1)
print (df)
A B C
0 1 4 5
1 2 5 7
2 3 6 9
</code></pre>
| 3 | 2016-10-02T06:27:50Z | [
"python",
"pandas",
"apply",
"args"
]
|
Sorting by value and printing both, key and value properly. PYTHON | 39,814,485 | <p><strong>Question 1</strong>: How Can I add to dictionary with asking user, I.E. Input ("Write Runners name"), Input ("Write elapsed time!")</p>
<p><strong>Question 2</strong>:
I would like to make the output like this.
Underneath my Code .... Drafts :)</p>
<pre><code>import operator
</code></pre>
<p><strong>Dictionary</strong></p>
<pre><code>runners = {"John": 9, "Mike": 2, "Venera": 4}
</code></pre>
<p>Output:</p>
<pre><code>1st. "Entered runner name ", came at, "input time"
2nd. "Entered runner name ", came at, "input time"
3rd. "Entered runner name ", came at, "input time"
</code></pre>
<p>Below it sorts from least to more</p>
<pre><code>s = sorted(runners.items(), key=operator.itemgetter(1))
print(s)
</code></pre>
<p>Example will give you full understanding my problem. So, example code is this, I just want to make it easier.</p>
<pre><code>names =[]
array_times = []
</code></pre>
<p>Looping it questions, to not write bunch of inputs
for i in range(3):</p>
<pre><code> name=input("Please write the name of Runner!")
#Appending name to the array name above!
names.append(name)
time_elapsed = float(input("Please write the time you spend!"))
#Appending it to the array above!
array_times.append(time_elapsed)
# Just to make it easier to understand, assigning the values in arrays above to variables.
runner1= names[0]
runner2=names[1]
runner3=names[2]
time1=array_times[0]
time2=array_times[1]
time3=array_times[2]
</code></pre>
<p>Writing if-else statement to check which one is which place. </p>
<pre><code>if time1<time2 and time1<time3 and time2<time3:#First winner, second in second, third is last.
print (runner1, "wins! His time is", time1, runner2, "is second place. His time is", time2, "and ", runner3, "is third place. his time is ", time3)
elif time2<time1 and time2<time3 and time1<time3:#Second winner, first in second place, third is last.
print (runner2, "wins! His time is", time2, runner1, "is second place. His time is", time1, "and ", runner3, "is third place. his time is ", time3)
elif time3<time1 and time3<time2 and time1<time2:#Third winner, First is second, second is last.
print (runner3, "wins! His time is", time3, runner1, "is second place. His timae is", time1, "and ", runner2, "is third place. his time is ", time2)
elif time3<time1 and time3<time2 and time2<time1:#Third winner, second is second, first is last.
print (runner3, "wins! His time is", time3, runner2, "is second place. His time is", time2, "and ", runner1, "is third place. his time is ", time1)
elif time2<time1 and time2<time3 and time3<time1:#Third winner, second is second, first is last.
print (runner2, "wins! His time is", time2, runner3, "is second place. His time is", time
</code></pre>
| -2 | 2016-10-02T06:34:11Z | 39,814,767 | <p>as mentioned in the python <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">doc</a></p>
<blockquote>
<p>It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)</p>
</blockquote>
<p>Use <a href="https://docs.python.org/3/library/collections.html#ordereddict-objects" rel="nofollow">OrderedDict</a></p>
<pre><code>from collections import OrderedDict
no_of_runners = int(input())
runners = dict()
for i in range(no_of_runners):
name = input()
time = float(input())
runners[name] = time
sorted_runners = OrderedDict(sorted(runners.items(), key=lambda t: t[1]))
runners_list = [(i,j) for i,j in sorted_runners.items()]
print (runners_list[0][0], "wins! His time is", runners_list[0][1], runners_list[1][0], "is in second place. His time is", runners_list[1][1], "and ", runners_list[2][0], "is in third place. his time is ", runners_list[2][1])
</code></pre>
| 0 | 2016-10-02T07:20:51Z | [
"python",
"sorting",
"dictionary"
]
|
Sorting by value and printing both, key and value properly. PYTHON | 39,814,485 | <p><strong>Question 1</strong>: How Can I add to dictionary with asking user, I.E. Input ("Write Runners name"), Input ("Write elapsed time!")</p>
<p><strong>Question 2</strong>:
I would like to make the output like this.
Underneath my Code .... Drafts :)</p>
<pre><code>import operator
</code></pre>
<p><strong>Dictionary</strong></p>
<pre><code>runners = {"John": 9, "Mike": 2, "Venera": 4}
</code></pre>
<p>Output:</p>
<pre><code>1st. "Entered runner name ", came at, "input time"
2nd. "Entered runner name ", came at, "input time"
3rd. "Entered runner name ", came at, "input time"
</code></pre>
<p>Below it sorts from least to more</p>
<pre><code>s = sorted(runners.items(), key=operator.itemgetter(1))
print(s)
</code></pre>
<p>Example will give you full understanding my problem. So, example code is this, I just want to make it easier.</p>
<pre><code>names =[]
array_times = []
</code></pre>
<p>Looping it questions, to not write bunch of inputs
for i in range(3):</p>
<pre><code> name=input("Please write the name of Runner!")
#Appending name to the array name above!
names.append(name)
time_elapsed = float(input("Please write the time you spend!"))
#Appending it to the array above!
array_times.append(time_elapsed)
# Just to make it easier to understand, assigning the values in arrays above to variables.
runner1= names[0]
runner2=names[1]
runner3=names[2]
time1=array_times[0]
time2=array_times[1]
time3=array_times[2]
</code></pre>
<p>Writing if-else statement to check which one is which place. </p>
<pre><code>if time1<time2 and time1<time3 and time2<time3:#First winner, second in second, third is last.
print (runner1, "wins! His time is", time1, runner2, "is second place. His time is", time2, "and ", runner3, "is third place. his time is ", time3)
elif time2<time1 and time2<time3 and time1<time3:#Second winner, first in second place, third is last.
print (runner2, "wins! His time is", time2, runner1, "is second place. His time is", time1, "and ", runner3, "is third place. his time is ", time3)
elif time3<time1 and time3<time2 and time1<time2:#Third winner, First is second, second is last.
print (runner3, "wins! His time is", time3, runner1, "is second place. His timae is", time1, "and ", runner2, "is third place. his time is ", time2)
elif time3<time1 and time3<time2 and time2<time1:#Third winner, second is second, first is last.
print (runner3, "wins! His time is", time3, runner2, "is second place. His time is", time2, "and ", runner1, "is third place. his time is ", time1)
elif time2<time1 and time2<time3 and time3<time1:#Third winner, second is second, first is last.
print (runner2, "wins! His time is", time2, runner3, "is second place. His time is", time
</code></pre>
| -2 | 2016-10-02T06:34:11Z | 39,814,899 | <p>python3</p>
<pre><code>import operator
runners = {}
for x in range(3):
name = input("name: ")
elapsed_time = int(input("time: "))
runners[name] = elapsed_time
templates = [
"{name} wins! His time is {time}.",
"{name} is in second place. His time is {time}",
"and {name} is in third place. His time is {time}"
]
for idx, (name, elapsed_time) in enumerate(sorted(runners.items(), key=operator.itemgetter(1))):
print(templates[idx].format(name=name, time=elapsed_time), end=" ")
print()
</code></pre>
| 0 | 2016-10-02T07:40:29Z | [
"python",
"sorting",
"dictionary"
]
|
Sorting by value and printing both, key and value properly. PYTHON | 39,814,485 | <p><strong>Question 1</strong>: How Can I add to dictionary with asking user, I.E. Input ("Write Runners name"), Input ("Write elapsed time!")</p>
<p><strong>Question 2</strong>:
I would like to make the output like this.
Underneath my Code .... Drafts :)</p>
<pre><code>import operator
</code></pre>
<p><strong>Dictionary</strong></p>
<pre><code>runners = {"John": 9, "Mike": 2, "Venera": 4}
</code></pre>
<p>Output:</p>
<pre><code>1st. "Entered runner name ", came at, "input time"
2nd. "Entered runner name ", came at, "input time"
3rd. "Entered runner name ", came at, "input time"
</code></pre>
<p>Below it sorts from least to more</p>
<pre><code>s = sorted(runners.items(), key=operator.itemgetter(1))
print(s)
</code></pre>
<p>Example will give you full understanding my problem. So, example code is this, I just want to make it easier.</p>
<pre><code>names =[]
array_times = []
</code></pre>
<p>Looping it questions, to not write bunch of inputs
for i in range(3):</p>
<pre><code> name=input("Please write the name of Runner!")
#Appending name to the array name above!
names.append(name)
time_elapsed = float(input("Please write the time you spend!"))
#Appending it to the array above!
array_times.append(time_elapsed)
# Just to make it easier to understand, assigning the values in arrays above to variables.
runner1= names[0]
runner2=names[1]
runner3=names[2]
time1=array_times[0]
time2=array_times[1]
time3=array_times[2]
</code></pre>
<p>Writing if-else statement to check which one is which place. </p>
<pre><code>if time1<time2 and time1<time3 and time2<time3:#First winner, second in second, third is last.
print (runner1, "wins! His time is", time1, runner2, "is second place. His time is", time2, "and ", runner3, "is third place. his time is ", time3)
elif time2<time1 and time2<time3 and time1<time3:#Second winner, first in second place, third is last.
print (runner2, "wins! His time is", time2, runner1, "is second place. His time is", time1, "and ", runner3, "is third place. his time is ", time3)
elif time3<time1 and time3<time2 and time1<time2:#Third winner, First is second, second is last.
print (runner3, "wins! His time is", time3, runner1, "is second place. His timae is", time1, "and ", runner2, "is third place. his time is ", time2)
elif time3<time1 and time3<time2 and time2<time1:#Third winner, second is second, first is last.
print (runner3, "wins! His time is", time3, runner2, "is second place. His time is", time2, "and ", runner1, "is third place. his time is ", time1)
elif time2<time1 and time2<time3 and time3<time1:#Third winner, second is second, first is last.
print (runner2, "wins! His time is", time2, runner3, "is second place. His time is", time
</code></pre>
| -2 | 2016-10-02T06:34:11Z | 39,814,980 | <p>Python 2.7</p>
<pre><code>runners={}
for i in range(3):
name=raw_input("Please write the name of Runner!")
time_elapsed = float(raw_input("Please write the time you spend!"))
runners[name]=time_elapsed
position=[]
for name, elapsed in sorted(runners.iteritems(), key=lambda elapsed: elapsed[1]):
position.append((name, elapsed))
print position[0][0], "wins! His time is", position[0][1],'\n', position[1][0], "is second. His time is", position[1][1], "\n", position[2][0], "is third. His time is ", position[2][1]
</code></pre>
<p>Python3</p>
<pre><code>runners={}
for i in range(3):
name=input("Please write the name of Runner!")
time_elapsed = float(input("Please write the time you spend!"))
runners[name]=time_elapsed
position=[]
for name, elapsed in sorted(runners.items(), key=lambda elapsed: elapsed[1]):
position.append((name, elapsed))
print ('\n',position[0][0], "wins! His time is", position[0][1],'\n', position[1][0], "is second. His time is", position[1][1], "\n", position[2][0], "is third. His time is ", position[2][1])
</code></pre>
| 0 | 2016-10-02T07:54:09Z | [
"python",
"sorting",
"dictionary"
]
|
How do you know when to close a file in python? | 39,814,679 | <pre><code>from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
#above is the original code.
</code></pre>
<p>He closes the files above. But then in the- common student questions- there is this. </p>
<p>Q. When I try to make this script shorter I get an error when I close the files at the end.</p>
<p>A. You probably did something like this, indata = open(from_file).read(), which means you don't need to then do in_file.close() when you reach the end of the script. It should already be closed by Python once that one line runs.</p>
<p>so,how do you know when to close the file and when not to?</p>
<p>Thank you everyone,i got it! :)</p>
| 0 | 2016-10-02T07:07:36Z | 39,814,903 | <p>When to close a file? always - once you are finished working on it. Otherwise it will just hog memory.</p>
| 0 | 2016-10-02T07:40:43Z | [
"python"
]
|
How do you know when to close a file in python? | 39,814,679 | <pre><code>from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
#above is the original code.
</code></pre>
<p>He closes the files above. But then in the- common student questions- there is this. </p>
<p>Q. When I try to make this script shorter I get an error when I close the files at the end.</p>
<p>A. You probably did something like this, indata = open(from_file).read(), which means you don't need to then do in_file.close() when you reach the end of the script. It should already be closed by Python once that one line runs.</p>
<p>so,how do you know when to close the file and when not to?</p>
<p>Thank you everyone,i got it! :)</p>
| 0 | 2016-10-02T07:07:36Z | 39,815,001 | <p>From <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">methods-of-file-objects</a>. </p>
<blockquote>
<blockquote>
<blockquote>
<p>It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite
finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:</p>
</blockquote>
</blockquote>
</blockquote>
<pre><code>>>> with open('workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
</code></pre>
| 3 | 2016-10-02T07:57:16Z | [
"python"
]
|
Twisted python to read from kafka and write to elasticsearch | 39,814,711 | <p>I am new to Twisted, this is my first program.</p>
<p>I can not find a way to use the KafkaConsumer from the kafka-python library and use treq to trigger a post request to elasticsearch.</p>
<p>I could decompose the problem in small pieces:
Create an kafka consumer iterator and read data from it (the topic may be huge)</p>
<pre><code>def consumeKafka():
consumer = KafkaConsumer(bootstrap_servers="kafka:9092", auto_offset_reset='earliest')
consumer.subscribe(['kafkapipeline'])
for v in consumer:
v.value
</code></pre>
<p>post to elasticsearch using treq</p>
<pre><code>def post(self):
d = treq.post('http://es:9200/pro/pr/', self.data)
d.addCallbacks(lambda x: print(x), lambda x: print("error %s " % x))
</code></pre>
<p>start the reactor</p>
<pre><code>from twisted.internet import reactor
reactor.callWhenRunning(consumeKafka)
reactor.run()
</code></pre>
<p>Any idea how to make this work?</p>
| 0 | 2016-10-02T07:12:34Z | 39,820,333 | <p>I don't use Kafka at all, so I'm not sure if this will work for you. Also, I'm assuming your having trouble running Kafka and treq at the same time. A generic way I deal with iterators in Twisted is to use <code>inlineCallbacks</code> to wait for a result and then do something with that result afterwards.</p>
<pre><code>from twisted.internet import defer
@defer.inlineCallbacks
def consumeKafka():
consumer = KafkaConsumer(bootstrap_servers="kafka:9092", auto_offset_reset='earliest')
consumer.subscribe(['kafkapipeline'])
for v in consumer:
value = yield v.value
# do stuff with value
</code></pre>
<p>Then you can simply call this function and the reactor will take care of the rest. So your main section will look like this:</p>
<pre><code>consumeKafka()
reactor.run()
</code></pre>
<p>Note that the <code>consumeKafka()</code> function returns a <code>Deferred</code> so you add callbacks and errbacks as needed. Once you get comfortable with this model, take a look at <code>Cooperator</code> objects for more functionality.</p>
| 0 | 2016-10-02T18:37:52Z | [
"python",
"asynchronous",
"twisted"
]
|
Cant be connected between two computers in the same Lan with sockets | 39,814,726 | <p>I have a server-client that work wonderfull when im trying to use them on my own machine. But - when im trying to use them on two different machines on the same Lan, it didnt work!
Here is my connection:</p>
<pre><code>Lan = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates the socket object
Lan.connect(('localhost', port))
</code></pre>
<p>I dont understand why should it be a problem</p>
| 0 | 2016-10-02T07:14:41Z | 39,814,816 | <p>When you are binding your socket, it gets bound to certain network interfaces, one of which is the loopback interface which is only available from your local computer. You're likely not binding to your actual network interface controller (NIC)</p>
<p>You want INADDR_ANY when you bind, though you didn't say what programming language, so I don't know specifically how to tell you to do it.</p>
<p>More info here:</p>
<p><a href="http://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming-c">understanding INADDR_ANY for socket programming - c</a></p>
| 1 | 2016-10-02T07:29:07Z | [
"python",
"sockets"
]
|
Blank Figure in Pyplot | 39,814,824 | <p>I use the below function, I get the plot shown in the window but the figure saved is blank. </p>
<pre><code>import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
def plot_embeddings(embeddings, names):
model = TSNE(n_components=2, random_state=0)
vectors = model.fit_transform(embeddings)
x, y = vectors[:, 0], vectors[:, 1]
fig, ax = plt.subplots()
ax.scatter(x, y)
for i, tname in enumerate(names):
ax.annotate(tname, (x[i], y[i]))
plt.show()
plt.savefig('foo.png', bbox_inches='tight')
</code></pre>
<p>I haven't found a solution that works.</p>
| 0 | 2016-10-02T07:30:02Z | 39,822,712 | <p>Use <code>savefig()</code> before <code>show()</code> </p>
<p><code>show()</code> open window and wait till you close it and maybe when it closes window then it clears image.</p>
| 1 | 2016-10-02T23:17:28Z | [
"python",
"matplotlib",
"plot",
"figure"
]
|
How to install dependencies on different python environment using pyenv | 39,814,854 | <p>I installed cmus in OSX and I run it with an awesome utility called cmus-osx.py which uses <code>pyobjc</code> and <code>tinytag</code>. It ran perfectly with Python 2.7.11.</p>
<p>But I wanted to also run <code>mpsyt</code>, which only works with Python 3, so I installed <code>pyenv</code> in order to be able to run both utilities without messing with my environment. It worked, but it caused me some problems with cmus-osx.py, so I created an issue at the GitHub repo: <a href="https://github.com/azadkuh/cmus-osx/issues/5" rel="nofollow">https://github.com/azadkuh/cmus-osx/issues/5</a>.</p>
<p>After some back and forward with the author, I realized that <code>pyobjc</code> became unavailable in any of the pyenv <code>python</code> environments after I installed <code>pyenv</code>. Now the notifications feature, which requires pyobjc, only works correctly when I run cmus-osx.py from <em>system</em> python environment. The utility's author recommended me to </p>
<blockquote>
<p>reinstall (share) dependencies (pyobjc and tinytag) on every
environment who launches the cmus-osx utlity</p>
</blockquote>
<p>The thing is that I've no idea how to do this. I use OSX and I run cmus-osx.py from a zsh shell. </p>
<p>I know I should be able to figure it out by reading pyenv documentation, but I'm still learning to code and to manage a *nix based system and I want to understand what's really going on.</p>
| 0 | 2016-10-02T07:34:37Z | 39,826,108 | <p>I would suggest doing some reading on the Python Virtual Environments tool, <a href="https://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>, such as the excellent guide <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">here</a>.</p>
<p>Basically the steps are:</p>
<pre><code>pip install virtualenv
virtualenv some_dir_name
</code></pre>
<p>You can specify which exact python to install to your virtual environment with the <code>-p</code> flag.</p>
<pre><code>some_dir_name/bin/acivate
</code></pre>
<p><em>Windows users will need to use <code>activate.bat</code></em></p>
<p>You are then in your specified python environment with no packages other than the standard library and pip installed and can install anything that you like with pip without any risk that it will impact any of your other installations.</p>
<p>When you are finished exit the terminal session. If you wish to go back to that environment, <em>with all of the libraries that you installed to it</em>, you can just activate it again.</p>
| 0 | 2016-10-03T07:04:26Z | [
"python",
"osx",
"pyobjc",
"pyenv"
]
|
python: convert pandas categorical values to integer when reading csv in chunks | 39,814,880 | <p>I have large csv file with 1000 columns, column 0 is an id, the other columns are categorical. I would like to convert them to integer values in order to use them for data analysis. First "dummy" way would work if I had enough memory:</p>
<pre><code>filename_cat_train = "../input/train_categorical.csv"
df = pd.read_csv(filename_cat_train, dtype=str)
for column in df.columns[1:]:
df[column] = df[column].astype('category')
columns = df.select_dtypes(['category']).columns
df[columns] = df[columns].apply(lambda x: x.cat.codes)
df.to_csv("../input/train_categorical_rawconversion.csv", index=False)
</code></pre>
<p>but it lasts very long, and definitely not a smart way to solve the task.</p>
<p>I could just load the data file in chunks and then combine after converting to int values using the approach above. However when loading in chunks (even 100k large), not all categories are present in my data. This means, having values T10, T11, T13 in the first chunk, and T10, T11, T12 in the second, different values appear for categories in chunks. </p>
<p>The optimal way for me would be:
0. create the list of categorical and corresponding int values (there are only like 100, and it is easy to retrieve them all from the data)
1. Load data in chunks
2. substitute the values from the list
3. save each chunk and them combine them.</p>
<p>How could I perform such steps efficiently? Maybe better approach exists?
Thanks!</p>
<p><strong>Update1:</strong> the categorical data in of the same 'type. They are keys like T12, T45689, A3333 etc. the csv file is like that:
4,,,,,T12,,,,,,A44,,,,,,B3333, </p>
| 1 | 2016-10-02T07:38:15Z | 39,815,003 | <p>In this case, it indeed seems that a two-pass scheme might be effective.</p>
<p>Starting with</p>
<pre><code>import pandas as pd
data=pd.read_csv(my_file_name, chunksize=my_chunk_size)
</code></pre>
<p>You could do:</p>
<pre><code>import collections
uniques = collections.defaultdict(list)
for chunk in data:
for col in chunk:
uniques[col].update(chunk[col].unique())
</code></pre>
<p>At this point, uniques should map each column name to the unique items appearing in it. To translate to a map, you can now use</p>
<pre><code>for col in uniques:
uniques[col] = dict((e[1], e[0]) for e in enumerate(uniques[col]))
</code></pre>
<p>Now read the file again, and translate each column using the map corresponding to it (see <a href="http://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict">here</a>.)</p>
<hr>
<p>If your columns all contain keys from "the same dictionary", you can do the following:</p>
<p>Starting with the following</p>
<pre><code>import pandas as pd
data=pd.read_csv(my_file_name, chunksize=my_chunk_size)
</code></pre>
<p>You could do:</p>
<pre><code>uniques = set([])
for chunk in data:
for col in cols:
uniques.update(chunk[col].unique())
</code></pre>
<p>At this point, uniques should contain the unique items appearing in the DataFrame. To translate to a map, you can now use</p>
<pre><code>uniques = dict((e[1], e[0]) for e in enumerate(uniques))
</code></pre>
<p>Now, load the DataFrame again, and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">pd.DataFrame.replace</a>.</p>
| 1 | 2016-10-02T07:57:25Z | [
"python",
"pandas",
"data-conversion"
]
|
How to set the History input of a RNN/LSTM cell to Zero? | 39,815,032 | <p>In order to do "Inference" with a trained RNN/LSTM model for sentences one by one. I think I need to set the <strong>History input parameter</strong> of a RNN/LSTM cell to Zero at the beginning of each sentence.</p>
<p>So how can it be done in Tensorflow?</p>
| 0 | 2016-10-02T08:01:13Z | 39,815,124 | <p>Based on <a href="http://stackoverflow.com/questions/38441589/tensorflow-rnn-initial-state">this answer</a> I believe that the state is set back to whatever state you pass in with the <code>initial_state</code> argument to <code>tf.nn.rnn</code> (or the other RNN creation functions).</p>
| 0 | 2016-10-02T08:15:08Z | [
"python",
"machine-learning",
"nlp",
"tensorflow"
]
|
Is it possible to capture any traceback generated by a Python application? | 39,815,135 | <p>I've been searching google for a way to somehow capture any traceback generated by a Python application.</p>
<p>I'd like to send an email/slack/notification to myself if <em>any</em> error occurs which generates a traceback (instead of relying on users to report issues to me).</p>
<p>I still haven't found anything <a href="http://code.activestate.com/recipes/442459-email-pretty-tracebacks-to-yourself-or-someone-you/" rel="nofollow">which doesn't involve you doing a try/except</a>. But of course I can't put everything I do inside individual try/except clauses since I'm writing applications which launch a UI (PySide/PyQt4/PySide2/PyQt5) and could error on user interaction.</p>
<p>Is this possible, and if so how can I capture any traceback generated?</p>
| 3 | 2016-10-02T08:17:22Z | 39,815,461 | <p>You can easily do it by creating custom <a href="https://docs.python.org/2/library/sys.html#sys.excepthook" rel="nofollow"><code>sys.excepthook</code></a>:</p>
<pre><code>import sys
import traceback
def report_exception(exc_type, exc_value, exc_tb):
# just a placeholder, you may send an e-mail here
print("Type", exc_type)
print("Value", exc_value)
print("Tb", ''.join(traceback.format_tb(exc_tb)))
def custom_excepthook(exc_type, exc_value, exc_tb):
report_exception(exc_type, exc_value, exc_tb)
sys.__excepthook__(exc_type, exc_value, exc_tb) # run standard exception hook
sys.excepthook = custom_excepthook
raise RuntimeError("I want to report exception here...")
</code></pre>
<p>For pretty-printing traceback objects refer to <a href="https://docs.python.org/2/library/traceback.html" rel="nofollow">traceback</a> module. </p>
| 4 | 2016-10-02T09:04:02Z | [
"python"
]
|
Matching multiple strings | 39,815,214 | <p>I am learning Python string operations and trying to convert delimited text into variables.</p>
<p>i.e. <code>"On Tap: 20 | Bottles: 957 | Cans: 139"</code></p>
<p>This string should assign value of 20 to Tap, 957 to Bottles, and 139 to Cans. This string is not fixed and may vary (for example 3 values or 0, also position of Tap, Bottles or Cans can be interchanged).</p>
<p>So far I have developed this:</p>
<pre><code>import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles"):
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans"):
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap"):
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
</code></pre>
<p>However it is not working as per my expectations and reassigning the value of Bottles every time.</p>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
Bottles: 957
Found Bottles
957
Cans: 139
Found Bottles
139
</code></pre>
<p>I have included many <code>print</code> statements to debug the code. My purpose is just to assign values to proper variables.</p>
| 1 | 2016-10-02T08:28:58Z | 39,815,248 | <p><code>find</code> returns <code>-1</code> when it can't find string and <code>-1</code> is treated as <code>True</code> (<code>bool(-1)</code> gives <code>True</code>) so you have to use <code>find(...) != -1</code></p>
<pre><code>import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles") != -1:
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans") != -1:
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap") != -1:
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
</code></pre>
<hr>
<p>BTW: with your data you don't need <code>re</code>. You can use <code>split</code> (and <code>strip</code>)</p>
<pre><code>Bottles = i.split(':')[1].strip()
Cans = i.split(':')[1].strip()
Tap = i.split(':')[1].strip()
</code></pre>
| 3 | 2016-10-02T08:35:27Z | [
"python",
"regex"
]
|
Matching multiple strings | 39,815,214 | <p>I am learning Python string operations and trying to convert delimited text into variables.</p>
<p>i.e. <code>"On Tap: 20 | Bottles: 957 | Cans: 139"</code></p>
<p>This string should assign value of 20 to Tap, 957 to Bottles, and 139 to Cans. This string is not fixed and may vary (for example 3 values or 0, also position of Tap, Bottles or Cans can be interchanged).</p>
<p>So far I have developed this:</p>
<pre><code>import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles"):
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans"):
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap"):
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
</code></pre>
<p>However it is not working as per my expectations and reassigning the value of Bottles every time.</p>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
Bottles: 957
Found Bottles
957
Cans: 139
Found Bottles
139
</code></pre>
<p>I have included many <code>print</code> statements to debug the code. My purpose is just to assign values to proper variables.</p>
| 1 | 2016-10-02T08:28:58Z | 39,815,314 | <p>The <code>str.find()</code> method is used for returning the location of the text in a string. If it doesn't find the text, it returns the integer -1. In Python, for checking if on string contains another, you may want to use the syntax <code>if subString in string:</code>, like so:</p>
<pre><code>...
if "Bottles" in i:
print("Found Bottles")
...
</code></pre>
<p>As the official documentation states:</p>
<blockquote>
<p>For the string and byte types, <code>x in y</code>
is only true if and only if <code>x</code> is a substring of <code>y</code>. An equivalent test is <code>y.find(x) != -1
</code> </p>
</blockquote>
<p>So, depending on your preferred coding style and/or particular needs, you can choose between "<code>x in y</code>" or "<code>y.find(x) != -1</code>" </p>
| 1 | 2016-10-02T08:44:37Z | [
"python",
"regex"
]
|
Matching multiple strings | 39,815,214 | <p>I am learning Python string operations and trying to convert delimited text into variables.</p>
<p>i.e. <code>"On Tap: 20 | Bottles: 957 | Cans: 139"</code></p>
<p>This string should assign value of 20 to Tap, 957 to Bottles, and 139 to Cans. This string is not fixed and may vary (for example 3 values or 0, also position of Tap, Bottles or Cans can be interchanged).</p>
<p>So far I have developed this:</p>
<pre><code>import re
strEx = "On Tap: 20 | Bottles: 957 | Cans: 139"
barServingText = strEx.split('|')
print(barServingText)
for i in barServingText:
print (i)
if i.find("Bottles"):
print("Found Bottles")
Bottles = re.sub('[^0-9]*','',i)
print(Bottles)
elif i.find("Cans"):
print("Found Cans")
Cans = re.sub('[^0-9]*','',i)
print(Cans)
elif i.find("Tap"):
print("Found Tap")
Tap = re.sub('[^0-9]*','',i)
print(Tap)
</code></pre>
<p>However it is not working as per my expectations and reassigning the value of Bottles every time.</p>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>['On Tap: 20 ', ' Bottles: 957 ', ' Cans: 139']
On Tap: 20
Found Bottles
20
Bottles: 957
Found Bottles
957
Cans: 139
Found Bottles
139
</code></pre>
<p>I have included many <code>print</code> statements to debug the code. My purpose is just to assign values to proper variables.</p>
| 1 | 2016-10-02T08:28:58Z | 39,815,317 | <p>The following regex should create key value pair for you:</p>
<pre><code>r"((.*?):(.*?)(\||$))"
</code></pre>
<p>The following approach however i think is better suited as it would make it dynamic and can have more than these 3 variables</p>
<pre><code> import re
regex = ur"((.*?):(.*?)(\||$))"
test_str = u"On Tap: 20 | Bottles: 957 | Cans: 139"
matches = re.finditer(regex, test_str)
for matchNum, match in enumerate(matches):
s=match.group(2).strip().split(' ')[-1]+"="+match.group(3).strip()
print(s)
exec(s)
print(Tap)
print(Bottles)
print(Cans)
</code></pre>
| 5 | 2016-10-02T08:45:06Z | [
"python",
"regex"
]
|
Defining columns in numpy array - TypeError: invalid type promotion | 39,815,321 | <p>I am defining an array which should look like this </p>
<pre><code>['word1', 2000, 21]
['word2', 2002, 33]
['word3', 1988, 51]
['word4', 1999, 26]
['word5', 2001, 72]
</code></pre>
<p>However when I append an a new entry I get a TypeError. </p>
<pre><code>import numpy as np
npdtype = [('word', 'S35'), ('year', int), ('wordcount', int)]
np_array = np.empty((0,3), dtype=npdtype)
word = 'word1'
year = '2001'
word_count = '21'
np_array = np.append(np_array, [['word1', int(year), int(word_count)]], axis=0)
</code></pre>
<p>Traceback </p>
<pre><code> File "/home/matt/.local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 4586, in append
return concatenate((arr, values), axis=axis)
TypeError: invalid type promotion
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks</p>
| 1 | 2016-10-02T08:45:31Z | 39,816,733 | <p><code>append</code> is a way of calling <code>np.concatenate</code>. Look at its code. Note it has to make sure the 2nd argument is an array. It does that without knowledge of your special <code>dtype</code>. Try that. It probably produces a string dtype. Then it tries the concatenate. So you need to make an array with the correct dtype first.</p>
<p>I discourage the use of <code>append</code>; it's better to use <code>concatenate</code> directly so you have understand all details.</p>
<p>======================</p>
<p>Expanding on your answer:</p>
<pre><code>In [75]: npdtype
Out[75]: [('word', 'S35'), ('year', numpy.int16), ('wordcount', numpy.int16)]
In [76]: column = np.array( [b'word1', np.int16(year), np.int16(word_count)], dtype=npdtype)
In [77]: column
Out[77]:
array([(b'word1', 0, 0),
(b'\xd1\x07', 0, 0),
(b'\x15', 0, 0)],
dtype=[('word', 'S35'), ('year', '<i2'), ('wordcount', '<i2')])
</code></pre>
<p>I don't think this is what you want.</p>
<p>The correct way to provide data for structured array record is with a tuple, or list of tuples (note the extra ()):</p>
<pre><code>In [78]: column = np.array( [(b'word1', np.int16(year), np.int16(word_count))], dtype=npdtype)
In [79]: column
Out[79]:
array([(b'word1', 2001, 21)],
dtype=[('word', 'S35'), ('year', '<i2'), ('wordcount', '<i2')])
In [80]: column.shape
Out[80]: (1,)
</code></pre>
<p>Now I have a 1d, 1 element array with 3 fields.</p>
<p>Without the [], I get a single element 0d array</p>
<pre><code>In [81]: column0 = np.array( (b'word1', np.int16(year), np.int16(word_count)), dtype=npdtype)
In [82]: column0.shape
Out[82]: ()
In [83]: column0
Out[83]:
array((b'word1', 2001, 21),
dtype=[('word', 'S35'), ('year', '<i2'), ('wordcount', '<i2')])
</code></pre>
<p>I can concatenate several of the 1d arrays:</p>
<pre><code>In [85]: np.concatenate([column,column,column])
Out[85]:
array([(b'word1', 2001, 21),
(b'word1', 2001, 21),
(b'word1', 2001, 21)],
dtype=[('word', 'S35'), ('year', '<i2'), ('wordcount', '<i2')])
In [86]: _.shape
Out[86]: (3,)
In [87]: __['year'] # access the 2nd field (not column)
Out[87]: array([2001, 2001, 2001], dtype=int16)
</code></pre>
<p>Regarding the need for <code>b</code>. You are using Py3 (as I am), and unicode is the default string type. So if you had used <code>U35</code> in <code>npdtype</code>, you could have left off the <code>b</code> (bytestring flag).</p>
<p>That <code>(0,3)</code> shape initial array is probably not what you want. 0 rows, 3 columns, but still has 3 dtype fields. Look at a <code>(1,3)</code> version</p>
<pre><code>In [88]: np.empty((1,3),dtype=npdtype)
Out[88]:
array([[(b'', 0, 0), (b'', 0, 0), (b'', 0, 0)]],
dtype=[('word', 'S35'), ('year', '<i2'), ('wordcount', '<i2')])
</code></pre>
<p>This has blanks and 0 because of what happens to be in the memory. They could have been random characters/numbers.</p>
<p><code>numpy</code> lets you make arrays with one or more 0 dimensions, but they usually aren't useful. About the only place they appear is as the starting point for an iterative array definition, e.g.</p>
<pre><code> arr = np.empty((0,3))
for i in range(10):
arr = np.append(arr, [i,i+1,i+2])
</code></pre>
<p>which is better writen as</p>
<pre><code> ll = []
for i in range(10):
ll.append([i,i+1,i+2])
arr = np.array(ll)
</code></pre>
<p>or</p>
<pre><code> arr = np.empty((10,3))
for i in range(10):
arr[i,:]=[i,i+1,i+2]
</code></pre>
<p>repeated array concatenate is slower.</p>
| 1 | 2016-10-02T11:54:17Z | [
"python",
"numpy"
]
|
Defining columns in numpy array - TypeError: invalid type promotion | 39,815,321 | <p>I am defining an array which should look like this </p>
<pre><code>['word1', 2000, 21]
['word2', 2002, 33]
['word3', 1988, 51]
['word4', 1999, 26]
['word5', 2001, 72]
</code></pre>
<p>However when I append an a new entry I get a TypeError. </p>
<pre><code>import numpy as np
npdtype = [('word', 'S35'), ('year', int), ('wordcount', int)]
np_array = np.empty((0,3), dtype=npdtype)
word = 'word1'
year = '2001'
word_count = '21'
np_array = np.append(np_array, [['word1', int(year), int(word_count)]], axis=0)
</code></pre>
<p>Traceback </p>
<pre><code> File "/home/matt/.local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 4586, in append
return concatenate((arr, values), axis=axis)
TypeError: invalid type promotion
</code></pre>
<p>What am I doing wrong?</p>
<p>Thanks</p>
| 1 | 2016-10-02T08:45:31Z | 39,818,557 | <p>Follow @hpaulj's advice and then tidy up.</p>
<pre><code>import numpy as np
npdtype = [('word', 'S35'), ('year', np.int16), ('wordcount', np.int16)]
np_array = np.empty((0,3), dtype=npdtype)
word = 'word1'
year = '2001'
word_count = '21'
column = np.array( [b'word1', np.int16(year), np.int16(word_count)], dtype=npdtype)
print (column.shape)
column.shape=-1,3
print (column.shape)
print (column)
result=np.concatenate((np_array,column),axis=0)
print (result)
#~ np_array = np.append(np_array, [['word1', int(year), int(word_count)]], axis=0)
</code></pre>
<p>The two things that I found:</p>
<ul>
<li>Meticulous matching of the types of record items is required, hence the use of numpy types in the definition of npdtype and conversions of strings; and also use of <strong>b</strong> prefix to the first element of the record.</li>
<li>The created column has a curious shape, thus the need to reshape it.</li>
</ul>
<p>Here's the output.</p>
<pre><code>>pythonw -u "temp.py"
(3,)
(1, 3)
[[(b'word1', 0, 0) (b'\xd1\x07', 0, 0) (b'\x15', 0, 0)]]
[[(b'word1', 0, 0) (b'\xd1\x07', 0, 0) (b'\x15', 0, 0)]]
>Exit code: 0
</code></pre>
| 0 | 2016-10-02T15:29:19Z | [
"python",
"numpy"
]
|
PyQt - Pass number variable between windows | 39,815,331 | <p>I create 2 windows testWidget and win2. First in testWidget, I click "Input maesure data " in Start menu, then I want to input number in LineEdit of L1(m) in win2, press "Analyze" and shows it in the testWidget. I did it, but it will pop up testWidget again. How to solve it?</p>
<p>Thanks!</p>
<pre><code>import sys
from PyQt4 import QtGui,QtCore
class testWidget(QtGui.QMainWindow):
def __init__(self):
super(testWidget, self).__init__()
self.setGeometry(25,150,1200,700)
self.setWindowTitle('test')
extractAction_1 = QtGui.QAction('&Input maesure data',self)
extractAction_1.triggered.connect( self.newWindow)
self.linetest = QtGui.QLineEdit()
self.linetest.setText("0.0")
layoutV = QtGui.QVBoxLayout()
layoutV.addWidget(self.linetest)
widget = QtGui.QWidget()
widget.setLayout(layoutV)
self.setCentralWidget(widget)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&Start')
fileMenu.addAction(extractAction_1)
def newWindow(self):
self.myOtherWindow = win2()
self.myOtherWindow.show()
def showtex(self,text_LT):
self.linetest.clear()
self.linetest.setText(text_LT)
class win2(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle("Set parameters")
self.setGeometry(150,300,300,200)
b2 = QtGui.QPushButton("Analyze")
b2.clicked.connect(self.getre)
layoutV = QtGui.QVBoxLayout()
layoutH = QtGui.QHBoxLayout()
lab1 = QtGui.QLabel("L1(m):")
self.line1 = QtGui.QLineEdit()
self.line1.setText("50")
lab2 = QtGui.QLabel("L2(m):")
self.line2 = QtGui.QLineEdit()
self.line2.setText("0.0")
self.line3test = QtGui.QLineEdit()
layoutH.addWidget(lab1)
layoutH.addWidget(self.line1)
layoutH.addWidget(lab2)
layoutH.addWidget(self.line2)
layoutV.addLayout(layoutH)
layoutV.addWidget(b2)
layoutV.addWidget(self.line3test)
self.widget = QtGui.QWidget()
self.widget.setLayout(layoutH)
self.widget.setLayout(layoutV)
self.setCentralWidget(self.widget)
self.winma=testWidget()
def getre(self):
text_LT = self.line1.text()
self.winma.showtex(text_LT)
self.winma.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
GUI = testWidget()
GUI.show()
app.exec_()
</code></pre>
| 1 | 2016-10-02T08:47:12Z | 39,818,338 | <p>You need to set a global variable for acessing.</p>
<pre><code>GUI = None
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
GUI = testWidget()
GUI.show()
app.exec_()
</code></pre>
<p>And, let the subwindow pass value to the GUI.</p>
<pre><code>def getre(self):
text_LT = self.line1.text()
GUI.linetest.setText(text_LT)
</code></pre>
| 1 | 2016-10-02T15:06:11Z | [
"python",
"class",
"pyqt4"
]
|
Jupyter, AttributeError: type object 'Widget' has no attribute 'observe' | 39,815,515 | <p>I tried to use observe for my toggleButton </p>
<pre><code>wtarget = widgets.ToggleButtons(
description='select target',
options=['A', 'B', 'C', 'D', 'E', 'F'])
wtarget.observe(target_on_value_change, names='value')
</code></pre>
<p>It displayed this error:</p>
<pre><code>AttributeError: 'ToggleButtons' object has no attribute 'observe'
</code></pre>
<p>I had no problem with another MacBook but this one showed the problem.
I am using MacBook, 10.12. Python Version 4.0.0. ipywidgets was installed via pip. </p>
<p>Thanks.</p>
| 0 | 2016-10-02T09:11:50Z | 39,828,971 | <p>This suggests that you have an old version of traitlets. <code>.observe</code> was added in traitlets 4.1:</p>
<pre><code>pip install --upgrade traitlets
</code></pre>
<p>You may want to upgrade more than that:</p>
<pre><code>pip install --upgrade ipywidgets
</code></pre>
| 0 | 2016-10-03T09:59:09Z | [
"python",
"ipython",
"jupyter"
]
|
Add up all posibilities in a list, with two variables | 39,815,551 | <p>I am trying to make a program in python that will accept a user's input and check if it is a Kaprekar number.
I'm still a beginner, and have been having a lot of issues, but my main issue now that I can't seem to solve is how I would add up all posibilities in a list, with only two variables. I'm probably not explaning it very well so here is an example:</p>
<p>I have a list that contains the numbers
<code>['2', '0', '2', '5']</code>.
How would I make python do <code>2 + 025</code>, <code>20 + 25</code> and <code>202 + 5</code>?</p>
<p>It would be inside an if else statement, and as soon as it would equal the user inputted number, it would stop.</p>
<p>Thanks</p>
<p>(<a href="http://pastebin.com/Kg9bQq47" rel="nofollow">Here</a> is what the entire code looks like if it helps- where it currently says <code>if 1 == 0:</code>, it should be adding them up.)</p>
| 2 | 2016-10-02T09:17:40Z | 39,815,584 | <p>Say you start with</p>
<pre><code>a = ['2', '0', '2', '5']
</code></pre>
<p>Then you can run</p>
<pre><code>>>> [(a[: i], a[i: ]) for i in range(1, len(a))]
[(['2'], ['0', '2', '5']), (['2', '0'], ['2', '5']), (['2', '0', '2'], ['5'])]
</code></pre>
<p>to obtain all the possible contiguous splits. </p>
<p>If you want to process it further, you can change it to numbers via</p>
<pre><code>>>> [(int(''.join(a[: i])), int(''.join(a[i: ]))) for i in range(1, len(a))]
[(2, 25), (20, 25), (202, 5)]
</code></pre>
<p>or add them up</p>
<pre><code>>>> [int(''.join(a[: i])) + int(''.join(a[i: ])) for i in range(1, len(a))]
[27, 45, 207]
</code></pre>
| 2 | 2016-10-02T09:23:17Z | [
"python",
"list",
"add"
]
|
Add up all posibilities in a list, with two variables | 39,815,551 | <p>I am trying to make a program in python that will accept a user's input and check if it is a Kaprekar number.
I'm still a beginner, and have been having a lot of issues, but my main issue now that I can't seem to solve is how I would add up all posibilities in a list, with only two variables. I'm probably not explaning it very well so here is an example:</p>
<p>I have a list that contains the numbers
<code>['2', '0', '2', '5']</code>.
How would I make python do <code>2 + 025</code>, <code>20 + 25</code> and <code>202 + 5</code>?</p>
<p>It would be inside an if else statement, and as soon as it would equal the user inputted number, it would stop.</p>
<p>Thanks</p>
<p>(<a href="http://pastebin.com/Kg9bQq47" rel="nofollow">Here</a> is what the entire code looks like if it helps- where it currently says <code>if 1 == 0:</code>, it should be adding them up.)</p>
| 2 | 2016-10-02T09:17:40Z | 39,817,800 | <p>Not a direct answer to your question, but you can write an expression to determine whether a number, N, is a Krapekar number more concisely.</p>
<pre><code>>>> N=45
>>> digits=str(N**2)
>>> Krapekar=any([N==int(digits[:_])+int(digits[_:]) for _ in range(1,len(digits))])
>>> Krapekar
True
</code></pre>
| 0 | 2016-10-02T14:05:17Z | [
"python",
"list",
"add"
]
|
Sort Excel file by column name containing string and integer | 39,815,597 | <p>I want to sort this Excel file using the second column that is Target. The Target column has data in the form of string and integer</p>
<p><a href="http://i.stack.imgur.com/adjkY.png" rel="nofollow"><img src="http://i.stack.imgur.com/adjkY.png" alt="enter image description here"></a></p>
<p>When I do a sort on the Excel file using the <code>pandas.dataFrame.sort_values()</code> function, I get something like this: </p>
<p><a href="http://i.stack.imgur.com/STwX2.png" rel="nofollow"><img src="http://i.stack.imgur.com/STwX2.png" alt="enter image description here"></a></p>
<p>This sorted order is wrong because Slide2.JPG, Slide3.JPG should be above Slide10.JPG etc. </p>
<p>How do I fix this?</p>
| 0 | 2016-10-02T09:25:28Z | 39,815,713 | <p>It seems you are looking for <a href="https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow">human sorting</a>. You can handle this type of problem using regular expressions in Python. </p>
<p>As explained in the attached article:</p>
<pre><code>import re
def sort_nicely( l ):
""" Sort the given list in the way that humans expect.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
data=["Slide2.JPG","Slide21.JPG","Slide10.JPG","Slide3.JPG"]
sort_nicely(data)
print data
</code></pre>
<p>returns: </p>
<pre><code>['Slide2.JPG', 'Slide3.JPG', 'Slide10.JPG', 'Slide21.JPG']
</code></pre>
| 0 | 2016-10-02T09:42:52Z | [
"python",
"pandas"
]
|
Python Pandas - Index' object has no attribute 'hour' | 39,815,625 | <p>I have a pandas dateframe and the following code works</p>
<pre><code>df['hour'] = df.index.hour
df['c'] = df['hour'].apply(circadian)
</code></pre>
<p>but i was trying to reduce the need to make a 'hour' coloumn, using the following code</p>
<pre><code>df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1)
</code></pre>
<p>but I get the error message</p>
<pre><code>AttributeError: ("'Index' object has no attribute 'hour'", u'occurred at index 2015-09-25 01:00:00')
</code></pre>
<p>anyone know how to do this?</p>
| 0 | 2016-10-02T09:28:59Z | 39,816,612 | <p><strong>Approach 1:</strong> </p>
<p>Convert the <code>DateTimeIndex</code> to <code>Series</code> and use <code>apply</code>.</p>
<pre><code>df['c'] = df.index.to_series().apply(lambda x: circadian(x.hour))
</code></pre>
<p><strong>Approach 2:</strong></p>
<p>Use <code>axis=0</code> which computes along the row-index. </p>
<pre><code>df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=0)
</code></pre>
| 2 | 2016-10-02T11:40:33Z | [
"python",
"pandas",
"apply"
]
|
Python Pandas - Index' object has no attribute 'hour' | 39,815,625 | <p>I have a pandas dateframe and the following code works</p>
<pre><code>df['hour'] = df.index.hour
df['c'] = df['hour'].apply(circadian)
</code></pre>
<p>but i was trying to reduce the need to make a 'hour' coloumn, using the following code</p>
<pre><code>df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1)
</code></pre>
<p>but I get the error message</p>
<pre><code>AttributeError: ("'Index' object has no attribute 'hour'", u'occurred at index 2015-09-25 01:00:00')
</code></pre>
<p>anyone know how to do this?</p>
| 0 | 2016-10-02T09:28:59Z | 39,818,351 | <p><strong><em>solution</em></strong><br>
use the datetime accessor <code>dt</code></p>
<pre><code>df['c'] = df.index.to_series().dt.hour.apply(circadian)
</code></pre>
| 1 | 2016-10-02T15:07:26Z | [
"python",
"pandas",
"apply"
]
|
I have get really confused in IP types with sockets (empty string, 'local host', etc...) | 39,815,633 | <p>Im using python.
I dont understand the purpose of empty string in IP to connect to if its not to connect between two Computers in the same LAN router.</p>
<p>My knowledge in network is close to zero, so when I reading in the internet somthing like this:</p>
<blockquote>
<p>empty string represents INADDR_ANY, and the string ''
represents INADDR_BROADCAST</p>
</blockquote>
<p>So if you please will be able to explain me, like you explain to a baby that dont know nothing - what is the purpose of any of the follows in the IP location in socket object:</p>
<blockquote>
<p>broadcast</p>
<p>''</p>
<p>localhost</p>
</blockquote>
<p>and if there is more, so I will be glad to know about them too. Tanks.</p>
| 1 | 2016-10-02T09:30:06Z | 39,815,976 | <p><code>'localhost'</code> (or <code>'127.0.0.1'</code>) is use to connect with program on the same computer - ie. database viewer <-> local database server, Doom client <-> local Doom server. This way you don't have to write different method to connect to local server. </p>
<p>Computer can have more then one network card (NIC) and every NIC has own IP address. You can use this IP and program will use only this one NIC to receive request/connection. This way you can have server which receive request only from LAN but not from Internet - very popular for databases used by web servers.</p>
<p>Empty string means <code>'0.0.0.0'</code> which means that program will receive request from all NICs.</p>
| 0 | 2016-10-02T10:19:20Z | [
"python",
"sockets"
]
|
Django calculation with many TimeFields | 39,815,638 | <p>I'm working on a webapp, which should calculate with several <code>TimeField</code> objects.
No I stuck at one point. How is it possible to add different <code>TimeFields</code> together and subtract a <code>DecimalField</code> from the outcome <code>TimeField</code>.
I've tried different ways. For example to convert the <code>TimeFields</code> into a <code>str-object</code> (which doesn't work either...). Does anyone of you got an idea how I can handle that issue? A small hint would be a pleasure for me.
Thanks! </p>
| 0 | 2016-10-02T09:30:23Z | 39,815,718 | <p>What are you <em>actually</em> trying to do? :) I'll have to guess to begin with...</p>
<p>Remember <code>TimeField</code>s carry <code>datetime.time</code> objects, which are "clock time", i.e. from midnight to midnight.
I'm assuming you want to convert them to a form that you can handle arithmetically -- seconds since midnight works fine for that.</p>
<p>I'm using raw <code>datetime.time</code> objects here for simplicity, but it's the same thing with Django's TimeFields.</p>
<pre><code>import datetime, decimal
def to_seconds_after_midnight(t):
return t.hour * 60 * 60 + t.minute * 60 + t.second + (t.microsecond / 1000000.)
hourly_fee = decimal.Decimal(90) # for example.
time_1 = datetime.time(13, 15)
time_2 = datetime.time(16, 20)
second_interval = decimal.Decimal(
to_seconds_after_midnight(time_2) -
to_seconds_after_midnight(time_1)
)
print(hourly_fee * (second_interval / 60 / 60)) # The output is 277.5.
</code></pre>
<p>HTH :)</p>
| 0 | 2016-10-02T09:43:25Z | [
"python",
"django"
]
|
Pandas: append dataframe to another df | 39,815,646 | <p>I have a problem with appending of dataframe.
I try to execute this code</p>
<pre><code>df_all = pd.read_csv('data.csv', error_bad_lines=False, chunksize=1000000)
urls = pd.read_excel('url_june.xlsx')
substr = urls.url.values.tolist()
df_res = pd.DataFrame()
for df in df_all:
for i in substr:
res = df[df['url'].str.contains(i)]
df_res.append(res)
</code></pre>
<p>And when I try to save <code>df_res</code> I get empty dataframe.
<code>df_all</code> looks like </p>
<pre><code>ID,"url","used_at","active_seconds"
b20f9412f914ad83b6611d69dbe3b2b4,"mobiguru.ru/phones/apple/comp/32gb/apple_iphone_5s.html",2015-10-01 00:00:25,1
b20f9412f914ad83b6611d69dbe3b2b4,"mobiguru.ru/phones/apple/comp/32gb/apple_iphone_5s.html",2015-10-01 00:00:31,30
f85ce4b2f8787d48edc8612b2ccaca83,"4pda.ru/forum/index.php?showtopic=634566&view=getnewpost",2015-10-01 00:01:49,2
d3b0ef7d85dbb4dbb75e8a5950bad225,"shop.mts.ru/smartfony/mts/smartfon-smart-sprint-4g-sim-lock-white.html?utm_source=admitad&utm_medium=cpa&utm_content=300&utm_campaign=gde_cpa&uid=3",2015-10-01 00:03:19,34
078d388438ebf1d4142808f58fb66c87,"market.yandex.ru/product/12675734/spec?hid=91491&track=char",2015-10-01 00:03:48,2
d3b0ef7d85dbb4dbb75e8a5950bad225,"avito.ru/yoshkar-ola/telefony/mts",2015-10-01 00:04:21,4
d3b0ef7d85dbb4dbb75e8a5950bad225,"shoppingcart.aliexpress.com/order/confirm_order",2015-10-01 00:04:25,1
d3b0ef7d85dbb4dbb75e8a5950bad225,"shoppingcart.aliexpress.com/order/confirm_order",2015-10-01 00:04:26,9
</code></pre>
<p>and <code>urls</code> looks like</p>
<pre><code>url
shoppingcart.aliexpress.com/order/confirm_order
ozon.ru/?context=order_done&number=
lk.wildberries.ru/basket/orderconfirmed
lamoda.ru/checkout/onepage/success/quick
mvideo.ru/confirmation?_requestid=
eldorado.ru/personal/order.php?step=confirm
</code></pre>
<p>When I print <code>res</code> in a loop it doesn't empty. But when I try print in a loop <code>df_res</code> after append, it return empty dataframe.
I can't find my error. How can I fix it?</p>
| 2 | 2016-10-02T09:31:18Z | 39,815,686 | <p>If you look at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow">the documentation for <code>pd.DataFrame.append</code></a></p>
<blockquote>
<p>Append rows of other to the end of this frame, <strong>returning a new object</strong>. Columns not in this frame are added as new columns.</p>
</blockquote>
<p>(emphasis mine). </p>
<p>Try </p>
<pre><code>df_res = df_res.append(res)
</code></pre>
<hr>
<p>Incidentally, note that pandas isn't that efficient for creating a DataFrame by successive concatenations. You might try this, instead:</p>
<pre><code>all_res = []
for df in df_all:
for i in substr:
res = df[df['url'].str.contains(i)]
all_res.append(res)
df_res = pd.concat(all_res)
</code></pre>
<p>This first creates a list of all the parts, then creates a DataFrame from all of them once at the end.</p>
| 2 | 2016-10-02T09:36:14Z | [
"python",
"pandas"
]
|
Python Flask: Sending a form class argument from another function to prepopulate default | 39,815,647 | <p>I need to prepopulate form fields with database (dataset) values.
The problem is that I don't know how to send the argument to the form class.</p>
<p><strong>forms.py</strong></p>
<pre><code># coding: utf-8
from db import produtosalca as produtos ##dataset imports db['table']
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, SubmitField, TextAreaField, validators, ValidationError
class ProductForm(FlaskForm,produto):
descricao = TextField("Nome", default=produto.Descricao)
classificacaoFiscal = TextField("NCM", default=produto.ClassificacaoFiscal)
mva = TextField("MVA",default=produto.MVA)
</code></pre>
<p>app.py</p>
<pre><code># coding: utf-8
import os
from werkzeug import secure_filename
from flask import (
Flask, request, send_from_directory, render_template, current_app, flash
)
from db import produtosalca
from forms import ContactForm, ProductForm
app = Flask("alcax")
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
app.config['MEDIA_ROOT'] = os.path.join(PROJECT_ROOT, 'media_files')
app.secret_key = 'development key'
@app.route('/productform', methods=['GET','POST'])
def productform(product):
form = ProductForm(request.form,product) ## here i was gonna send product
if request.method == 'POST':
'posted'
elif request.method == 'GET':
return render_template('productform.html', form=form.content())
</code></pre>
<p>Well everything I tried always get me the error </p>
<pre><code>'produto' is not defined
</code></pre>
<p>I'm a beginner in py. Have been researching all night long. Thanks in advance.</p>
| 1 | 2016-10-02T09:31:23Z | 39,816,039 | <p>Note that <code>class ProductForm(FlaskForm)</code> means ProductForm inherets from FlaskForm. A simple solution for your case would be as follows:</p>
<p><strong>forms.py:</strong></p>
<pre><code>from flask_wtf import FlaskForm
from wtforms import TextField
class ProductForm(FlaskForm):
descricao = TextField("Nome")
classificacaoFiscal = TextField("NCM")
mva = TextField("MVA")
</code></pre>
<p><strong>app.py:</strong></p>
<pre><code>from flask import Flask, render_template, redirect, request
from forms import ProductForm
app = Flask(__name__)
app.secret_key = 'development key'
@app.route('/productform', methods=['GET','POST'])
def productform():
form = ProductForm(descricao='default_descricao', classificacaoFiscal='default_classificacaoFiscal', mva='default_mva')
if form.validate_on_submit():
form = ProductForm(request.form)
# Do something with your form and redirect the user to some page.
return render_template('productform.html', form=form)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
</code></pre>
<p><strong>templates/_formhelpers.html</strong></p>
<pre><code>{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
</code></pre>
<p><strong>templates/productform.html</strong></p>
<pre><code><html !DOCTYPE>
<head>
<title>Flask WTF</title>
</head>
<body>
{% from "_formhelpers.html" import render_field %}
<form method="POST" action="/submit">
<dl>
{{ form.hidden_tag() }}
{{ render_field(form.descricao, size=20) }}
{{ render_field(form.classificacaoFiscal, size=20) }}
{{ render_field(form.mva, size=20) }}
</dl>
<input type="submit" value="Go">
</form>
</body>
</html>
</code></pre>
<p><strong>Edit to take into account the new queries in the comments below:</strong></p>
<p><strong><em>forms.py:</em></strong></p>
<pre><code>class ProductForm(FlaskForm):
descricao = TextField("Nome")
classificacaoFiscal = TextField("NCM")
mva = TextField("MVA")
# ...
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
if 'product' in kwargs:
self.descricao.data = kwargs['product'][0]
self.classificacaoFiscal.data = kwargs['product'][1]
self.mva.data = kwargs['product'][2]
# ...
</code></pre>
<p><strong><em>app.py:</em></strong></p>
<pre><code>@app.route('/productform', methods=['GET','POST'])
def productform():
# product to be retrieved from your database
form = ProductForm(product=product)
if form.validate_on_submit():
form = ProductForm(request.form)
# Do something with your form and redirect the user to some page.
return render_template('productform.html', form=form)
</code></pre>
| -2 | 2016-10-02T10:27:24Z | [
"python",
"forms",
"flask",
"arguments",
"flask-wtforms"
]
|
How else part work in continue statement? | 39,815,695 | <p>I'm not sure how the <code>continue</code> statement is interpreted when it is inside a <code>for</code> loop with an <code>else</code> clause.</p>
<p>If the condition is true, the <code>break</code> will exit from a <code>for</code> loop and <code>else</code> part will not be executed. And if the condition is False then <code>else</code> part will be executed. </p>
<p>But, what about <code>continue</code> statement? I tested it seems that the after the <code>continue</code> statement is reached, the <code>else</code> part will be executed. Is this true?? Here is a code example:</p>
<pre><code># when condition found and it's `true` then `else` part is executing :
edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`
</code></pre>
<p>If I remove "spam" from the list, now the condition is always <code>false</code> and never found but still the <code>else</code> part is executed:</p>
<pre><code>edibles = ["ham","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
</code></pre>
| 4 | 2016-10-02T09:38:00Z | 39,815,739 | <p>Your <code>else</code> part will be executed in both cases.
<code>else</code> part executed when loop terminate when condition didn't found.Which is what is happening in your code. But it will also work same without <code>continue</code> statement.</p>
<p>now what about break statement's else part, Break statement's else part will be executed only if:</p>
<ul>
<li>If the loop completes normally without any break.</li>
<li>If the loop doesn't encounter a break.</li>
</ul>
<p><a href="http://i.stack.imgur.com/yPLeC.png" rel="nofollow"><img src="http://i.stack.imgur.com/yPLeC.png" alt="enter image description here"></a></p>
| 3 | 2016-10-02T09:45:47Z | [
"python",
"for-loop",
"for-else"
]
|
How else part work in continue statement? | 39,815,695 | <p>I'm not sure how the <code>continue</code> statement is interpreted when it is inside a <code>for</code> loop with an <code>else</code> clause.</p>
<p>If the condition is true, the <code>break</code> will exit from a <code>for</code> loop and <code>else</code> part will not be executed. And if the condition is False then <code>else</code> part will be executed. </p>
<p>But, what about <code>continue</code> statement? I tested it seems that the after the <code>continue</code> statement is reached, the <code>else</code> part will be executed. Is this true?? Here is a code example:</p>
<pre><code># when condition found and it's `true` then `else` part is executing :
edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`
</code></pre>
<p>If I remove "spam" from the list, now the condition is always <code>false</code> and never found but still the <code>else</code> part is executed:</p>
<pre><code>edibles = ["ham","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
</code></pre>
| 4 | 2016-10-02T09:38:00Z | 39,815,753 | <p>With a <code>for</code> loop in Python, the <code>else</code> block is executed when the loop finishes normally, i.e. there is no <code>break</code> statement. A <code>continue</code> does not affect it either way.</p>
<p>If the for loop ends because of a <code>break</code> statement, then <code>else</code> block will not execute. If the loop exits normally (no <code>break</code>), then the <code>else</code> block will be executed.</p>
<p>From the <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">docs</a>:</p>
<blockquote>
<p>When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statementâs else clause runs when no exception occurs, and a loopâs else clause runs when no break occurs.</p>
</blockquote>
<p>I always remember it because of how Raymond Hettinger <a href="https://youtu.be/OSGv2VnC0go?t=17m44s" rel="nofollow">describes it</a>. He said it should have been called <code>nobreak</code> instead of <code>else</code>. (That's also a good video that explains the usefulness of the for-else construct)</p>
<p>Example:</p>
<pre><code>numbers = [1,2,3]
for number in numbers:
if number == 4:
print("4 was found")
break
else:
print("4 was not found")
</code></pre>
<p>When you run the above code, since <code>4</code> is not in the list, the loop will not <code>break</code> and the <code>else</code> clause will print. If you add <code>4</code> to the list and run it again, it will <code>break</code> and the <code>else</code> will not print. In most other languages, you would have to add some sentinel boolean like <code>found</code> and make it <code>True</code> if you find a <code>4</code>, then only print the statement after the loop if <code>found</code> is <code>False</code>. </p>
| 4 | 2016-10-02T09:47:38Z | [
"python",
"for-loop",
"for-else"
]
|
Raspberry crontab python script at boot | 39,815,791 | <p>I've been trying to launch a python script at the boot of the Rpi, but everything I've tried until now did not work.</p>
<p>The script is some version of this : <a href="https://www.raspberrypi.org/learning/temperature-log/worksheet/" rel="nofollow">https://www.raspberrypi.org/learning/temperature-log/worksheet/</a> :</p>
<pre><code>#!/usr/bin/python
import os, sys
from subprocess import check_output
from re import findall
from time import sleep, strftime, time
def get_temp():
temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
temp = float(findall("\d+\.\d+",temp)[0])
return(temp)
while True:
log=open("cpu_temp.txt","a")
temp = get_temp()
log.write("{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp))+" degreeC\r\n")
sleep(60)
log.close()
</code></pre>
<p>It works fine on its own. I tried editing crontab, with and without the absolute path to Python, as well as editing /etc/rc.local</p>
<p>I know it doesn't work, because it should create a text file and edit it each minute, and it's not created at boot. I have other commands in crontab and rc.local that are working. </p>
<p>Need some help please !</p>
| 1 | 2016-10-02T09:55:15Z | 39,815,861 | <p>You can call your script in the <code>~/.bashrc</code> file. It will be called at boot or terminal opening.</p>
<p>Just write :</p>
<pre><code>python /path/to/your/script.py
</code></pre>
<p>At the end of the .bashrc file.</p>
| -1 | 2016-10-02T10:04:08Z | [
"python",
"raspberry-pi",
"crontab",
"boot"
]
|
Raspberry crontab python script at boot | 39,815,791 | <p>I've been trying to launch a python script at the boot of the Rpi, but everything I've tried until now did not work.</p>
<p>The script is some version of this : <a href="https://www.raspberrypi.org/learning/temperature-log/worksheet/" rel="nofollow">https://www.raspberrypi.org/learning/temperature-log/worksheet/</a> :</p>
<pre><code>#!/usr/bin/python
import os, sys
from subprocess import check_output
from re import findall
from time import sleep, strftime, time
def get_temp():
temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
temp = float(findall("\d+\.\d+",temp)[0])
return(temp)
while True:
log=open("cpu_temp.txt","a")
temp = get_temp()
log.write("{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp))+" degreeC\r\n")
sleep(60)
log.close()
</code></pre>
<p>It works fine on its own. I tried editing crontab, with and without the absolute path to Python, as well as editing /etc/rc.local</p>
<p>I know it doesn't work, because it should create a text file and edit it each minute, and it's not created at boot. I have other commands in crontab and rc.local that are working. </p>
<p>Need some help please !</p>
| 1 | 2016-10-02T09:55:15Z | 39,815,871 | <pre><code>sudo crontab -e
@reboot /usr/bin/python /path/to/file/script.py
</code></pre>
<p><code>/path/to/file/script.py</code> would probably be something like <code>/home/username/script.py</code></p>
<p>If it still doesn't work you can try giving it execute permission with this:</p>
<pre><code>chmod a+x script.py
</code></pre>
| 0 | 2016-10-02T10:05:16Z | [
"python",
"raspberry-pi",
"crontab",
"boot"
]
|
Raspberry crontab python script at boot | 39,815,791 | <p>I've been trying to launch a python script at the boot of the Rpi, but everything I've tried until now did not work.</p>
<p>The script is some version of this : <a href="https://www.raspberrypi.org/learning/temperature-log/worksheet/" rel="nofollow">https://www.raspberrypi.org/learning/temperature-log/worksheet/</a> :</p>
<pre><code>#!/usr/bin/python
import os, sys
from subprocess import check_output
from re import findall
from time import sleep, strftime, time
def get_temp():
temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
temp = float(findall("\d+\.\d+",temp)[0])
return(temp)
while True:
log=open("cpu_temp.txt","a")
temp = get_temp()
log.write("{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp))+" degreeC\r\n")
sleep(60)
log.close()
</code></pre>
<p>It works fine on its own. I tried editing crontab, with and without the absolute path to Python, as well as editing /etc/rc.local</p>
<p>I know it doesn't work, because it should create a text file and edit it each minute, and it's not created at boot. I have other commands in crontab and rc.local that are working. </p>
<p>Need some help please !</p>
| 1 | 2016-10-02T09:55:15Z | 39,815,875 | <p>If your script is located at <code>/home/pi/tempcheck.py</code> the you should edit crontab with </p>
<pre><code>sudo crontab -e
</code></pre>
<p>and append the line</p>
<pre><code>@reboot python /home/pi/tempcheck.py &
</code></pre>
<p>then save and exit.</p>
<p>Further details can be found at <a href="http://www.raspberrypi-spy.co.uk/2013/07/running-a-python-script-at-boot-using-cron/" rel="nofollow">http://www.raspberrypi-spy.co.uk/2013/07/running-a-python-script-at-boot-using-cron/</a></p>
<p>You can check it is running with</p>
<pre><code>ps aux | grep tempcheck.py
</code></pre>
<p>Note that if you edit root's crontab, the python process will be run as root. So you should use absolute filenames in the python script:</p>
<pre><code>log=open("/home/pi/cpu_temp.txt","a")
</code></pre>
| 1 | 2016-10-02T10:05:29Z | [
"python",
"raspberry-pi",
"crontab",
"boot"
]
|
XMLRPC - wp.newPost with custom post type and custom fields | 39,815,857 | <p>I'm trying to add new posts over XMLRPC, but for some reason I cannot add custom fields (other content like title and description works).</p>
<p>Pseudo code that I use:</p>
<pre><code>from xmlrpc import client
user = 'admin'
passwd = 'pass'
server = client.ServerProxy('http://domain.tld/xmlrpc.php')
blog_id = 0
custom_fields = []
custom_fields.append(
{'key' : 'my_meta_key', 'value' : 123}
)
blog_content = {
'post_title': title,
'post_content': content,
'post_type': 'product',
'custom_fields': custom_fields
}
post_id = int(server.wp.newPost(blog_id, user, passwd, blog_content, 0))
</code></pre>
<p>Posts gets added, however my custom field named <code>my_meta_key</code> is empty.</p>
<p>Cant see what I'm doing wrong. </p>
| 0 | 2016-10-02T10:03:44Z | 39,834,301 | <p>Try using:</p>
<pre><code>custom_fields = {}
custom_fields.update(
{'my_meta_key': 123}
</code></pre>
<p>)</p>
| 0 | 2016-10-03T14:42:31Z | [
"python",
"wordpress",
"xml-rpc"
]
|
XMLRPC - wp.newPost with custom post type and custom fields | 39,815,857 | <p>I'm trying to add new posts over XMLRPC, but for some reason I cannot add custom fields (other content like title and description works).</p>
<p>Pseudo code that I use:</p>
<pre><code>from xmlrpc import client
user = 'admin'
passwd = 'pass'
server = client.ServerProxy('http://domain.tld/xmlrpc.php')
blog_id = 0
custom_fields = []
custom_fields.append(
{'key' : 'my_meta_key', 'value' : 123}
)
blog_content = {
'post_title': title,
'post_content': content,
'post_type': 'product',
'custom_fields': custom_fields
}
post_id = int(server.wp.newPost(blog_id, user, passwd, blog_content, 0))
</code></pre>
<p>Posts gets added, however my custom field named <code>my_meta_key</code> is empty.</p>
<p>Cant see what I'm doing wrong. </p>
| 0 | 2016-10-02T10:03:44Z | 39,862,816 | <p>Problem is with naming of meta keys. I name them with underscore, like <code>_my_meta_key</code>, which means they are protected for the API.</p>
| 0 | 2016-10-04T22:36:46Z | [
"python",
"wordpress",
"xml-rpc"
]
|
How efficient is list.index(value, start, end)? | 39,815,879 | <p>Today I realized that python's <code>list.index</code> can also take an optional <code>start</code> (and even <code>end</code>) parameter.</p>
<p>I was wondering whether or not this is efficiently implemented and which of these two is better:</p>
<pre><code>pattern = "qwertyuytresdftyuioknn"
words_list = ['queen', 'quoin']
for word in words_list:
i = 1
for character in word:
try:
i += pattern[i:].index(character)
except ValueError:
break
else:
yield word
</code></pre>
<p>or</p>
<pre><code>pattern = "qwertyuytresdftyuioknn"
words_list = ['queen', 'quoin']
for word in words_list:
i = 1
for character in word:
try:
i = pattern.index(character, i)
except ValueError:
break
else:
yield word
</code></pre>
<p>So basically <code>i += pattern[i:].index(character)</code> vs <code>i = pattern.index(character, i)</code>. </p>
<p>Searching for this on <em>generic_search_machine</em> returns nothing helpful, except a lot of beginner tutorials trying to teach me what a list is.</p>
<p><strong>Background:</strong>
This code tries to find all words from <code>words_list</code> which match <code>pattern</code>. <code>pattern</code> is a list of characters a user entered by swiping over the keyboard, like on most modern mobile device's keyboards. </p>
<p>In the actual implementation there is the additional requirement that the returned word should be longer than 5 characters and the first and last character have to exactly match. These lines are omitted here for brevity, since they are trivial to implement.</p>
| 0 | 2016-10-02T10:05:50Z | 39,816,050 | <p>This calls a built-in function implemented in C:</p>
<pre><code>i = pattern.index(character, i)
</code></pre>
<p>Even without looking at the <a href="https://hg.python.org/cpython/file/v3.5.2/Objects/listobject.c#l2147" rel="nofollow">source code</a>, you can always assume that the underlying implementation is smart enough to implement that efficiently, i.e. that it does not look at the first <code>i</code> values in the list.</p>
<p>As a rule of thumb, using a built-in functionality is <em>always</em> faster than (or at least as fast as) the best thing you can implement yourself.</p>
<p><strong>The attempt to make it better:</strong></p>
<pre><code>i += pattern[i:].index(character)
</code></pre>
<p>This is deffinitely worse. It makes a <strong>copy of</strong> <code>pattern[i:]</code> and then looks for <code>character</code> in it.</p>
<p>So, in the worst case, if you have a <code>pattern</code> of 1 GB and <code>i=1</code>, this copies 1 GB of data in memory in attempt to skip the first element (which whould have been skipped anyway).</p>
| 3 | 2016-10-02T10:29:07Z | [
"python",
"list",
"indexof"
]
|
how to create date wizard in odoo 8 | 39,815,895 | <p>I am trying to create a wizard to streamline my search. I have created the report and xml and it works fine. However when I try to do the search it brings all the payslip of all the months not the months I selected. I hence, tried to use a wizard to filter my search. This has been given my issues.</p>
<p>My wizard code is </p>
<pre><code>import time
from datetime import datetime
from dateutil import relativedelta
from openerp.osv import fields, osv
class ReportWizard(osv.osv_memory):
_name = 'bluspiral.sche.schedule'
# _inherit = 'account.invoice'
_description = 'Cash Payroll Schedule'
_columns = {
'date_from': fields.date('Date From', required=True),
'date_to': fields.date('Date To', required=True),
}
_defaults = {
'date_from': lambda *a: time.strftime('%Y-%m-01'),
'date_to': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10],
}
def print_payroll_schedule_report(self, cr, uid, ids, context=None):
datas = {}
if context is None:
context = {}
data = self.read(cr, uid, ids,['date_from', 'date_to'], context=context)
date_from = data[0]['date_from']
date_to = data[0]['date_to']
obj = self.pool['hr.payslip']
ids = obj.search(cr, uid, [('date_from','>=',date_from), ('date_from','<=',date_to)])
datas = {
'ids': ids,
'model': 'bluspiral.sche.schedule.template',
'form': data
}
return self.pool['report'].get_action(
cr, uid, [], 'bluspiral_sche.cash_report', data=datas, context=context
)
</code></pre>
<p>And the error i keep getting is:</p>
<p>Traceback (most recent call last):
File "/opt/openerp-8.0/openerp/addons/report/controllers/main.py", line 125, in report_download
response = self.report_routes(reportname, converter='pdf', **dict(data))
File "/opt/openerp-8.0/openerp/http.py", line 396, in response_wrap
response = f(*args, **kw)
File "/opt/openerp-8.0/openerp/addons/report/controllers/main.py", line 65, in report_routes
pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
File "/opt/openerp-8.0/openerp/api.py", line 241, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/openerp-8.0/openerp/addons/report/models/report.py", line 190, in get_pdf
html = self.get_html(cr, uid, ids, report_name, data=data, context=context)
File "/opt/openerp-8.0/openerp/api.py", line 241, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/openerp-8.0/openerp/addons/report/models/report.py", line 165, in get_html
return particularreport_obj.render_html(cr, uid, ids, data=data, context=context)
File "/opt/openerp-8.0/openerp/api.py", line 241, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/openerp-8.0/openerp/addons/report/models/abstract_report.py", line 35, in render_html
if data and data.get('form', {}).get('landscape'):
AttributeError: 'list' object has no attribute 'get'</p>
<p>Any Ideas please?</p>
| 0 | 2016-10-02T10:08:05Z | 39,816,028 | <p>Odoo expects a dict and it found a list for <code>form</code> variable (<code>read</code> function returns a list of dicts), you need to change: </p>
<pre><code>'form': data
</code></pre>
<p>To: </p>
<pre><code>'form': data[0]
</code></pre>
| 0 | 2016-10-02T10:25:42Z | [
"python",
"python-2.7",
"openerp",
"odoo-8"
]
|
Python - Extract strings from a log file and write them into another file | 39,816,094 | <p>I've got a log file like below:</p>
<pre><code>sw2 switch_has sw2_p3.
sw1 transmits sw2_p2
/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(#t_air_sens2)]),DataHasValue(DataProperty(#qos_type),^^(latency,http://www.xcx.org/1900/02/22-rdf-syntax-ns#PlainLiteral))) */
/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(#t_air_sens2)]),DataHasValue(DataProperty(#topic_type),^^(periodic,http://www.xcx.org/1901/11/22-rdf-syntax-ns#PlainLiteral))) */
...
</code></pre>
<p>what I'm interested in, is to extract specific words from <code>/* BUG...</code> lines and write them into separate file, something like below:</p>
<pre><code>t_air_sens2 qos_type latency
t_air_sens2 topic_type periodic
...
</code></pre>
<p>I can do this with the help of <code>awk</code> and regex in shell like below:</p>
<pre><code>awk -F'#|\\^\\^\\(' '{for (i=2; i<NF; i++) printf "%s%s", gensub(/[^[:alnum:]_].*/,"",1,$i), (i<(NF-1) ? OFS : ORS) }' output.txt > ./LogErrors/Properties.txt
</code></pre>
<p>How can I extract them using Python? (shall I use regex again, or..?)</p>
| 0 | 2016-10-02T10:35:20Z | 39,816,303 | <p>You can of course use regex. I would read line by line, grab the lines the start with <code>'/* BUG:'</code>, then parse those as needed.</p>
<pre><code>import re
target = r'/* BUG:'
bugs = []
with open('logfile.txt', 'r') as infile, open('output.txt', 'w') as outfile:
# loop through logfile
for line in infile:
if line.startswith(target):
# add line to bug list and strip newlines
bugs.append(line.strip())
# or just do regex parsing here
# create match pattern groups with parentheses, escape literal parentheses with '\'
match = re.search(r'NamedIndividual\(([\w#]+)\)]\),DataHasValue\(DataProperty\(([\w#]+)\),\^\^\(([\w#]+),', line)
# if matches are found
if match:
# loop through match groups, write to output
for group in match.groups():
outfile.write('{} '.format(group))
outfile.write('\n')
</code></pre>
<p>Python has a pretty powerful regex module built-in: <a href="https://docs.python.org/3/library/re.html" rel="nofollow">re module</a></p>
<p>You can <a href="https://docs.python.org/3/library/re.html#match-objects" rel="nofollow">search for a given pattern, then print out the matched groups as needed</a>.</p>
<p>Note: <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow">raw strings</a> (<code>r'xxxx'</code>) let you use unescaped characters.</p>
| 1 | 2016-10-02T11:00:23Z | [
"python",
"file"
]
|
How to get a list of two different elements with their parents being the same | 39,816,139 | <p>As an exercise I am trying to <strong>print</strong> all the titles of posts with more than 200 comments from the site reddit.com.</p>
<p>What I tried:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url1 = "https://www.reddit.com/"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
res = requests.get(url1, headers=headers)
res.raise_for_status()
soup = BeautifulSoup(res.content, "html5lib")
g = soup.select('ul > li.first')
j = soup.select('#siteTable div.entry.unvoted > p.title > a ')
list1 = []
for t in j:
list.append(t.text)
list2=[]
for s in g:
for p in s.text.split(" "):
if p.isdigit():
p = int(p)
if p > 100:
list2.append(p)
for q,l in zip(list1, list2):
if l > 200:
print(q,l)
</code></pre>
<p>Problem:</p>
<p>It works halfway until there is a <strong>hiccup somewhere</strong> and the lists don't match anymore. As a result, I get titles that have less than 200 comments.</p>
<p>Output:</p>
<pre><code>What the F David Blaine!! 789
So NYC MTA (subway) banned all dogs unless the owner carries them in a bag. I think this owner nailed it. 1075
Bad to the bone 307
TIL there is a "white man" café in Tokyo, where Japanese ladies ring a bell to summon tuxedo-wearing caucasians who respond with "yes, princess?" and serve them cake 2145
Earthquake Warning Issued in California 1410
Man impersonating officer busted for attempting to pull over unmarked cruiser 1022
Use of body-worn cameras sees complaints against police âvirtually vanishâ, study finds 2477
Amazing one handed interception 759
A purrfectly executed leap 518
"This bed has a fur pillow, I'll lay here." 792
Back in 'Nam, 1969. Guy on the left is a good friend of mine's dad. He's in hospice now and not doing well but he'll live on in photos. 264
Nintendo Entertainment System: NES Classic Edition - with 30 games - Available in US 11/11/16 290
A scenic view ruined by a drunk driver (Star Wars: Battlefront) 2737
Clouds battling a sunset over Olympic National Park, WA, USA (1334x750) [OC] 2222
What company is totally guilty of false advertising and why? 2746
South Korean President Park Geun-hye has called on North Koreans to abandon their country and defect, just a day after a soldier walked across the heavily fortified border into the South 410
TIFU by underestimating the stupidity of multiple people 334
Special Trump burger at a burger chain in South Africa 311
This Special Ed Teacher Had All of Her Students in Her Wedding 984
</code></pre>
<p>The messup starts after <em>"A scenic view ruined by..."</em></p>
<p>Can someone point me to what is the exact problem here or an alternative way?</p>
| 0 | 2016-10-02T10:39:23Z | 39,817,799 | <p>Instead of saving it first to lists and hoping that both lists would match up (list1[0]~~list2[0])....I tried to find the most common denominator (parent) and applied the class selection (beautifulsoup) a second time to delve further down the dom (children) and printing it instantly. While scraping a heavily used website such as reddit, it is a good possibility to change even if its split seconds apart and a viable cause for hiccups when saving data to lists and comparing them. </p>
<p>Solution:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url1 = "https://www.reddit.com/"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
res = requests.get(url1, headers=headers)
res.raise_for_status()
soup = BeautifulSoup(res.content, "html5lib")
k= soup.select('#siteTable div.entry.unvoted') # partent
for v in k:
d = v.select('ul > li.first') #comment
o = v.select('p.title > a') #title
for z,x in zip(d,o):
for p in z.text.split(" "): # convert "351 comments" to integer "351" and compare with 200
if p.isdigit():
p = int(p)
if p > 200:
print(z.text, x.text) #print comments first then title
</code></pre>
| 0 | 2016-10-02T14:05:09Z | [
"python",
"web-scraping",
"beautifulsoup"
]
|
How to make an One-Liner list with multiple variables in Python? | 39,816,176 | <p>I was interested whether I can define <em>ascii_combinations</em> list in one line and not using the loop I used in the following example...</p>
<pre><code>ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = []
for x1 in ascii_printable:
for x2 in ascii_printable:
for x3 in ascii_printable:
ascii_combinations.append(x1 + x2 + x3)
</code></pre>
<p>I wanted to create a list of all possible 3 characters long combinations using 95 single-character ASCII characters. I made it work using this code but as I managed to shorten <em>ascii_printable</em> into One-Liner, I was interested whether I can do the same thing with the other list.</p>
| 1 | 2016-10-02T10:43:31Z | 39,816,258 | <p>Since you want to create a cartesian product, standard way to do so is using <code>itertools.product</code>.</p>
<pre><code>import itertools
ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = [x1+x2+x3 for x1, x2, x3 in itertools.product(ascii_printable, repeat=3)]
</code></pre>
| 3 | 2016-10-02T10:55:09Z | [
"python"
]
|
How to make an One-Liner list with multiple variables in Python? | 39,816,176 | <p>I was interested whether I can define <em>ascii_combinations</em> list in one line and not using the loop I used in the following example...</p>
<pre><code>ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = []
for x1 in ascii_printable:
for x2 in ascii_printable:
for x3 in ascii_printable:
ascii_combinations.append(x1 + x2 + x3)
</code></pre>
<p>I wanted to create a list of all possible 3 characters long combinations using 95 single-character ASCII characters. I made it work using this code but as I managed to shorten <em>ascii_printable</em> into One-Liner, I was interested whether I can do the same thing with the other list.</p>
| 1 | 2016-10-02T10:43:31Z | 39,816,289 | <p>You might use <code>itertools.product</code> as</p>
<pre><code>from itertools import product
ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = [x1 + x2 + x3 for x1, x2, x3 in product(ascii_printable, repeat=3)]
</code></pre>
<p>Also <code>chr(count) for count in range(32, 127)</code> is way less clear than</p>
<pre><code>from itertools import product
from string import printable
ascii_combinations = [x1 + x2 + x3 for x1, x2, x3 in product(printable[:-5], repeat=3)]
</code></pre>
<p>Lastly, comprehensions are nice but sometimes it's easier to think, imho, in terms of maps of iterables, thus</p>
<pre><code>from itertools import product
from string import printable
list(map(''.join, product(printable[:-5], repeat=3)))
</code></pre>
| 2 | 2016-10-02T10:59:00Z | [
"python"
]
|
How to make an One-Liner list with multiple variables in Python? | 39,816,176 | <p>I was interested whether I can define <em>ascii_combinations</em> list in one line and not using the loop I used in the following example...</p>
<pre><code>ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = []
for x1 in ascii_printable:
for x2 in ascii_printable:
for x3 in ascii_printable:
ascii_combinations.append(x1 + x2 + x3)
</code></pre>
<p>I wanted to create a list of all possible 3 characters long combinations using 95 single-character ASCII characters. I made it work using this code but as I managed to shorten <em>ascii_printable</em> into One-Liner, I was interested whether I can do the same thing with the other list.</p>
| 1 | 2016-10-02T10:43:31Z | 39,816,291 | <p>This results in True:</p>
<pre><code>ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = []
for x1 in ascii_printable:
for x2 in ascii_printable:
for x3 in ascii_printable:
ascii_combinations.append(x1 + x2 + x3)
test = [x1+x2+x3 for x1 in ascii_printable for x2 in ascii_printable for x3 in ascii_printable]
print(test == ascii_combinations)
</code></pre>
| 0 | 2016-10-02T10:59:30Z | [
"python"
]
|
Call a function with a single character in Python | 39,816,327 | <p>If I have a function that computes the factorial of a number, is there any way that this function can be called with the character '!' ?</p>
<p>Essentially, I would like to type</p>
<pre><code>In [1]: 5!
</code></pre>
<p>and receive:</p>
<pre><code>120
</code></pre>
<p>I am using Python 3.5 with the Spyder IDE.</p>
| 0 | 2016-10-02T11:03:13Z | 39,816,744 | <p>You can try something like this:</p>
<pre><code>from math import factorial
input_string = "5!"
def is_int(input_string):
try:
int(input_string[:-1])
return True
except ValueError:
return False
if input_string[-1] == "!" and is_int(input_string):
print(factorial(int(input_string[:-1])))
</code></pre>
<p>This is not exactly you want but it looks like closest solution
This code formatted for python 2.7</p>
| 0 | 2016-10-02T11:55:45Z | [
"python",
"function",
"spyder"
]
|
spacing for triangle pattern in python | 39,816,382 | <p>The following code prints a pattern but I have problem with spacing. I want to print it in a triangle fashion </p>
<pre><code>def triangle(n):
s = ""
for i in range(0,n):
s += "{}".format((i+1)%10)
j=s*1
print( s,'*1=',j)
triangle(9)
</code></pre>
<p>This is the output I get</p>
<pre class="lang-none prettyprint-override"><code>1 *1= 1
12 *1= 12
123 *1= 123
1234 *1= 1234
12345 *1= 12345
123456 *1= 123456
1234567 *1= 1234567
12345678 *1= 12345678
123456789 *1= 123456789
</code></pre>
| 0 | 2016-10-02T11:10:47Z | 39,816,497 | <p>If you meen this</p>
<pre><code> 1 * 1 = 1
12 * 1 = 12
123 * 1 = 123
1234 * 1 = 1234
12345 * 1 = 12345
123456 * 1 = 123456
1234567 * 1 = 1234567
12345678 * 1 = 12345678
123456789 * 1 = 123456789
</code></pre>
<p>then you need ie. <code>{:9s}</code> (for <code>string</code>) to add extra spaces (or <code>{:9d}</code> for <code>int</code>)</p>
<pre><code>def triangle(n):
a = 0
b = 1
for i in range(1, n+1):
a = 10*a + i
print('{:9d} * {} = {}'.format(a, b, a*b))
triangle(9)
</code></pre>
<p>See: <a href="https://pyformat.info/" rel="nofollow">pyformat.info</a></p>
<hr>
<p><strong>EDIT:</strong> to use <code>n</code> instead of <code>9</code> you need <code>{:{}d}</code> and <code>.format(a, n, ...)</code></p>
<pre><code> print('{:{}d} * {} = {}'.format(a, n, b, a*b))
</code></pre>
<hr>
<p><strong>EDIT:</strong> version with two arguments</p>
<pre><code>def triangle(n, b):
a = 0
for i in range(1, n+1):
a = 10*a + i
print('{:{}d} * {} = {}'.format(a, n, b, a*b))
triangle(5, 3)
1 * 3 = 3
12 * 3 = 36
123 * 3 = 369
1234 * 3 = 3702
12345 * 3 = 37035
</code></pre>
<hr>
<p><strong>EDIT:</strong> some explanations:</p>
<p><strong>Line</strong> <code>a = 10*a + i</code>:</p>
<p>You used string and concatenation to create string <code>"1234"</code> from string <code>"123"</code> - <code>"1234" = "123" + "4"</code>. I use integer and <code>*10</code> to create integer <code>1234</code> from integer <code>123</code> - <code>1234 = 123*10 + 4</code>. (and now I can use integer <code>1234</code> to calcutate <code>1234*b</code> in next line)</p>
<p><strong>Line</strong> <code>print('{:{}d} * {} = {}'.format(a, n, b, a*b))</code></p>
<p>To make more readable you can use </p>
<ul>
<li><p>numbers (because arguments in <code>format()</code> are numbered - 0,1,2,...)</p>
<pre><code>print('{0:{1}d} * {2} = {3}'.format(a, n, b, a*b))
</code></pre>
<p>or even (<code>d</code> means <code>decimal</code> or <code>int</code>)</p>
<pre><code>print('{0:{1:d}d} * {2:d} = {3:d}'.format(a, n, b, a*b))
</code></pre></li>
<li><p>names</p>
<pre><code>print('{x:{y}d} * {z} = {v}'.format(x=a, y=n, z=b, v=a*b))
</code></pre>
<p>or even</p>
<pre><code>print('{x:{y:d}d} * {z:d} = {v:d}'.format(x=a, y=n, z=b, v=a*b))
</code></pre></li>
</ul>
<p><code>{:9}</code> (or <code>{x:9d}</code>) will get integer value and create 9 char length text aligned to right so you get extra spaces on left side. </p>
<p>Try <code>{:<9}</code> to get 9 char length text aligned to left </p>
<pre><code>1 * 3 = 3
12 * 3 = 36
123 * 3 = 369
1234 * 3 = 3702
12345 * 3 = 37035
123456 * 3 = 370368
1234567 * 3 = 3703701
12345678 * 3 = 37037034
123456789 * 3 = 370370367
</code></pre>
<p>or <code>{:^9}</code> to get centered text</p>
<pre><code> 1 * 3 = 3
12 * 3 = 36
123 * 3 = 369
1234 * 3 = 3702
12345 * 3 = 37035
123456 * 3 = 370368
1234567 * 3 = 3703701
12345678 * 3 = 37037034
123456789 * 3 = 370370367
</code></pre>
<p>See more: <a href="https://pyformat.info/" rel="nofollow">pyformat.info</a></p>
| 3 | 2016-10-02T11:25:56Z | [
"python",
"string-formatting"
]
|
Complex workflow on Celery | 39,816,433 | <p>I am trying to build a workflow basing on Celery. I use groups and chords.</p>
<p>In the example below there are independent groups ([mytask1, mytask1, mytask1, ..] -> myfinaltask1) where <code>mytask1</code> might be executed in parallel, but <code>myfinaltask1</code> should be called after each group.</p>
<p>Code:</p>
<pre><code>def func1(date):
subtasks = []
for filepath in all_files:
kwargs = {'date': date, 'hfile': filepath}
subtask = mytask1.subtask(kwargs=kwargs)
subtasks.append(subtask)
chrd = chord(subtasks)
chrdr = chrd(myfinaltask1.s(kwargs={'date': date}))
return chrdr
def main(all_dates):
subtasks = []
for ad in all_dates:
subtasks.append(func1(ad))
g = group(subtasks)
gr = g.apply_async()
results = gr.get(propagate=False) # sync wait!
main([2014, 2015, 2016])
</code></pre>
<p>Exception thrown:</p>
<pre><code>File "/mypath/get_evi.py", line 265, in get_evi_year
gr = g.apply_async()
File "/opt/venv/lib/python3.5/site-packages/celery/canvas.py", line 502, in apply_async
type = self.type
File "/opt/venv/lib/python3.5/site-packages/celery/canvas.py", line 569, in type
return self.app.tasks[self['task']]
File "/opt/venv/lib/python3.5/site-packages/celery/canvas.py", line 560, in app
return self._app or (self.tasks[0].app if self.tasks else current_app)
AttributeError: 'bool' object has no attribute 'app'
</code></pre>
<p>What do I do wrong?</p>
| 5 | 2016-10-02T11:17:57Z | 39,817,066 | <p>It seems you've forgot to wrap <code>subtasks</code> to <code>group</code>.</p>
<pre><code>def func1(date):
subtasks = []
for filepath in all_files:
kwargs = {'date': date, 'hfile': filepath}
subtask = mytask1.subtask(kwargs=kwargs)
subtasks.append(subtask)
chrd = chord(header=group(subtasks), body=myfinaltask1.subtask(kwargs={'date': date}))
return chrdr
</code></pre>
| 1 | 2016-10-02T12:36:35Z | [
"python",
"celery"
]
|
Python and time / datetime | 39,816,500 | <p>I've recently began work on a Python program as seen in the fragment below.</p>
<pre><code># General Variables
running = False
new = True
timeStart = 0.0
timeElapsed = 0.0
def endProg():
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
quit()
# Draw
def draw():
stdscr.addstr(1, 1, ">", curses.color_pair(6))
stdscr.border()
if running:
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.ctime( timeStart - timeElapsed ) ) )
stdscr.redrawwin()
stdscr.refresh()
# Calculate
def calc():
if running:
timeElapsed = t.clock() - timeStart
stdscr.border()
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )
# Main Loop
while True:
# Get Input
kInput = stdscr.getch()
# Close the program
if kInput == ord('q'):
endProg()
# Stop the current run
elif kInput == ord('s'):
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )
running = False
new = True
# Start a run
elif kInput == ord(' ') and new:
running = not running
new = not new
timeStart = dt.datetime.now()
# Toggle the timer
elif kInput == ord('p') and not new:
timeStart = dt.datetime.now() - timeStart
running = not running
calc()
draw()
</code></pre>
<p><strong>My program is a bit between solutions currently</strong>, sorry if something doesn't look right. I'll be more than happy to explain.</p>
<p>I've spent the last several hours reading online about the time and datetime modules for python, trying to figure out how I can use them to accomplish my goals, but however I've tried to implement them it's been no use.</p>
<p>Essentially, I need my program to measure the elapsed time from when a button is pressed and be able to display it in a hour:minute.second format. The subtraction has made it very difficult, having to implement things such as timedelta. From what I have read online there is no way to do what I'm wanting without the datetime module, but it's given me nothing but problems.</p>
<p>Is there an easier solution, does my code have any outstanding errors, and how stupid am I?</p>
| -1 | 2016-10-02T11:26:10Z | 39,816,608 | <p>Using Ëtime.time`:</p>
<pre><code>import time
star = time.time()
# run long processing...
elapsed = time.time() - start
</code></pre>
<p>Et voilà !</p>
| 0 | 2016-10-02T11:39:45Z | [
"python",
"datetime",
"time",
"timer"
]
|
Python and time / datetime | 39,816,500 | <p>I've recently began work on a Python program as seen in the fragment below.</p>
<pre><code># General Variables
running = False
new = True
timeStart = 0.0
timeElapsed = 0.0
def endProg():
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
quit()
# Draw
def draw():
stdscr.addstr(1, 1, ">", curses.color_pair(6))
stdscr.border()
if running:
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.ctime( timeStart - timeElapsed ) ) )
stdscr.redrawwin()
stdscr.refresh()
# Calculate
def calc():
if running:
timeElapsed = t.clock() - timeStart
stdscr.border()
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )
# Main Loop
while True:
# Get Input
kInput = stdscr.getch()
# Close the program
if kInput == ord('q'):
endProg()
# Stop the current run
elif kInput == ord('s'):
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )
running = False
new = True
# Start a run
elif kInput == ord(' ') and new:
running = not running
new = not new
timeStart = dt.datetime.now()
# Toggle the timer
elif kInput == ord('p') and not new:
timeStart = dt.datetime.now() - timeStart
running = not running
calc()
draw()
</code></pre>
<p><strong>My program is a bit between solutions currently</strong>, sorry if something doesn't look right. I'll be more than happy to explain.</p>
<p>I've spent the last several hours reading online about the time and datetime modules for python, trying to figure out how I can use them to accomplish my goals, but however I've tried to implement them it's been no use.</p>
<p>Essentially, I need my program to measure the elapsed time from when a button is pressed and be able to display it in a hour:minute.second format. The subtraction has made it very difficult, having to implement things such as timedelta. From what I have read online there is no way to do what I'm wanting without the datetime module, but it's given me nothing but problems.</p>
<p>Is there an easier solution, does my code have any outstanding errors, and how stupid am I?</p>
| -1 | 2016-10-02T11:26:10Z | 39,816,950 | <pre><code>def draw():
stdscr.border()
if running:
stdscr.addstr(1, 1, ">", curses.color_pair(8))
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( timeElapsed ) ) )
if not running:
stdscr.addstr(1, 1, ">", curses.color_pair(7))
stdscr.redrawwin()
stdscr.refresh()
# Calculate
def calc():
if running:
timeElapsed = t.time() - timeStart
stdscr.border()
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.time() - t.time() ) ) )
# Main Loop
while True:
# Get Input
kInput = stdscr.getch()
# Close the program
if kInput == ord('q'):
endProg()
# Stop the current run
elif kInput == ord('s'):
running = False
new = True
# Start a run
elif kInput == ord(' ') and new:
running = not running
new = not new
timeStart = t.time()
# Toggle the timer
elif kInput == ord('p') and not new:
running = not running
timeStart = t.time() - timeStart
calc()
draw()
</code></pre>
<p>Well, I managed to get rid of all of the errors I was encountering. However, the time displayed is incorrect.</p>
<p>Since we're looking to find the elapsed time, it should start at 0 and increase. My program is starting at 12:21.xx and increasing.</p>
<p>Looking at my code I don't see any errors, but there's obviously one in there somewhere.</p>
| 0 | 2016-10-02T12:22:16Z | [
"python",
"datetime",
"time",
"timer"
]
|
Run remote python code via ssh with uninstalled modules | 39,816,564 | <p>I wish to connect to a Linux machine by ssh (from my code) and run some code that is using python libraries that are not installed on the remote machine, what would be the best way to do so?</p>
<p>using a call like this:</p>
<pre><code>cat main.py | ssh user@server python -
</code></pre>
<p>will run main.py on the server, but wont help me with the dependencies, is there a way to somehow 'compile' the relevant libraries and have them sent over just for the running my code? </p>
<p>I wish to avoid installing the libraries on the remote machine if possible</p>
| 0 | 2016-10-02T11:34:17Z | 39,816,650 | <p>Try <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a>:</p>
<pre><code>pip install virtualenv
</code></pre>
<p>then use</p>
<pre><code>virtualenv venv
</code></pre>
<p>to create a seperated python environment in current path(in folder <code>venv</code>).</p>
<p>Instead of installing multiple packages in default python path, virtualenv needs only one package installed.</p>
| 0 | 2016-10-02T11:44:38Z | [
"python",
"linux",
"ssh"
]
|
How can I get data from Goodreads and use it in Telegram Bot API | 39,816,636 | <p>I've come up with an idea of writing an inline telegram bot and use a Goodreads API for this. But I don't know how to properly extract a book info from Goodreads and put it into special fields in bot api request. I will be so much grateful for helping me with this issue! :)</p>
| 0 | 2016-10-02T11:43:20Z | 39,984,067 | <p>It should be pretty easy, just consume API, store data in the memory, and use it when you need it.</p>
<p>Here is example with Node.js: <a href="https://github.com/ro31337/exbot" rel="nofollow">https://github.com/ro31337/exbot</a></p>
<p>This app is using API feed to fetch data. You can see how it works by adding @goa_bot to your Telegram.</p>
| 0 | 2016-10-11T18:21:35Z | [
"python",
"python-3.x",
"telegram",
"telegram-bot",
"python-telegram-bot"
]
|
Pandas populate new dataframe column based on matching columns in another dataframe | 39,816,671 | <p>I have a <code>df</code> which contains my main data which has one million <code>rows</code>. My main data also has 30 <code>columns</code>. Now I want to add another column to my <code>df</code> called <code>category</code>. The <code>category</code> is a <code>column</code> in <code>df2</code> which contains around 700 <code>rows</code> and two other <code>columns</code> that will match with two <code>columns</code> in <code>df</code>.</p>
<p>I begin with setting an <code>index</code> in <code>df2</code> and <code>df</code> that will match between the frames, however some of the <code>index</code> in <code>df2</code> doesn't exist in <code>df</code>.</p>
<p>The remaining columns in <code>df2</code> are called <code>AUTHOR_NAME</code> and <code>CATEGORY</code>.</p>
<p>The relevant column in <code>df</code> is called <code>AUTHOR_NAME</code>. </p>
<p>Some of the <code>AUTHOR_NAME</code> in <code>df</code> doesn't exist in <code>df2</code> and vice versa.</p>
<p>The instruction I want is: when <code>index</code> in <code>df</code> matches with <code>index</code> in <code>df2</code> and <code>title</code> in <code>df</code> matches with <code>title</code> in <code>df2</code>, add <code>category</code> to <code>df</code>, else add NaN in <code>category</code>.</p>
<p>Example data:</p>
<pre><code>df2
AUTHOR_NAME CATEGORY
Index
Pub1 author1 main
Pub2 author1 main
Pub3 author1 main
Pub1 author2 sub
Pub3 author2 sub
Pub2 author4 sub
df
AUTHOR_NAME ...n amount of other columns
Index
Pub1 author1
Pub2 author1
Pub1 author2
Pub1 author3
Pub2 author4
expected_result
AUTHOR_NAME CATEGORY ...n amount of other columns
Index
Pub1 author1 main
Pub2 author1 main
Pub1 author2 sub
Pub1 author3 NaN
Pub2 author4 sub
</code></pre>
<p>If I use <code>df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME'])</code> my <code>df</code> becomes three times bigger than it is supposed to be.</p>
<p>So I thought maybe merging was the wrong way to go about this. What I am really trying to do is use <code>df2</code> as a lookup table and then return <code>type</code> values to <code>df</code> depending on if certain conditions are met.</p>
<pre><code>def calculate_category(df2, d):
category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
return str(category_row['CATEGORY'].iat[0])
df.apply(lambda d: calculate_category(df2, d), axis=1)
</code></pre>
<p>However, this throws me an error:</p>
<pre><code>IndexError: ('index out of bounds', u'occurred at index 7614')
</code></pre>
| 2 | 2016-10-02T11:47:03Z | 39,816,998 | <p><strong>APPROACH 1:</strong></p>
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> instead and drop the duplicated values present in both <code>Index</code> and <code>AUTHOR_NAME</code> columns combined. After that, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin</code></a> for checking membership:</p>
<pre><code>df_concat = pd.concat([df2, df]).reset_index().drop_duplicates(['Index', 'AUTHOR_NAME'])
df_concat.set_index('Index', inplace=True)
df_concat[df_concat.index.isin(df.index)]
</code></pre>
<p><a href="http://i.stack.imgur.com/wjWdz.png" rel="nofollow"><img src="http://i.stack.imgur.com/wjWdz.png" alt="Image"></a></p>
<p>Note: The column <code>Index</code> is assumed to be set as the index column for both the <code>DF's</code>.</p>
<hr>
<p><strong>APPROACH 2:</strong></p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> after setting the index column correctly as shown:</p>
<pre><code>df2.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.join(df2).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/vRkQP.png" rel="nofollow"><img src="http://i.stack.imgur.com/vRkQP.png" alt="Image"></a></p>
| 1 | 2016-10-02T12:27:53Z | [
"python",
"pandas",
"merge",
"populate"
]
|
Pandas populate new dataframe column based on matching columns in another dataframe | 39,816,671 | <p>I have a <code>df</code> which contains my main data which has one million <code>rows</code>. My main data also has 30 <code>columns</code>. Now I want to add another column to my <code>df</code> called <code>category</code>. The <code>category</code> is a <code>column</code> in <code>df2</code> which contains around 700 <code>rows</code> and two other <code>columns</code> that will match with two <code>columns</code> in <code>df</code>.</p>
<p>I begin with setting an <code>index</code> in <code>df2</code> and <code>df</code> that will match between the frames, however some of the <code>index</code> in <code>df2</code> doesn't exist in <code>df</code>.</p>
<p>The remaining columns in <code>df2</code> are called <code>AUTHOR_NAME</code> and <code>CATEGORY</code>.</p>
<p>The relevant column in <code>df</code> is called <code>AUTHOR_NAME</code>. </p>
<p>Some of the <code>AUTHOR_NAME</code> in <code>df</code> doesn't exist in <code>df2</code> and vice versa.</p>
<p>The instruction I want is: when <code>index</code> in <code>df</code> matches with <code>index</code> in <code>df2</code> and <code>title</code> in <code>df</code> matches with <code>title</code> in <code>df2</code>, add <code>category</code> to <code>df</code>, else add NaN in <code>category</code>.</p>
<p>Example data:</p>
<pre><code>df2
AUTHOR_NAME CATEGORY
Index
Pub1 author1 main
Pub2 author1 main
Pub3 author1 main
Pub1 author2 sub
Pub3 author2 sub
Pub2 author4 sub
df
AUTHOR_NAME ...n amount of other columns
Index
Pub1 author1
Pub2 author1
Pub1 author2
Pub1 author3
Pub2 author4
expected_result
AUTHOR_NAME CATEGORY ...n amount of other columns
Index
Pub1 author1 main
Pub2 author1 main
Pub1 author2 sub
Pub1 author3 NaN
Pub2 author4 sub
</code></pre>
<p>If I use <code>df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME'])</code> my <code>df</code> becomes three times bigger than it is supposed to be.</p>
<p>So I thought maybe merging was the wrong way to go about this. What I am really trying to do is use <code>df2</code> as a lookup table and then return <code>type</code> values to <code>df</code> depending on if certain conditions are met.</p>
<pre><code>def calculate_category(df2, d):
category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
return str(category_row['CATEGORY'].iat[0])
df.apply(lambda d: calculate_category(df2, d), axis=1)
</code></pre>
<p>However, this throws me an error:</p>
<pre><code>IndexError: ('index out of bounds', u'occurred at index 7614')
</code></pre>
| 2 | 2016-10-02T11:47:03Z | 39,818,193 | <p>see <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1966/merge-join-and-concatenate/23978/what-is-the-difference-between-join-and-merge#t=201610021451405843568">What is the difference between join and merge</a></p>
<p>consider the following dataframes <code>df</code> and <code>df2</code></p>
<pre><code>df = pd.DataFrame(dict(
AUTHOR_NAME=list('AAABBCCCCDEEFGG'),
title= list('zyxwvutsrqponml')
))
df2 = pd.DataFrame(dict(
AUTHOR_NAME=list('AABCCEGG'),
title =list('zwvtrpml'),
CATEGORY =list('11223344')
))
</code></pre>
<p><strong><em>option 1</em></strong><br>
<code>merge</code></p>
<pre><code>df.merge(df2, how='left')
</code></pre>
<p><strong><em>option 2</em></strong><br>
<code>join</code></p>
<pre><code>cols = ['AUTHOR_NAME', 'title']
df.join(df2.set_index(cols), on=cols)
</code></pre>
<hr>
<p><strong><em>both options yield</em></strong></p>
<p><a href="http://i.stack.imgur.com/AYxvS.png" rel="nofollow"><img src="http://i.stack.imgur.com/AYxvS.png" alt="enter image description here"></a></p>
| 1 | 2016-10-02T14:50:21Z | [
"python",
"pandas",
"merge",
"populate"
]
|
Is there a way to remove too many if else conditions? | 39,816,697 | <p>I am currently making an interactive system using python, that is able to understand and reply. Hence for this there are lots of conditions for machine to analyze and process. For eg. take the following code(for reference only):</p>
<pre><code> if ('goodbye') in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
speekmodule.speek(rand,n,mixer)
break
if ('hello') in message or ('hi') in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand,n,mixer)
if ('thanks') in message or ('tanks') in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
speekmodule.speek(rand,n,mixer)
if message == ('jarvis'):
rand = ['Yes Sir?', 'What can I doo for you sir?']
speekmodule.speek(rand,n,mixer)
if ('how are you') in message or ('and you') in message or ('are you okay') in message:
rand = ['Fine thank you']
speekmodule.speek(rand,n,mixer)
if ('*') in message:
rand = ['Be polite please']
speekmodule.speek(rand,n,mixer)
if ('your name') in message:
rand = ['My name is Jarvis, at your service sir']
speekmodule.speek(rand,n,mixer)
</code></pre>
<p>So, is there a way in which I can replace all these if else conditions?? Because there are much more conditions going to be, and it will make the execution slower. </p>
| -2 | 2016-10-02T11:50:02Z | 39,816,814 | <p><code>if/elif/else</code> is a natural way to structure this kind of code in Python. As @imant noted, you may use dict-based approach in case of simple branching, but I see some mildly complex logic in your <code>if</code> predicates, so you'll have to check all predicates in any case and you won't have any performance gains with another code structure.</p>
<p>Though it may be a little bit more readable and easier to maintain if you factor out your predicates and actions like this:</p>
<pre><code>from collections import OrderedDict
def goodbye_p(message):
return 'goodbye' in message
def goodbye_a():
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
# As @Moinuddin Quadri I also assume that your `speek` method
# says random message from a list.
# Otherwise you can use `random.choice` method
# to get a random message out of a list: `random.choice(messages)`.
speekmodule.speek(rand, n, mixer)
def hello_p(message):
return 'hello' in message or 'hi' in message
def hello_a():
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand, n, mixer)
# Use `OrderedDict` instead of `dict` to control order
# of checks and actions.
branches = OrderedDict([
# (predicate as key, action as value)
(goodbye_p, goodbye_a),
(hello_p, hello_a),
])
for predicate, action in branches.items():
if predicate(message):
action_result = action()
# You can add some logic here based on action results.
# E.g. you can return some special object from `goodbye_a`
# and then shut down Jarvis here.
# Or if your actions are exclusive, you can add `break` here.
</code></pre>
<p>If all your predicates are the same and contain only substring checks, then it may be more performant to have tuples (e.g. <code>('hello', 'hi')</code>) as dict keys. Then you can iterate over those keys like this:</p>
<pre><code>for words, action in branches.items():
if any(word in message for word in words):
action()
</code></pre>
| 0 | 2016-10-02T12:05:32Z | [
"python"
]
|
Is there a way to remove too many if else conditions? | 39,816,697 | <p>I am currently making an interactive system using python, that is able to understand and reply. Hence for this there are lots of conditions for machine to analyze and process. For eg. take the following code(for reference only):</p>
<pre><code> if ('goodbye') in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
speekmodule.speek(rand,n,mixer)
break
if ('hello') in message or ('hi') in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand,n,mixer)
if ('thanks') in message or ('tanks') in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
speekmodule.speek(rand,n,mixer)
if message == ('jarvis'):
rand = ['Yes Sir?', 'What can I doo for you sir?']
speekmodule.speek(rand,n,mixer)
if ('how are you') in message or ('and you') in message or ('are you okay') in message:
rand = ['Fine thank you']
speekmodule.speek(rand,n,mixer)
if ('*') in message:
rand = ['Be polite please']
speekmodule.speek(rand,n,mixer)
if ('your name') in message:
rand = ['My name is Jarvis, at your service sir']
speekmodule.speek(rand,n,mixer)
</code></pre>
<p>So, is there a way in which I can replace all these if else conditions?? Because there are much more conditions going to be, and it will make the execution slower. </p>
| -2 | 2016-10-02T11:50:02Z | 39,816,833 | <p>Firstly create a <code>dict</code> object with the key as <code>tuple</code> of string you want to match in your <code>message</code> and associate it with the value <code>string</code> which your Jarvis is suppose to respond. For example:</p>
<pre><code>jarvis_dict = {
('goodbye',) : ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'],
('hello',
'hi') : ['Wellcome to Jarvis virtual intelligence project. At your service sir.'],
('thanks',
'tanks',
'thank you') : ['You are wellcome', 'no problem'],
('jarvis',) : ['Yes Sir?', 'What can I doo for you sir?'],
('how are you',
'and you',
'are you okay'): ['Fine thank you'],
('*',) : ['Be polite please'],
('your name',): ['My name is Jarvis, at your service sir']
}
</code></pre>
<p>Now iterate each key of you <code>dict</code> to check whether any sub-string is the part of the message and if there is any match, call the <code>speekmodule.speek(rand,n,mixer)</code> function as:</p>
<pre><code>for key, value in jarvis_dict.items():
if any(item in message for item in key):
speekmodule.speek(value, n, mixer)
</code></pre>
<p><em>Note:</em> Here I am assuming that <code>speekmodule.speek(value, n, mixer)</code> in your code is working as there is no information available in your code regarding there declaration. I just replaced your <code>rand</code> with <code>value</code> as it the same list of <code>str</code> returned by the <code>dict</code> which is used in your code.</p>
| 0 | 2016-10-02T12:08:09Z | [
"python"
]
|
Is there a way to remove too many if else conditions? | 39,816,697 | <p>I am currently making an interactive system using python, that is able to understand and reply. Hence for this there are lots of conditions for machine to analyze and process. For eg. take the following code(for reference only):</p>
<pre><code> if ('goodbye') in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
speekmodule.speek(rand,n,mixer)
break
if ('hello') in message or ('hi') in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand,n,mixer)
if ('thanks') in message or ('tanks') in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
speekmodule.speek(rand,n,mixer)
if message == ('jarvis'):
rand = ['Yes Sir?', 'What can I doo for you sir?']
speekmodule.speek(rand,n,mixer)
if ('how are you') in message or ('and you') in message or ('are you okay') in message:
rand = ['Fine thank you']
speekmodule.speek(rand,n,mixer)
if ('*') in message:
rand = ['Be polite please']
speekmodule.speek(rand,n,mixer)
if ('your name') in message:
rand = ['My name is Jarvis, at your service sir']
speekmodule.speek(rand,n,mixer)
</code></pre>
<p>So, is there a way in which I can replace all these if else conditions?? Because there are much more conditions going to be, and it will make the execution slower. </p>
| -2 | 2016-10-02T11:50:02Z | 39,816,853 | <p>Use dictionary:</p>
<pre><code>someCollections = {
'goodbye': "Something1",
'hello': "Somthing2",
...
}
speekmodule(someCollections [SomeKey],...)
</code></pre>
| 0 | 2016-10-02T12:10:01Z | [
"python"
]
|
Is there a way to remove too many if else conditions? | 39,816,697 | <p>I am currently making an interactive system using python, that is able to understand and reply. Hence for this there are lots of conditions for machine to analyze and process. For eg. take the following code(for reference only):</p>
<pre><code> if ('goodbye') in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
speekmodule.speek(rand,n,mixer)
break
if ('hello') in message or ('hi') in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand,n,mixer)
if ('thanks') in message or ('tanks') in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
speekmodule.speek(rand,n,mixer)
if message == ('jarvis'):
rand = ['Yes Sir?', 'What can I doo for you sir?']
speekmodule.speek(rand,n,mixer)
if ('how are you') in message or ('and you') in message or ('are you okay') in message:
rand = ['Fine thank you']
speekmodule.speek(rand,n,mixer)
if ('*') in message:
rand = ['Be polite please']
speekmodule.speek(rand,n,mixer)
if ('your name') in message:
rand = ['My name is Jarvis, at your service sir']
speekmodule.speek(rand,n,mixer)
</code></pre>
<p>So, is there a way in which I can replace all these if else conditions?? Because there are much more conditions going to be, and it will make the execution slower. </p>
| -2 | 2016-10-02T11:50:02Z | 39,816,902 | <p>Make a exclusive "if":</p>
<pre><code>if 'goodbye' in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
elif 'hello' in message or 'hi' in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
elif 'thanks' in message or 'tanks' in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
elif message == 'jarvis':
rand = ['Yes Sir?', 'What can I doo for you sir?']
elif 'how are you' in message or 'and you' in message or ('are you okay') in message:
rand = ['Fine thank you']
elif '*' in message:
rand = ['Be polite please']
elif 'your name' in message:
rand = ['My name is Jarvis, at your service sir']
else:
raise NotImplementedError("What to do?")
speekmodule.speek(rand, n, mixer)
</code></pre>
<p>With a mapping of RegEx:</p>
<pre><code>mapping = {
r"\bgoodbye\b": ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0'],
r"\bhello\b": ['Wellcome to Jarvis virtual intelligence project. At your service sir.'],
...}
for regex, rand in mapping.items():
if re.search(message, flags=re.I):
break
else:
raise NotImplementedError("What to do?")
speekmodule.speek(rand, n, mixer)
</code></pre>
<p>It's up to you to decide. </p>
| 1 | 2016-10-02T12:16:21Z | [
"python"
]
|
Error installing MySQL-python: Unable to find vcvarsall.bat | 39,816,780 | <p>I was trying to install <code>mysql-python</code> using <strong>pip</strong><br>
I'm getting the following error: </p>
<pre><code>error: Unable to find vcvarsall.bat
----------------------------------------
Failed building wheel for mysql-python
...
...
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat
----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools,
tokenize;__file__='c:\\users\\hp\\appdata\\local\\temp\\pip-build-
jy5yhb\\mysql-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)
(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record
c:\users\hp\appdata\local\temp\pip-jditig-record\install-record.txt --single-
version-externally-managed --compile" failed with error code 1 in
c:\users\hp\appdata\local\temp\pip-build-jy5yhb\mysql-python\
</code></pre>
<p>Background works did: </p>
<ul>
<li>Installed MySQL from official website(<a href="https://www.mysql.com/why-mysql/windows/" rel="nofollow">link</a>)</li>
<li>Installed SQLite3</li>
<li>Installed Visual C++ Redistributable 2008, 2010, 2013, 2015</li>
<li>Installed C++ Compiler for python (latest)</li>
</ul>
<p>I have tried all the answers that already exist in Stack Overflow and other Websites, nothing helped.</p>
<p>Context: </p>
<p>I'm trying to run a <em>Django</em> server in my laptop, for which I need mysql-python.<br>
(OS: Windows 10)</p>
| 1 | 2016-10-02T12:01:01Z | 39,850,868 | <p>First check your Python installation & Windows 10 Installation [i.e. Is it 32Bit or 64Bit].</p>
<h1>Visual C++ Redistributable comes with x86 as well x64 make sure you have installed compatible package.</h1>
| 0 | 2016-10-04T11:16:19Z | [
"python",
"mysql",
"windows"
]
|
How to add a specific number of characters to the end of string in Pandas? | 39,816,795 | <p>I am using the Pandas library within Python and I am trying to increase the length of a column with text in it to all be the same length. I am trying to do this by adding a specific character (this will be white space normally, in this example I will use "_") a number of times until it reaches the maximum length of that column. </p>
<p>For example:</p>
<p><strong>Col1_Before</strong></p>
<pre><code>A
B
A1R
B2
AABB4
</code></pre>
<p><strong>Col1_After</strong></p>
<pre><code>A____
B____
A1R__
B2___
AABB4
</code></pre>
<p>So far I have got this far (using the above table as the example). It is the next part (and the part that does it that I am stuck on).</p>
<pre><code>df['Col1_Max'] = df.Col1.map(lambda x: len(x)).max()
df['Col1_Len'] = df.Col1.map(lambda x: len(x))
df['Difference_Len'] = df ['Col1_Max'] - df ['Col1_Len']
</code></pre>
<p>I may have not explained myself well as I am still learning. If this is confusing let me know and I will clarify. </p>
| 3 | 2016-10-02T12:03:14Z | 39,816,915 | <p>It isn't the most pandas-like solution, but you can try the following:</p>
<pre><code>col = np.array(["A", "B", "A1R", "B2", "AABB4"])
data = pd.DataFrame(col, columns=["Before"])
</code></pre>
<p>Now compute the maximum length, the list of individual lengths, and the differences:</p>
<pre><code>max_ = data.Before.map(lambda x: len(x)).max()
lengths_ = data.Before.map(lambda x: len(x))
diffs_ = max_ - lengths_
</code></pre>
<p>Create a new column called <code>After</code> adding the underscores, or any other character:</p>
<pre><code>data["After"] = data["Before"] + ["_"*i for i in diffs_]
</code></pre>
<p>All this gives:</p>
<pre><code> Before After
0 A A____
1 B B____
2 A1R A1R__
3 AABB4 AABB4
</code></pre>
| 2 | 2016-10-02T12:17:36Z | [
"python",
"pandas",
"dataframe",
"string-length",
"maxlength"
]
|
How to add a specific number of characters to the end of string in Pandas? | 39,816,795 | <p>I am using the Pandas library within Python and I am trying to increase the length of a column with text in it to all be the same length. I am trying to do this by adding a specific character (this will be white space normally, in this example I will use "_") a number of times until it reaches the maximum length of that column. </p>
<p>For example:</p>
<p><strong>Col1_Before</strong></p>
<pre><code>A
B
A1R
B2
AABB4
</code></pre>
<p><strong>Col1_After</strong></p>
<pre><code>A____
B____
A1R__
B2___
AABB4
</code></pre>
<p>So far I have got this far (using the above table as the example). It is the next part (and the part that does it that I am stuck on).</p>
<pre><code>df['Col1_Max'] = df.Col1.map(lambda x: len(x)).max()
df['Col1_Len'] = df.Col1.map(lambda x: len(x))
df['Difference_Len'] = df ['Col1_Max'] - df ['Col1_Len']
</code></pre>
<p>I may have not explained myself well as I am still learning. If this is confusing let me know and I will clarify. </p>
| 3 | 2016-10-02T12:03:14Z | 39,817,006 | <p>Without creating extra columns:</p>
<pre><code>In [63]: data
Out[63]:
Col1
0 A
1 B
2 A1R
3 B2
4 AABB4
In [64]: max_length = data.Col1.map(len).max()
In [65]: data.Col1 = data.Col1.apply(lambda x: x + '_'*(max_length - len(x)))
In [66]: data
Out[66]:
Col1
0 A____
1 B____
2 A1R__
3 B2___
4 AABB4
</code></pre>
| 2 | 2016-10-02T12:29:08Z | [
"python",
"pandas",
"dataframe",
"string-length",
"maxlength"
]
|
How to add a specific number of characters to the end of string in Pandas? | 39,816,795 | <p>I am using the Pandas library within Python and I am trying to increase the length of a column with text in it to all be the same length. I am trying to do this by adding a specific character (this will be white space normally, in this example I will use "_") a number of times until it reaches the maximum length of that column. </p>
<p>For example:</p>
<p><strong>Col1_Before</strong></p>
<pre><code>A
B
A1R
B2
AABB4
</code></pre>
<p><strong>Col1_After</strong></p>
<pre><code>A____
B____
A1R__
B2___
AABB4
</code></pre>
<p>So far I have got this far (using the above table as the example). It is the next part (and the part that does it that I am stuck on).</p>
<pre><code>df['Col1_Max'] = df.Col1.map(lambda x: len(x)).max()
df['Col1_Len'] = df.Col1.map(lambda x: len(x))
df['Difference_Len'] = df ['Col1_Max'] - df ['Col1_Len']
</code></pre>
<p>I may have not explained myself well as I am still learning. If this is confusing let me know and I will clarify. </p>
| 3 | 2016-10-02T12:03:14Z | 39,818,021 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])
</code></pre>
<p><strong><em>solution</em></strong><br>
use <code>str.ljust</code></p>
<pre><code>m = s.str.len().max()
s.str.ljust(m, '_')
0 A____
1 B____
2 A1R__
3 B2___
4 AABB4
dtype: object
</code></pre>
<hr>
<p><strong><em>for your case</em></strong> </p>
<pre><code>m = df.Col1.str.len().max()
df.Col1 = df.Col1.ljust(m '_')
</code></pre>
| 6 | 2016-10-02T14:31:05Z | [
"python",
"pandas",
"dataframe",
"string-length",
"maxlength"
]
|
Unable to launch specific module properly | 39,816,911 | <p>I am installing <a href="https://github.com/GTB3NW/SteamTradingServices" rel="nofollow">specific module</a> from Github, but i am having problems using it's functions.</p>
<p>These are steps i took to install module:</p>
<ol>
<li>Downloaded the zip file and unzipped it normally.</li>
<li>Launched <code>setup.py</code> with <code>install</code> option. (<code>python setup.py install</code>)</li>
<li>The module didn't have any documentation, so i checked <code>setup.py</code> and it's name was "Exchange".</li>
<li>I tried importing the module ( <code>import Exchange</code> ) and it worked.</li>
<li>Now since i couldn't find any documentation, i viewed <code>exchange.py</code> from github ( /Exchange/exchange.py ).</li>
<li>I tried using one of the functions, didn't work.</li>
</ol>
<p>Then i realized that i was in folder file, so:</p>
<ol>
<li>i imported <code>exchange.py</code> itself ( <code>from Exchange import exchange</code>).</li>
<li>Now from <code>exchange.py</code> i imported <code>Exchange</code> class (<code>from Exchange.exchange import Exchange</code> ).</li>
<li>I tried to call the class, (<code>Exchange</code>), but i needed to specify 7 arguments for <code>__init__</code>.</li>
</ol>
<hr>
<p>and again, i realized that i needed to launch the <code>exchange.py</code> itself, so i would have no problems, this is where i got stuck, i couldn't launch it.</p>
<p>How could i launch the module properly? Am i right that i need to start from <code>exchange.py</code>? If so how could i launch it? If not then what's the proper entry point?</p>
| 0 | 2016-10-02T12:16:52Z | 39,817,576 | <p>Fixed the problem, Thanks to @metatoaster.</p>
<p>The entry of module, is <code>main</code> function from <code>exchange.py</code>, after calling it, module will be started.</p>
<p>So to start application, you need to import <code>exchange.py</code> from Exchange package, and from <code>exchange.py</code>, import and call <code>main</code> function.</p>
<ol>
<li><code>from Exchange.exchange import main</code></li>
<li><code>main()</code></li>
</ol>
| 0 | 2016-10-02T13:37:39Z | [
"python"
]
|
count words of different classes separately in a text file | 39,816,922 | <p>I have some text files in Persian. each file contains a lot of sentences, each in a new line. And in front of each sentence there is a tab, then a word, then a tab and then an English word. These English words in some files are 2, in some are 3, in some are 5 and in some other, are more or less. Actually, they show the sentences classes. I have to count each class's total words separately (just count the words of sentences not the words after them). For that I have to change the file to a list, so that I can achieve the sentences. Now the problem is that, how should I write the code that it returns each class's total words separately. Below is the sample sentences. </p>
<p><a href="http://i.stack.imgur.com/lMLsP.png" rel="nofollow"><img src="http://i.stack.imgur.com/lMLsP.png" alt="enter image description here"></a></p>
<pre><code>corpus = []
def CountWords (file):
with open (file, encoding = "utf-8") as f1:
for line in f1:
t = line.strip().split("\t")
corpus.append(t)
for row in corpus:
if row[2] != row[2]:
</code></pre>
<p>Now I don't know how to continue. I appreciate a lot if someone can help. (I have no background in programming).</p>
| 1 | 2016-10-02T12:19:06Z | 39,817,002 | <p>Try to formulate your algorithm on paper then convert it to Python: I'm sure you'll find your solution by yourself.</p>
<p>If you encounter problems or errors, post your question here, we will be happy to help.</p>
<p>An advice: </p>
<ul>
<li>You can use Ëcsv` module to read your file. Look for some tutorial with this keyword.</li>
<li>You can use Ëcollection.Counter` to count the number of occurrences of words. This can be useful. </li>
</ul>
| 0 | 2016-10-02T12:28:26Z | [
"python",
"nlp"
]
|
count words of different classes separately in a text file | 39,816,922 | <p>I have some text files in Persian. each file contains a lot of sentences, each in a new line. And in front of each sentence there is a tab, then a word, then a tab and then an English word. These English words in some files are 2, in some are 3, in some are 5 and in some other, are more or less. Actually, they show the sentences classes. I have to count each class's total words separately (just count the words of sentences not the words after them). For that I have to change the file to a list, so that I can achieve the sentences. Now the problem is that, how should I write the code that it returns each class's total words separately. Below is the sample sentences. </p>
<p><a href="http://i.stack.imgur.com/lMLsP.png" rel="nofollow"><img src="http://i.stack.imgur.com/lMLsP.png" alt="enter image description here"></a></p>
<pre><code>corpus = []
def CountWords (file):
with open (file, encoding = "utf-8") as f1:
for line in f1:
t = line.strip().split("\t")
corpus.append(t)
for row in corpus:
if row[2] != row[2]:
</code></pre>
<p>Now I don't know how to continue. I appreciate a lot if someone can help. (I have no background in programming).</p>
| 1 | 2016-10-02T12:19:06Z | 39,817,109 | <p>If I get you correctly then the next code might work. Please note, that I use Python 3.x.</p>
<pre><code>from collections import Counter
counter = Counter()
with open(filename, encoding='utf-8') as f:
for line in f:
*persian_words, word_class = line.strip().split()
counter[word_class] += len(persian_words) - 1
# Print the top 10 word classes with respective number of Persian words
for word_class, count in counter.most_common(10):
print('{}\t{}'.format(word_class, count))
</code></pre>
| 0 | 2016-10-02T12:40:55Z | [
"python",
"nlp"
]
|
Cannot get HTML to display SQLite3 data with python & flask | 39,816,944 | <p>I'm having an issue getting an HTML page to display my SQLite3 data using Python & Flask. I found a question on here and used the same code, plus different variations to no success. There are no error messages and the HTML page loads, however there is no data present. This is the code I am using to get the data;</p>
<pre><code>@app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
</code></pre>
<p>this is the code I attempting to use to display the data;</p>
<pre class="lang-html prettyprint-override"><code><table>
{% for item in items %}
<tr>
<td>{{column1}}</td>
<td>{{column2}}</td>
<td>{{column3}}</td>
<td>{{column4}}</td>
<td>{{column5}}</td>
<td>{{column6}}</td>
<td>{{column7}}</td>
<td>{{column8}}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>I tried changing 'column' to the actual db column name, with the same issue. I tried calling SELECT * instead of each individual column, same issue. If I run this code in python;</p>
<pre><code>con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson, shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
packages = getpackages.fetchall()
for row in packages:
print(row)
</code></pre>
<p>It returns the desired results. So I am thinking there is an issue with the HTML somewhere but I cannot figure it out.</p>
| -1 | 2016-10-02T12:21:44Z | 39,816,997 | <p>Please try the following code and let me know if it works for you:</p>
<pre><code><table>
{% for item in items %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
<td>{{ item[4] }}</td>
<td>{{ item[5] }}</td>
<td>{{ item[6] }}</td>
<td>{{ item[7] }}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p><strong>Test with the following code:</strong></p>
<p><strong><em>app.py</em></strong></p>
<pre><code>from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
app.secret_key = 'development key'
@app.route('/users')
def get_users():
con = sqlite3.connect('mydb.db')
db = con.cursor()
db.execute('insert into user values ("Aaa", "AAA")')
db.execute('insert into user values ("Bbb", "BBB")')
res = db.execute('select * from user')
return render_template('users.html', users=res.fetchall())
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
</code></pre>
<p><strong><em>templates/users.html</em></strong></p>
<pre><code><html !DOCTYPE>
<head>
<title>SQLite</title>
</head>
<body>
<table>
{% for user in users %}
<tr>
<td>{{ user[0] }}</td>
<td>{{ user[1] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
</code></pre>
| 0 | 2016-10-02T12:27:48Z | [
"python",
"html",
"flask",
"sqlite3",
"jinja2"
]
|
Cannot get HTML to display SQLite3 data with python & flask | 39,816,944 | <p>I'm having an issue getting an HTML page to display my SQLite3 data using Python & Flask. I found a question on here and used the same code, plus different variations to no success. There are no error messages and the HTML page loads, however there is no data present. This is the code I am using to get the data;</p>
<pre><code>@app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
</code></pre>
<p>this is the code I attempting to use to display the data;</p>
<pre class="lang-html prettyprint-override"><code><table>
{% for item in items %}
<tr>
<td>{{column1}}</td>
<td>{{column2}}</td>
<td>{{column3}}</td>
<td>{{column4}}</td>
<td>{{column5}}</td>
<td>{{column6}}</td>
<td>{{column7}}</td>
<td>{{column8}}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>I tried changing 'column' to the actual db column name, with the same issue. I tried calling SELECT * instead of each individual column, same issue. If I run this code in python;</p>
<pre><code>con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson, shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
packages = getpackages.fetchall()
for row in packages:
print(row)
</code></pre>
<p>It returns the desired results. So I am thinking there is an issue with the HTML somewhere but I cannot figure it out.</p>
| -1 | 2016-10-02T12:21:44Z | 39,817,387 | <p>Here is what I had to do.. For anyone else having this issue, I'm not sure why but Jinja did not want to let me access by index so I did..</p>
<pre><code>@app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
con.row_factory = sqlite3.Row
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
</code></pre>
<p>and change the HTML to..</p>
<pre><code><table>
{% for col in items %}
<tr>
<td>{{ col['pck_id'] }}</td>
<td>{{ col['client_id'] }}</td>
<td>{{ col['date'] }}</td>
<td>{{ col['price'] }}</td>
<td>{{ col['privatelesson'] }}</td>
<td>{{ col['shortgamelesson'] }}</td>
<td>{{ col['playinglesson'] }}</td>
<td>{{ col['notes'] }}</td>
</tr>
{% endfor %}
</table>
</code></pre>
<p>All working now, thank for pointing me in the right direction!</p>
| 0 | 2016-10-02T13:13:20Z | [
"python",
"html",
"flask",
"sqlite3",
"jinja2"
]
|
Scrapy extracting the wrong IMG SRC | 39,817,067 | <p>I'm trying to use Scrapy to get the <a href="https://www.tripadvisor.com/Attraction_Review-g155032-d1494256-Reviews-Gray_Line-Montreal_Quebec.html" rel="nofollow">URLs of images on a page</a> with ID <code>HERO_PHOTO</code>. The target element has the following HTML code</p>
<p><code><img alt="Photo of Gray Line" style="position: relative; left: -50px; top: 0px;" id="HERO_PHOTO" class="flexibleImage" src="https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg" width="352" height="260"></code></p>
<p>Within Chrome browser, running</p>
<pre><code>$('#HERO_PHOTO').attr('src')
</code></pre>
<p>grabs the URL correctly</p>
<pre><code>"https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg"
</code></pre>
<hr>
<p><strong>Problem</strong>:
However using the following CSS selector in Scrapy,</p>
<pre><code>response.css('#HERO_PHOTO::attr(src)').extract_first()
</code></pre>
<p>and</p>
<pre><code>response.css('#HERO_PHOTO').xpath('@src').extract_first()
</code></pre>
<p>and</p>
<pre><code>response.css('#HERO_PHOTO[src]').extract_first()
</code></pre>
<p>is giving us</p>
<pre><code>https://static.tacdn.com/img2/x.gif
</code></pre>
<p>Using <code>.extract()</code> also returned the same incorrect URL.</p>
<p>Why is Scrapy grabbing a different SRC value?</p>
| 1 | 2016-10-02T12:37:03Z | 39,817,707 | <p>I believe you are using the wrong css selector. Looking at <a href="http://www.w3schools.com/cssref/css_selectors.asp" rel="nofollow">w3 schools</a> it seems to select your attribute you want [src].</p>
<p>Try this.</p>
<p>response.css('#HERO_PHOTO[src]').extract_first()</p>
<p>my next suggestion is to see what you get without using the extract_first(). See if it's in the return value of response.css('#HERO_PHOTO[src]')</p>
<p><strong>EDIT:</strong> I think the issue you're experiencing is you are querying the page source, not the rendered html. Here's a link to what I believe is happening.</p>
<p><a href="http://stackoverflow.com/questions/18244908/inspect-element-and-view-source-code-are-showing-two-different-things">This Questions first answer</a></p>
<p>You are querying what the server had responded, not what JavaScript has had a chance to manipulate.</p>
| 0 | 2016-10-02T13:53:43Z | [
"python",
"css",
"python-2.7",
"scrapy"
]
|
Scrapy extracting the wrong IMG SRC | 39,817,067 | <p>I'm trying to use Scrapy to get the <a href="https://www.tripadvisor.com/Attraction_Review-g155032-d1494256-Reviews-Gray_Line-Montreal_Quebec.html" rel="nofollow">URLs of images on a page</a> with ID <code>HERO_PHOTO</code>. The target element has the following HTML code</p>
<p><code><img alt="Photo of Gray Line" style="position: relative; left: -50px; top: 0px;" id="HERO_PHOTO" class="flexibleImage" src="https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg" width="352" height="260"></code></p>
<p>Within Chrome browser, running</p>
<pre><code>$('#HERO_PHOTO').attr('src')
</code></pre>
<p>grabs the URL correctly</p>
<pre><code>"https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg"
</code></pre>
<hr>
<p><strong>Problem</strong>:
However using the following CSS selector in Scrapy,</p>
<pre><code>response.css('#HERO_PHOTO::attr(src)').extract_first()
</code></pre>
<p>and</p>
<pre><code>response.css('#HERO_PHOTO').xpath('@src').extract_first()
</code></pre>
<p>and</p>
<pre><code>response.css('#HERO_PHOTO[src]').extract_first()
</code></pre>
<p>is giving us</p>
<pre><code>https://static.tacdn.com/img2/x.gif
</code></pre>
<p>Using <code>.extract()</code> also returned the same incorrect URL.</p>
<p>Why is Scrapy grabbing a different SRC value?</p>
| 1 | 2016-10-02T12:37:03Z | 39,829,111 | <p>The image links are in the page, but not directly as <code><img></code> tags. There are indeed processed with some JavaScript code.
There is a JavaScript snippet inside the HTML with the image links you want (reformatted a bit):</p>
<pre><code>...
}(window,ta));
</script>
<script type="text/javascript">
var lazyImgs = [{
"data": "//maps.google.com/maps/api/staticmap?&channel=ta.desktop&zoom=15&size=340x225&client=gme-tripadvisorinc&sensor=falselanguageParam&center=45.503395,-73.573174&maptype=roadmap&&markers=icon:http%3A%2F%2Fc1.tacdn.com%2Fimg2%2Fmaps%2Ficons%2Fpin_v2_CurrentCenter.png|45.503395,-73.57317&signature=FqI7Z1egbpsVrlEE0yjw9HmsMJ8=",
"scroll": false,
"tagType": "img",
"id": "lazyload_1098682971_0",
"priority": 500,
"logerror": false
}, {
"data": "//ad.atdmt.com/i/img;p=11007200799198;cache=?ord=1475487471489",
"scroll": false,
"tagType": "img",
"id": "lazyload_1098682971_1",
"priority": 1000,
"logerror": false
}, {
"data": "//ad.doubleclick.net/ad/N4764.TripAdvisor/B7050081;sz=1x1?ord=1475487471489",
"scroll": false,
"tagType": "img",
"id": "lazyload_1098682971_2",
"priority": 1000,
"logerror": false
}, {
"data": "https://static.tacdn.com/img2/maps/icons/spinner24.gif",
"scroll": false,
"tagType": "img",
"id": "lazyload_1098682971_3",
"priority": 100,
"logerror": false
}, {
"data": "https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg",
"scroll": false,
"tagType": "img",
"id": "HERO_PHOTO",
"priority": 100,
"logerror": false
}, {
"data": "https://media-cdn.tripadvisor.com/media/photo-s/0c/f5/19/98/montreal-night-tour.jpg",
"scroll": false,
"tagType": "img",
"id": "THUMB_PHOTO1",
"priority": 100,
"logerror": false
}, {
"data": "https://media-cdn.tripadvisor.com/media/photo-s/0c/f5/19/8f/montreal-night-tour.jpg",
"scroll": false,
"tagType": "img",
"id": "THUMB_PHOTO2",
"priority": 100,
"logerror": false
}, {
"data": "https://static.tacdn.com/img2/generic/site/no_user_photo-v1.gif",
"scroll": false,
"tagType": "img",
"id": "lazyload_1098682971_4",
"priority": 100,
"logerror": false
}...
</code></pre>
<p>One way to parse this is to use <a href="https://pypi.python.org/pypi/js2xml" rel="nofollow"><code>js2xml</code></a>:</p>
<pre><code>from pprint import pprint
# get all `<script>`s content
for js in response.xpath('.//script[@type="text/javascript"]/text()').extract():
try:
jstree = js2xml.parse(js)
# look for assignment of `var lazyImgs`
for imgs in jstree.xpath('//var[@name="lazyImgs"]/*'):
# use js2xml.make_dict() -- poor name I know
# to build a useful Python object
data = js2xml.make_dict(imgs)
pprint(data)
break
except Exception as e:
pass
</code></pre>
<p>This is what you get out:</p>
<pre><code>[{'data': '//maps.google.com/maps/api/staticmap?&channel=ta.desktop&zoom=15&size=340x225&client=gme-tripadvisorinc&sensor=falselanguageParam&center=45.503395,-73.573174&maptype=roadmap&&markers=icon:http%3A%2F%2Fc1.tacdn.com%2Fimg2%2Fmaps%2Ficons%2Fpin_v2_CurrentCenter.png|45.503395,-73.57317&signature=FqI7Z1egbpsVrlEE0yjw9HmsMJ8=',
'id': 'lazyload_-1977833463_0',
'logerror': False,
'priority': 500,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/maps/icons/spinner24.gif',
'id': 'lazyload_-1977833463_1',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-s/04/71/70/7c/gray-line-tours-montreal.jpg',
'id': 'HERO_PHOTO',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-s/0c/f5/19/98/montreal-night-tour.jpg',
'id': 'THUMB_PHOTO1',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-s/0c/f5/19/8f/montreal-night-tour.jpg',
'id': 'THUMB_PHOTO2',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/generic/site/no_user_photo-v1.gif',
'id': 'lazyload_-1977833463_2',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/08/38/19/cb/gayle-h.jpg',
'id': 'lazyload_-1977833463_3',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_01.png',
'id': 'lazyload_-1977833463_4',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_02.png',
'id': 'lazyload_-1977833463_5',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_6',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_7',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/b1/32/93/holidays1958.jpg',
'id': 'lazyload_-1977833463_8',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_04.png',
'id': 'lazyload_-1977833463_9',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_04.png',
'id': 'lazyload_-1977833463_10',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_11',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_12',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_13',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-o/06/4d/bc/f6/disneybus.jpg',
'id': 'lazyload_-1977833463_14',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_06.png',
'id': 'lazyload_-1977833463_15',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_06.png',
'id': 'lazyload_-1977833463_16',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_17',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_18',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_19',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/a7/avatar078.jpg',
'id': 'lazyload_-1977833463_20',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_01.png',
'id': 'lazyload_-1977833463_21',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_22',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_23',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/9f/avatar070.jpg',
'id': 'lazyload_-1977833463_24',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_02.png',
'id': 'lazyload_-1977833463_25',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_03.png',
'id': 'lazyload_-1977833463_26',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_27',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_28',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/03/9f/a6/94/facebook-avatar.jpg',
'id': 'lazyload_-1977833463_29',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_04.png',
'id': 'lazyload_-1977833463_30',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_05.png',
'id': 'lazyload_-1977833463_31',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_32',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_33',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_34',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/06/f3/32/86/complsv.jpg',
'id': 'lazyload_-1977833463_35',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_04.png',
'id': 'lazyload_-1977833463_36',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_05.png',
'id': 'lazyload_-1977833463_37',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_38',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_39',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_40',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/05/f2/4d/68/christine-n.jpg',
'id': 'lazyload_-1977833463_41',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_03.png',
'id': 'lazyload_-1977833463_42',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_04.png',
'id': 'lazyload_-1977833463_43',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_44',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_45',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_46',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/80/avatar001.jpg',
'id': 'lazyload_-1977833463_47',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_03.png',
'id': 'lazyload_-1977833463_48',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_04.png',
'id': 'lazyload_-1977833463_49',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_50',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_51',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_52',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/0a/45/46/e2/tracey-g.jpg',
'id': 'lazyload_-1977833463_53',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/lvl_06.png',
'id': 'lazyload_-1977833463_54',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/rev_06.png',
'id': 'lazyload_-1977833463_55',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/FunLover.png',
'id': 'lazyload_-1977833463_56',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/badges/20px/Appreciated.png',
'id': 'lazyload_-1977833463_57',
'logerror': False,
'priority': 100,
'scroll': False,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/gray_flag.png',
'id': 'lazyload_-1977833463_58',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-f/02/6d/40/b2/montreal-amphi-bus-tour.jpg',
'id': 'lazyload_-1977833463_59',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/39/2d/43/old-montreal-walking.jpg',
'id': 'lazyload_-1977833463_60',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/06/df/96/c7/excursions-montreal-private.jpg',
'id': 'lazyload_-1977833463_61',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/02/ad/57/0a/filename-p1010076-jpg.jpg',
'id': 'lazyload_-1977833463_62',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-o/04/b5/6a/8d/ali-l.jpg',
'id': 'lazyload_-1977833463_63',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/87/avatar008.jpg',
'id': 'lazyload_-1977833463_64',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-o/06/8a/c5/7d/leonard-d.jpg',
'id': 'lazyload_-1977833463_65',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-o/05/6d/32/ca/rpm13111.jpg',
'id': 'lazyload_-1977833463_66',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/87/avatar008.jpg',
'id': 'lazyload_-1977833463_67',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/neighborhood/icon_hood_white.png',
'id': 'lazyload_-1977833463_68',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/oyster/500/08/5b/34/b0/sherbrooke-street-west-shopping--.jpg',
'id': 'lazyload_-1977833463_69',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/maps/icons/icon_mapControl_expand_idle_30x30.png',
'id': 'lazyload_-1977833463_70',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/maps/icons/icon_mapControl_expand_hover_30x30.png',
'id': 'lazyload_-1977833463_71',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/a1/f2/6b/marche-atwater.jpg',
'id': 'lazyload_-1977833463_72',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/01/41/78/a3/mcgill-university-lower.jpg',
'id': 'lazyload_-1977833463_73',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/04/06/16/08/musee-grevin.jpg',
'id': 'lazyload_-1977833463_74',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/03/4a/9a/85/laurie-raphael.jpg',
'id': 'lazyload_-1977833463_75',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/09/45/53/16/cafe-humble-lion.jpg',
'id': 'lazyload_-1977833463_76',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://media-cdn.tripadvisor.com/media/photo-l/03/2f/37/03/essence.jpg',
'id': 'lazyload_-1977833463_77',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/branding/logo_with_tagline.png',
'id': 'LOGOTAGLINE',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'},
{'data': 'https://static.tacdn.com/img2/icons/bell.png',
'id': 'lazyload_-1977833463_78',
'logerror': False,
'priority': 100,
'scroll': True,
'tagType': 'img'}]
</code></pre>
| 1 | 2016-10-03T10:07:16Z | [
"python",
"css",
"python-2.7",
"scrapy"
]
|
recursion of the form var += func(var, n-1) | 39,817,078 | <p>TL/DR How do you evaluate statements of the form <code>var += func(var, n-1)</code>?</p>
<p>edit: By 'evaluate' I mean, how is the value being called by the right side of this statement determined. Within the function given below, <code>var += func(var, n-1)</code> always results in <code>sum += sum</code>. But why is <code>sum</code> always called? why not <code>sum += (n-1)</code>? What determines which value is called by the right side? With the help of a few responses, I think I figured it out (see below), but more light on the subject will always be appreciated. I've only been learning programming for a few days.</p>
<p>I <a href="https://stackoverflow.com/questions/39814341/recursion-think-python-2-exercise-5-5/39814559#39814559">asked a question regarding a recursive function</a> and received an answer that I was satisfied with, but which raised several more questions. I've been looking through previous questions on the topic but I'm still missing something. It feels like recursion is a fundamental concept that must be grasped completely to succeed with programming, so I'd like to keep asking questions until I figure it out. The answerer offered another example function for me to contemplate:</p>
<pre><code>def foo(sum, n):
if (n == 0):
return sum
sum += foo(sum, n-1)
sum /= 2
return foo(sum, n-1)
</code></pre>
<p>I've never seen += used with a function with multiple arguments and I have no idea how to evaluate this. I added <code>print(sum)</code> after <code>sum += foo(sum, n-1)</code> and <code>sum /= 2</code> to try and see what was happening. Running <code>foo(10, 3)</code> resulted in:</p>
<pre class="lang-none prettyprint-override"><code>20
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
</code></pre>
<p>I decided to change the <code>+=</code> to <code>*=</code> to see if that would make what was happening more clear. This is that program:</p>
<pre><code>def foo(sum, n):
if (n == 0):
return sum
sum *= foo(sum, n-1)
print(sum)
sum /= 2
print(sum)
return foo(sum, n-1)
foo(10, 3)
</code></pre>
<p>It produced the following:</p>
<pre class="lang-none prettyprint-override"><code>100
50.0
500.0
250.0
62500.0
31250.0
312500.0
156250.0
24414062500.0
12207031250.0
1907348632812500.0
953674316406250.0
9.094947017729283e+29
4.5474735088646414e+29
</code></pre>
<p>I can trace a few different interwoven patterns in this output, (i.e. the original sum 10 is called in the 1st, 2nd and 4th instances; the output is in groups of two recursions, two recursions, and three recursions; the output of <code>sum/2</code> feeds the input of the 3rd, 5th and 7th instances), but I can't seem to unravel it without knowing how to evaluate the <code>sum *= foo(sum, n-1)</code> or the original <code>sum += foo(sum, n-1)</code>.</p>
| -1 | 2016-10-02T12:38:28Z | 39,817,146 | <p>In python, <code>x += y</code> is same as <em><code>x = x + y</code> i.e. add <code>y</code> to the value of <code>x</code> and save to <code>x</code></em>.</p>
<p>In your case, <code>sum += foo(sum, n-1)</code> means <em>add value returned by <code>foo(sum, n-1)</code> with <code>sum</code> and save it as <code>sum</code></em>.</p>
<p>It similarly goes for <code>*=</code>, <code>-=</code>, etc. For example: <code>x *= y</code> means <em>multiply y with x and save it as x</em>. Hope that answered your question.</p>
<p>Read: <a href="https://docs.python.org/2/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">Augmented Assignment Statements</a> for more information.</p>
| 0 | 2016-10-02T12:46:21Z | [
"python",
"python-3.x",
"recursion"
]
|
recursion of the form var += func(var, n-1) | 39,817,078 | <p>TL/DR How do you evaluate statements of the form <code>var += func(var, n-1)</code>?</p>
<p>edit: By 'evaluate' I mean, how is the value being called by the right side of this statement determined. Within the function given below, <code>var += func(var, n-1)</code> always results in <code>sum += sum</code>. But why is <code>sum</code> always called? why not <code>sum += (n-1)</code>? What determines which value is called by the right side? With the help of a few responses, I think I figured it out (see below), but more light on the subject will always be appreciated. I've only been learning programming for a few days.</p>
<p>I <a href="https://stackoverflow.com/questions/39814341/recursion-think-python-2-exercise-5-5/39814559#39814559">asked a question regarding a recursive function</a> and received an answer that I was satisfied with, but which raised several more questions. I've been looking through previous questions on the topic but I'm still missing something. It feels like recursion is a fundamental concept that must be grasped completely to succeed with programming, so I'd like to keep asking questions until I figure it out. The answerer offered another example function for me to contemplate:</p>
<pre><code>def foo(sum, n):
if (n == 0):
return sum
sum += foo(sum, n-1)
sum /= 2
return foo(sum, n-1)
</code></pre>
<p>I've never seen += used with a function with multiple arguments and I have no idea how to evaluate this. I added <code>print(sum)</code> after <code>sum += foo(sum, n-1)</code> and <code>sum /= 2</code> to try and see what was happening. Running <code>foo(10, 3)</code> resulted in:</p>
<pre class="lang-none prettyprint-override"><code>20
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
20.0
10.0
</code></pre>
<p>I decided to change the <code>+=</code> to <code>*=</code> to see if that would make what was happening more clear. This is that program:</p>
<pre><code>def foo(sum, n):
if (n == 0):
return sum
sum *= foo(sum, n-1)
print(sum)
sum /= 2
print(sum)
return foo(sum, n-1)
foo(10, 3)
</code></pre>
<p>It produced the following:</p>
<pre class="lang-none prettyprint-override"><code>100
50.0
500.0
250.0
62500.0
31250.0
312500.0
156250.0
24414062500.0
12207031250.0
1907348632812500.0
953674316406250.0
9.094947017729283e+29
4.5474735088646414e+29
</code></pre>
<p>I can trace a few different interwoven patterns in this output, (i.e. the original sum 10 is called in the 1st, 2nd and 4th instances; the output is in groups of two recursions, two recursions, and three recursions; the output of <code>sum/2</code> feeds the input of the 3rd, 5th and 7th instances), but I can't seem to unravel it without knowing how to evaluate the <code>sum *= foo(sum, n-1)</code> or the original <code>sum += foo(sum, n-1)</code>.</p>
| -1 | 2016-10-02T12:38:28Z | 39,823,561 | <p>While I still haven't figured exactly why the given function produces the output it does, I have finally figured the main question of the topic, namely, how to evaluate statements of the form <code>var += func(var, n-1)</code>.</p>
<p>While a statement of the form <code>x += y</code> is simple enough to understand, the function on the right side of the statement in question has multiple arguments. What I couldn't understand was which value from <code>func(var, n-1)</code> was to be used and how that was determined. So I experimented. I added a new first statement <code>mus = 3</code> to the function and replaced <code>sum += foo(sum, n-1)</code> with <code>mus += foo(sum, n-1)</code> and printed the result. I reversed the arguments positions in the function and checked the result. And I added a third argument to the function and checked that. Every time, the value of <code>sum</code> was called in every variation of <code>sum += foo(sum, n-1)</code>. </p>
<p>And then I deleted <code>sum</code> from <code>return sum</code> and ran it, which produced a <code>TypeError</code> and then it clicked. So I changed it to <code>return n-1</code>, and then that became the value that was called in <code>sum += foo(sum, n-1)</code>. I changed it to the new third variable I had added, <code>return x</code> and then that was the value called.</p>
<p>So it seems that in order to evaluate statements of the form <code>var += func(var, n-1)</code>, you must check to see which argument is returned in the base case when the function is run. Corrections would be greatly appreciated if I'm wrong~</p>
| 0 | 2016-10-03T01:50:20Z | [
"python",
"python-3.x",
"recursion"
]
|
typing.Any vs object? | 39,817,081 | <p>Is there any difference between using <code>typing.Any</code> as opposed to <code>object</code> in typing? For example:</p>
<pre><code>def get_item(L: list, i: int) -> typing.Any:
return L[i]
</code></pre>
<p>Compared to:</p>
<pre><code>def get_item(L: list, i: int) -> object:
return L[i]
</code></pre>
| 4 | 2016-10-02T12:38:34Z | 39,817,126 | <p>Yes, there is a difference. Although in Python 3, all objects are instances of <code>object</code>, including <code>object</code> itself, only <code>Any</code> documents that the return value should be disregarded by the typechecker.</p>
<p>The <code>Any</code> type docstring states that object is a subclass of <code>Any</code> and vice-versa:</p>
<pre><code>>>> import typing
>>> print(typing.Any.__doc__)
Special type indicating an unconstrained type.
- Any object is an instance of Any.
- Any class is a subclass of Any.
- As a special case, Any and object are subclasses of each other.
</code></pre>
<p>However, a proper typechecker (one that goes beyond <code>isinstance()</code> checks, and which inspects how the object is actually <em>used</em> in the function) can readily object to <code>object</code> where <code>Any</code> is always accepted.</p>
<p>From the <a href="https://docs.python.org/3/library/typing.html#the-any-type" rel="nofollow"><code>Any</code> type documentation</a>:</p>
<blockquote>
<p>Notice that no typechecking is performed when assigning a value of type <code>Any</code> to a more precise type.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Contrast the behavior of <code>Any</code> with the behavior of <code>object</code>. Similar to <code>Any</code>, every type is a subtype of <code>object</code>. However, unlike <code>Any</code>, the reverse is not true: object is not a subtype of every other type.</p>
<p>That means when the type of a value is <code>object</code>, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error.</p>
</blockquote>
<p>and from the mypy documentation section <a href="http://mypy.readthedocs.io/en/latest/dynamic_typing.html#any-vs-object" rel="nofollow"><em>Any vs. object</em></a>:</p>
<blockquote>
<p>The type <code>object</code> is another type that can have an instance of arbitrary type as a value. Unlike <code>Any</code>, <code>object</code> is an ordinary static type (it is similar to <code>Object</code> in Java), and only operations valid for all types are accepted for object values.</p>
</blockquote>
<p><code>object</code> can be <a href="http://mypy.readthedocs.io/en/latest/casts.html#casts" rel="nofollow">cast</a> to a more specific type, while <code>Any</code> really means <em>anything goes</em> and a type checker disengages from any use of the object (even if you later assign such an object to a name that <em>is</em> typechecked).</p>
<p>You already painted your function into a an un-typed corner by accepting <code>list</code>, which comes down to being the same thing as <code>List[Any]</code>. The typechecker <em>disengaged there</em> and the return value no longer matters, but since your function accepts a list containing <code>Any</code> objects, the proper return value would be <code>Any</code> here.</p>
<p>To properly participate in type-checked code, you need to mark your input as <code>List[T]</code> (a genericly typed container) for a typechecker to then be able to care about the return value. Which in your case would be <code>T</code> since you are retrieving a value from the list. Create <code>T</code> from a <code>TypeVar</code>:</p>
<pre><code>from typing import TypeVar, List
T = TypeVar('T')
def get_item(L: List[T], i: int) -> T:
return L[i]
</code></pre>
| 5 | 2016-10-02T12:43:19Z | [
"python",
"python-3.5",
"type-hinting"
]
|
typing.Any vs object? | 39,817,081 | <p>Is there any difference between using <code>typing.Any</code> as opposed to <code>object</code> in typing? For example:</p>
<pre><code>def get_item(L: list, i: int) -> typing.Any:
return L[i]
</code></pre>
<p>Compared to:</p>
<pre><code>def get_item(L: list, i: int) -> object:
return L[i]
</code></pre>
| 4 | 2016-10-02T12:38:34Z | 39,821,459 | <p><code>Any</code> and <code>object</code> are superficially similar, but in fact are entirely <em>opposite</em> in meaning.</p>
<p><code>object</code> is the <em>root</em> of Python's metaclass hierarchy. Every single class inherits from <code>object</code>. That means that <code>object</code> is in a certain sense the most restrictive type you can give values. If you have a value of type <code>object</code>, the only methods you are permitted to call are ones that are a part of every single object. For example:</p>
<pre><code>foo = 3 # type: object
# Error, not all objects have a method 'hello'
bar = foo.hello()
# OK, all objects have a __str__ method
print(str(foo))
</code></pre>
<p>In contrast, <code>Any</code> is an <em>escape hatch</em> meant to allow you to mix together dynamic and statically typed code. <code>Any</code> is the least restrictive type -- any possible method or operation is permitted on a value of type <code>Any</code>. For example:</p>
<pre><code>from typing import Any
foo = 3 # type: Any
# OK, foo could be any type, and that type might have a 'hello' method
# Since we have no idea what hello() is, `bar` will also have a type of Any
bar = foo.hello()
# Ok, for similar reasons
print(str(foo))
</code></pre>
<p>You should generally try and use <code>Any</code> only for cases where...</p>
<ol>
<li>As a way of mixing together dynamic and statically typed code. For example, if you have many dynamic and complex functions, and don't have time to fully statically type all of them, you could settle for just giving them a return type of Any to nominally bring them into the typechecked work. (Or to put it another way, Any is a useful tool for helping migrate an untypechecked codebase to a typed codebase in stages).</li>
<li>As a way of giving a type to an expression that is difficult to type. For example, Python's type annotations currently do not support recursive types, which makes typing things like arbitrary JSON dicts difficult. As a temporary measure, you might want to give your JSON dicts a type of <code>Dict[str, Any]</code>, which is a bit better then nothing.</li>
</ol>
<p>In contrast, use <code>object</code> for cases where you want to indicate in a typesafe way that a value MUST literally work with any possible object in existence.</p>
<p>My recommendation is to avoid using <code>Any</code> except in cases where there is no alternative. <code>Any</code> is a concession -- a mechanism for allowing dynamism where we'd really rather live in a typesafe world.</p>
<p>For more information, see:</p>
<ul>
<li><a href="https://docs.python.org/3/library/typing.html#the-any-type" rel="nofollow">https://docs.python.org/3/library/typing.html#the-any-type</a></li>
<li><a href="http://mypy.readthedocs.io/en/latest/kinds_of_types.html#the-any-type" rel="nofollow">http://mypy.readthedocs.io/en/latest/kinds_of_types.html#the-any-type</a></li>
</ul>
<hr>
<p>For your particular example, I would use <em>TypeVars</em>, rather then either object or Any. What you want to do is to indicate that you want to return the type of whatever is contained within the list. If the list will always contain the same type (which is typically the case), you would want to do:</p>
<pre><code>from typing import List, TypeVar
T = TypeVar('T')
def get_item(L: List[T], i: int) -> T:
return L[i]
</code></pre>
<p>This way, your <code>get_item</code> function will return the most precise type as possible.</p>
| 3 | 2016-10-02T20:37:09Z | [
"python",
"python-3.5",
"type-hinting"
]
|
How to get python tcp server/client to allow multiple clients on ant the same time | 39,817,110 | <p>I have started to make my own TCP server and client. I was able to get the server and the client to connect over my LAN network. But when I try to have another client connect to make a three way connection, it does not work. What will happen is only when the first connected client has terminated the connection between, the server and the client, can the other client connect and start the chat session. I do not understand why this happens. I have tried threading, loops, and everything else I can think of. I would appreciate any advice. I feel like there is just one small thing i am missing and I can not figure out what it is.</p>
<h2>Here is my server:</h2>
<pre><code>import socket
from threading import Thread
def whatBeip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
local_ip_address = s.getsockname()[0]
print('Current Local ip: ' + str(local_ip_address))
def clietConnect():
conn, addr = s.accept()
print 'Connection address:', addr
i = True
while i == True:
data = conn.recv(BUFFER_SIZE)
if not data:
break
print('IM Recieved: ' + data)
conn.sendall(data) # echo
whatBeip()
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 1024
peopleIn = 4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(peopleIn)
for client in range(peopleIn):
Thread(target=clietConnect()).start()
conn.close()
</code></pre>
<h2>Here is my client</h2>
<pre><code>import socket
TCP_IP = '10.255.255.3'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
i = True
while i == True:
s.sendall(raw_input('Type IM: '))
data = s.recv(BUFFER_SIZE)
s.close()
</code></pre>
| 0 | 2016-10-02T12:40:59Z | 39,817,244 | <p>This is your main problem: <code>Thread(target=clietConnect()).start()</code> executes the function <code>clientConnect</code> and uses it's return value as the Thread function (which is None, so the Thread does nothing)</p>
<p>Also have a look at:</p>
<p>1) You should wait for all connections to close instead of <code>conn.close()</code> in the end of the server:</p>
<pre><code>threads = list()
for client in range(peopleIn):
t = Thread(target=clietConnect)
t.start()
threads.append(t)
for t in threads: t.join()
</code></pre>
<p>and to close the connection when no data is received:</p>
<pre><code> if not data:
conn.close()
return
</code></pre>
<p>2) You probably want to use SO_REUSEADDR [ <a href="http://stackoverflow.com/questions/14388706/">Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?</a> , <a href="http://stackoverflow.com/questions/6380057/">Python: Binding Socket: "Address already in use"</a> ]</p>
<p>3) And have a look at asyncio for python</p>
| 0 | 2016-10-02T12:56:28Z | [
"python",
"tcp"
]
|
Python, when import from module cmd I haven't all attribute | 39,817,181 | <p>When i import module urllib in cmd i have only magic fuctions but when I import this module from Spyder I have all attribute.
I'a adding printscreen of this.
Why can not I import all attribute?</p>
<p><a href="http://i.stack.imgur.com/h1PGf.png" rel="nofollow">enter image description here</a></p>
| 0 | 2016-10-02T12:49:33Z | 39,817,288 | <p>To import all attributes of a module into the global namespace use <code>from module import *</code>. </p>
<p>While <code>dir()</code> simply lists the attributes of the global namespace, <code>dir(module)</code> lists the ones in the scope of the specific module.</p>
<p>Anyway, when you <code>import urllib</code> you can still reach all attributes if you specify the module name, e.g. <code>urllib.request</code>. </p>
| 0 | 2016-10-02T13:01:52Z | [
"python",
"python-3.x",
"cmd"
]
|
PYTHON: AttributeError: 'int' object has no attribute 'hand' | 39,817,223 | <p>So I have an exercise on python - building a BlackJack game.
I have started with defining how every phrase of the game would go.
Now when I run this code below, In case the input is '0' - which means you don't want cards anymore, it runs perfectly. But when the input is '1' - which means you want to pick card, I get an error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 1, in <module>
class blackjack(object):
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 34, in blackjack
player(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 25, in player
PickCard(1)
File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 18, in PickCard
self.hand+= random.randrange(1, 13)
AttributeError: 'int' object has no attribute 'hand'
</code></pre>
<p>The code:</p>
<pre><code>class blackjack(object):
#this func defines how player should react
def player(self):
#this func defines what case of technical loosing
def loser():
print("You have reached", hand , ". Which is beyond 21. Therefor, you have lost the game. Better luck next time!")
#this func is responsible for picking card issue.
def PickCard(self):
import random
x=1
while x == 1:
pick = int(raw_input("Enter 1 if you want another card, else Enter 0"))
if pick == 1:
self.hand = self.hand + random.randrange(1, 13)
else:
x=0
import random
print "Now your first card will automatically be given to you:"
hand=random.randrange(1,13)
print "hand: ", hand
PickCard(1)
print hand
if hand>21:
loser()
elif hand==21:
pass
else:
pass
player(1)
</code></pre>
<p>Thanks in advance.</p>
| 0 | 2016-10-02T12:54:22Z | 39,817,321 | <p>You are making the function call as <code>player(1)</code> where the <code>player</code> function expects the argument as of <code>self</code> type .i.e. instance of the class <code>blackjack</code>. Hence, while doing <code>self.hand = self.hand + random.randrange(1, 13)</code> it is throwing the above mentioned error.</p>
<hr>
<p><em>I think</em> you do not want to make a call to <code>player()</code> function from within the class, Is it? Move that part to outside the class. Firstly create the object of class <code>blackjack</code> (Note: In Python, class names should be defined as CamelCase variables like: BlackJack). For example:</p>
<pre><code>blackjack_obj = blackjack()
</code></pre>
<p>Then call the <code>player()</code> function as:</p>
<pre><code>blackjack_obj.player()
</code></pre>
| 0 | 2016-10-02T13:06:20Z | [
"python",
"python-2.7",
"int",
"attributeerror"
]
|
QPlainTextEdit widget in PyQt5 with clickable text | 39,817,251 | <p>I am trying to build a simple code/text editor in PyQt5. Three important functionalities of a code-editor come to my mind:<br>
(1) <em>Syntax highlighting</em><br>
(2) <em>Code completion</em><br>
(3) <em>Clickable functions and variables</em><br>
<br>
I plan to base the code editor on a <code>QPlainTextEdit</code> widget. For the syntax highlighting, I will use the <code>QSyntaxHighlighter</code>:<br>
<a href="https://doc.qt.io/qt-5/qsyntaxhighlighter.html#details" rel="nofollow">https://doc.qt.io/qt-5/qsyntaxhighlighter.html#details</a> <br>
I have not yet figured out how to do code completion, but will worry about that feature later on. The showstopper right now is 'clickable functions and variables'. In mature code editors, one can click on a function call and jump to the definition of that function. The same holds for variables.<br>
<br>
I know that asking "how do I implement this feature?" is way too broad. So let's narrow it down to the following problem:<br>
<em>How can you make a certain word clickable in a <code>QPlainTextEdit</code> widget? An arbitrary Python function should get called when the word gets clicked. That Python function should also know what word was clicked to take appropriate action. Making the word light up blue-ish when the mouse hovers over it would be a nice bonus.</em>
<br>
<br>
I have written a small test-code, so you have a Qt window with a <code>QPlainTextEdit</code> widget in the middle to play around with:
<a href="http://i.stack.imgur.com/BmK5L.png" rel="nofollow"><img src="http://i.stack.imgur.com/BmK5L.png" alt="enter image description here"></a></p>
<p>Here is the code:</p>
<pre><code>import sys
import os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
##################################################
# 'testText' is a snippet of C-code that #
# will get displayed in the text editor. #
##################################################
testText = '\
# include <stdio.h>\n\
# include <stdbool.h>\n\
# include <stdint.h>\n\
# include "../FreeRTOS/Kernel/kernel.h"\n\
\n\
int main(void)\n\
{\n\
/* Reset all peripherals*/\n\
HAL_Init();\n\
\n\
/* Configure the system clock */\n\
SystemClock_Config();\n\
\n\
/* Initialize all configured peripherals */\n\
MX_GPIO_Init();\n\
MX_SPI1_Init();\n\
MX_SPI2_Init();\n\
MX_SPI3_Init();\n\
}\n\
'
##################################################
# A simple text editor #
# #
##################################################
class MyMainWindow(QMainWindow):
def __init__(self):
super(MyMainWindow, self).__init__()
# Define the geometry of the main window
self.setGeometry(200, 200, 800, 800)
self.setWindowTitle("text editor test")
# Create center frame
self.centerFrm = QFrame(self)
self.centerFrm.setStyleSheet("QWidget { background-color: #ddeeff; }")
self.centerLyt = QVBoxLayout()
self.centerFrm.setLayout(self.centerLyt)
self.setCentralWidget(self.centerFrm)
# Create QTextEdit
self.myTextEdit = QPlainTextEdit()
self.myTextEdit.setPlainText(testText)
self.myTextEdit.setStyleSheet("QPlainTextEdit { background-color: #ffffff; }")
self.myTextEdit.setMinimumHeight(500)
self.myTextEdit.setMaximumHeight(500)
self.myTextEdit.setMinimumWidth(700)
self.myTextEdit.setMaximumWidth(700)
self.centerLyt.addWidget(self.myTextEdit)
self.show()
if __name__== '__main__':
app = QApplication(sys.argv)
QApplication.setStyle(QStyleFactory.create('Fusion'))
myGUI = MyMainWindow()
app.exec_()
del app
sys.exit()
</code></pre>
| 0 | 2016-10-02T12:57:01Z | 39,818,545 | <p>Maybe you can utilize <a href="https://github.com/hlamer/qutepart" rel="nofollow">qutepart</a>. It looks like it does what you need. If you can't use it, then maybe you can look at the source code to see how they implemented different features, like clickable text.</p>
| 1 | 2016-10-02T15:28:31Z | [
"python",
"qt",
"pyqt",
"pyqt5"
]
|
Regex pattern within text | 39,817,302 | <p>I have a long string of data which looks like:</p>
<pre><code>dstgfsda12345.123gsrsvrvsdfcsd23456.234tsrsd
</code></pre>
<p>Notice that the '12345.123' pattern is the same. I want to split the string on it using python (so <code>s.split(<regex>)</code>).</p>
<p>What would be the appropriate regex?</p>
<pre><code>'[0-9]{5}.[0-9]{3}'
</code></pre>
<p>does not work; I presume it expects whitespace around it(?).</p>
| 2 | 2016-10-02T13:03:42Z | 39,817,357 | <p>Just escape <code>.</code>, and you are done:</p>
<pre><code>\d{5}\.\d{3}
</code></pre>
<p>You can use Regex token <code>\d</code> as a shorthand for <code>[0-9]</code>.</p>
<p><strong>Example:</strong></p>
<pre><code>>>> re.split(r'\d{5}\.\d{3}', 'dstgfsda12345.123gsrsvrvsdfcsd23456.234tsrsd')
['dstgfsda', 'gsrsvrvsdfcsd', 'tsrsd']
</code></pre>
| 4 | 2016-10-02T13:10:12Z | [
"python",
"regex"
]
|
Regex pattern within text | 39,817,302 | <p>I have a long string of data which looks like:</p>
<pre><code>dstgfsda12345.123gsrsvrvsdfcsd23456.234tsrsd
</code></pre>
<p>Notice that the '12345.123' pattern is the same. I want to split the string on it using python (so <code>s.split(<regex>)</code>).</p>
<p>What would be the appropriate regex?</p>
<pre><code>'[0-9]{5}.[0-9]{3}'
</code></pre>
<p>does not work; I presume it expects whitespace around it(?).</p>
| 2 | 2016-10-02T13:03:42Z | 39,817,375 | <p>I don't understand exactly what's your actual need but seems that you want your regex to isolate each occurrence of 5 digits, dot, 3 digits.</p>
<p>So instead of <code>'[0-9]{5}.[0-9]{3}'</code> you must use <code>'[0-9]{5}\.[0-9]{3}'</code>, because <code>.</code> matches any character, while <code>\.</code> matches only a dot.</p>
| 1 | 2016-10-02T13:12:17Z | [
"python",
"regex"
]
|
Regex pattern within text | 39,817,302 | <p>I have a long string of data which looks like:</p>
<pre><code>dstgfsda12345.123gsrsvrvsdfcsd23456.234tsrsd
</code></pre>
<p>Notice that the '12345.123' pattern is the same. I want to split the string on it using python (so <code>s.split(<regex>)</code>).</p>
<p>What would be the appropriate regex?</p>
<pre><code>'[0-9]{5}.[0-9]{3}'
</code></pre>
<p>does not work; I presume it expects whitespace around it(?).</p>
| 2 | 2016-10-02T13:03:42Z | 39,817,406 | <p>Your regex should be <code>'\d{5}\.\d{3}'</code>. </p>
<p>Check the usage of <code>.</code> instead of <code>\.</code>. That is because, '.' (Dot.) in the default mode, matches any character except a newline. Refer <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regex</a> document. Whereas <code>\s</code> means <code>dot</code> in your string.</p>
<p>For example:</p>
<pre><code>import re
my_string = 'dstgfsda12345.123gsrsvrvsdfcsd23456.234tsrsd'
my_regex = '\d{5}\.\d{3}'
re.split(my_regex, my_string)
# returns: ['dstgfsda', 'gsrsvrvsdfcsd', 'tsrsd']
</code></pre>
<p><strong>Explanation</strong> on how <code>'\d{5}\.\d{3}'</code> works:</p>
<p><code>\d</code> means any digit between <code>0-9</code>. <code>\d{5}</code> sub-string with any 5 consecutive digits. <code>\.</code> means digits followed by single <code>.</code>. At last <code>\d{3}</code> means any 3 digits after <code>.</code> </p>
| 1 | 2016-10-02T13:15:02Z | [
"python",
"regex"
]
|
Not understanding return behavior in python | 39,817,307 | <p>I was just trying a simple code:</p>
<pre><code>import sys
def main():
print "this is main"
return "string1"
if __name__ == "__main__":
sys.exit(main())
</code></pre>
<p>And when I run this piece of code, it gives random result, sometimes "string1" before "this is main" and sometimes after it.</p>
<p>Why is it so?</p>
<p>2 sample outputs:</p>
<blockquote>
<p>this is main </p>
<p>string1</p>
<p>Process finished with exit code 1</p>
</blockquote>
<p>============</p>
<blockquote>
<p>string1</p>
<p>this is main</p>
<p>Process finished with exit code 1</p>
</blockquote>
| 1 | 2016-10-02T13:03:57Z | 39,817,337 | <p><code>sys.exit</code> takes the return value of <code>main()</code> and produces it as the error code of the application. The value should usually be numeric, though Python is being a bit tricky here.</p>
<p>From the documentation of <a href="https://docs.python.org/2/library/sys.html?highlight=sys%20exit#sys.exit" rel="nofollow">sys.exit</a>:</p>
<blockquote>
<p>If another type of object is passed, None is equivalent to passing
zero, and any other object is printed to stderr and results in an exit
code of 1. In particular, sys.exit("some error message") is a quick
way to exit a program when an error occurs.</p>
</blockquote>
<p>So what may be happening is a race between flushing of <code>stdout</code> (for <code>print</code>) and the output to <code>stderr</code> as specified above.</p>
<p>I suggest you try to flush <code>stdout</code> after the <code>print</code> (<code>sys.stdout.flush</code>) and see if you get consistent output that way.</p>
| 2 | 2016-10-02T13:08:05Z | [
"python"
]
|
How can I allow spaces in a Django username regex? | 39,817,348 | <p>I am trying to allow spaces to be accepted into the username field of the default django.contrib.auth.models User, other people have asked directly or similar questions before: <a href="http://stackoverflow.com/questions/19911087/how-can-i-allow-spaces-in-a-django-username">Here</a>, <a href="http://stackoverflow.com/questions/1214453/allowing-the-character-in-usernames-in-the-django-admin-interface">Here</a>, and <a href="http://stackoverflow.com/questions/9828177/django-auth-manipulate-model-fields-allow-space-in-usernames">Here</a>. I have tried to implement these suggestions however I cannot seem to find a good example of how to get this to work. </p>
<p>From what I understand I need to change the regex in the username field validator, to do this I can override the UserCreationForm from contrib.auth.forms to implement a different field for username and provide my own validation. (as suggested in <a href="http://stackoverflow.com/questions/9828177/django-auth-manipulate-model-fields-allow-space-in-usernames">this</a> answer). </p>
<p>How specifically do I do this?</p>
<p>for reference, this is currently what I am using as a signup form:</p>
<pre><code>class SignUpForm(forms.ModelForm):
"""
This form class is for creating a player
"""
username = forms.CharField(label='Gamertag', max_length=16, widget=forms.TextInput(attrs={'placeholder': 'Gamertag', 'class': 'form-input'}))
email = forms.EmailField(label='email', widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-input', 'type':'email'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-input'}))
class Meta:
model = User
fields = ['username',
'email',
'password']
widgets = {
'password': forms.PasswordInput(),
}
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError(u'A user with that email already exists.')
return email
</code></pre>
| 0 | 2016-10-02T13:09:33Z | 39,820,162 | <p>You'll need to modify the user where the validator exists. The following code should work for Django 1.9. </p>
<p>With this user below you should be able to use <code>MyUser</code> instead of <code>User</code> for the form that you wrote. </p>
<pre><code>from django.contrib.auth.models import AbstractUser
from django.core import validators
class MyUser(AbstractUser):
validators=[
validators.RegexValidator(
r'^[\w.@+-\s]+$',
_('Enter a valid username. This value may contain only '
'letters, numbers, spaces ' 'and @/./+/-/_ characters.')
),
],
class Meta:
proxy = True # If no new field is added.
</code></pre>
<p>If you want to do it in Django 1.10 you'll have to change the code slightly. In Django 1.10 a new property was added <code>username_validator</code> and you'll have to override that. You can read more about it in the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.username_validator" rel="nofollow">manual</a>. </p>
<p>If you're using python2 you'll have to override <code>ASCIIUsernameValidator</code> or if you using python3 you'll have to override <code>UnicodeUsernameValidator</code>. For simplicity I'll assume that you're using python3. You can see the source code of the validation <a href="https://github.com/django/django/blob/1.10.1/django/contrib/auth/validators.py#L19-L26" rel="nofollow">here</a>.</p>
<pre><code>from django.contrib.auth.models import User
from django.contrib.auth.validators import UnicodeUsernameValidator
class MyValidator(UnicodeUsernameValidator):
regex = r'^[\w.@+-\s]+$'
class MyUser(User):
username_validator = MyValidator
class Meta:
proxy = True # If no new field is added.
</code></pre>
| 0 | 2016-10-02T18:18:58Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
]
|
Python - generating parent/child dict structure | 39,817,405 | <p>I have method:</p>
<pre><code>@staticmethod
def get_blocks():
"""Public method that can be extended to add new blocks.
First item is the most parent. Last item is the most child.
Returns:
blocks (list)
"""
return ['header', 'body', 'footer']
</code></pre>
<p>As docstring describes, this method can be extended , to return any kind of blocks in particular order.</p>
<p>So I want to make a mapping that would indicate which block is parent/child to each other (only caring about "nearest" parent/child).</p>
<pre><code>def _get_blocks_mapping(blocks):
mp = {'parent': {}, 'child': {}}
if not blocks:
return mp
mp['parent'][blocks[0]] = None
mp['child'][blocks[-1]] = None
blocks_len = len(blocks)
if blocks_len > 1:
mp['parent'][blocks[-1]] = blocks[-2]
for i in range(1, len(blocks)-1):
mp['parent'][blocks[i]] = blocks[i-1]
mp['child'][blocks[i]] = blocks[i+1]
return mp
</code></pre>
<p>So result if we have three blocks like in <code>get_blocks</code> method is this:</p>
<pre><code>{
'parent': {
'header': None,
'body': 'header',
'footer': 'body',
},
'child': {
'header': 'body',
'body': 'footer',
'footer': None
}
}
</code></pre>
<p>Well it works, but it is kind of hacky to me. So maybe someone could suggest a better way to create such mapping? (or maybe there is some used way of creating parent/child mapping? Using different structure than I intend to use?)</p>
| 1 | 2016-10-02T13:14:58Z | 39,817,468 | <p>You want to loop over the list in pairs, giving you the natural parent-child relationships:</p>
<pre><code>mp = {'parent': {}, 'child': {}}
if blocks:
mp['parent'][blocks[0]] = mp['child'][blocks[-1]] = None
for parent, child in zip(blocks, blocks[1:]):
mp['parent'][child] = parent
mp['child'][parent] = child
</code></pre>
<p><code>zip()</code> here pairs up each block with the next one in the list.</p>
<p>Demo:</p>
<pre><code>>>> blocks = ['header', 'body', 'footer']
>>> mp = {'parent': {}, 'child': {}}
>>> if blocks:
... mp['parent'][blocks[0]] = mp['child'][blocks[-1]] = None
... for parent, child in zip(blocks, blocks[1:]):
... mp['parent'][child] = parent
... mp['child'][parent] = child
...
>>> from pprint import pprint
>>> pprint(mp)
{'child': {'body': 'footer', 'footer': None, 'header': 'body'},
'parent': {'body': 'header', 'footer': 'body', 'header': None}}
</code></pre>
| 1 | 2016-10-02T13:23:20Z | [
"python",
"list",
"python-2.7",
"dictionary",
"parent-child"
]
|
contact form on google app engine | 39,817,482 | <p>I have a website running on google app engine and would like to include a contact form.
My app.yaml looks like this:</p>
<pre><code>version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /
static_files: www/index.html
upload: www/index.html
- url: /(.*)
static_files: www/\1
upload: www/(.*)
</code></pre>
<p>which is working fine for the static files, but how can i include the py file for the contact form?</p>
<p>I already tried to run it with this app.yaml file:</p>
<pre><code>version: 1
runtime: python27
api_version: 1
threadsafe: true
libraries:
- name: jinja2
version: latest
- name: webapp2
version: latest
handlers:
- url: /
static_files: www/index.html
upload: www/index.html
- url: /(.*)
static_files: www/\1
upload: www/(.*)
- url: /.*
script: www/contactForm.app
</code></pre>
<p>but it didn't work, e-mail isn't sent
my py file looks like this:</p>
<pre><code>import webapp2
import jinja2
import os
from google.appengine.api import mail
jinja_environment = jinja2.Environment(autoescape=True,loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class contact(webapp2.RequestHandler):
template = jinja_environment.get_template('contact.html')
def get(self):
self.response.out.write(self.template.render())
def post(self):
# takes input from user
vorname=self.request.get("vorname")
...
message=mail.EmailMessage(sender="authorized sender address",subject="Kontaktformular")
if not mail.is_email_valid(userMail):
self.response.out.write("Wrong email! Check again!")
message.to="..."
message.body=""" Hallo:
Vorname: %s
...
Text: %s""" %(vorname,...,text)
message.send()
self.response.out.write("Message sent!")
app = webapp2.WSGIApplication([('/contact',contact)], debug=True)
</code></pre>
<p>Does someone know how to make it work?</p>
| 3 | 2016-10-02T13:24:48Z | 39,818,474 | <p>Your contact form handler isn't being hit because you have a catch-all rule that precedes it. Also, your contact form handler needs its own URL rather than it too having a catch-all pattern. Try this:</p>
<pre><code>version: 1
runtime: python27
api_version: 1
threadsafe: true
libraries:
- name: jinja2
version: latest
- name: webapp2
version: latest
handlers:
- url: /
static_files: www/index.html
upload: www/index.html
- url: /contact
script: www/contactForm.app
- url: /(.*)
static_files: www/\1
upload: www/(.*)
</code></pre>
<p>Also, your Python appears invalid due to lack of tabs/spaces to indent your code. Should be more like:</p>
<pre><code>import webapp2
import jinja2
import os
from google.appengine.api import mail
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__),
'templates')))
class contact(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('contact.html')
self.response.out.write(self.template.render())
def post(self):
# takes input from user
vorname=self.request.get("vorname")
# ...
if not mail.is_email_valid(userMail):
self.response.out.write("Wrong email! Check again!")
message=mail.EmailMessage(sender="authorized sender address",
subject="Kontaktformular")
message.to="..."
message.body=""" Hallo:
Vorname: %s
...
Text: %s""" %(vorname,...,text)
message.send()
self.response.out.write("Message sent!")
app = webapp2.WSGIApplication([('/contact',contact)], debug=True)
</code></pre>
| 1 | 2016-10-02T15:21:08Z | [
"python",
"google-app-engine",
"web-deployment",
"contact-form"
]
|
Python sorted plot | 39,817,545 | <p>I want to use seaborn to perform a <code>sns.barplot</code> where the values are ordered e.g. in ascending order.</p>
<p>In case the <code>order</code> parameter of seaborn is set the plot seems to duplicate the labels for all non-NaN labels.</p>
<p>Trying to pre-sort the values like <code>mydf.sort_values(['myValueField'], ascending=False)</code> does not change the result as seaborn does not seem to interpret it.</p>
| 1 | 2016-10-02T13:33:44Z | 39,817,575 | <p>Do you save the changes by <code>pd.sort_values</code>? If not, probably you have to add the <code>inplace</code> keyword:</p>
<p><code>mydf.sort_values(['myValueField'], ascending=False, inplace=True)</code></p>
| 1 | 2016-10-02T13:37:37Z | [
"python",
"sorting",
"plot",
"bar-chart",
"seaborn"
]
|
Import my cythonized package in python | 39,817,572 | <p>I have a script_function_cython.pyx file containing a single function:</p>
<pre><code>import numpy as np
import scipy.misc as misc
import matplotlib.pyplot as plt
def my_function(img, kernel):
assert kernel.shape==(3, 3)
res = np.zeros(img.shape)
for i in range(1, img.shape[0]-1):
for j in range(1, img.shape[1]-1):
res[i, j] = np.sum(np.array([[img[i-1, j-1], img[i-1, j], img[i-1, j+1]],
[img[i, j-1], img[i, j], img[i, j+1]],
[img[i+1, j], img[i+1, j], img[i+1, j+1]]])*kernel)
return res
if __name__ == '__main__':
kernel = np.array([[-1, -1, -1], [-1, 3, -1], [-1, -1, -1]])
img = misc.face()[:256, :256, 0]
res = my_function(img, kernel)
plt.figure()
plt.imshow(res, cmap=plt.cm.gray)
</code></pre>
<p>I have thus created a setup.py file:</p>
<pre><code>from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize('script_function_cython.pyx'),
)
</code></pre>
<p>Then, I compile it:</p>
<pre><code>python setup.py build_ext --inplace
</code></pre>
<p>And install it:</p>
<pre><code>python setup.py install
</code></pre>
<p>However, when I try to further import it,</p>
<pre><code>import script_function_cython
</code></pre>
<p>I get:</p>
<pre><code>ImportError: No module named script_function_cython
</code></pre>
| 1 | 2016-10-02T13:37:21Z | 39,817,663 | <p>with the <code>--inplace</code> build there is no need for install. You'll need to import from project directory though.</p>
<pre><code>python setup.py build --inplace
python -c 'import script_function_cython'
</code></pre>
<p>should raise no error.</p>
| 1 | 2016-10-02T13:48:34Z | [
"python",
"numpy",
"cython",
"distutils"
]
|
How to send a json object using tcp socket in python | 39,817,641 | <p>here is my python tcp client. I want to send a json object to the server.But I can't send the object using the sendall() method. how can I do this?</p>
<pre><code>import socket
import sys
import json
HOST, PORT = "localhost", 9999
m ='{"id": 2, "name": "abc"}'
jsonObj = json.loads(m)
data = jsonObj
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(jsonObj)
# Receive data from the server and shut down
received = sock.recv(1024)
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
</code></pre>
| 0 | 2016-10-02T13:46:14Z | 39,817,677 | <p>Skip the <code>json.loads()</code> part. Send the json object as the json string and load it from the string at the TCP client.</p>
<p>Also check: <a href="http://stackoverflow.com/questions/6341823/python-sending-dictionary-throught-tcp">Python sending dictionary throught TCP</a></p>
| 0 | 2016-10-02T13:50:19Z | [
"python",
"json",
"sockets",
"tcp"
]
|
urllib.request.urlretrieve not downloading files over HTTPS | 39,817,671 | <p>The below URL is the download link to download a text file.
If I paste the URL in the Firefox it downloads the actual contents i.e text file. But, when used <code>urlretrieve</code> it is giving me some html source code file.</p>
<pre><code>>>> import urllib
>>> down_link='URL' #URL is a ***HTTPS*** link to download .txt file
>>> file=urllib.request.urlretrieve(down_link)
</code></pre>
<p>this is the output I get:</p>
<pre><code>>>>
('C:\\Users\\rakesh.j.kulkarni\\AppData\\Local\\Temp\\tmps7559wgi'
http.client.HTTPMessage object at 0x03A3C610>)
</code></pre>
<p>when opened the file I get html source file which when opened with browser it the same webpage's login form,</p>
<p>So i have to come up with the alternate process to do the same for time being until the problem gets resolved</p>
<pre><code>subprocess.Popen(["C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", down_link])
</code></pre>
<p>I then go to downloads and work on the file.</p>
| 0 | 2016-10-02T13:49:25Z | 39,817,826 | <p>First of, you should import <code>urllib.request</code>, and not just urllib (in Py3).<br> And you are assigning the object to a variable so its giving you the object instance as output.
Nothing wrong with that, just to give you a quick fix, try doing:</p>
<pre><code>In [1]: import urllib.request
In [2]: down_link = "http://vignette3.wikia.nocookie.net/shipoffools/images/4/42/Surprised_Luffy.jpg/revision/latest?cb=20120921134043"
In [3]: path_to_save = "../luffy.jpg"
In [4]: urllib.request.urlretrieve(down_link, path_to_save)
Out[4]: ('../luffy.jpg', <http.client.HTTPMessage at 0x47f6af0>)
</code></pre>
<p>This will work just fine, saving the image where you want.
If you dont specify the path_to_save, then thats fine too, as it will download anyways and the path will be the <code>tmp</code> directory, In your case it would be <code>C:\\Users\\rakesh.j.kulkarni\\AppData\\Local\\Temp\\</code> folder.</p>
<p>In the case of <code>https</code> related error or any other problem, there is a cleaner way of doing it, by reading the file with <code>urlopen</code> and saving it in a file on your computer:</p>
<pre><code>In [5]: import urllib.request as req
In [6]: down_link = "https://vignette3.wikia.nocookie.net/shipoffools/images/4/42/
...: Surprised_Luffy.jpg/revision/latest?cb=20120921134043"
In [7]: fname = "../luffy.jpg"
In [8]: with req.urlopen(down_link) as d, open(fname, "wb") as opfile:
...: data = d.read()
...: opfile.write(data)
...:
</code></pre>
<p><strong>NOTE</strong>: This method can take some time, but works just fine for normal small files.</p>
| 1 | 2016-10-02T14:07:47Z | [
"python",
"python-3.x",
"urllib"
]
|
Find combinations of a list of sets | 39,817,675 | <p>I'm using python 2.7. Given a list of sets, is there any quick and efficient way to generate the combinations? Input sets always have one item in each set and output sets all have length of 2 <br><br>
From:</p>
<pre><code>[set(['item1']), set(['item2']), set(['item3'])]
</code></pre>
<p>To:</p>
<pre><code>[set(['item1','item2']), set(['item2','item3']), set(['item3','item1'])]
</code></pre>
| -1 | 2016-10-02T13:50:11Z | 39,817,828 | <p>As John pointed out <code>itertools</code> might be of help. Here's a quick example:</p>
<pre><code>import itertools as it
sets = [set(range(0, 3)), set(range(2, 5)), set(range(4, 7))]
comb = list(it.combinations(sets, r=2))
comb
</code></pre>
<p>output: <code>[({0, 1, 2}, {2, 3, 4}), ({0, 1, 2}, {4, 5, 6}), ({2, 3, 4}, {4, 5, 6})]</code></p>
<p>Then create an intersection in each iteration:</p>
<pre><code>comb_sets = [a.intersection(b) for a, b in comb]
comb_sets
</code></pre>
<p>output: <code>[{2}, set(), {4}]</code></p>
| 0 | 2016-10-02T14:08:03Z | [
"python",
"python-2.7",
"set",
"combinations"
]
|
Find combinations of a list of sets | 39,817,675 | <p>I'm using python 2.7. Given a list of sets, is there any quick and efficient way to generate the combinations? Input sets always have one item in each set and output sets all have length of 2 <br><br>
From:</p>
<pre><code>[set(['item1']), set(['item2']), set(['item3'])]
</code></pre>
<p>To:</p>
<pre><code>[set(['item1','item2']), set(['item2','item3']), set(['item3','item1'])]
</code></pre>
| -1 | 2016-10-02T13:50:11Z | 39,818,310 | <p>Since the elements in your list of sets are all 1-element sets, the combinations that you are looking for are just the 2-element subsets of the union of those sets. You can obtain them like this:</p>
<pre><code>>>> import itertools
>>> sets = [set(['item1']), set(['item2']), set(['item3'])]
>>> elements = set()
>>> for s in sets: elements.update(s)
</code></pre>
<p>thus</p>
<pre><code>>>> elements
{'item1', 'item2', 'item3'}
</code></pre>
<p>And then, just this:</p>
<pre><code>>>> pairs = [set(combo) for combo in itertools.combinations(elements,2)]
>>> pairs
[{'item1', 'item2'}, {'item1', 'item3'}, {'item2', 'item3'}]
</code></pre>
| 1 | 2016-10-02T15:03:24Z | [
"python",
"python-2.7",
"set",
"combinations"
]
|
How can I create this list of dicts | 39,817,702 | <p>I have a list of dicts</p>
<pre><code>[{'name_field': u'casino_logo', 'contentid_id': 15L, 'value': u'assets/images/crown.png', 'title': u'Royal casino casino4'}, {'name_field': u'casino_logo', 'contentid_id': 16L, 'value': u'assets/images/crown.png', 'title': u'Royal casino casino1'}, {'name_field': u'casino_logo', 'contentid_id': 17L, 'value': u'assets/images/crown.png', 'title': u'Royal casino casino3'}, {'name_field': u'casino_logo', 'contentid_id': 18L, 'value': u'assets/images/crown.png', 'title': u'Royal casino casino2'}, {'name_field': u'raiting_casino', 'contentid_id': 15L, 'value': u'9.9', 'title': u'Royal casino casino4'}, {'name_field': u'raiting_casino', 'contentid_id': 16L, 'value': u'9', 'title': u'Royal casino casino1'}, {'name_field': u'raiting_casino', 'contentid_id': 17L, 'value': u'8.2', 'title': u'Royal casino casino3'}, {'name_field': u'raiting_casino', 'contentid_id': 18L, 'value': u'9.3', 'title': u'Royal casino casino2'}, {'name_field': u'bonus_code', 'contentid_id': 15L, 'value': u'AX777', 'title': u'Royal casino casino4'}, {'name_field': u'bonus_code', 'contentid_id': 16L, 'value': u'AX7772', 'title': u'Royal casino casino1'}, {'name_field': u'bonus_code', 'contentid_id': 17L, 'value': u'AX777', 'title': u'Royal casino casino3'}, {'name_field': u'bonus_code', 'contentid_id': 18L, 'value': u'AX7772', 'title': u'Royal casino casino2'}, {'name_field': u'bonus_summa', 'contentid_id': 15L, 'value': u'200', 'title': u'Royal casino casino4'}, {'name_field': u'bonus_summa', 'contentid_id': 16L, 'value': u'200', 'title': u'Royal casino casino1'}, {'name_field': u'bonus_summa', 'contentid_id': 17L, 'value': u'200', 'title': u'Royal casino casino3'}, {'name_field': u'bonus_summa', 'contentid_id': 18L, 'value': u'200', 'title': u'Royal casino casino2'}, {'name_field': u'bonus_min_depozit', 'contentid_id': 15L, 'value': u'1000000', 'title': u'Royal casino casino4'}, {'name_field': u'bonus_min_depozit', 'contentid_id': 16L, 'value': u'1000000', 'title': u'Royal casino casino1'}, {'name_field': u'bonus_min_depozit', 'contentid_id': 17L, 'value': u'1000000', 'title': u'Royal casino casino3'}, {'name_field': u'bonus_min_depozit', 'contentid_id': 18L, 'value': u'1000000', 'title': u'Royal casino casino2'}, '...(remaining elements truncated)...']
</code></pre>
<p>How can I get the structure</p>
<pre><code>{casinos:[{'id':16,'title':Royal casino casino3,'fields':[{'name_feild':'bonus_min_depozit','value':'10',...}],...}]}
</code></pre>
<p>I tried:</p>
<pre><code>for item in casinos:
info_casino[item['contentid_id']].append({'name_field':item['name_field'],'value':item['value']})
casino[item['contentid_id']] = {'fields':info_casino[item['contentid_id']],'title':item['title']}
</code></pre>
<p>but it didn't work. </p>
| 0 | 2016-10-02T13:53:03Z | 39,817,739 | <p>You can use a <em>"dictionary comprehension"</em> to achieve this as:</p>
<pre><code>my_dict = {item['name_field']: item for item in my_list}
</code></pre>
<p>where <code>my_list</code> is the list of <code>dict</code> as is mentioned in the question.</p>
<p>In case you want to remove the <code>'name_field'</code> value of the resulting dict, you can create the new <code>dict</code> as:</p>
<pre><code>my_dict = {}
for item in my_list:
my_dict[item['name_field']] = item
del item['name_field']
</code></pre>
| 1 | 2016-10-02T13:57:02Z | [
"python",
"list",
"dictionary",
"data-structures"
]
|
django image upload rest framework and test client | 39,817,737 | <p>I'm trying to upload a picture with rest framework and to test it with the django test client. It almost works, however when I save the file I have this on the top of my file:</p>
<pre><code>--BoUnDaRyStRiNg
Content-Disposition: form-data; name="plop.png"
</code></pre>
<p>If I delete those lines, I can perfectly read my picture, but I don't know how to rid of them.</p>
<p>models.py</p>
<pre><code>class GenericUser(User):
avatar = models.ImageField(upload_to=user_directory_path)
</code></pre>
<p>views.py</p>
<pre><code>class AvatarView(APIView):
parser_classes = (FileUploadParser,)
def post(self, request):
up_file = request.data['file']
user = get_object_or_404(GenericUser, pk=request.user.id)
user.avatar.save(up_file.name, up_file)
user.save()
return Response(status=204)
</code></pre>
<p>tests.py</p>
<pre><code>cl = Client(HTTP_AUTHORIZATION="Token {}".format(token))
with open(MY_FILE, 'rb') as f:
data = f.read()
res = cl.post('/avatar', {"plop.png" : data}, HTTP_CONTENT_DISPOSITION="attachment; filename=plop.png;")
</code></pre>
<p>any hints, how I could make this work?</p>
| 0 | 2016-10-02T13:56:53Z | 39,820,142 | <p>Try this:</p>
<pre><code>res = cl.post('/avatar?filename=plop.png', {"plop.png" : data})
</code></pre>
<p>Or more or less from the Django docs:</p>
<pre><code>with open(MY_FILE, 'rb') as f:
cl.post('/avatar', {"filename" : f})
</code></pre>
| 0 | 2016-10-02T18:16:42Z | [
"python",
"django",
"django-rest-framework"
]
|
django image upload rest framework and test client | 39,817,737 | <p>I'm trying to upload a picture with rest framework and to test it with the django test client. It almost works, however when I save the file I have this on the top of my file:</p>
<pre><code>--BoUnDaRyStRiNg
Content-Disposition: form-data; name="plop.png"
</code></pre>
<p>If I delete those lines, I can perfectly read my picture, but I don't know how to rid of them.</p>
<p>models.py</p>
<pre><code>class GenericUser(User):
avatar = models.ImageField(upload_to=user_directory_path)
</code></pre>
<p>views.py</p>
<pre><code>class AvatarView(APIView):
parser_classes = (FileUploadParser,)
def post(self, request):
up_file = request.data['file']
user = get_object_or_404(GenericUser, pk=request.user.id)
user.avatar.save(up_file.name, up_file)
user.save()
return Response(status=204)
</code></pre>
<p>tests.py</p>
<pre><code>cl = Client(HTTP_AUTHORIZATION="Token {}".format(token))
with open(MY_FILE, 'rb') as f:
data = f.read()
res = cl.post('/avatar', {"plop.png" : data}, HTTP_CONTENT_DISPOSITION="attachment; filename=plop.png;")
</code></pre>
<p>any hints, how I could make this work?</p>
| 0 | 2016-10-02T13:56:53Z | 39,860,207 | <p>This worked as I expected:
views.py</p>
<pre><code>class AvatarView(APIView):
parser_classes = (MultiPartParser,)
def post(self, request):
up_file = request.data["file"]
user = get_object_or_404(GenericUser, pk=request.user.id)
user.avatar.save(up_file.name, up_file)
user.save()
return Response(status=204)
</code></pre>
<p>test.py</p>
<pre><code>cl = Client(HTTP_AUTHORIZATION="Token {}".format(token))
with open(MY_FILE, 'rb') as f:
res = cl.post('/avatar', {"file" : f})
</code></pre>
| 0 | 2016-10-04T19:23:54Z | [
"python",
"django",
"django-rest-framework"
]
|
Plotting data using higcharts in flask web application | 39,817,834 | <p>I am trying to plot data from mysql server and display it in a web server. I am using highcharts javascript library for plotting. I can get data from mysql database and data is sent from server-side to client-side as json data. Then by using highcharts I want to display it. But chart shows nothing when I try to plot.</p>
<p>Here is important snippet code in server side (I am using AJAX):</p>
<pre><code>def background_process():
start = request.form['name_start']
finish = request.form['name_finish']
df_sorted = mutechDataManipulate.sort_by_time(df, pd.to_datetime(str(start)), pd.to_datetime(str(finish)), 'Date')
print df_sorted['Date'].head()
df_out_json = df_sorted[['Date', 'High']].to_json(orient='values')
return json.dumps(df_out_json)
</code></pre>
<p>Here is client side (I get json data from server successfully):</p>
<pre><code>$(document).ready(function(){
$(document).on("click", "#btn1", function() {
console.log("alii");
var user = $('input[name="name_start"]').val();
var pass = $('input[name="name_finish"]').val();
console.log("sivgin");
$.ajax({
url: '/background_process',
data: $("form").serialize(),
type: "POST",
success: function(response) {
$('#result').highcharts({
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'High'
}
},
legend: {
enabled: false
},
series: [{
type: 'area',
name: 'USD to EUR',
data: response
}]
});
console.log(response)
},
error: function(error) {
console.log(error);
}
});
});
});
</code></pre>
<p>Finally, I get a blank graph like this:</p>
<p><img src="http://i.stack.imgur.com/ShYae.jpg" alt="empty chart"></p>
<p>In addition I try to plot time series line chart. What is wrong? </p>
<p>Edit: Forgot to html file:</p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<title>Mutech</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/css/bootstrap.min.css">
<script src="static/js/jquery.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
<script src="static/js/script.js"></script>
<script src="static/js/jquery-1.9.1.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<br/>
<div class="container">
<form class="form-inline" id="form1" method="post" >
<div class="form-group">
<label>Start Date</label>
<input class="form-control" id="id_start" name ="name_start">
</div>
<div class="form-group">
<label for="pwd">Finish Date</label>
<input class="form-control" id="id_finish" name ="name_finish">
</div>
<br/><br/>
<br/>
<button type="button" class="btn btn-default" id= "btn1">Submit</button>
</form>
</div>
<div class="container" id = "result">
</div>
</body>
</html>
</code></pre>
| 0 | 2016-10-02T14:08:43Z | 39,821,868 | <p>It doesn't look your data is formatted correctly for Highcharts. If you look at <a href="http://stackoverflow.com/questions/29643609/how-to-pass-json-data-to-highcharts-series">this other StackOverlow question about JSON data and Highcharts</a> you'll see that the data should be a list of dictionaries.</p>
<p>To do this why pandas, you pass the value <code>"records"</code> into the <code>orient</code> option.</p>
<pre><code>df_out_json = df_sorted[['Date', 'High']](orient="records")
#[{"Date":1285632000000, "High":None}, {"Date":1285545600000, "High":25.39}]
</code></pre>
<p>See more in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow">pandas documentation</a> for <code>to_json</code>.</p>
| 0 | 2016-10-02T21:26:14Z | [
"javascript",
"jquery",
"python",
"highcharts",
"flask"
]
|
Getopt multiple argument syntaxes | 39,817,973 | <p>So I'm working on an assignment in a python class that I'm taking, but have gotten stuck with something I can't really find any further information about (neither on SO, Google or in the courseware). </p>
<p>I need help with how to handle arguments with multiple types of syntaxes - like <strong>[arg] and < arg ></strong>, which is something I've been unable to find any further information about.</p>
<p>Here is an example use-case that SHOULD work.</p>
<pre><code>>>> ./marvin-cli.py --output=<filename.txt> ping <http://google.com>
>>> Syntax error near unexpected token 'newline'
</code></pre>
<p>The below code works fine for any use-case where I haven't defined any further output than writing to the console:</p>
<pre><code># Switch through all options
try:
opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help","version","silent", "get=", "ping=", "verbose", "input=", "json"])
for opt, arg in opts:
if opt in ("-h", "--help"):
printUsage(EXIT_SUCCESS)
elif opt in ("-s", "--silent"):
VERBOSE = False
elif opt in ("--verbose"):
VERBOSE = True
elif opt in ("--ping"):
ping(arg)
elif opt in ("--input"):
print("Printing to: ", arg)
else:
assert False, "Unhandled option"
except Exception as err:
print("Error " ,err)
print(MSG_USAGE)
# Prints the callstack, good for debugging, comment out for production
#traceback.print_exception(Exception, err, None)
sys.exit(EXIT_USAGE)
#print(sys.argv[1])
</code></pre>
<p>Example usage:</p>
<pre><code>>>> ./marvin-cli.py ping http://google.com
>>> Latency 100ms
</code></pre>
<p>And this is a snippet showing how the ping works:</p>
<pre><code>def ping(URL):
#Getting necessary imports
import requests
import time
#Setting up variables
start = time.time()
req = requests.head(URL)
end = time.time()
#printing result
if VERBOSE == False:
print("I'm pinging: ", URL)
print("Received HTTP response (status code): ", req.status_code)
print("Latency: {}ms".format(round((end - start) * 1000, 2)))
</code></pre>
| 0 | 2016-10-02T14:25:48Z | 39,818,787 | <p><code>[]</code> and <code><></code> are commonly used to visually indicate option requirement. Typically <code>[xxxx]</code> means the option or argument is optional and <code><xxxx></code> required.</p>
<p>The sample code you provide handles option flags, but not the required arguments. Code below should get you started in the right direction.</p>
<pre><code>try:
opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help", "version", "silent", "verbose", "output=", "json"])
for opt, arg in opts:
if opt in ("-h", "--help"):
printUsage(EXIT_SUCCESS)
elif opt in ("-s", "--silent"):
VERBOSE = False
elif opt in ("--verbose"):
VERBOSE = True
elif opt in ("--output"):
OUTPUTTO = arg
print("Printing to: ", arg)
else:
assert False, "Unhandled option"
assert len(args) > 0, "Invalid command usage"
# is there a "<command>" function defined?
assert args[0] in globals(), "Invalid command {}".format(args[0])
# pop first argument as the function to call
command = args.pop(0)
# pass args list to function
globals()[command](args)
def ping(args):
#Getting necessary imports
import requests
import time
# validate arguments
assert len(args) != 1, "Invalid argument to ping"
URL = args[0]
#Setting up variables
start = time.time()
req = requests.head(URL)
end = time.time()
#printing result
if VERBOSE == False:
print("I'm pinging: ", URL)
print("Received HTTP response (status code): ", req.status_code)
print("Latency: {}ms".format(round((end - start) * 1000, 2)))
</code></pre>
| 1 | 2016-10-02T15:53:14Z | [
"python",
"python-2.7",
"python-3.x",
"getopt"
]
|
how to setup multiple python version on debian (pip, virtualenvwrapper etc) | 39,818,095 | <p>I'm starting to use python and would like to setup my workstation which is running on linux (debian). Multiple version of python are installed:</p>
<pre><code>ot@station:/home/ot# ls -l /usr/bin/py
py3clean pydoc3.4 python2 python3.4m-config
py3compile pygettext python2.6 python3-config
py3versions pygettext2.7 python2.7 python3m
pybuild pygettext3 python2.7-config python3m-config
pyclean pygettext3.4 python2-config python-config
pycompile pygmentex python3 pythontex
pydoc pygmentize python3.4 pythontex3
pydoc2.7 pyste python3.4-config pyversions
pydoc3 python python3.4m
root@thinkstation:/home/nicolas# ls -l /usr/bin/py
</code></pre>
<p>My first question is regarding the package management system pip. I see the following output:</p>
<pre><code>ot@station:/home/ot# pip
pip pip2 pip2.7
</code></pre>
<p>How can I check which pip is used for which python version? They must be linked somehow. From the output above I guess pip2.7 is used for the installed version of python2.7. But what about the others? Why isnt there a pip2.6 and how can I use pip to install packages for the newest version (python 3.4?).</p>
<p>Once this is sorted out I would like to start some coding projects for which virtualenv seems extremely helpful. At this point I know which pip links to which python version. If my project should run under python3 I use the corresponding pip to install virtualenv and virtualenvwrapper. This implies there are different version of virtualenv and virtualenvwrapper on my local machine. How can I then use the right one for creating local environment?</p>
| 1 | 2016-10-02T14:39:05Z | 39,818,175 | <pre><code>sudo apt-get install python3-pip # install pip3
pip3 install virtualenv
virtualenv venv # create virtualenv called venv
source /venv/bin/activate # activate the virtualenv
pip install xyz
[...]
deactivate
</code></pre>
<p>Note: to install packages <strong>within</strong> the virtual environment you simply use <code>pip</code>, even if its an python3 environment.</p>
<p>For further info on pip versions check out <a href="http://stackoverflow.com/questions/2812520/pip-dealing-with-multiple-python-versions">this</a> post.</p>
| 1 | 2016-10-02T14:48:42Z | [
"python",
"virtualenv",
"virtualenvwrapper"
]
|
Ansible not reading credentials from ~/.aws/credentials | 39,818,098 | <p>I am running ansible with <code>dynamic inventory</code>. When the <code>aws cli</code> was setup with aws configure command than the ansible commands with dynamic invetory was running properly. But I want to have multiple profiles to be used by dynamic inventory so I have added profile in <code>~/.aws/credentials</code></p>
<pre><code>[personal]
aws_access_key_id = XXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXX
[default]
aws_access_key_id = XXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXX
</code></pre>
<p>ansible not picking up these credentials and on running <code>./ec2.py --list</code> it is giving the error:</p>
<pre><code>Looks like AWS is down again:
EC2ResponseError: 401 Unauthorized
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>Authorization header or parameters are not formatted correctly.</Message></Error></Errors><RequestID>349d5311-54db-4e79-9bbc-2d60b9f15da5</RequestID></Response>
</code></pre>
| 2 | 2016-10-02T14:39:25Z | 39,818,189 | <p>Have you tried adding --profile PROFILE switch to ec2.py as below.</p>
<pre><code>./ec2.py --list --profile personal
</code></pre>
| 0 | 2016-10-02T14:49:57Z | [
"python",
"amazon-web-services",
"ansible",
"aws-cli"
]
|
Ansible not reading credentials from ~/.aws/credentials | 39,818,098 | <p>I am running ansible with <code>dynamic inventory</code>. When the <code>aws cli</code> was setup with aws configure command than the ansible commands with dynamic invetory was running properly. But I want to have multiple profiles to be used by dynamic inventory so I have added profile in <code>~/.aws/credentials</code></p>
<pre><code>[personal]
aws_access_key_id = XXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXX
[default]
aws_access_key_id = XXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXX
</code></pre>
<p>ansible not picking up these credentials and on running <code>./ec2.py --list</code> it is giving the error:</p>
<pre><code>Looks like AWS is down again:
EC2ResponseError: 401 Unauthorized
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>Authorization header or parameters are not formatted correctly.</Message></Error></Errors><RequestID>349d5311-54db-4e79-9bbc-2d60b9f15da5</RequestID></Response>
</code></pre>
| 2 | 2016-10-02T14:39:25Z | 39,823,521 | <p>After @uptime365's answer, this is most likely not an Ansible/ec2.py problem. Here's my troubleshooting steps:</p>
<h3>Can you use the <code>awscli</code> with those credentials?</h3>
<pre><code>aws ec2 describe-instances --page-size 5
aws ec2 describe-instances --page-size 5 --profile personal
</code></pre>
<h2>Can you use <code>awscli</code> with the credentials manually included?</h2>
<p>Note there's no need to use <code>profile</code> since you are specifying the keys.</p>
<pre><code>AWS_ACCESS_KEY_ID="AKIA.." AWS_SECRET_ACCESS_KEY=".." aws ec2 describe-instances --page-size 5
</code></pre>
<p>If it complains about the region, add <code>AWS_DEFAULT_REGION="us-east-1"</code> or the region of your choice.</p>
<h2>Neither of these work</h2>
<p>You have a problem with your access key or secret. How many characters are in each? The key should be 20 characters, all uppercase letters and numbers. The secret is 40 characters, upper/lower/numbers/punctuation.</p>
| 0 | 2016-10-03T01:44:09Z | [
"python",
"amazon-web-services",
"ansible",
"aws-cli"
]
|
python/django: model object has no attribute 'prefetch_related' | 39,818,121 | <p>I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he updates the vehicle location. I wanted to get the latest location for which i did as in my below code. I use prefetch_related in my view to returns the location values for a particular vehicle. But, when after running the server, it raises an error : "TripStatus object has no attribute 'prefetch_related'". I would appreciate helping me solve this.
models.py:</p>
<pre><code>class VehicleDetails(models.Model):
Vehicle_No = models.CharField(max_length=20)
class TripStatus(models.Model):
vehicledetails = models.ForeignKey(VehicleDetails, related_name='statuses')
CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata'))
Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20)
statustime = models.DateTimeField(auto_now=False, auto_now_add=True)
</code></pre>
<p>views.py:</p>
<pre><code>def status(request):
tripstatus = TripStatus.objects.all().latest('statustime').prefetch_related('statuses')
context = {
"tripstatus": tripstatus,
}
return render(request, 'loggedin_load/active_deals.html', context)
</code></pre>
<p>template:</p>
<pre><code>{% for status in vehicledetails.statuses.all %}
{{status.Vehicle_Status}}
{% endfor %}
</code></pre>
| 0 | 2016-10-02T14:42:29Z | 39,818,183 | <p>prefetch_related works on a queryset object. Latest returns a single model not a queryset. </p>
<p>This should work :</p>
<pre><code>tripstatus = TripStatus.objects.all().prefetch_related('statuses').latest('statustime')
</code></pre>
| 1 | 2016-10-02T14:49:12Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.