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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Beautifulsoup can't extract data in this website | 38,694,480 | <pre><code>import requests
from bs4 import BeautifulSoup
import lxml
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
f =open('ala2009link.csv','r')
s=open('2009alanews.csv','w')
for row in csv.reader(f):
url=row[0]
print url
res = requests.get(url)
print res.content
soup = BeautifulSoup(res.content)
print soup
data=soup.find_all("article",{"class":"article-wrapper news"})
#data=soup.find_all("main",{"class":"main-content"})
for item in data:
title= item.find_all("h2",{"class","article-headline"})[0].text
s.write("%s \n"% title)
content=soup.find_all("p")
for main in content:
k=main.text.encode('utf-8')
s.write("%s \n"% k)
#k=csv.writer(s)
#k.writerow('%s\n'% (main))
s.close()
f.close()
</code></pre>
<p>this is my code to extract data in website ,but i don't know why i can't extract data ,is this ad blocker warning to block my beautifulsoup ?
<a href="http://i.stack.imgur.com/Elq7c.png" rel="nofollow"><img src="http://i.stack.imgur.com/Elq7c.png" alt="enter image description here"></a>
this is the example link:<a href="http://www.rolltide.com/news/2009/6/23/Bert_Bank_Passes_Away.aspx?path=football" rel="nofollow">http://www.rolltide.com/news/2009/6/23/Bert_Bank_Passes_Away.aspx?path=football</a></p>
| 0 | 2016-08-01T08:45:01Z | 38,698,345 | <p>The reason that no results are returned is because this website requires that you have a User-Agent header in your request.</p>
<p>To fix this add a headers parameter with a <code>User-Agent</code> to the <code>requests.get()</code> like so.</p>
<pre><code>url = 'http://www.rolltide.com/news/2009/6/23/Bert_Bank_Passes_Away.aspx?path=football'
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/29.0.1547.65 Chrome/29.0.1547.65 Safari/537.36',
}
res = requests.get(url, headers=headers)
</code></pre>
| 0 | 2016-08-01T12:00:50Z | [
"python",
"request",
"beautifulsoup"
] |
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python | 38,694,486 | <p>I am getting below error while trying to do this </p>
<pre><code>from datetime import datetime
time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)
</code></pre>
<p>Error is ...</p>
<pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
</code></pre>
| 2 | 2016-08-01T08:45:09Z | 38,694,701 | <p>this works in python 3.4, conforms to the datetime documentation</p>
<pre><code>from datetime import datetime
time1 = '2016-08-01 13:39:00+0530'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S%z')
print(x)
</code></pre>
<p>gives</p>
<pre><code>2016-08-01 13:39:00+05:30
</code></pre>
| 0 | 2016-08-01T08:56:39Z | [
"python",
"datetime"
] |
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python | 38,694,486 | <p>I am getting below error while trying to do this </p>
<pre><code>from datetime import datetime
time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)
</code></pre>
<p>Error is ...</p>
<pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
</code></pre>
| 2 | 2016-08-01T08:45:09Z | 38,698,484 | <p>If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the <a href="https://dateutil.readthedocs.io/en/latest/" rel="nofollow"><code>dateutil</code></a> library for <a class='doc-link' href="http://stackoverflow.com/documentation/python/484/date-and-time/1592/parsing-a-string-into-a-timezone-aware-datetime-object#t=201608011200137436166">converting a string to a timezone aware object</a>.</p>
<p>The code to do this is simple:</p>
<pre><code>>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2016-08-01 13:39:00+05:30')
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=tzoffset(None, 19800))
</code></pre>
<hr>
<p>If you are using Python 3.2 or later, <a class='doc-link' href="http://stackoverflow.com/documentation/python/484/date-and-time/1594/parsing-a-string-into-a-timezone-aware-datetime-object-python-3-2#t=201608011203237433949">the <code>%z</code> option has been added as a formatting option when parsing a date</a>. You can accomplish this task without using <code>dateutil</code> in these versions by doing this:</p>
<pre><code>>>> import datetime
>>> dt = datetime.datetime.strptime('2016-08-01 13:39:00+0530', "%Y-%m-%d %H:%M:%S%z")
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))
</code></pre>
<p>Unfortunately, you do have to strip the colon (<code>:</code>) from the offset for this to work as expected. </p>
| 1 | 2016-08-01T12:08:26Z | [
"python",
"datetime"
] |
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python | 38,694,486 | <p>I am getting below error while trying to do this </p>
<pre><code>from datetime import datetime
time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)
</code></pre>
<p>Error is ...</p>
<pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
</code></pre>
| 2 | 2016-08-01T08:45:09Z | 39,757,674 | <p>Consider using <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow">dateparser</a>:</p>
<pre><code>>>> dateparser.parse('2016-08-01 13:39:00+05:30')
datetime.datetime(2016, 8, 1, 13, 39)
>>> dateparser.parse('2016-08-01 13:39:00+05:30', settings={'TO_TIMEZONE': 'UTC'})
datetime.datetime(2016, 8, 1, 8, 9)
</code></pre>
| 0 | 2016-09-28T21:06:59Z | [
"python",
"datetime"
] |
Slicing a graph | 38,694,540 | <p>I have created a graph in python but I now need to take a section of the graph and expand this by using a small range of the original data, but I don't know how to find the row number of the results that form the range or how I can create a graph using just these results form the file. This is the code I have for the graph:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
#variable for data to plot
spec_to_plot = "SN2012fr_20121129.42_wifes_BR.dat"
#tells python where to look for the file
spec_directory = '/home/fh1u16/Documents/spectra/'
data = np.loadtxt(spec_directory + spec_to_plot, dtype=np.float)
x = data[:,0]
y = data[:,1]
plt.plot(x, y)
plt.xlabel("Wavelength")
plt.ylabel("Flux")
plt.title(spec_to_plot)
plt.show()
</code></pre>
<p>edit: data is between 3.5e+3 and 9.9e+3 in the first column, I need to use just the data between 5.5e+3 and 6e+3 to plot another graph, but this only applies to the first column. Hope this makes a bit more sense?
Python version 2.7</p>
| -1 | 2016-08-01T08:48:12Z | 38,694,846 | <p>If I understand you correctly, you could do it this way:</p>
<pre><code>my_slice = slice(np.argwhere(x>5.5e3)[0], np.argwhere(x>6e3)[0])
x = data[my_slice,0]
y = data[my_slice,1]
</code></pre>
<p><code>np.argwhere(x>5.5e3)[0]</code> is the index of the first occurrence of <code>x>5.5e3</code> and like wise for the end of the slice. (assuming your data is sorted)</p>
<p>A more general way working even if your data is not sorted:</p>
<pre><code>mask = (x>5.5e3) & (x<6e3)
x = data[mask, 0]
y = data[mask, 1]
</code></pre>
| 0 | 2016-08-01T09:05:11Z | [
"python",
"indexing",
"graph",
"slice"
] |
Slicing a graph | 38,694,540 | <p>I have created a graph in python but I now need to take a section of the graph and expand this by using a small range of the original data, but I don't know how to find the row number of the results that form the range or how I can create a graph using just these results form the file. This is the code I have for the graph:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
#variable for data to plot
spec_to_plot = "SN2012fr_20121129.42_wifes_BR.dat"
#tells python where to look for the file
spec_directory = '/home/fh1u16/Documents/spectra/'
data = np.loadtxt(spec_directory + spec_to_plot, dtype=np.float)
x = data[:,0]
y = data[:,1]
plt.plot(x, y)
plt.xlabel("Wavelength")
plt.ylabel("Flux")
plt.title(spec_to_plot)
plt.show()
</code></pre>
<p>edit: data is between 3.5e+3 and 9.9e+3 in the first column, I need to use just the data between 5.5e+3 and 6e+3 to plot another graph, but this only applies to the first column. Hope this makes a bit more sense?
Python version 2.7</p>
| -1 | 2016-08-01T08:48:12Z | 38,695,763 | <p>solved by using</p>
<pre><code>plt.axis([5500, 6000, 0, 8e-15])
</code></pre>
<p>thanks for help.</p>
| 0 | 2016-08-01T09:48:38Z | [
"python",
"indexing",
"graph",
"slice"
] |
fill in a column only if its not none or empty | 38,694,675 | <p>I am trying to fill in the missing values of county column based on its add_suburb value. I tried the following two codes which doesn't work</p>
<pre><code>for index, row in fileco.iterrows():
df.loc[df['add_suburb'].str.contains(str(row['place'])) & ( df['county'].str=='') , 'county'] = str('County '+row['county']).title()
for index, row in fileco.iterrows():
df.loc[df['add_suburb'].str.contains(str(row['place'])) & ( df['county'].str is None) , 'county'] = str('County '+row['county']).title()
</code></pre>
<p>But the following code works if i do not check for None or ==''. </p>
<pre><code>for index, row in fileco.iterrows():
df.loc[df['add_suburb'].str.contains(str(row['place'])) , 'county'] = str('County '+row['county']).title()
</code></pre>
<p>What's the correct way to fill in only the missing column values? How should I correct the condition after the & ?</p>
| 0 | 2016-08-01T08:55:17Z | 38,697,879 | <p>I don't exactly understand what you're trying to do in the loop (what are you looping over?), but I think it should work if you enclose your conditions in brackets like this:</p>
<pre><code>df.loc[(condition1) & (condition2)] = "replacement"
</code></pre>
| 0 | 2016-08-01T11:38:07Z | [
"python",
"dataframe"
] |
Why os.fdopen doesn't work on fd 2? | 38,694,837 | <p>Take stderr for example:</p>
<pre><code>import os
fh = os.fdopen(2, "w")
fh.write("hello\n")
</code></pre>
<p>It doesn't output anything, what's wrong with the codes?</p>
| 0 | 2016-08-01T09:04:45Z | 38,694,861 | <p>You just need to flush it out.</p>
<pre><code>fh.flush()
</code></pre>
| 1 | 2016-08-01T09:06:06Z | [
"python"
] |
Django Send mail only when one perticular field is changed | 38,694,948 | <p>I am using :
<a href="https://github.com/ui/rq-scheduler" rel="nofollow">RQ scheduler</a></p>
<p>There is a Job model in my project:</p>
<pre><code>class Job(models.Model):
# Other fields
status = models.CharField(
max_length=2, choices=choices.JOB_STATE_CHOICES, default=choices.PENDING_APPROVAL)
</code></pre>
<p>I have scheduled a task daily at night which will check for all the Jobs that are approved today and send mails to my users about it.</p>
<p>So Query: </p>
<pre><code>jobs = Job.objects.filter(status='APPROVED',
updated_at__date=datetime.today().date())
</code></pre>
<p>Problem with this query is how do I know that for this job status field was changed today only.</p>
<p>This query will job a job even if job's title was changed today and status was changed 5 days back.</p>
<p>I need to extract only those jobs whose "status" field was changed today. Thank you for help.</p>
| 1 | 2016-08-01T09:10:31Z | 38,695,098 | <p>You shoud use <a href="https://github.com/romgar/django-dirtyfields" rel="nofollow">django-dirtyfields</a> and send email immediately or add this job_id to RQ.
Full docs <a href="http://django-dirtyfields.readthedocs.io/en/develop/" rel="nofollow">here</a></p>
<p>Or update <code>updated_at</code> field only when <code>status</code> changes (again django-dirtyfields) by write own save() method like.</p>
<pre><code>def save(self):
if self.status = 'aproved' and 'status' in self.get_dirty_fields():
# add to RQ
# or set updated_at = datetime.now() # if you dont use on_update=datetime.now
super(...).save()
</code></pre>
| 1 | 2016-08-01T09:17:19Z | [
"python",
"django",
"redis"
] |
Why is there no delay between same-line printing? | 38,695,003 | <pre><code>print 'foo',
time.sleep(1)
print 'bar'
</code></pre>
<p>This seems to run <code>time.sleep(1)</code> first, then prints <code>"foo bar"</code> all at once.</p>
<p>However, printing both <code>foo</code> and <code>bar</code> on its own lines produces the expected delay between the print statements:</p>
<pre><code>print 'foo'
time.sleep(1)
print 'bar'
</code></pre>
<p>Is there something that stacks all print statements until a new line character is received?</p>
| 2 | 2016-08-01T09:12:55Z | 38,695,092 | <p><code>print</code> by default prints to sys.stdout and it is line-buffered. you could flush the buffer each time after a print statement</p>
<pre><code>import time
import sys
print 'foo'
sys.stdout.flush()
time.sleep(1)
print 'bar
</code></pre>
<p>reference: <a href="https://docs.python.org/3/library/sys.html" rel="nofollow">sys</a></p>
<p>read also: <a href="http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print">How to flush output of Python print?</a></p>
| 6 | 2016-08-01T09:17:04Z | [
"python",
"printing",
"output",
"delay"
] |
Python pause thread, do manually and reset time | 38,695,060 | <p>I need to call function every x seconds but with option to call it manually and in this case reset time. I have sth like this:</p>
<pre><code>import time
import threading
def printer():
print("do it in thread")
def do_sth(event):
while not event.is_set():
printer()
time.sleep(10)
event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
t.daemon = True
t.start()
a = input()
if a == 't':
event.set()
elif a == 'm':
event.wait()
printer()
event.clear()
</code></pre>
<p>UPDATE:
I have found something that helped me a lot: <a href="http://stackoverflow.com/questions/33640283/python-thread-that-i-can-pause-and-resume">Python - Thread that I can pause and resume</a>
Now my code look like this:</p>
<pre><code>import threading, time, sys
class ThreadClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.can_run = threading.Event()
self.thing_done = threading.Event()
self.thing_done.set()
self.can_run.set()
def run(self):
while True:
self.can_run.wait()
try:
self.thing_done.clear()
self.do_in_thread()
finally:
self.thing_done.set()
time.sleep(5)
def pause(self):
self.can_run.clear()
self.thing_done.wait()
def resume(self):
self.can_run.set()
def do_in_thread(self):
print("Thread...1")
time.sleep(2)
print("Thread...2")
time.sleep(2)
print("Thread...3")
def do_in_main():
print("Main...1")
time.sleep(2)
print("Main...2")
time.sleep(2)
print("Main...3")
if __name__ == '__main__':
t = ThreadClass()
t.daemon = True
t.start()
while True:
i = input()
if i == 'm':
t.pause()
do_in_main()
t.resume()
elif i == 't':
sys.exit()
# t.join()
</code></pre>
<p>The only problem is that when I terminate, a would like thread to finish its job before it exits.</p>
| 0 | 2016-08-01T09:15:41Z | 38,699,054 | <p>It may be that <em>buffered outputs</em> are the culprits and thus - you're are getting your expected behaviour.</p>
<p>I changed your code to the following, and it seems to do something (if that's what you wanted, is up to you):</p>
<pre><code>import time
import threading
def printer():
print("do it in thread")
def do_sth(event):
print("event.is_set:", event.is_set())
while not event.is_set():
printer()
time.sleep(10)
event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
print("t:",t)
t.daemon = True
t.start()
a = input()
if a == 't':
event.set()
elif a == 'm':
event.wait()
printer()
event.clear()
</code></pre>
| 0 | 2016-08-01T12:34:26Z | [
"python",
"multithreading"
] |
Pandas combining keys when grouping by multiple column | 38,695,103 | <p>I have 3 levels of grouping based on 3 keys: key1, key2, key3
I want to get the sum of a column (c1) for the following combination:</p>
<pre><code>key1, sum(c1)
key1, key2, sum(c1)
key1, key2, key3, sum(c1)
</code></pre>
<p>I am getting the sums in 3 different dfs. (sum_k1, sum_k1k2, sum_k1k2k3)
I want to combine the dataframe and thereupon convert it to json as follows:</p>
<pre><code>{
key1: {
sum: x1,
key2: {
sum: x2,
key3: {
sum: x3
}
}
}
}
</code></pre>
<p>How do I go about this?</p>
| 1 | 2016-08-01T09:17:26Z | 38,698,654 | <p>I don't know if this is the most efficient way to go about it, but this is what I came up with</p>
<pre><code>import pandas as pd
import random
# Prepare the sample dataset
table = []
for i in range(100000):
row = {'key1': random.choice('ABC'),
'key2': random.choice('KLM'),
'key3': random.choice('XYZ'),
'val' : random.randint(0,500)}
table.append(row)
df = pd.DataFrame(table)
# Aggregate the first level
dict_agg = (df.groupby('key1')
.sum()
.rename(columns={'val':'sum'})
.to_dict('index'))
# Convert from numpy.int64 to Python scalar
for idx, value in dict_agg.items():
dict_agg[idx]['sum'] = int(dict_agg[idx]['sum'])
# Aggregate the second level
df_lvl2 = (df.groupby(['key1','key2'])
.sum()
.rename(columns={'val':'sum'})
.to_dict('index'))
# Assign the second level aggregation
for idx, value in df_lvl2.items():
dict_agg[idx[0]][idx[1]] = {'sum': int(value['sum'])}
# Aggregate the final level
df_lvl3 = (df.groupby(['key1','key2','key3'])
.sum()
.rename(columns={'val':'sum'})
.to_dict('index'))
# Assign the third level aggregation
for idx, value in df_lvl3.items():
dict_agg[idx[0]][idx[1]][idx[2]] = {'sum': int(value['sum'])}
</code></pre>
<p>The end result will look like this:</p>
<pre><code>{'A': {'K': {'X': {'sum': 929178},
'Y': {'sum': 940925},
'Z': {'sum': 938008},
'sum': 2808111},
'L': {'X': {'sum': 902581},
'Y': {'sum': 953821},
'Z': {'sum': 942942},
'sum': 2799344},
'M': {'X': {'sum': 930117},
'Y': {'sum': 929257},
'Z': {'sum': 910905},
'sum': 2770279},
'sum': 8377734},
'B': {'K': {'X': {'sum': 888818},
â¦
</code></pre>
<p>As this is a <code>dict</code>, you need to convert it to json, by doing:</p>
<pre><code>import json
output = json.dumps(dict_agg)
</code></pre>
| 1 | 2016-08-01T12:17:00Z | [
"python",
"json",
"pandas",
"numpy"
] |
Pandas combining keys when grouping by multiple column | 38,695,103 | <p>I have 3 levels of grouping based on 3 keys: key1, key2, key3
I want to get the sum of a column (c1) for the following combination:</p>
<pre><code>key1, sum(c1)
key1, key2, sum(c1)
key1, key2, key3, sum(c1)
</code></pre>
<p>I am getting the sums in 3 different dfs. (sum_k1, sum_k1k2, sum_k1k2k3)
I want to combine the dataframe and thereupon convert it to json as follows:</p>
<pre><code>{
key1: {
sum: x1,
key2: {
sum: x2,
key3: {
sum: x3
}
}
}
}
</code></pre>
<p>How do I go about this?</p>
| 1 | 2016-08-01T09:17:26Z | 38,760,884 | <p>I used multilevel index for this and xs for this one.
Get the lowest level aggregates.</p>
<pre><code>lvl3_grp = df.groupby(['key1', 'key2', 'key3'])['col1', 'col2'].sum()
lvl3_grp = lvl3_grp.reset_index()
lvl3_grp.set_index(['key1', 'key2', 'key3'], inplace=True)
res = {}
for k1 in lvl3_grp.index.levels[0]:
sums = lvl3_grp.xs(k1).sum()
lvl2_grp = lvl3_grp.xs(k1).reset_index()
lvl2_grp.set_index(['key2', 'key3'], inplace=True)
lvl2_dict = {}
for k2 in lvl2_grp.index.levels[0]:
sums = lvl2_grp.xs(k1).sum()
</code></pre>
<p>For the last level <code>.index.levels[0]</code> wont work as its single index. I used <code>.index.values</code> for iterable list and <code>.loc</code> inside the for loop for accessing the values.</p>
<p>I'll expand the answer at a later time.</p>
| 0 | 2016-08-04T07:20:54Z | [
"python",
"json",
"pandas",
"numpy"
] |
Search for word in text file in Python | 38,695,194 | <p>I have this text file:</p>
<pre><code>MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need to find the line with the model.</p>
<p>My code:</p>
<pre><code>term = "model"
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print line
file.close()
</code></pre>
<p>This is the output:</p>
<pre><code>model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need only this line as output: </p>
<pre><code> model,3,2016-07-30 15:39:59,075
</code></pre>
<p>How can I do this?</p>
| -1 | 2016-08-01T09:22:04Z | 38,695,340 | <p>Just replace the line:</p>
<pre><code>if term in line:
</code></pre>
<p>with line :</p>
<pre><code>if line.startswith('model,'):
</code></pre>
| 2 | 2016-08-01T09:28:24Z | [
"python",
"python-2.7"
] |
Search for word in text file in Python | 38,695,194 | <p>I have this text file:</p>
<pre><code>MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need to find the line with the model.</p>
<p>My code:</p>
<pre><code>term = "model"
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print line
file.close()
</code></pre>
<p>This is the output:</p>
<pre><code>model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need only this line as output: </p>
<pre><code> model,3,2016-07-30 15:39:59,075
</code></pre>
<p>How can I do this?</p>
| -1 | 2016-08-01T09:22:04Z | 38,695,388 | <p>It depends on what your file contains. Your example is quite light, but I see a few immediate solutions that don't change your code too much :</p>
<ol>
<li><p>Replace <code>term = 'model'</code> by <code>term = 'model,'</code> and this will only show the line you want.</p></li>
<li><p>Use some additional criteria, like <em>"must not contain <code>'name'</code>"</em>:</p></li>
</ol>
<p>Like this:</p>
<pre><code>term = 'model'
to_avoid = 'name'
with open('file.txt') as f:
for line in file:
line = line.strip().split('/n')
if term in line and to_avoid not in line:
print line
</code></pre>
<p><strong>Additional remarks</strong></p>
<ul>
<li>You could use <a href="http://www.tutorialspoint.com/python/string_startswith.htm" rel="nofollow"><code>startswith('somechars')</code></a> to check for some characters at the beginning of a string</li>
<li>You need to assign the result of <code>strip()</code> and <code>split(\n)</code> in your variable, otherwise nothing happens.</li>
<li>It's also better to use the keyword <a class='doc-link' href="http://stackoverflow.com/documentation/python/928/context-managers-with-statement#t=201608010937131691698"><code>with</code></a> instead of opening/closing files</li>
<li>In general, I think you'd be better served with <a class='doc-link' href="http://stackoverflow.com/documentation/python/632/regular-expressions#t=20160801093758110191">regular expressions</a> for that type of thing you're doing. However, as pointed out by Nander Speerstra's <a href="http://stackoverflow.com/questions/38695194/serach-for-word-in-text-file-in-python/38695388?noredirect=1#comment64769667_38695388">comment</a>, this could be dangerous.</li>
</ul>
| 1 | 2016-08-01T09:30:48Z | [
"python",
"python-2.7"
] |
Search for word in text file in Python | 38,695,194 | <p>I have this text file:</p>
<pre><code>MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need to find the line with the model.</p>
<p>My code:</p>
<pre><code>term = "model"
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print line
file.close()
</code></pre>
<p>This is the output:</p>
<pre><code>model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
</code></pre>
<p>I need only this line as output: </p>
<pre><code> model,3,2016-07-30 15:39:59,075
</code></pre>
<p>How can I do this?</p>
| -1 | 2016-08-01T09:22:04Z | 38,695,424 | <p>You can split the line by <code>,</code> and check for the first field:</p>
<pre><code>term = "model"
file = open('file.txt')
for line in file:
line = line.strip().split(',') # <---
if term == line[0]: # <--- You can also stay with "if term in line:" if you doesn't care which field the "model" is.
print line
file.close()
</code></pre>
| 1 | 2016-08-01T09:32:34Z | [
"python",
"python-2.7"
] |
Adding a new column for substruction : Length of values does not match length of index | 38,695,196 | <p>I have a dataframe which contains: <code>TIMESTAMP</code>, <code>P_ACT_KW</code> and <code>P_SOUSCR</code>.</p>
<pre><code>df2 = pd.read_csv('C:/Users/Demonstrator/Downloads/power.csv',delimiter=';')
</code></pre>
<p>First, I dropped missing observations: </p>
<pre><code>df_no_missing = df2.dropna()
</code></pre>
<p>Then, I try to add a new column named <code>depassement</code> , which contains the value 0 <code>if(df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0 else df2['P_ACT_KW']- df2['P_SOUSCR']</code>.</p>
<pre><code>df_no_missing['depassement'] = np.where((df_no_missing['P_SOUSCR'] - df_no_missing['P_ACT_KW']) < 0), 0, df_no_missing['P_ACT_KW'] - df_no_missing['P_SOUSCR']
</code></pre>
<p>But I get this error : </p>
<pre>
ValueError
Traceback (most recent call last) in ()
----> 1 df_no_missing['depassement'] = np.where((df_no_missing['P_SOUSCR'] - df_no_missing['P_ACT_KW']) 2357 self._set_item(key, value) 2358 2359 def _setitem_slice(self, key, value):
C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value) 2421 2422 self._ensure_valid_index(value)
-> 2423 value = self._sanitize_column(key, value) 2424 NDFrame._set_item(self, key, value) 2425
C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value) 2576 2577 # turn me into an ndarray
-> 2578 value = _sanitize_index(value, self.index, copy=False) 2579 if not isinstance(value, (np.ndarray, Index)): 2580 if isinstance(value, list) and len(value) > 0:
C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\series.py in _sanitize_index(data, index, copy) 2768 2769 if len(data) != len(index):
-> 2770 raise ValueError('Length of values does not match length of ' 'index') 2771 2772 if isinstance(data, PeriodIndex):
ValueError: Length of values does not match length of index
</pre>
<p>Any idea please to resolve this problem? </p>
| 1 | 2016-08-01T09:22:06Z | 38,695,371 | <p>You can add parameter <code>inplace=True</code> to <code>df2</code> for inplace removing <code>NaN</code> and correct parentheses:</p>
<pre><code>import pandas as pd
import numpy as np
df2 = pd.DataFrame({'P_SOUSCR':[10,2,1,np.nan],
'P_ACT_KW':[4,5,6,4]})
df2.dropna(inplace=True)
print (df2)
P_ACT_KW P_SOUSCR
0 4 10.0
1 5 2.0
2 6 1.0
df2['depassement'] = np.where((df2['P_SOUSCR'] - df2['P_ACT_KW']) < 0,
0,
df2['P_ACT_KW'] - df2['P_SOUSCR'])
print (df2)
P_ACT_KW P_SOUSCR depassement
0 4 10.0 -6.0
1 5 2.0 0.0
2 6 1.0 0.0
</code></pre>
<p>Another solution is add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow"><code>copy</code></a>:</p>
<pre><code>df_no_missing = df2.dropna().copy()
</code></pre>
| 0 | 2016-08-01T09:30:02Z | [
"python",
"pandas"
] |
My form's is_valid method returns false | 38,695,315 | <p>I have a form as below :</p>
<pre><code>class CookDuty(forms.Form ):
# cook = None
def __init__(self, *args, **kwargs):
cook = kwargs.pop('cook')
super(CookDuty, self).__init__(*args, **kwargs)
self.fields['duty'].choices = foods_for_cook(cook)
duty = forms.ChoiceField(widget=forms.CheckboxSelectMultiple, required=False)
</code></pre>
<p>I have used it in a view as below, but <code>form.is_valid</code> returns false! I have checked <code>form.errors</code> and it's empty, <code>form.data</code> is empty, and form.is_bound is <code>False</code>.</p>
<pre><code>def duty_list_cook(request):
if request.method == 'POST':
c = Cook.objects.all()[0]
form = CookDuty(cook=c)
if form.is_valid():
print(form.cleaned_data)
return render(request, 'employee/cook_duty.html', {'form':form})
else:
c = Cook.objects.all()[0]
form = CookDuty(cook=c)
return render (request, 'employee/cook_duty.html', {'form':form})
</code></pre>
| 1 | 2016-08-01T09:27:26Z | 38,695,428 | <p>When it is a post request, you need to pass the POST data to the form.</p>
<pre><code>if request.method == 'POST':
c = Cook.objects.all()[0]
form = CookDuty(cook=c, data=request.POST)
</code></pre>
<p>Without the post data, the form is unbound, so will always be invalid.</p>
<p>See the docs on <a href="https://docs.djangoproject.com/en/1.9/ref/forms/api/#bound-and-unbound-forms" rel="nofollow">bound and unbound forms</a> for more info.</p>
<p>The second problem is that the <code>ChoiceField</code> field (used for selecting a single choice) isn't compatible with the <code>CheckboxSelectMultiple</code> widget (used for selecting multiple choices). If you want to select multiple choices, then you need to use <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#multiplechoicefield" rel="nofollow"><code>MultipleChoiceField</code></a> instead of <code>ChoiceField</code>.</p>
<pre><code>duty = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, required=False)
</code></pre>
| 1 | 2016-08-01T09:32:41Z | [
"python",
"django",
"django-forms",
"django-views"
] |
Invoking a pyramid framework application from inside another application | 38,695,372 | <p>I have a Python application running in a framework that drives a network protocol to control remote devices. Now I want to add a browser-based monitoring and control and I am looking at the Pyramid framework to build it.</p>
<p>Normally you start a Pyramid application using <strong>pserve</strong> from a command line, but I can't find any documentation or examples for how to invoke it inside a host application framework. This needs to be done in such a way that the Pyramid code can access objects in the host application.</p>
<p>Is this a practical use case for Pyramid or should I be looking for some other WSGI-based framework to do this?</p>
| 1 | 2016-08-01T09:30:04Z | 38,709,093 | <p>A WSGI app is basically a function which receives some input and returns a response, you don't really need <code>pserve</code> to serve a WSGI app, it's more like a wrapper which assembles an application from an .ini file.</p>
<p>Have a look at <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/firstapp.html" rel="nofollow">Creating Your First Pyramid Application</a> chapter in Pyramid docs:</p>
<pre><code>from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello %(name)s!' % request.matchdict)
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/hello/{name}')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
</code></pre>
<p>the last two lines create a server which listens on port 8080.</p>
<p>Now, the trickier problem is that the <code>serve_forever</code> call is <em>blocking</em>, i.e.the program stops on that line until you hit <kbd>Ctrl</kbd>-<kbd>C</kbd> and stop the script. This makes it a bit non-trivial to have your program to "drive a network protocol to control remote devices" and to serve web pages at the same time (this is unlike other event-based platforms such as Node.js where it's trivial to have two servers to listen on different ports within the same process).</p>
<p>One possible solution to this problem would be to run the webserver in a separate thread. </p>
| 1 | 2016-08-01T22:30:34Z | [
"python",
"python-3.x",
"pyramid",
"wsgi"
] |
Read a line from a file in python | 38,695,508 | <p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p>
<pre><code>no-syslog = yes # (or no to disable)
logfile = /tmp/logfile
</code></pre>
<p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <code>no-syslog = yes</code> then program has to check for the tag <code>logfile</code> and will read the <code>logfile</code> tag. Can anyone let me know how I can get the value <code>/tmp/logfile</code></p>
<pre><code>with open('/etc/mcelog/mcelog.conf', 'r+') as fp:
for line in fp:
if re.search("no-syslog =", line) and re.search("= no", line):
memoryErrors = readLogFile("/var/log/messages")
mcelogPathFound = true
break
elif re.search("no-syslog =", line) and re.search("= yes", line):
continue
elif re.search("logfile =", line):
memoryErrors = readLogFile(line) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed
mcelogPathFound = true
break
fp.close()
</code></pre>
| 0 | 2016-08-01T09:36:50Z | 38,695,656 | <p>You can just split the line to get the value you want:</p>
<pre><code>line.split(' = ')[1]
</code></pre>
<p>However, you might want to look at the documentation for <a href="https://docs.python.org/3/library/configparser.html" rel="nofollow">configparser module</a>.</p>
| 2 | 2016-08-01T09:43:36Z | [
"python",
"file-io"
] |
Read a line from a file in python | 38,695,508 | <p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p>
<pre><code>no-syslog = yes # (or no to disable)
logfile = /tmp/logfile
</code></pre>
<p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <code>no-syslog = yes</code> then program has to check for the tag <code>logfile</code> and will read the <code>logfile</code> tag. Can anyone let me know how I can get the value <code>/tmp/logfile</code></p>
<pre><code>with open('/etc/mcelog/mcelog.conf', 'r+') as fp:
for line in fp:
if re.search("no-syslog =", line) and re.search("= no", line):
memoryErrors = readLogFile("/var/log/messages")
mcelogPathFound = true
break
elif re.search("no-syslog =", line) and re.search("= yes", line):
continue
elif re.search("logfile =", line):
memoryErrors = readLogFile(line) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed
mcelogPathFound = true
break
fp.close()
</code></pre>
| 0 | 2016-08-01T09:36:50Z | 38,695,684 | <p>Change the code to:</p>
<pre><code>with open('/etc/mcelog/mcelog.conf', 'r+') as fp:
for line in fp:
if re.search("no-syslog =", line) and re.search("= no", line):
memoryErrors = readLogFile("/var/log/messages")
mcelogPathFound = true
break
elif re.search("no-syslog =", line) and re.search("= yes", line):
continue
elif re.search("logfile =", line):
emoryErrors = readLogFile(line.split("=")[1].strip()) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed
mcelogPathFound = true
break
fp.close()
</code></pre>
<p>This is because you want to read only a part of the line rather the whole thing so I have just split it up by the "=" sign and then stripped it to remove any blanks</p>
| 1 | 2016-08-01T09:44:29Z | [
"python",
"file-io"
] |
Read a line from a file in python | 38,695,508 | <p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p>
<pre><code>no-syslog = yes # (or no to disable)
logfile = /tmp/logfile
</code></pre>
<p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <code>no-syslog = yes</code> then program has to check for the tag <code>logfile</code> and will read the <code>logfile</code> tag. Can anyone let me know how I can get the value <code>/tmp/logfile</code></p>
<pre><code>with open('/etc/mcelog/mcelog.conf', 'r+') as fp:
for line in fp:
if re.search("no-syslog =", line) and re.search("= no", line):
memoryErrors = readLogFile("/var/log/messages")
mcelogPathFound = true
break
elif re.search("no-syslog =", line) and re.search("= yes", line):
continue
elif re.search("logfile =", line):
memoryErrors = readLogFile(line) # Here I want to pass the value "/tmp/logfile" but currently "logfile = /tmp/logfile" is getting passed
mcelogPathFound = true
break
fp.close()
</code></pre>
| 0 | 2016-08-01T09:36:50Z | 38,704,654 | <p>I liked the suggestion of the <code>configparser</code> module, so here is an example of that (Python 3)</p>
<p>For the given input, it will output <code>reading /var/log/messages</code></p>
<pre><code>import configparser, itertools
config = configparser.ConfigParser()
filename = "/tmp/mcelog.conf"
def readLogFile(filename):
if filename:
print("reading", filename)
else:
raise ValueError("unable to read file")
section = 'global'
with open(filename) as fp:
config.read_file(itertools.chain(['[{}]'.format(section)], fp), source = filename)
no_syslog = config[section]['no-syslog']
if no_syslog == 'yes':
logfile = "/var/log/messages"
elif no_syslog == 'no':
logfile = config[section]['logfile']
if logfile:
mcelogPathFound = True
memoryErrors = readLogFile(logfile)
</code></pre>
| 0 | 2016-08-01T17:21:45Z | [
"python",
"file-io"
] |
Lists in Python | 38,695,557 | <p>I noticed that you can multiply list by scalar but the behavior is weird
If I multiply: </p>
<pre><code>[2,3,4] * 3
</code></pre>
<p>I get:<br>
<code>[2,3,4,2,3,4,2,3,4</code>]<br>
I understand the results but what it's good for? Is there any other weird operations like that?</p>
| 1 | 2016-08-01T09:38:33Z | 38,695,585 | <p>The main purpose of this operand is for initialisation. For example, if you want to initialize a list with 20 equal numbers you can do it using a for loop:</p>
<pre><code>arr=[]
for i in range(20):
arr.append(3)
</code></pre>
<p>An alternative way will be using this operator:</p>
<pre><code>arr = [3] * 20
</code></pre>
<p>More weird and normal list operation on lists you can find here <a href="http://www.discoversdk.com/knowledge-base/using-lists-in-python" rel="nofollow">http://www.discoversdk.com/knowledge-base/using-lists-in-python</a></p>
| 3 | 2016-08-01T09:40:30Z | [
"python"
] |
Lists in Python | 38,695,557 | <p>I noticed that you can multiply list by scalar but the behavior is weird
If I multiply: </p>
<pre><code>[2,3,4] * 3
</code></pre>
<p>I get:<br>
<code>[2,3,4,2,3,4,2,3,4</code>]<br>
I understand the results but what it's good for? Is there any other weird operations like that?</p>
| 1 | 2016-08-01T09:38:33Z | 38,695,647 | <p>The operation has a use of creating arrays initialized with some value.</p>
<p>For example <code>[5]*1000</code> means "create an array of length 1000 initialized with 5".</p>
<p>If you want to multiply each element by 3, use</p>
<pre><code>map(lambda x: 3*x, arr)
</code></pre>
| 0 | 2016-08-01T09:43:11Z | [
"python"
] |
jupyter notebook not working in Mac | 38,695,693 | <p>I can have already gone through the following questions: </p>
<p><a href="http://stackoverflow.com/questions/35029029/jupyter-notebook-command-does-not-work-on-mac">Jupyter notebook command does not work on Mac</a></p>
<p><a href="http://stackoverflow.com/questions/35313876/after-installing-with-pip-jupyter-command-not-found">After installing with pip, "jupyter: command not found"</a></p>
<p>None of them helped me. I have installed <code>jupyter</code> and <code>notebook</code> through pip.</p>
<p>The error I get is: </p>
<pre><code>â ~ jupyter notebook
zsh: permission denied: jupyter
</code></pre>
<p>So, when I sudo it:</p>
<pre><code>â ~ sudo jupyter notebook
Password:
sudo: jupyter: command not found
</code></pre>
| 0 | 2016-08-01T09:44:51Z | 38,695,949 | <p>you can check a couple of issues:</p>
<p>⢠Verify you have Python correctly installed. I recommend installing with <a href="http://brew.sh" rel="nofollow">Homebrew</a> for the right dependencies to be installed too:</p>
<pre><code>brew install python
</code></pre>
<p>⢠You can also install Python and Jupyter Notebook together with the Anaconda package, which installs both them, plus other useful packages for scientific computing and data science:</p>
<p><a href="https://www.continuum.io/downloads" rel="nofollow">Anaconda</a></p>
| 1 | 2016-08-01T09:57:30Z | [
"python",
"osx",
"jupyter",
"jupyter-notebook"
] |
RethinkDB Join and Order using Python | 38,695,756 | <p>I would like to join and order the field in RethinkDB. My tables and sample data is:</p>
<p>Category Table</p>
<pre><code>{
"id": "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"name": "IT"
} {
"id": "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"name": "Electronic"
} {
"id": "61774bf5-b197-4676-be95-873d6f701243" ,
"name": "Motor"
}
</code></pre>
<p>Item table</p>
<pre><code>{
"id": "8d14ac9f-713c-4424-aba8-de2e6fb4d51a" ,
"category_id": "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Computer'
}
{
"id": "266f34a7-b850-45b3-b15a-9fb59c90113d" ,
"category_id": "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Notebook'
}
{
"id": "397e574c-0597-4198-97c6-33a50c6f464a" ,
"category_id": "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Smart Phone'
}
{
"id": "3a080b71-a250-4616-a22b-c14483ce8be0" ,
"category_id": "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"item_name": 'Generator'
}
{
"id": "5a66eb5e-271a-47d6-8c4e-036fa06a0ea2" ,
"category_id": "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"item_name": 'Air-Con'
}
{
"id": "449ec1ef-dac0-42a3-aef9-e79f0556452a" ,
"category_id": "61774bf5-b197-4676-be95-873d6f701243" ,
"item_name": 'Car'
}
</code></pre>
<p>I want to join and order by field count that tables in python. I want to following result</p>
<pre><code>{
"id": "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"name": "IT",
"count": 3
} {
"id": "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"name": "Electronic",
"count": 2
} {
"id": "61774bf5-b197-4676-be95-873d6f701243" ,
"name": "Motor",
'count': 1
}
</code></pre>
<p>Help me please.</p>
| 0 | 2016-08-01T09:48:12Z | 38,720,752 | <pre><code> r.table('Category').merge(lambda row:{'count':r.table('Item').filter({'category_id':row['id']}).count()}).order_by(r.desc('count')).run()
</code></pre>
<p>I got the solution. Thanks all.</p>
| 0 | 2016-08-02T12:43:42Z | [
"python",
"rethinkdb-python"
] |
Can't find efficient way to replicate original code after refactoring of pandas .resample() | 38,695,811 | <p>I am passing a dictionary of pandas DataFrames (or a pandas panel) into the function below in order convert from daily to monthly data. Each DataFrame represents a field (eg Open, High, Low or Close) in datetime v stock code space. The function works fine but I am getting deprecation warnings. I can't find an efficient implementation using the newly refactored resample() though. Most of the examples I can find use the agg() function to apply different methods to different columns of a single dataframe. My panel has a separate frame for each field though so this doesn't quite fit. I've tried using apply(lambda) and it works but is unreasonably slow. I'm sure there is an efficient implementation for this. I've noticed several questions that have been answered based on the deprecated implementation and a similar question to mine that has not yet been answered.</p>
<p>Here's my original function:</p>
<pre><code># function to convert daily data to monthly and return dictionary or panel
def to_monthly(fields, data_d, create_panel=True):
how_dict={'Open':'first', 'High':'max', 'Low':'min', 'Close':'last'}
data_m={}
for field in fields:
data_m[field]=data_d[field].resample(rule='M', how=how_dict[field]).ffill()
if create_panel:
data_m = pd.Panel(data_m)
return data_m
</code></pre>
<p>This runs fine but I get the deprecation warnings. My attempt to solve this is:</p>
<pre><code># alternative function to handle refactoring of .resample()
def to_monthly(fields, data_d, create_panel=True):
how_dict={
'Open': (lambda x: x[0]),
'High': (lambda x: x.max()),
'Low': (lambda x: x.min()),
'Close': (lambda x: x[-1]),
'Volume': lambda x: x.sum()
}
data_m={}
for field in fields:
data_m[field]=data_d[field].resample('M').apply(how_dict[field]).ffill()
if create_panel:
data_m = pd.Panel(data_m)
return data_m
</code></pre>
<p>I haven't found it easy to locate a replacement syntax for all the old "how" options. Some assistance on this would also be appreciated. The Pandas documentation doesn't always seem to provide all the options under a given field or usage. I've seen others have had similar problems.</p>
<p>Any help would be greatly appreciated</p>
<p>Thank you</p>
| 1 | 2016-08-01T09:51:15Z | 38,696,609 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.tseries.resample.Resampler.aggregate.html" rel="nofollow"><code>Resampler.aggregate</code></a> and pass a dict of the Column names as keys with it's respective intended operation as the values.</p>
<pre><code>dict_ohlcv = {'Open':'first', 'High':'max', 'Low':'min', 'Close':'last', 'Volume':'sum'}
data_m[field]=data_d[field].resample('M')
.agg(dict_ohlcv[field])
.ffill()
</code></pre>
<p>The <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/whatsnew.html#previous-api-will-work-but-with-deprecations" rel="nofollow"><code>deprecation warnings</code></a> you get is due to the fact that API breaking change to the <code>.resample</code> method to make it more <code>.groupby</code> like.[<em>source:</em> <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/whatsnew.html#resample-api" rel="nofollow"><code>Resample API</code></a>]</p>
| 0 | 2016-08-01T10:32:47Z | [
"python",
"pandas",
"resampling",
"deprecation-warning"
] |
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame' | 38,695,947 | <p>I have dataframe and I need to make an assessment of the quality before using nearest neighbor method.
I use <code>sklearn.cross_validation.KFold</code>, but I don't know, how can I give a dataframe to this function. </p>
<pre><code>quality = KFold(df, n_folds=5, shuffle=True, random_state=42)
</code></pre>
<p>But it return</p>
<pre><code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
</code></pre>
<p>How can I fix it?</p>
| -6 | 2016-08-01T09:57:22Z | 38,696,065 | <p>Does <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.KFold.html" rel="nofollow">documentation</a> say you can pass a dataframe as the first argument? No.
It accepts number. Read the docs carefully. </p>
| -1 | 2016-08-01T10:02:17Z | [
"python",
"pandas",
"scikit-learn"
] |
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame' | 38,695,947 | <p>I have dataframe and I need to make an assessment of the quality before using nearest neighbor method.
I use <code>sklearn.cross_validation.KFold</code>, but I don't know, how can I give a dataframe to this function. </p>
<pre><code>quality = KFold(df, n_folds=5, shuffle=True, random_state=42)
</code></pre>
<p>But it return</p>
<pre><code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
</code></pre>
<p>How can I fix it?</p>
| -6 | 2016-08-01T09:57:22Z | 38,696,348 | <p>You're supposed to pass the number of rows you want to perform the split on:</p>
<pre><code>quality = KFold(len(df), n_folds=5, shuffle=True, random_state=42)
</code></pre>
<p>this will use the number of rows of the df and return you an array of indices to perform the splits on, you can then use this to slice the df:</p>
<pre><code>for train_index, test_index in quality:
# do something with slices
df.iloc[train_index]
df.iloc[test_index]
</code></pre>
<p>if your df index is an int64 index and is monotonic and increases from <code>0</code> then you can use <code>loc</code> instead of <code>iloc</code></p>
| 3 | 2016-08-01T10:18:23Z | [
"python",
"pandas",
"scikit-learn"
] |
Optimising the generation of a large number of random numbers using python 3 | 38,696,070 | <p>I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too slow for <code>N > 10^6</code>, especially when I am averaging over N trials <code>n_t = 25</code> more times! I am currently getting this code to run in around <em>12 seconds</em> for <code>N = 10^5</code>, meaning that it will take <em>20 minutes</em> for <code>N = 10^7</code>, which doesn't seem optimal (it may be, I don't know!).</p>
<p>My code is as follows:</p>
<pre><code>import random
import datetime
from numpy import pi
from numpy import sin
import numpy
t1 = datetime.datetime.now()
def trial(N):
total = []
uniform = numpy.random.uniform
append = total.append
for j in range(N):
sum = 0
for i in range (8):
sum+= uniform(0, pi/8)
append(sin(sum))
return total
N = 1000000
n_t = 25
total_squared = 0
ans = []
for k in range (n_t):
total = trial(N)
f_mean = (numpy.sum(total))/N
ans.append(f_mean*((pi/8)**8)*1000000)
sum_square = 0
for e in ans:
sum_square += e**2
sum = numpy.sum(ans)
mean = sum/n_t
variance = sum_square/n_t - mean**2
s_d = variance**0.5
print (mean, " ± ", s_d)
t2 = datetime.datetime.now()
print ("Execution time: %s" % (t2-t1))
</code></pre>
<p>If anyone can help me optimise this it would be much appreciated!</p>
<p>Thank you :)</p>
| 2 | 2016-08-01T10:02:31Z | 38,696,572 | <p>By the Central Limit Theorem, your random variable will closely follow a normal law.</p>
<p>The sum of the eight uniform variables has a bell-shaped distribution over the range [0, Ï]. If I am right, the distribution can be represented as a B-spline of order 8. Taking the sine gives a value in range [0, 1]. You can find the expectation µ and variance ϲ by simple numerical integration.</p>
<p>Then use a normal generator with mean µ and variance ϲ/N. That will be instantaneous in comparison.</p>
| 1 | 2016-08-01T10:30:17Z | [
"python",
"python-3.x",
"optimization",
"random",
"numbers"
] |
Optimising the generation of a large number of random numbers using python 3 | 38,696,070 | <p>I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too slow for <code>N > 10^6</code>, especially when I am averaging over N trials <code>n_t = 25</code> more times! I am currently getting this code to run in around <em>12 seconds</em> for <code>N = 10^5</code>, meaning that it will take <em>20 minutes</em> for <code>N = 10^7</code>, which doesn't seem optimal (it may be, I don't know!).</p>
<p>My code is as follows:</p>
<pre><code>import random
import datetime
from numpy import pi
from numpy import sin
import numpy
t1 = datetime.datetime.now()
def trial(N):
total = []
uniform = numpy.random.uniform
append = total.append
for j in range(N):
sum = 0
for i in range (8):
sum+= uniform(0, pi/8)
append(sin(sum))
return total
N = 1000000
n_t = 25
total_squared = 0
ans = []
for k in range (n_t):
total = trial(N)
f_mean = (numpy.sum(total))/N
ans.append(f_mean*((pi/8)**8)*1000000)
sum_square = 0
for e in ans:
sum_square += e**2
sum = numpy.sum(ans)
mean = sum/n_t
variance = sum_square/n_t - mean**2
s_d = variance**0.5
print (mean, " ± ", s_d)
t2 = datetime.datetime.now()
print ("Execution time: %s" % (t2-t1))
</code></pre>
<p>If anyone can help me optimise this it would be much appreciated!</p>
<p>Thank you :)</p>
| 2 | 2016-08-01T10:02:31Z | 38,696,624 | <p>Given your requirement of obtaining the result with this method, <code>np.sin(np.random.uniform(0,np.pi/8,size=(8,10**6,25)).sum(axis=0)).mean(axis=0)</code> gets you your 25 trials pretty quickly... This is fully vectorised (and concise which is always a bonus!) so I doubt you could do any better...</p>
<p>Explanation:</p>
<p>You generate a big random 3d array of size <code>(8 x 10**6 x 25)</code>. <code>.sum(axis=0)</code> will get you the sum over the first dimension (<code>8</code>). <code>np.sin(...)</code> applies elementwise. <code>.mean(axis=0)</code> will get you the mean over the first remaining dimension (<code>10**6</code>) and leave you with a 1d array of length (<code>25</code>) corresponding to your trials.</p>
| 6 | 2016-08-01T10:33:29Z | [
"python",
"python-3.x",
"optimization",
"random",
"numbers"
] |
Python: How to check the number of occurrences and top (n) values in a dataframe? | 38,696,101 | <p>I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.</p>
<pre><code> Date Location
0 09/17/1908 Virginia
1 07/12/1912 New Jersey
2 08/06/1913 Canada
3 09/09/1913 England
4 10/17/1913 Germany
5 03/05/1915 Belgium
6 09/03/1915 Germany
7 07/28/1916 Bulgeria
8 09/24/1916 England
9 10/01/1916 England
</code></pre>
<p>Result value should be something like below:</p>
<pre><code>Location Count
England 3
Germany 2
</code></pre>
| -1 | 2016-08-01T10:04:55Z | 38,696,167 | <pre><code>countCollection = df['collection'].value_counts()
</code></pre>
<p><code>.value_counts()</code> will give you a count for the items from the collection named <code>collection</code> in a dataFrame.</p>
<p>Also, as you mentioned you're new to Python, to get the final value:</p>
<pre><code>countCollection["a"]
</code></pre>
<p>will get the count value from the returned collection of counts, for the row with key "a".</p>
| 1 | 2016-08-01T10:08:40Z | [
"python",
"python-3.x",
"pandas"
] |
Python: How to check the number of occurrences and top (n) values in a dataframe? | 38,696,101 | <p>I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.</p>
<pre><code> Date Location
0 09/17/1908 Virginia
1 07/12/1912 New Jersey
2 08/06/1913 Canada
3 09/09/1913 England
4 10/17/1913 Germany
5 03/05/1915 Belgium
6 09/03/1915 Germany
7 07/28/1916 Bulgeria
8 09/24/1916 England
9 10/01/1916 England
</code></pre>
<p>Result value should be something like below:</p>
<pre><code>Location Count
England 3
Germany 2
</code></pre>
| -1 | 2016-08-01T10:04:55Z | 38,697,308 | <p>You may use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> together with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow">size</a>:</p>
<pre><code>counts = df.groupby('Location').size()
</code></pre>
<p><code>counts</code> is of type <code>pandas.Series</code>. You may order it by</p>
<pre><code>counts.sort_values(inplace=True)
</code></pre>
<hr>
<p>Comparision to the answer of <a href="http://stackoverflow.com/users/2483271/nick-bull">Nick</a>:</p>
<pre><code>import pandas as pd
import numpy as np
# number of items in list
N = 1e4
# create a list uniformely samples characters
l = np.random.choice( list('abcd'), N )
# create a DataFrame
df = pd.DataFrame( l, columns=['char'] )
</code></pre>
<p>using the ipython magic command <a href="https://ipython.org/ipython-doc/3/interactive/magics.html" rel="nofollow">timeit</a> for <code>N=1e4</code></p>
<pre><code>In [1]: %timeit df.char.value_counts()
1000 loops, best of 3: 1.34 ms per loop
In [2]: %timeit df.groupby('char').size()
1000 loops, best of 3: 1.01 ms per loop
</code></pre>
<p>and <code>N=1e6</code></p>
<pre><code>In [1]: %timeit df.char.value_counts()
10 loops, best of 3: 64.2 ms per loop
In [2]: %timeit df.groupby('char').size()
10 loops, best of 3: 73.2 ms per loop
</code></pre>
<p>For smaller DataFrames, <code>groupby</code> & <code>size</code> is faster than <code>value_counts</code>, but for larger DateFrames <code>value_counts</code> is faster than <code>groupby</code> & <code>size</code></p>
| 0 | 2016-08-01T11:09:07Z | [
"python",
"python-3.x",
"pandas"
] |
python source file analysis and transformation using Rascal | 38,696,394 | <p>I would like to scan all project files in a python project, identify all instantiations of objects that are subclass of a certain type and then:
1. Add the "yield" keyword to the object instantiation
2. identify all call stack for that object creation, and add a decorator to all functions in that call stack.</p>
<p>is that doable using Rascal?</p>
| 1 | 2016-08-01T10:21:07Z | 38,777,882 | <p>When you have a representation of your Python source code as tree (parse tree or abstract syntax tree) you
can convert this to a Rascal data type and use Rascal for
further processing. This can be achieved by using and connecting an existing Python parser to generate the Rascal
representation of your Python program. This could be done by simply
dumping the parse tree in a format that can be read by Rascal.</p>
<p>Why this complex solution: because the built-in parser
generator of Rascal is not (yet) well equipped to parse
indentation-sensitive languages like Python.</p>
| 1 | 2016-08-04T21:43:05Z | [
"python",
"callstack",
"rascal"
] |
Creating a Django demo-user who can't save to the database | 38,696,423 | <p>I'm creating a Django web application on which users can create an account for free. I have also set-up a demo user which is already configured and has data attached to its account. Purpose of this demo account is to give a new user a quick overview of what the application can do.</p>
<p>Now I would like to have this demo user access all my views but not save to the database when the user saves a form.</p>
<p>Off course there are multiple ways off doing this that I know off. But they all require me to edit multiple pages or views:</p>
<ul>
<li>When saving a form check if it is the demo user, if yes: don't save</li>
<li>Remove the save button from my templates when the demo user is logged in</li>
</ul>
<p>Is there a easier/cleaner solution to do this? How can I set-up my application in a way that a specific user can never save to the database?</p>
<p><strong>The solution I used</strong></p>
<p>marcusshep's idea provided a solution for me. I created the following Views for pages where the form should be loaded but not saved when hitting the save button. Until now I wasn't able to do that. At this moment the pages below will render a 303 immediately </p>
<pre><code>class FormViewOPRadio(FormView):
def dispatch(self, request, *args, **kwargs):
# Return 403 for demo user
temp = 'temp'
if self.request.user.email == 'demo@opradio.nl':
raise PermissionDenied
else:
return super(FormViewOPRadio, self).dispatch(request, *args, **kwargs)
class UpdateViewOPRadio(UpdateView):
def dispatch(self, request, *args, **kwargs):
# Return 403 for demo user
temp = 'temp'
if self.request.user.email == 'demo@opradio.nl':
raise PermissionDenied
else:
return super(UpdateViewOPRadio, self).dispatch(request, *args, **kwargs)
class DeleteViewOPRadio(DeleteView):
def dispatch(self, request, *args, **kwargs):
# Return 403 for demo user
temp = 'temp'
if self.request.user.email == 'demo@opradio.nl':
raise PermissionDenied
else:
return super(DeleteViewOPRadio, self).dispatch(request, *args, **kwargs)
</code></pre>
<p>Furthermore there are also some pages which should be inaccessible for which I used</p>
<pre><code>from braces.views import UserPassesTestMixin
class UserNotDemoUser(UserPassesTestMixin):
raise_exception = True
def test_func(self, user):
return user.email != 'demo@opradio.nl'
</code></pre>
<p><strong>What I tried</strong></p>
<p>I created the following Views for pages where the form should be loaded but not saved when hitting the save button</p>
<pre><code>class FormViewOPRadio(FormView):
def form_valid(self, form):
# Return 403 for demo user
if self.request.user.email == 'demo@opradio.nl':
raise PermissionDenied
else:
return super(FormViewOPRadio, self).form_valid(form)
class AddStream(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, FormViewOPRadio):
"""Is the page used to add a Stream"""
template_name = 'opradioapp/addoreditstream.html'
form_class = AddStreamForm
success_url = reverse_lazy('opradioapp_home')
success_message = "De stream is opgeslagen"
# Validate if the user is the maintainer of the station
def test_func(self):
user = self.request.user
mainuserstation = MainUserStation.objects.get(slugname=self.kwargs['mainuserstationslug'])
if mainuserstation.maintainer == user:
return True
else:
return False
def form_valid(self, form):
user = self.request.user
mainuserstation = MainUserStation.objects.get(slugname=self.kwargs['mainuserstationslug'])
userstream = UserStream()
userstream.mainuserstation = mainuserstation
userstream.name = form.cleaned_data['name']
userstream.slugname = 'temp'
userstream.description = form.cleaned_data['description']
userstream.save()
member = Member.objects.get(user=user, mainuserstation=mainuserstation)
member.streamavailable.add(userstream)
member.save()
return super(AddStream, self).form_valid(form)
</code></pre>
<p>When doing it this way </p>
<pre><code> if self.request.user.email == 'demo@opradio.nl':
raise PermissionDenied
</code></pre>
<p>is called after the save() calls. How can I change this? I tried calling super earlier but than I ran into problems.</p>
| 1 | 2016-08-01T10:22:31Z | 38,702,863 | <blockquote>
<p>Off course there are multiple ways of doing this that I know of. But they all require me to edit multiple pages or views:</p>
</blockquote>
<p>Well, you won't have to repeat the logic for every template or view if you utilize certain <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a> features of Python and Django.</p>
<p><a href="http://www.programiz.com/python-programming/inheritance" rel="nofollow">Class Based View Inheritance</a></p>
<pre><code>class CheckForDemoUser(View):
def dispatch(self, request, *args, **kwargs):
# check for demo user
# handle which ever way you see fit.
super(CheckForDemoUser, self).dispatch(request, *a, **kw)
class ChildClass(CheckForDemoUser): # notice inheritance here
def get(request, *args, **kwargs):
# continue with normal request handling
# this view will always check for demo user
# without the need to repeat yourself.
</code></pre>
<p><a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">Function Decorators</a></p>
<pre><code>def check_for_demo_user(func):
def func_wrapper(request, *args, **kwargs):
# implement logic to determine what the view should
# do if the request.user is demo user.
return func_wrapper
@check_for_demo_user
def my_view(request, *args, **kwargs):
# automatic checking happening before view gets to this point.
</code></pre>
<p>With <a href="https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#inclusion-tags" rel="nofollow">Inclusion Tags</a> you can isolate the logic of hiding/showing form submit buttons in one place and refer to your custom tag in multiple pages that the demo user would be on.</p>
<p>These are just some of the ways you can implement this logic without having to repeat yourself over and over.</p>
| 1 | 2016-08-01T15:38:11Z | [
"python",
"django"
] |
Why does this for loop not work | 38,696,469 | <p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p>
<p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. The code is incomplete, it needs to be run using a particular online software. The link to the entire program is below.</p>
<p><a href="http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py" rel="nofollow">http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py</a> </p>
<p>I want to use the for loop to populate the canvas with the 14 numbers in the range 0-7. </p>
<p>Here's the code, let me know if you're able to spot the error.</p>
<pre><code>#card width:
C_W = 50
#card height:
C_H = 98
#upper left corner of a card:
u_l = [1 , 1]
deck = range(0,8)
deck1 = deck
deck.extend(deck1)
#called by a button on the GUI
def new_game():
random.shuffle(deck)
# cards are 50x100 pixels in size
def draw(canvas):
global C_W, C_H, deck
count = 0
for card in deck:
canvas.draw_text(str(deck[count]), (C_W / 3, C_H - 25), 60, "White")
C_W += C_W
count += 1
</code></pre>
| -2 | 2016-08-01T10:24:52Z | 38,696,692 | <p>It looks like your <code>draw</code> function is called in an infinite loop, probably here:
<code>frame.set_draw_handler(draw)</code> so you should lookup that frame function.</p>
<p>Also no need for <code>deck1</code> just do:
<code>deck = range(8) * 2</code></p>
| 1 | 2016-08-01T10:36:35Z | [
"python",
"python-2.7"
] |
Why does this for loop not work | 38,696,469 | <p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p>
<p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. The code is incomplete, it needs to be run using a particular online software. The link to the entire program is below.</p>
<p><a href="http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py" rel="nofollow">http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py</a> </p>
<p>I want to use the for loop to populate the canvas with the 14 numbers in the range 0-7. </p>
<p>Here's the code, let me know if you're able to spot the error.</p>
<pre><code>#card width:
C_W = 50
#card height:
C_H = 98
#upper left corner of a card:
u_l = [1 , 1]
deck = range(0,8)
deck1 = deck
deck.extend(deck1)
#called by a button on the GUI
def new_game():
random.shuffle(deck)
# cards are 50x100 pixels in size
def draw(canvas):
global C_W, C_H, deck
count = 0
for card in deck:
canvas.draw_text(str(deck[count]), (C_W / 3, C_H - 25), 60, "White")
C_W += C_W
count += 1
</code></pre>
| -2 | 2016-08-01T10:24:52Z | 38,697,297 | <p>The <code>draw()</code> function in simplegui is called about 60 per second and the code in the <code>for</code> loop inside your version doubles the global <code>C_W</code> 16 times each time the function is called. This means its value quickly becomes astronomical and the text is drawn way off the screen to the right somewhere outside our galaxy.</p>
<p>Here's a simple way to avoid that problem:</p>
<pre><code>def draw(canvas):
global C_W, C_H, deck
count = 0
c_w = C_W # init with value of global variable
for card in deck: # note "card" is not being used
canvas.draw_text(str(deck[count]), (c_w / 3, C_H - 25), 60, "White")
c_w += c_w
count += 1
</code></pre>
| 1 | 2016-08-01T11:08:29Z | [
"python",
"python-2.7"
] |
Why does this for loop not work | 38,696,469 | <p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p>
<p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. The code is incomplete, it needs to be run using a particular online software. The link to the entire program is below.</p>
<p><a href="http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py" rel="nofollow">http://www.codeskulptor.org/#user41_ZFQIR6Hm1W_0.py</a> </p>
<p>I want to use the for loop to populate the canvas with the 14 numbers in the range 0-7. </p>
<p>Here's the code, let me know if you're able to spot the error.</p>
<pre><code>#card width:
C_W = 50
#card height:
C_H = 98
#upper left corner of a card:
u_l = [1 , 1]
deck = range(0,8)
deck1 = deck
deck.extend(deck1)
#called by a button on the GUI
def new_game():
random.shuffle(deck)
# cards are 50x100 pixels in size
def draw(canvas):
global C_W, C_H, deck
count = 0
for card in deck:
canvas.draw_text(str(deck[count]), (C_W / 3, C_H - 25), 60, "White")
C_W += C_W
count += 1
</code></pre>
| -2 | 2016-08-01T10:24:52Z | 38,697,498 | <p>Try this loop:</p>
<pre><code>for card,count in enumerate(deck):
canvas.draw_text(str(card), (C_W * count+1 / 3, C_H - 25), 60, "White")
</code></pre>
<p>It prevents the global value from changing, and gives you the intended effect.</p>
| 0 | 2016-08-01T11:18:31Z | [
"python",
"python-2.7"
] |
Python Serial communition with device | 38,696,483 | <p><a href="http://i.stack.imgur.com/GnHLc.jpg" rel="nofollow">enter image description here</a></p>
<p>I am making serial port communication device from a genious guy's work instructables.com.</p>
<p>It will measure the distance of the hamster's running in a day or month.</p>
<p>Using 4, 6 pin of the serial port cable, if the hamster runs, the device can count the numbers how many time did she run.</p>
<p>When I run the py file with Python27 like below, some errors occure.
"python hamster-serial.py progress.txt"</p>
<p>I cannot understand what's going on.
I am using windows8 and Python2.7 version.</p>
<p>Could you check my source, please?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import datetime
import serial
import sys
# Check for commandline argument. The first argument is the the name of the program.
if len(sys.argv) < 2:
print "Usage: python %s [Out File]" % sys.argv[0]
exit()
# Open the serial port we'll use the pins on and the file we'll write to.
ser = serial.Serial("/dev/ttyS1")
# Open the file we're going to write the results to.
f = open(sys.argv[1], 'a')
# Bring DTR to 1. This will be shorted to DSR when the switch is activated as the wheel turns.
ser.setDTR(1)
# The circumferance of the wheel.
circ = 0.000396 # miles
# Total distance traveled in this run of the program.
distance = 0.0
print "%s] Starting logging." % datetime.datetime.now()
start = datetime.datetime.now()
# This function a period of the wheel to a speed of the hamster.
def toSpeed(period):
global circ
seconds = period.days * 24 * 60 * 60 + period.seconds + period.microseconds / 1000000.
return circ / (seconds / 60. / 60.)
# Waits for the DSR pin on the serial port to turn off. This indicates that the
# switch has turned off and the magnet is no longer over the switch.
def waitForPinOff():
while ser.getDSR() == 1:
1 # Don't do anything while we wait.
# Waits for the DSR pin on the serial port to turn on. This indicates that the
# switch has turned on and the magnet is current over the switch.
def waitForPinOn():
while ser.getDSR() == 0:
1 # Don't do anything while we wait.
# The main loop of the program.
while 1:
waitForPinOn()
# Calculate the speed.
end = datetime.datetime.now()
period = end - start
start = end
speed = toSpeed(period)
# Increment the distance.
distance = distance + circ
waitForPinOff()
# We'll calculate the time the switch was held on too so but this isn't too useful.
hold = datetime.datetime.now() - start
# If the switch bounces or the hamster doesn't make a full revolution then
# it might seem like the hamster is running really fast. If the speed is
# more than 4 mph then ignore it, because the hamster can't run that fast.
if speed < 4.0:
# Print out our speed and distance for this session.
print "%s] Distance: %.4f miles Speed: %.2f mph" % (datetime.datetime.now(), distance, speed)
# Log it to and flush the file so it actually gets written.
f.write("%s\t%.2f\n" % (datetime.datetime.now().strftime("%D %T"), speed))
f.flush()
</code></pre>
</div>
</div>
</p>
| 1 | 2016-08-01T10:25:45Z | 38,700,384 | <p>Well, <code>ser = serial.Serial("/dev/ttyS1")</code> is for a linux machine, on windows you'll need something like <code>ser = serial.Serial("COM1")</code> (you can check what COM do you need in the device manager).</p>
<p>As a side note, </p>
<pre><code>def waitForPinOff():
while ser.getDSR() == 1:
1 # Don't do anything while we wait.
</code></pre>
<p>Will eat you CPU. You are better of with:</p>
<pre><code>def waitForPinOff():
while ser.getDSR() == 1:
time.sleep(1) # Don't do anything while we wait.
</code></pre>
| 0 | 2016-08-01T13:39:23Z | [
"python",
"serial-port",
"port",
"distance",
"period"
] |
make a 2D matrix of strings to match mesh coordinates | 38,696,546 | <p>I have a structured mesh. The mesh has coordinates (X,Y), but each mesh cell also has an alphanumerical code assigned.
The mesh X and Y coordinates are generated as 2D arrays with meshgrid. </p>
<p>The series with the alphanumerical codes looks like this</p>
<pre><code>Index Code
0 aa1
1 aa2
2 aa3
3 aa4
4 bb1
5 bb2
6 bb3
7 bb4
8 ab1
9 ab2
10 ab3
11 ab4
.... .....
</code></pre>
<p>My thought was to make a 2D array of the alphanumerical codes so that the row and column index of each element will correspond to the same row and column index of the X and Y 2D arrays.</p>
<p>the alphanumerical values are in a pandas series of the same length as the size of the X and Y 2D arrays. I need to slice the alphanumerical values every nth element (so take for instance 0 to 2 and make this the first row) and form the first row of the 2D array and continue like this filling the rest.</p>
<p>and in the end i want to have this:</p>
<pre><code>0 0 1 2
1 aa1 aa2 aa3
2 aa4 bb1 bb2
3 bb3 bb4 ab1
4 ab2 ab3 ab4
.....................
</code></pre>
<p>Any suggestions on how to make this work?
i managed to get to this:</p>
<pre><code>interval = 2
alphanum = [array[i:i+interval] for i in range(len(df.series))[::interval]]
</code></pre>
<p>which gives me a list of series and not a 2D array</p>
| 1 | 2016-08-01T10:28:50Z | 38,696,734 | <p>Well, if you know the length of each row you can use just a list.
You can make the 2D array in "your head" and convert the coordinates into their position in an array.</p>
<p><strong>Example</strong>:</p>
<p>You have got a row_length x column_length grid, therefore you have a list with a row_length*column_length entries.
To access a specific coordinate you access the following entry of the list:</p>
<pre><code>Pos(x|y) = mygrid[xcoord*rowlength+columnlength]
</code></pre>
<p><br></p>
<p><strong>Explanation/Clarification</strong>:</p>
<p>Instead of using an actual 2D array, you can just use a 1D list. If you know the size of each row, that isn't a problem but instead, increases the speed your program is working with. Let's assume we have got a 3x3 grid containing a letter at each position, our coordinates will look like that: (0|0, 0|1, 0|2, 1|0, 1|1, ...)</p>
<p>We could represent this grid with:</p>
<pre><code> 0 1 2
0 'a' 'q' 'x'
1 'm' 'f' 'b'
2 'l' 's' 'r'
</code></pre>
<p>Or, instead of creating an actual 2D grid, we just create a 1D array.</p>
<pre><code>data = ['a', 'q', 'x', 'm', 'f', 'b', 'l', 's', 'r']
</code></pre>
<p>To get the index of a specific coordinate we can now multiply the row_number with the length of each row and add the column_number to it.</p>
<p>For example, to access the coordinate (2|1) of the grid above, we can just access:</p>
<pre><code>data[2*3+1]
</code></pre>
<p>If you check both values, you will see that both are delivering the letter 's' as it should.</p>
| 0 | 2016-08-01T10:38:43Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
make a 2D matrix of strings to match mesh coordinates | 38,696,546 | <p>I have a structured mesh. The mesh has coordinates (X,Y), but each mesh cell also has an alphanumerical code assigned.
The mesh X and Y coordinates are generated as 2D arrays with meshgrid. </p>
<p>The series with the alphanumerical codes looks like this</p>
<pre><code>Index Code
0 aa1
1 aa2
2 aa3
3 aa4
4 bb1
5 bb2
6 bb3
7 bb4
8 ab1
9 ab2
10 ab3
11 ab4
.... .....
</code></pre>
<p>My thought was to make a 2D array of the alphanumerical codes so that the row and column index of each element will correspond to the same row and column index of the X and Y 2D arrays.</p>
<p>the alphanumerical values are in a pandas series of the same length as the size of the X and Y 2D arrays. I need to slice the alphanumerical values every nth element (so take for instance 0 to 2 and make this the first row) and form the first row of the 2D array and continue like this filling the rest.</p>
<p>and in the end i want to have this:</p>
<pre><code>0 0 1 2
1 aa1 aa2 aa3
2 aa4 bb1 bb2
3 bb3 bb4 ab1
4 ab2 ab3 ab4
.....................
</code></pre>
<p>Any suggestions on how to make this work?
i managed to get to this:</p>
<pre><code>interval = 2
alphanum = [array[i:i+interval] for i in range(len(df.series))[::interval]]
</code></pre>
<p>which gives me a list of series and not a 2D array</p>
| 1 | 2016-08-01T10:28:50Z | 38,697,546 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html" rel="nofollow"><code>numpy.array_split</code></a> or even <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow"><code>numpy.split</code></a> to split the arrays into multiple sub-arrays. But the former does not raise an exception if an equal division cannot be made.</p>
<pre><code>In [2]: np.array(np.array_split(df['Code'].values, 4))
Out[2]:
array([['aa1', 'aa2', 'aa3'],
['aa4', 'bb1', 'bb2'],
['bb3', 'bb4', 'ab1'],
['ab2', 'ab3', 'ab4']], dtype=object)
</code></pre>
<p><strong>EDIT :</strong></p>
<p>You mean like this?</p>
<pre><code>In [5]: np.array(np.array_split(df.as_matrix(columns=['Code']), 4))
Out[5]:
array([[['aa1'],
['aa2'],
['aa3']],
[['aa4'],
['bb1'],
['bb2']],
[['bb3'],
['bb4'],
['ab1']],
[['ab2'],
['ab3'],
['ab4']]], dtype=object)
</code></pre>
| 1 | 2016-08-01T11:20:45Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
Writing to particular address in memory in python | 38,696,575 | <p>I know python is a high level language and manages the memory allocation etc. on its own user/developer doesn't need to worry much unlike other languages like c, c++ etc.</p>
<p>but is there a way through will we can write some value in a particular memory address in python</p>
<p>i know about id() which if hex type casted can give hexadecimal location but how can we write at a location. </p>
| 1 | 2016-08-01T10:30:34Z | 38,696,887 | <p>Python itself does not include any facilities to allow the programmer direct access to memory. This means that sadly (or happily, depending on your outlook) the answer to your question is "no".</p>
| 1 | 2016-08-01T10:47:46Z | [
"python",
"python-2.7"
] |
Writing to particular address in memory in python | 38,696,575 | <p>I know python is a high level language and manages the memory allocation etc. on its own user/developer doesn't need to worry much unlike other languages like c, c++ etc.</p>
<p>but is there a way through will we can write some value in a particular memory address in python</p>
<p>i know about id() which if hex type casted can give hexadecimal location but how can we write at a location. </p>
| 1 | 2016-08-01T10:30:34Z | 38,706,483 | <p>To begin with, as noted in the comments, it's quite a question why you would want to do such a thing at all. You should consider carefully whether there is any alternative.</p>
<p>Having said that, it is quite easy to do so via extensions. Python itself is built so that it is easy to <a href="https://docs.python.org/3/extending/extending.html" rel="nofollow">extend it via C or C++</a>. It's even easier doing it via <a href="http://cython.org/" rel="nofollow">Cython</a>.</p>
<p>The following sketches how to build a Python-callable function taking integers <code>p</code> and <code>v</code>. It will write the value <code>v</code> to the memory address whose numeric address is <code>p</code>. </p>
<p><strong>Note</strong> Once again, note, this is a technical answer only. The entire operation, and parts of it, are questionable, and you should consider what you're trying to achieve.</p>
<p>Create a file <code>modify.h</code>, with the content:</p>
<pre><code>void modify(int p, int v);
</code></pre>
<p>Create a file <code>modify.c</code>, with the content:</p>
<pre><code>#include "modify.h"
void modify(int p, int v)
{
*(int *)(p) = v;
}
</code></pre>
<p>Create a file <code>modify.pyx</code>, with the content:</p>
<pre><code>cdef extern from "modify.h"
void modify(int p, int v)
def py_modify(p, v):
modify(p, v)
</code></pre>
<p>Finally, create <code>setup.py</code>, with the content:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension(
name="modify",
sources=["modify.pyx", "modify.c"])]
</code></pre>
<p>setup(
name = 'modify',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
# ext_modules = cythonize(ext_modules) ? not in 0.14.1
# version=
# description=
# author=
# author_email=
)</p>
<hr>
<p>I hope you use this answer for learning purposes only.</p>
| 2 | 2016-08-01T19:16:56Z | [
"python",
"python-2.7"
] |
Regular expression to match the word but not the word inside other strings | 38,696,658 | <p>I have a rich text like </p>
<pre><code>Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala...
Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple!
</code></pre>
<p>What I want to match is the word <code>leoshi</code>, but not inside of <code><a></code> elements, So in this example it's only <code>leoshi</code> in <code>leoshi for details....</code></p>
<p>Solution and explanation are welcome!</p>
| -1 | 2016-08-01T10:35:04Z | 38,696,810 | <p>I used a positive lookbehind to start the match <strong>AFTER</strong> the closing tag <code></a></code>. And then matched <code>leoshi</code> with a parentheses when it is used as a separate word.</p>
<p>Regex: <code>(?<=<\/a>).*?\b(leoshi)</code></p>
<p><a href="https://regex101.com/r/rM4eQ9/6" rel="nofollow">DEMO</a></p>
| 0 | 2016-08-01T10:43:27Z | [
"javascript",
"python",
"regex"
] |
Regular expression to match the word but not the word inside other strings | 38,696,658 | <p>I have a rich text like </p>
<pre><code>Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala...
Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple!
</code></pre>
<p>What I want to match is the word <code>leoshi</code>, but not inside of <code><a></code> elements, So in this example it's only <code>leoshi</code> in <code>leoshi for details....</code></p>
<p>Solution and explanation are welcome!</p>
| -1 | 2016-08-01T10:35:04Z | 38,696,876 | <p>The best approach (using regex) would be to first remove all of the tags, then detect the word in the remaining string. For example:</p>
<pre><code>var str_without_links = str.replace(/<a\b.*?<\/a>/, '')
str_without_links.match(/leoshi/)
</code></pre>
<p>If you need to preserve the string length (for correspondence with the original string), consider using placeholder characters in place of the original tag.</p>
<pre><code>var str_without_links = str.replace(/<a\b.*?<\/a>/, function(s) { return s.replace(/./g, ' ') })
</code></pre>
| -1 | 2016-08-01T10:47:16Z | [
"javascript",
"python",
"regex"
] |
Regular expression to match the word but not the word inside other strings | 38,696,658 | <p>I have a rich text like </p>
<pre><code>Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala...
Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple!
</code></pre>
<p>What I want to match is the word <code>leoshi</code>, but not inside of <code><a></code> elements, So in this example it's only <code>leoshi</code> in <code>leoshi for details....</code></p>
<p>Solution and explanation are welcome!</p>
| -1 | 2016-08-01T10:35:04Z | 38,697,800 | <p>A trick aimed to handle such "find a word but not a specific context" cases is described here: <a href="http://www.rexegg.com/regex-best-trick.html" rel="nofollow">http://www.rexegg.com/regex-best-trick.html</a>.</p>
<p>In essence it is: match your word in the undesired context or (using alternation) just this word but in a capture group. Then analyze the captures.</p>
<p>The regex in your case would be:</p>
<pre><code><a.*?>.*leoshi.*<\/a>|(leoshi)
</code></pre>
<p>Demo: <a href="https://regex101.com/r/zO0tV2/1" rel="nofollow">https://regex101.com/r/zO0tV2/1</a></p>
<p>Then you need to check captures:</p>
<pre><code>var input = "...";
var pattern = /<a.*?>.*leoshi.*<\/a>|(leoshi)/;
var match = pattern.exec(input);
var inputMatches = match !== null && match[1] !== null;
</code></pre>
<p>Demo: <a href="https://ideone.com/KkAl2I" rel="nofollow">https://ideone.com/KkAl2I</a></p>
| 0 | 2016-08-01T11:33:32Z | [
"javascript",
"python",
"regex"
] |
Maya command not return reference list from *.ma | 38,696,668 | <p>In Maya I execute command to get the list for references included in the file:</p>
<pre><code>cmds.file(fileName, q=True, reference=True)
</code></pre>
<p>It returns a list of the first level for references. And there is already a problem. If the file has an extension *.mb - then everything comes back. But if the file is saved as a *.ma - the command returns an empty list</p>
<p>I tried to run the command on MEL - the same result. I suspect that it is necessary to specify what that additional flags, but nothing like this in the documentation can not be found.</p>
<p>Tell me how to solve the problem?</p>
| 0 | 2016-08-01T10:35:25Z | 38,880,238 | <p>use <a href="http://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/CommandsPython/referenceQuery.html" rel="nofollow">referenceQuery</a> instead if you just want information about what is referenced from the file</p>
| 0 | 2016-08-10T17:46:43Z | [
"python",
"reference",
"maya",
"mel"
] |
Maya command not return reference list from *.ma | 38,696,668 | <p>In Maya I execute command to get the list for references included in the file:</p>
<pre><code>cmds.file(fileName, q=True, reference=True)
</code></pre>
<p>It returns a list of the first level for references. And there is already a problem. If the file has an extension *.mb - then everything comes back. But if the file is saved as a *.ma - the command returns an empty list</p>
<p>I tried to run the command on MEL - the same result. I suspect that it is necessary to specify what that additional flags, but nothing like this in the documentation can not be found.</p>
<p>Tell me how to solve the problem?</p>
| 0 | 2016-08-01T10:35:25Z | 39,084,039 | <p>which maya version is the .ma file in compare to the main session where the "cmds.file(fileName, q=True, reference=True)" command will call </p>
| 0 | 2016-08-22T16:03:14Z | [
"python",
"reference",
"maya",
"mel"
] |
How to set variable of a class from another function? | 38,696,669 | <p>I want to replace 'YouTube' with 'Gmail' from fat function. This class and function are in two separate files.</p>
<pre><code>class Data():
url = 'YouTube'
from . import Data
def fat():
r = 'Gmail'
Data.url = r
return "something"
</code></pre>
<p>how can i do this?</p>
| 0 | 2016-08-01T10:35:26Z | 38,698,775 | <p>Actually It's showing 'Youtube' because you are not calling fat() function i guess here is the code please go for it</p>
<p>file class_var contains</p>
<pre><code>class Data():
url = 'YouTube'
</code></pre>
<p>file func_var contains</p>
<pre><code>from class_var import Data
def fat():
r = 'Gmail'
Data.url = r
return "something"
fat()
print Data.url
</code></pre>
<p>In this criteria both files are in same directory.
Hope this will help you</p>
| 0 | 2016-08-01T12:22:33Z | [
"python"
] |
Python pandas display dataframe as a table with tabs and not spaces | 38,696,799 | <p>How can I print or display a <code>pandas.DataFrame</code> object like a "real" table? I mean using <strong>only one tab</strong> between columns and <strong>not more spaces</strong>. In IPython Jupyter Notebook I can use the following code to get a "real" table style:</p>
<pre><code>from IPython.core.display import display
display(df.head(50))
</code></pre>
<p>instead of <code>print(df.head(50))</code> which uses spaces.
Is there any same in IPython console using Spyder? I did no find a proper <code>pd.set_option()</code> value...</p>
| 0 | 2016-08-01T10:42:48Z | 38,696,850 | <p>Unfortunately the Jupyter Notebook is a specialized environment, which knows how to tell objects to render themselves as HTML inside the Jupyter (web) interface. I don't believe Spyder has this capability.</p>
| 1 | 2016-08-01T10:46:06Z | [
"python",
"pandas",
"printing"
] |
HTTP Requests (Python + VBA) | 38,696,804 | <p>can anyone guide me in the right direction when it comes to http requests with python? What I'm after is a Excel-VBA add-in which will track which workbooks the user opens and when etc. While that's already done, I would now like to get the information to a database.</p>
<p>For that purpose I can imagine running a very simple Python server which would be used to store the information. The question thus is, how do I set up a simple http server so that VBA can post a simple string which then gets stored?</p>
<p>Thanks!</p>
<p>EDIT:</p>
<p>Thanks chf! I went ahead and followed your advice - I replaced flask with django though as I had some brief experience with that. I've got my first API ever created now but can't post using the VBA code you posted. I can do httpie like so: "http POST http:/127.0.0.1 name="somename" workbookname="someworkbook". </p>
<pre><code>Sub TestFramework()
Dim newClient As New WebClient
Dim newRequest As New WebRequest
Dim Response As WebResponse
newClient.BaseUrl = "http://127.0.0.1:8000/api/create/"
newRequest.Method = HttpPost
newRequest.Format = WebFormat.plaintext
newRequest.AddBodyParameter "name", "somename"
newRequest.AddBodyParameter "workbook_name", "Sheet1"
Set Response = newClient.Execute(newRequest)
End Sub
</code></pre>
<p>Any chance you might point me to the right way?</p>
<blockquote>
<p>RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/api/create/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
[03/Aug/2016 20:13:18] "POST /api/create HTTP/1.1" 500 60534</p>
</blockquote>
<p>Edit2: nevermind, got it working :)</p>
| 0 | 2016-08-01T10:43:11Z | 38,697,144 | <p>Nice project!
You can use <a href="https://flask-restful.readthedocs.io/en/latest/" rel="nofollow">Flask</a> for the Python part to build a small REST Api and for the VBA part you can use <a href="https://github.com/VBA-tools/VBA-Web" rel="nofollow">VBA-WEB</a> to consume that API. </p>
<p>Both Flask than VBA-WEB are very well documented with a lot of examples.
I use VBA-WEB in a lot of small "SAK" (swiss army knife) utilities in Excel and it's very useful and powerful.
For some rest apis with json output Flask is a nice tool to use.</p>
| 1 | 2016-08-01T11:01:05Z | [
"python",
"vba",
"server"
] |
plot multiple columns on one axis python | 38,696,813 | <p>I'm new to data analysis and am looking to plot a table that has multiple date columns as one of the axis. I have tried this:</p>
<pre><code>years = [data['1996'],data['1997'],data['1998'],data['1999'],data['2000']]
data.plot(x=years,y=data['City'])
</code></pre>
<p>and </p>
<pre><code>[data.plot(data[:,x],data2['City']) for x in range(3,5)]
plot.show()
</code></pre>
<p>where data is a pandas dataframer, neither are working. I feel like this is probably simple but can't seem to find the solution anywhere.</p>
<p>Thanks </p>
| 0 | 2016-08-01T10:43:31Z | 38,697,101 | <p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from column <code>City</code>, then transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><code>T</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow"><code>DataFrame.plot</code></a>:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame({'City':['a','b','c','d'],
'1996':[1,2,7,5],
'1997':[4,0,6,3],
'1998':[7,8,6,9],
'1999':[0,5,3,0]})
print (data)
1996 1997 1998 1999 City
0 1 4 7 0 a
1 2 0 8 5 b
2 7 6 6 3 c
3 5 3 9 0 d
print (data.set_index('City').T)
City a b c d
1996 1 2 7 5
1997 4 0 6 3
1998 7 8 6 9
1999 0 5 3 0
data.set_index('City').T.plot()
plt.show()
</code></pre>
| 0 | 2016-08-01T10:58:40Z | [
"python",
"pandas",
"matplotlib"
] |
How to replace/bypass a property in Python? | 38,696,819 | <p>I would like to have a class with an attribute <code>attr</code> that, when accessed for the first time, runs a function and returns a value, and then <em>becomes</em> this value (its type changes, etc.).</p>
<p>A similar behavior can be obtained with:</p>
<pre><code>class MyClass(object):
@property
def attr(self):
try:
return self._cached_result
except AttributeError:
result = ...
self._cached_result = result
return result
obj = MyClass()
print obj.attr # First calculation
print obj.attr # Cached result is used
</code></pre>
<p>However, <code>.attr</code> does not <em>become</em> the initial result, when doing this. It would be more efficient if it did.</p>
<p>A difficulty is that after <code>obj.attr</code> is set to a property, it cannot be set easily to something else, because infinite loops appear naturally. Thus, in the code above, the <code>obj.attr</code> property has no setter so it cannot be directly modified. If a setter is defined, then replacing <code>obj.attr</code> in this setter creates an infinite loop (the setter is accessed from within the setter). I also thought of first <em>deleting</em> the setter so as to be able to do a regular <code>self.attr = â¦</code>, with <code>del self.attr</code>, but this calls the property deleter (if any), which recreates the infinite loop problem (modifications of <code>self.attr</code> anywhere generally tend to go through the property rules).</p>
<p>So, is there a way to bypass the property mechanism and replace the bound property <code>obj.attr</code> by anything, from within <code>MyClass.attr.__getter__</code>?</p>
| 1 | 2016-08-01T10:44:03Z | 38,697,657 | <p>This looks a bit like premature optimization : you want to skip a method call by making a descriptor change itself. </p>
<p>It's perfectly possible, but it would have to be justified.</p>
<p>To modify the descriptor from your property, you'd have to be editing your class, which is probably not what you want.</p>
<p>I think a better way to implement this would be to :</p>
<ul>
<li>do not define <code>obj.attr</code></li>
<li>override <code>__getattr__</code>, if argument is "attr", <code>obj.attr = new_value</code>, otherwise raise <code>AttributeError</code></li>
</ul>
<p>As soon as <code>obj.attr</code> is set, <code>__getattr__</code> will not be called any more, as it is only called when the attribute does not exist. (<code>__getattribute__</code> is the one that would get called all the time.)</p>
<p>The main difference with your initial proposal is that the first attribute access is slower, because of the method call overhead of <code>__getattr__</code>, but then it will be as fact as a regular <code>__dict__</code> lookup.</p>
<p><strong>Example :</strong></p>
<pre><code>class MyClass(object):
def __getattr__(self, name):
if name == 'attr':
self.attr = ...
return self.attr
raise AttributeError(name)
obj = MyClass()
print obj.attr # First calculation
print obj.attr # Cached result is used
</code></pre>
| 2 | 2016-08-01T11:27:00Z | [
"python",
"properties",
"attributes"
] |
Regex - Why won't this regex work in Python? | 38,696,855 | <p>I have this expression</p>
<pre><code>:([^"]*) \(([^"]*)\)
</code></pre>
<p>and this text</p>
<pre><code>:chkpf_uid ("{4astr-hn389-918ks}")
:"#cert" ("false")
</code></pre>
<p>Im trying to match it so that on the first sentence ill get these groups:</p>
<ol>
<li>chkpf_uid</li>
<li>{4astr-hn389-918ks}</li>
</ol>
<p>and on the second, ill get these:</p>
<ol>
<li><code>#cert</code></li>
<li>false</li>
</ol>
<p>I want to avoid getting the quotes.</p>
<p>I can't seem to understand why the expression I use won't match these, especially if I switch the <code>[^"]*</code> to a <code>(.*)</code>.</p>
<p>with <code>([^"]*)</code>: <a href="https://regex101.com/r/kC2rV3/1" rel="nofollow">wont match</a></p>
<p>with (.*): <a href="https://regex101.com/r/jT0jQ3/1" rel="nofollow">does match, but with quotes</a></p>
<p>This is using the <code>re</code> module in python 2.7</p>
| 1 | 2016-08-01T10:46:18Z | 38,697,436 | <p><em>Sidenote: your input may require a specific parser to handle, especially if it may have escape sequences.</em></p>
<p>Answering the question itself, remember that a regex is processed from left to right <em>sequentially</em>, and the string is processed the same here. A match is returned if the pattern matches a portion/whole string (depending on the method used). </p>
<p>If there are quotation marks in the string, and your pattern does not let match those quotes, the match will be failed, no match will be returned.</p>
<p>A possible solution can be adding the quotes as otpional subpatterns:</p>
<pre><code>:"?([^"]*)"? \("?([^"]*)"?\)
^^ ^^ ^^ ^^
</code></pre>
<p>See the <a href="https://regex101.com/r/dC4xK2/2" rel="nofollow">regex demo</a></p>
<p>The parts you need are captured into groups, and the quotes, present or not, are just matched, left out of your <code>re.findall</code> reach.</p>
| 1 | 2016-08-01T11:15:13Z | [
"python",
"regex"
] |
Python Flask failing on combined GET and POST request | 38,697,035 | <p>I'm writing a function in Python Flask to deal with the oauth2 call backs of multiple api's.</p>
<p>The function as it stands is:</p>
<pre><code>@app.route('/external_api/<api>/oauth2callback', methods=['POST', 'GET'])
def gdrive_oauth2callback(api):
toReturn = external_api.APIs[api]['lib'].oauth2callback(os.path.join(APP_OAUTH, str(api + '_id.json')))
userSession = UserSession()
userSession.addUserAuth(api)
return toReturn
</code></pre>
<p>However this causes a build error:</p>
<pre><code>raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None)
</code></pre>
<p>I'm confused as to why this is happening, as when i replace the api variable with the string 'gdrive' no error is created and it works perfectly. I'm calling the function in the same manner on both occasions (example.com/external_api/gdrive/oauth2callback), I'm wondering if Flask is unable to deal with both a POST request and a GET request at the same time, and if anyone else has had the same issue?</p>
<p>The full error log is below:</p>
<pre><code>ERROR:app:Exception on /external_api/gdrive/connect [GET]
Traceback (most recent call last):
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/app/views.py", line 43, in gdrive_connect
toReturn = external_api.APIs[api]['lib'].makeConnection()
File "/app/app/external_api/gdrive/api.py", line 14, in makeConnection
return flask.redirect(flask.url_for('gdrive_oauth2callback'))
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/routing.py", line 1616, in build
raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None) - at=info method=GET path
</code></pre>
<p>If anyone could give me any pointers on this that would be great! Thanks!</p>
| 1 | 2016-08-01T10:55:32Z | 38,699,342 | <p>I think that flask must not be failing, if you take a look to this example, it works perfectly, <a href="http://flask.pocoo.org/snippets/62/" rel="nofollow">http://flask.pocoo.org/snippets/62/</a>.</p>
<p>I tried:
</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/<name>",methods=['POST', 'GET'])
def hello(name):
return "Hello World!"+name
if __name__ == "__main__":
app.run()
</code></pre>
<p>and it works fine on post and get requests. I know that isnt enougth but it shows what the problem probably isnât. </p>
| 0 | 2016-08-01T12:48:23Z | [
"python",
"flask"
] |
how to convert Python 2 unicode() function into correct Python 3.x syntax | 38,697,037 | <p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p>
<p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and found no hint how to upgrade: </p>
<p>I don't want to switch to Python3 now, but maybe in the future.</p>
<p>The code contains about 500 calls to <code>unicode()</code></p>
<p>How to proceed?</p>
<p><strong>Update</strong></p>
<p>The comment of user vaultah to read the <a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">pyporting</a> guide has received several upvotes.</p>
<p>My current solution is this (thanks to Peter Brittain):</p>
<pre><code>from builtins import str
</code></pre>
<p>... I could not find this hint in the pyporting docs.....</p>
<p><strong>Update2</strong></p>
<p>I love down-votes, if you leave a comment why you down-vote :-)</p>
| -10 | 2016-08-01T10:55:35Z | 38,750,151 | <p>You can test whether there is such a function as <code>unicode()</code> in the version of Python that you're running. If not, you can create a <code>unicode()</code> alias for the <code>str()</code> function, which does in Python 3 what <code>unicode()</code> did in Python 2, as all strings are unicode in Python 3.</p>
<pre><code># Python 3 compatibility hack
try:
unicode('')
except NameError:
unicode = str
</code></pre>
<p>Note that a more complete port is probably a better idea; see <a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">the porting guide</a> for details.</p>
| 1 | 2016-08-03T17:28:37Z | [
"python",
"python-3.x",
"python-unicode"
] |
how to convert Python 2 unicode() function into correct Python 3.x syntax | 38,697,037 | <p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p>
<p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and found no hint how to upgrade: </p>
<p>I don't want to switch to Python3 now, but maybe in the future.</p>
<p>The code contains about 500 calls to <code>unicode()</code></p>
<p>How to proceed?</p>
<p><strong>Update</strong></p>
<p>The comment of user vaultah to read the <a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">pyporting</a> guide has received several upvotes.</p>
<p>My current solution is this (thanks to Peter Brittain):</p>
<pre><code>from builtins import str
</code></pre>
<p>... I could not find this hint in the pyporting docs.....</p>
<p><strong>Update2</strong></p>
<p>I love down-votes, if you leave a comment why you down-vote :-)</p>
| -10 | 2016-08-01T10:55:35Z | 38,751,157 | <p>As has already been pointed out in the comments, there is already <a href="https://docs.python.org/3/howto/pyporting.html">advice on porting from 2 to 3</a>.</p>
<p>Having recently had to port some of my own code from 2 to 3 and maintain compatibility for each for now, I wholeheartedly recommend using <a href="http://python-future.org/overview.html">python-future</a>, which provides a great tool to help update your code (<code>futurize</code>) as well as clear guidance for <a href="http://python-future.org/compatible_idioms.html">how to write cross-compatible code</a>.</p>
<p>In your specific case, I would simply convert all calls to unicode to use str and then <a href="http://python-future.org/compatible_idioms.html#unicode">import str from builtins</a>. Any IDE worth its salt these days will do that global search and replace in one operation.</p>
<p>Of course, that's the sort of thing futurize should catch too, if you just want to use automatic conversion (and to look for other potential issues in your code).</p>
| 10 | 2016-08-03T18:30:41Z | [
"python",
"python-3.x",
"python-unicode"
] |
how to convert Python 2 unicode() function into correct Python 3.x syntax | 38,697,037 | <p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p>
<p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and found no hint how to upgrade: </p>
<p>I don't want to switch to Python3 now, but maybe in the future.</p>
<p>The code contains about 500 calls to <code>unicode()</code></p>
<p>How to proceed?</p>
<p><strong>Update</strong></p>
<p>The comment of user vaultah to read the <a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">pyporting</a> guide has received several upvotes.</p>
<p>My current solution is this (thanks to Peter Brittain):</p>
<pre><code>from builtins import str
</code></pre>
<p>... I could not find this hint in the pyporting docs.....</p>
<p><strong>Update2</strong></p>
<p>I love down-votes, if you leave a comment why you down-vote :-)</p>
| -10 | 2016-08-01T10:55:35Z | 38,782,128 | <p>First, as a strategy, I would take a small part of your program and try to port it. The number of <code>unicode</code> calls you are describing suggest to me that your application cares about string representations more than most and each use-case is often different.</p>
<p>The important consideration is that <em>all strings are unicode in Python 3</em>. If you are using the <code>str</code> type to store "bytes" (for example, if they are read from a file), then you should be aware that those will not be bytes in Python3 but will be unicode characters to begin with.</p>
<p>Let's look at a few cases.</p>
<p>First, if you do not have any non-ASCII characters at all and really are not using the Unicode character set, it is easy. Chances are you can simply change the <code>unicode()</code> function to <code>str()</code>. That will assure that any object passed as an argument is properly converted. However, it is wishful thinking to assume it's that easy.</p>
<p>Most likely, you'll need to look at the argument to <code>unicode()</code> to see what it is, and determine how to treat it.</p>
<p>For example, if you are reading UTF-8 characters from a file in Python 2 and converting them to Unicode your code would look like this:</p>
<pre><code>data = open('somefile', 'r').read()
udata = unicode(data)
</code></pre>
<p>However, in Python3, <code>read()</code> returns Unicode data to begin with, and the unicode decoding must be specified when opening the file:</p>
<pre><code>udata = open('somefile', 'r', encoding='UTF-8').read()
</code></pre>
<p>As you can see, transforming <code>unicode()</code> simply when porting may depend heavily on how and why the application is doing Unicode conversions, where the data has come from, and where it is going to.</p>
<p>Python3 brings greater clarity to string representations, which is welcome, but can make porting daunting. For example, Python3 has a proper <code>bytes</code> type, and you convert byte-data to unicode like this:</p>
<pre><code>udata = bytedata.decode('UTF-8')
</code></pre>
<p>or convert Unicode data to character form using the opposite transform.</p>
<pre><code>bytedata = udata.encode('UTF-8')
</code></pre>
<p>I hope this at least helps determine a strategy.</p>
| 4 | 2016-08-05T06:01:12Z | [
"python",
"python-3.x",
"python-unicode"
] |
how to convert Python 2 unicode() function into correct Python 3.x syntax | 38,697,037 | <p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p>
<p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and found no hint how to upgrade: </p>
<p>I don't want to switch to Python3 now, but maybe in the future.</p>
<p>The code contains about 500 calls to <code>unicode()</code></p>
<p>How to proceed?</p>
<p><strong>Update</strong></p>
<p>The comment of user vaultah to read the <a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow">pyporting</a> guide has received several upvotes.</p>
<p>My current solution is this (thanks to Peter Brittain):</p>
<pre><code>from builtins import str
</code></pre>
<p>... I could not find this hint in the pyporting docs.....</p>
<p><strong>Update2</strong></p>
<p>I love down-votes, if you leave a comment why you down-vote :-)</p>
| -10 | 2016-08-01T10:55:35Z | 38,860,645 | <p>Short answer: Replace all <code>unicode</code> calls with <code>str</code> calls.</p>
<p>Long answer: In Python 3, Unicode was replaced with strings because of its abundance. The following solution should work if you are only using Python 3:</p>
<pre><code>unicode = str
# the rest of your goes goes here
</code></pre>
<p>If you are using it with both Python 2 or Python 3, use this instead:</p>
<pre><code>import sys
if sys.version_info.major == 3:
unicode = str
# the rest of your code goes here
</code></pre>
<p>The other way: run this in the command line</p>
<pre><code>$ 2to3 package -w
</code></pre>
<p>Please see the documentation: <a class='doc-link' href="http://stackoverflow.com/documentation/python/809/compatibility-between-python-3-and-python-2/2796/strings-bytes-versus-unicode#t=201608102110415325438">Strings: Bytes versus Unicode</a></p>
| 0 | 2016-08-09T21:20:51Z | [
"python",
"python-3.x",
"python-unicode"
] |
How to pass parmeters to functions inside tf.cond in Tensorflow? | 38,697,045 | <p>I have following simple placeholders:</p>
<pre><code>x = tf.placeholder(tf.float32, shape=[1])
y = tf.placeholder(tf.float32, shape=[1])
z = tf.placeholder(tf.float32, shape=[1])
</code></pre>
<p>There are two functions <code>f1</code> and <code>f2</code> defined as:</p>
<pre><code>def fn1(a, b):
return tf.mul(a, b)
def fn2(a, b):
return tf.add(a, b)
</code></pre>
<p>Now I want to calculate result based on pred condition:</p>
<pre><code>pred = tf.placeholder(tf.bool, shape=[1])
result = tf.cond(pred, f1(x,y), f2(y,z))
</code></pre>
<p>But it gives me an error saying <code>fn1 and fn2 must be callable</code>.</p>
<p>How can I write <code>fn1</code> and <code>fn2</code> so that they can receive parameters at runtime?
I want to call the following:</p>
<pre><code>sess.run(result, feed_dict={x:1,y:2,z:3,pred:True})
</code></pre>
| 1 | 2016-08-01T10:56:02Z | 38,700,367 | <p>The easiest would be to define your functions in the call:</p>
<pre><code>result = tf.cond(pred, lambda: tf.mul(a, b), lambda: tf.add(a, b))
</code></pre>
| 0 | 2016-08-01T13:38:26Z | [
"python",
"if-statement",
"tensorflow"
] |
How to pass parmeters to functions inside tf.cond in Tensorflow? | 38,697,045 | <p>I have following simple placeholders:</p>
<pre><code>x = tf.placeholder(tf.float32, shape=[1])
y = tf.placeholder(tf.float32, shape=[1])
z = tf.placeholder(tf.float32, shape=[1])
</code></pre>
<p>There are two functions <code>f1</code> and <code>f2</code> defined as:</p>
<pre><code>def fn1(a, b):
return tf.mul(a, b)
def fn2(a, b):
return tf.add(a, b)
</code></pre>
<p>Now I want to calculate result based on pred condition:</p>
<pre><code>pred = tf.placeholder(tf.bool, shape=[1])
result = tf.cond(pred, f1(x,y), f2(y,z))
</code></pre>
<p>But it gives me an error saying <code>fn1 and fn2 must be callable</code>.</p>
<p>How can I write <code>fn1</code> and <code>fn2</code> so that they can receive parameters at runtime?
I want to call the following:</p>
<pre><code>sess.run(result, feed_dict={x:1,y:2,z:3,pred:True})
</code></pre>
| 1 | 2016-08-01T10:56:02Z | 39,573,566 | <p>You can pass parameters to the functions using <strong>lambda</strong> and the code is as bellows.</p>
<pre><code>x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = tf.placeholder(tf.float32)
def fn1(a, b):
return tf.mul(a, b)
def fn2(a, b):
return tf.add(a, b)
pred = tf.placeholder(tf.bool)
result = tf.cond(pred, lambda: fn1(x, y), lambda: fn2(y, z))
</code></pre>
<p>Then you can call it as bellowing:</p>
<pre><code>with tf.Session() as sess:
print sess.run(result, feed_dict={x: 1, y: 2, z: 3, pred: True})
# The result is 2.0
</code></pre>
| 0 | 2016-09-19T12:46:21Z | [
"python",
"if-statement",
"tensorflow"
] |
In Python, how to do groupby, sort the elements within the group and then write the output to a file | 38,697,064 | <p>My python data frame contents looks like this:</p>
<pre><code>ID [enter image description here][1] ROLE DOB
E548621 MANAGER 1980-12-31
E548622 Dy MANAGER 1983-06-01
E548623 MANAGER 1978-01-05
E548624 SSE 1988-12-31
E548625 MANAGER 1983-05-11
E548626 Dy MANAGER 1985-10-25
E548627 SSE 1987-10-20
E548628 MANAGER 1981-04-02
E548629 Dy MANAGER 1986-09-10
E548630 SSE 1989-02-15
</code></pre>
<p>My objective is to group by ROLE. Within each group, sort the records using DOB such elder ones will appear first in the list than the younger ones. After grouping and sorting I want to write the output to a file.
I have to generate the output file which looks like this.</p>
<pre><code>ROLE LIST
MANAGER [E548623 1978-01-05, E548621 1980-12-31, E548628 1981-04-02, E548625 1983-05-11]
Dy MANAGER [E548622 1983-06-01, E548626 1985-10-25, E548629 1986-09-10]
SSE [E548627 1987-10-20, E548624 1988-12-31, E548630 1989-02-15]
</code></pre>
<p>Please help me to do it. Thank you very much</p>
| -2 | 2016-08-01T10:56:55Z | 38,698,088 | <p>I think Below query will do fine if not do correct me</p>
<pre><code>query_obj = db.session.query(Table_name).group_by(Table_name.ROLE).order_by(desc(Table_name.DOB))
</code></pre>
<p>Then run a for loop in query_obj to retrieve values as one row</p>
| 0 | 2016-08-01T11:48:33Z | [
"python",
"file",
"sorting",
"group-by"
] |
Transform string column to vector column Spark DataFrames | 38,697,066 | <p>I have a Spark dataframe that looks as follows:</p>
<pre><code>+-----------+-------------------+
| ID | features |
+-----------+-------------------+
| 18156431|(5,[0,1,4],[1,1,1])|
| 20260831|(5,[0,4,5],[2,1,1])|
| 91859831|(5,[0,1],[1,3]) |
| 206186631|(5,[3,4,5],[1,5]) |
| 223134831|(5,[2,3,5],[1,1,1])|
+-----------+-------------------+
</code></pre>
<p>In this dataframe the features column is a sparse vector. In my scripts I have to save this DF as file on disk. When doing this, the features column is saved as as text column: example <code>"(5,[0,1,4],[1,1,1])"</code>.
When importing again in Spark the column stays string, as you could expect. How can I convert the column back to (sparse) vector format?</p>
| 1 | 2016-08-01T10:56:56Z | 38,699,366 | <p>Not particularly efficient (it would be a good idea to use a format that preserves types) due to UDF overhead but you can do something like this:</p>
<pre><code>from pyspark.mllib.linalg import Vectors, VectorUDT
from pyspark.sql.functions import udf
df = sc.parallelize([
(18156431, "(5,[0,1,4],[1,1,1])")
]).toDF(["id", "features"])
parse = udf(lambda s: Vectors.parse(s), VectorUDT())
df.select(parse("features"))
</code></pre>
<p>Please note this doesn't port directly to 2.0.0+ and <code>ML</code> <code>Vector</code>. Since ML vectors don't provide <code>parse</code> method you'd have to parse to <code>MLLib</code> and use <code>asML</code>.</p>
| 1 | 2016-08-01T12:49:27Z | [
"python",
"pyspark",
"spark-dataframe"
] |
type object 'UploadSerializers' has no attribute 'HyperlinkedModelSerializer' | 38,697,068 | <p>trying to do the Django Rest Framework foreign key serialization ,,however I got this error,</p>
<blockquote>
<p>models.py</p>
</blockquote>
<pre><code>class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "é model number å·²ç¶è¢«è¨»åäº ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
def get_image_path(instance, filename):
return '/'.join(['thing_images', instance.thing.slug, filename])
class Upload(models.Model):
thing = models.ForeignKey(ProductsTbl, related_name="uploads")
image = models.ImageField(upload_to=get_image_path, verbose_name='Image')
def save(self, *args, **kwargs):
super(Upload, self).save(*args, **kwargs)
if self.image:
image = Image.open(self.image)
i_width, i_height = image.size
max_size = (640, 480)
if i_width > 1000:
image.thumbnail(max_size, Image.ANTIALIAS)
image.save(self.image.path)
</code></pre>
<blockquote>
<p>api/serializers.py</p>
</blockquote>
<pre><code>from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class UploadSerializers(serializers.ModelSerializer):
class Meta:
model = Upload
fields = ('image',)
class ProductsTblSerializer(serializers.HyperlinkedModelSerializer):
uploads = UploadSerializers.HyperlinkedModelSerializer(many=True,read_only=True)
class Meta:
model = ProductsTbl
fields = ('model_number',
'created',
'name',
'release',
'twtime',
'hktime',
'shtime',
'jptime',
'feature',
'material',
'suggest',
'description',
'cataloggroup',
'place',
'scale',
'slug',
'user',
'uploads')
</code></pre>
<blockquote>
<p>api/urls.py</p>
</blockquote>
<pre><code>from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),
]
</code></pre>
<blockquote>
<p>api/views.py</p>
</blockquote>
<pre><code>from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from rest_framework.permissions import AllowAny
class ProductsTblListView(generics.ListCreateAPIView):
queryset = ProductsTbl.objects.order_by('-created')
serializer_class = ProductsTblSerializer
class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ProductsTbl.objects.all()
serializer_class = ProductsTblSerializer
</code></pre>
<p>however ,,if I changed the <code>api/serializers.py</code> like below</p>
<pre><code>......
class ProductsTblSerializer(serializers.ModelSerializer):
uploads = UploadSerializers(many=True,read_only=True)
......
</code></pre>
<p>I can see <a href="http://127.0.0.1:8000/api/productsTbls/" rel="nofollow">http://127.0.0.1:8000/api/productsTbls/</a> my page come out,,but without the image link,how can I show the image link in <code>"uploads":[]</code>? thank you (django rest framework 3.4)</p>
<p><a href="http://i.stack.imgur.com/8iJQ4.png" rel="nofollow"><img src="http://i.stack.imgur.com/8iJQ4.png" alt="enter image description here"></a></p>
| 0 | 2016-08-01T10:56:57Z | 38,698,511 | <p>You've inherited your <code>UploadSerializer</code> class from serializers.ModelSerializer, not from <code>serializers.HyperLinkedModelSerializer</code> </p>
<pre><code>class UploadSerializers(serializers.ModelSerializer):
class Meta:
model = Upload
fields = ('image',)
</code></pre>
<p>So when you try to use it as </p>
<p><code>uploads = UploadSerializers.HyperlinkedModelSerializer(many=True,read_only=True)</code> </p>
<p>it doesn't have that attribute. </p>
<p>If you make your initial declaration of <code>UploadSerializers</code> inherit from the hyperlink class, it should work. </p>
<pre><code>class UploadSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = Upload
fields = ('image',)
</code></pre>
<p>Then you should be able to use:</p>
<p><code>uploads = UploadSerializers(many=True,read_only=True)</code></p>
| 1 | 2016-08-01T12:09:38Z | [
"python",
"django",
"django-rest-framework"
] |
Compiling Python 2.7.12 with non-system Openssl on Centos 5 | 38,697,181 | <p>I'm currently trying to get Python 2.7.12 to compile with Openssl 1.0.2h on a Centos 5 host.</p>
<p>The reason for this is that I need Paramiko 2 to run on this host but that doesn't support the system provided OpenSSL version which is 0.9.8e-fips-rhel5 01 Jul 2008.</p>
<p>I've found some great hints and tips on here but it just doesn't seem to work. I'm now posting this in hope that someone will spot what I've done wrong/is missing.</p>
<p>For the OpenSSL setup I've done the following:</p>
<pre><code>OPENSSL_ROOT="$HOME/.build/openssl-1.0.1e"
cd /tmp
curl http://www.openssl.org/source/openssl-1.0.2h.tar.gz | tar zxvf -
cd openssl-1.0.2.h
mkdir -p "$OPENSSL_ROOT"
./config no-hw --prefix="$OPENSSL_ROOT" --openssldir=...
make install
</code></pre>
<p>Then since I don't want to replace the system installed Python with 2.7.12 I've done the following:</p>
<p>First I added /usr/local/lib to /etc/ld.so.conf and ran ldconfig.</p>
<p>After that I've run:</p>
<pre><code>cd /tmp
wget http://python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz
tar xf Python-2.7.12.tar.xz
cd Python-2.7.12
./configure CPPFLAGS="-I$OPENSSL_ROOT/include" LDFLAGS="-L$OPENSSL_ROOT/lib" --prefix=/usr/local --enable-unicode=ucs4 --enable-shared
make && make altinstall
</code></pre>
<p>This is when I thought I'd have it compiled against the new version of OpenSSL but no, as you can see from the output here:</p>
<pre><code>[root@an-host openssl-1.0.2h]# python2.7 -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
</code></pre>
<p>And I'm sure that I'm running the newly compiled version since that is echoed here:</p>
<pre><code>[root@an-host openssl-1.0.2h]# python2.7
Python 2.7.12 (default, Aug 1 2016, 11:46:42)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
</code></pre>
<p>I have even gone as far as removing openssl-devel with Yum but it still doesn't seem to care/compile against 1.0.2h.</p>
<p>This is driving me slightly mad at the moment so any input/feedback/help is greatly appreciated.</p>
| 0 | 2016-08-01T11:03:07Z | 38,700,814 | <p>I think I tried to copy too cute solutions and mix and match - tidied up and simplified a bit and got it to work in the end.</p>
<p>This is what I did this time:</p>
<p><em>Download and install OpenSSL</em> </p>
<pre><code>cd /tmp
curl http://www.openssl.org/source/openssl-1.0.2h.tar.gz | tar zxvf -
cd openssl-1.0.2.h
./config shared --prefix=/usr/local/
make && make install
</code></pre>
<p><em>Set up some environment variables</em></p>
<pre><code>export LDFLAGS="-L/usr/local/lib/"
export LD_LIBRARY_PATH="/usr/local/lib/"
export CPPFLAGS="-I/usr/local/include -I/usr/local/include/openssl"
</code></pre>
<p><em>Download and install Python 2.7.12</em></p>
<pre><code>wget http://python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz
tar xf Python-2.7.12.tar.xz
cd Python-2.7.12
./configure --prefix=/usr/local/ --enable-unicode=ucs4 --enable-shared
make && make altinstall
</code></pre>
<p>And now it works as expected, displaying the newer OpenSSL version.</p>
<pre><code>[root@an-host Python-2.7.12]# python2.7
Python 2.7.12 (default, Aug 1 2016, 14:48:09)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> print ssl.OPENSSL_VERSION
OpenSSL 1.0.2h 3 May 2016
</code></pre>
<p>However, it still didn't work as expected. :( Running the program I got the following error from Paramiko:</p>
<pre><code>RuntimeError: You are linking against OpenSSL 0.9.8, which is no longer support by the OpenSSL project. You need to upgrade to a newer version of OpenSSL.
</code></pre>
<p>The solution I found was to uninstall and reinstall the Cryptography bits and pieces by running.</p>
<pre><code>pip2.7 uninstall cryptography
pip2.7 install cryptography
</code></pre>
<p>After all that - it now works.</p>
| 0 | 2016-08-01T13:58:39Z | [
"python",
"linux",
"compilation",
"openssl",
"centos5"
] |
How to get a number from a string with regex | 38,697,212 | <p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p>
<pre><code>Showing Results (1 â 15 of 96,831)
</code></pre>
<p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number.</p>
<pre><code>"Showing Results (1 â 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ â \d+)/g, '')
</code></pre>
<p>Its output is as follow. This output contains spaces which are not required.</p>
<pre><code>" 96,831"
</code></pre>
<p>I want a way to do this in python. Can anyone help me?</p>
| -2 | 2016-08-01T11:04:25Z | 38,697,329 | <p>This is clear case where you should avoid regex as it just needs simple <code>strip</code> and <code>split</code>, like so:</p>
<pre><code>>>> s = 'Showing Results (1 â 15 of 96,831)'
>>> num = s.split()[-1]
'96,831)'
>>> num.strip(')')
'96,831'
</code></pre>
<p>Or, using <code>str.rstrip</code>:</p>
<pre><code>>>> num = s.rsplit(maxsplit=1)[-1]
>>> num
'96,831)'
>>> num.strip(')')
'96,831'
</code></pre>
<p>But if you insist on using regex, then this pattern might do the job for you:</p>
<pre><code>>>> import re
>>> nums = re.findall(r'\d+,?\d*', s)
['1 ', '15 ', '96,831']
>>> nums[-1]
'96,831'
</code></pre>
<p>And if you want to convert it to <code>float</code> don't forget to replace <code>,</code> with <code>.</code>:</p>
<pre><code>>>> num
'96,831'
>>>
>>> num = num.replace(',','.')
>>> num
'96.831'
>>> float(num)
96.831
</code></pre>
| 2 | 2016-08-01T11:09:55Z | [
"python",
"regex"
] |
How to get a number from a string with regex | 38,697,212 | <p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p>
<pre><code>Showing Results (1 â 15 of 96,831)
</code></pre>
<p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number.</p>
<pre><code>"Showing Results (1 â 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ â \d+)/g, '')
</code></pre>
<p>Its output is as follow. This output contains spaces which are not required.</p>
<pre><code>" 96,831"
</code></pre>
<p>I want a way to do this in python. Can anyone help me?</p>
| -2 | 2016-08-01T11:04:25Z | 38,697,453 | <p>One compact way of doing it without regex:</p>
<pre><code>str = "Showing Results (1 â 15 of 96,831)"
print str.split(" ")[-1].strip(")")
</code></pre>
| 2 | 2016-08-01T11:16:08Z | [
"python",
"regex"
] |
How to get a number from a string with regex | 38,697,212 | <p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p>
<pre><code>Showing Results (1 â 15 of 96,831)
</code></pre>
<p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number.</p>
<pre><code>"Showing Results (1 â 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ â \d+)/g, '')
</code></pre>
<p>Its output is as follow. This output contains spaces which are not required.</p>
<pre><code>" 96,831"
</code></pre>
<p>I want a way to do this in python. Can anyone help me?</p>
| -2 | 2016-08-01T11:04:25Z | 38,697,457 | <p><strong>NOTE:</strong> I assume regex is necessary.</p>
<pre><code>import re
print (re.findall(re.compile(u'of ([0-9,]+)'), u"Showing Results (1 â 15 of 96,831)")[0].replace(",", ""))
</code></pre>
| 2 | 2016-08-01T11:16:16Z | [
"python",
"regex"
] |
How to get a number from a string with regex | 38,697,212 | <p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p>
<pre><code>Showing Results (1 â 15 of 96,831)
</code></pre>
<p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number.</p>
<pre><code>"Showing Results (1 â 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ â \d+)/g, '')
</code></pre>
<p>Its output is as follow. This output contains spaces which are not required.</p>
<pre><code>" 96,831"
</code></pre>
<p>I want a way to do this in python. Can anyone help me?</p>
| -2 | 2016-08-01T11:04:25Z | 38,697,674 | <p>Assuming all of your test strings share the same format you can simply do:</p>
<pre><code>>>> import re
>>> regex = "\d+,\d+"
>>> pattern = re.compile(regex)
>>> str = "Showing Results (1 â 15 of 96,831")
>>> pattern.findall(str)
['96,831']
</code></pre>
| 2 | 2016-08-01T11:27:53Z | [
"python",
"regex"
] |
Can`t render django form in the template | 38,697,257 | <p>after reading the <a href="https://docs.djangoproject.com/ja/1.9/topics/forms/" rel="nofollow">doc on django form</a>, I tried to build my own form but the form just won`t render in the template. I also went through similar questions on stackoverflow but no solutions can solve my problem.<br>
I have this simple form based on model. Here`s the snippet of my code.<br>
The model:</p>
<pre><code>class Tweet(activity.Activity, models.Model):
user = models.ForeignKey('auth.User')
text = models.CharField(max_length=160)
created_at = models.DateTimeField(auto_now_add=True)
#...
</code></pre>
<p>The form:</p>
<pre><code>class TweetForm(ModelForm):
#text = forms.CharField(label = 'Tweet', max_length = 100)
class Meta:
model = Tweet
fields = '__all__'
</code></pre>
<p>The view:</p>
<pre><code>def user(request, user_name):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
form = TweetForm()
user = get_object_or_404(User, username=user_name)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
</code></pre>
<p>The html: </p>
<pre><code><form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Tweet" />
</code></pre>
<p></p>
<p>Actually, I <strong>could</strong> render the form in the python shell so there`s nothing wrong with the form. However, I found out that the problem lies here: </p>
<pre><code>form = TweetForm()
#...
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form #see although the form is passed to the context,
} #I can`t access variable form in the html
return render(request, 'look/user.html', context)
</code></pre>
<p>The key/value pair <code>{'form':form}</code> in the <code>context</code> is not rendered normally and that`s why the <code>{{ form }}</code> doesn`t work. But any other variables in the <code>context</code> works just fine.<br>
It really bothers me and I couldn`t figure out why the context is not working. Thanks in advance for any ideas.<br>
P.S.<br>
I tried this: </p>
<pre><code>{% if form %} form is true
{% else %} form is false
{% endif %}
</code></pre>
<p>in my html template and the result is <code>form is false</code> which indicates that the <code>form</code> variable is not passed through context or something I can`t explain happened. Any thoughts on this would be appreciated. Thanks again.</p>
| 1 | 2016-08-01T11:06:20Z | 38,698,857 | <p>I have rendered my form using a loop in my template:</p>
<pre><code>{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
<br/>
<br/>
{% endfor %}
</code></pre>
<p>This displays the form correctly in my project.</p>
| 0 | 2016-08-01T12:25:56Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
Can`t render django form in the template | 38,697,257 | <p>after reading the <a href="https://docs.djangoproject.com/ja/1.9/topics/forms/" rel="nofollow">doc on django form</a>, I tried to build my own form but the form just won`t render in the template. I also went through similar questions on stackoverflow but no solutions can solve my problem.<br>
I have this simple form based on model. Here`s the snippet of my code.<br>
The model:</p>
<pre><code>class Tweet(activity.Activity, models.Model):
user = models.ForeignKey('auth.User')
text = models.CharField(max_length=160)
created_at = models.DateTimeField(auto_now_add=True)
#...
</code></pre>
<p>The form:</p>
<pre><code>class TweetForm(ModelForm):
#text = forms.CharField(label = 'Tweet', max_length = 100)
class Meta:
model = Tweet
fields = '__all__'
</code></pre>
<p>The view:</p>
<pre><code>def user(request, user_name):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
form = TweetForm()
user = get_object_or_404(User, username=user_name)
feeds = feed_manager.get_user_feed(user.id)
activities = feeds.get(limit=25)['results']
activities = enricher.enrich_activities(activities)
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form
}
return render(request, 'look/user.html', context)
</code></pre>
<p>The html: </p>
<pre><code><form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Tweet" />
</code></pre>
<p></p>
<p>Actually, I <strong>could</strong> render the form in the python shell so there`s nothing wrong with the form. However, I found out that the problem lies here: </p>
<pre><code>form = TweetForm()
#...
context = {
'activities': activities,
'user': user,
'login_user': request.user,
'form': form #see although the form is passed to the context,
} #I can`t access variable form in the html
return render(request, 'look/user.html', context)
</code></pre>
<p>The key/value pair <code>{'form':form}</code> in the <code>context</code> is not rendered normally and that`s why the <code>{{ form }}</code> doesn`t work. But any other variables in the <code>context</code> works just fine.<br>
It really bothers me and I couldn`t figure out why the context is not working. Thanks in advance for any ideas.<br>
P.S.<br>
I tried this: </p>
<pre><code>{% if form %} form is true
{% else %} form is false
{% endif %}
</code></pre>
<p>in my html template and the result is <code>form is false</code> which indicates that the <code>form</code> variable is not passed through context or something I can`t explain happened. Any thoughts on this would be appreciated. Thanks again.</p>
| 1 | 2016-08-01T11:06:20Z | 38,711,412 | <p>I finally found out what went wrong... And it`s something silly. I actually rendered the <code>user.html</code> in another function so anything I did in method <code>user</code> is not working. After instantiating a <code>form</code> instance in the <em>right</em> view method, the <code>TweetForm</code> is rendered successfully.</p>
| 0 | 2016-08-02T03:42:10Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
Windows path with spaces in python | 38,697,330 | <p>I have a problem with passing windows path to a function in python. Now, if I hard code the path everything actually works. So, my code is:</p>
<pre><code>from pymatbridge import Matlab
lab = Matlab(executable=r'"c:\Program Files \MATLAB\bin\matlab.exe"')
lab.start()
</code></pre>
<p>This works fine as I am using the raw string formatting to the hard-coded string. Now, the issue is that the string is passed as a variable. So, imagine I have a variable like:</p>
<pre><code>path="c:\Program Files \MATLAB\bin\matlab.exe"
</code></pre>
<p>Now, I am unable to figure out how to get the equivalent raw string from this. I tried may things like <code>shlex.quote(path)</code> and this makes issue with the <code>\b</code>. Without conversion to the raw string, the space in <code>Program Files</code> causes a problem, I think. </p>
| 0 | 2016-08-01T11:10:00Z | 38,697,937 | <pre><code>def testpath(path):
print path
testpath(path='c:\\Program Files \\MATLAB\\bin\\matlab.exe')
</code></pre>
<p>output is:</p>
<pre><code>c:\Program Files \MATLAB\bin\matlab.exe
</code></pre>
<p>If you are facing issues with space between <code>Program Files</code> use <code>Progra~1</code> instead</p>
| 0 | 2016-08-01T11:40:42Z | [
"python"
] |
Pandas - Explanation on apply function being slow | 38,697,404 | <p>Apply function seems to work very slow with a large dataframe (about 1~3 million rows).</p>
<p>I have checked related questions here, like <a href="http://stackoverflow.com/questions/31363908/speeding-up-pandas-apply-function">Speed up Pandas apply function</a>, and <a href="http://stackoverflow.com/questions/38267210/counting-within-pandas-apply-function">Counting within pandas apply() function</a>, it seems the best way to speed it up is not to use apply function :)</p>
<p>For my case, I have two kinds of tasks to do with the apply function.</p>
<p>First: apply with lookup dict query</p>
<pre><code>f(p_id, p_dict):
return p_dict[p_dict['ID'] == p_id]['value']
p_dict = DataFrame(...) # it's another dict works like lookup table
df = df.apply(f, args=(p_dict,))
</code></pre>
<p>Second: apply with groupby</p>
<pre><code>f(week_id, min_week_num, p_dict):
return p_dict[(week_id - min_week_num < p_dict['WEEK']) & (p_dict['WEEK'] < week_id)].ix[:,2].mean()
f_partial = partial(f, min_week_num=min_week_num, p_dict=p_dict)
df = map(f, df['WEEK'])
</code></pre>
<p>I guess for the fist case, it could be done with dataframe join, while I am not sure about resource cost for such join on a large dataset.</p>
<p>My question is: </p>
<ol>
<li>Is there any way to substitute apply in the two above cases?</li>
<li>Why is apply so slow? For the dict lookup case, I think it should be O(N), it shouldn't cost that much even if N is 1 million.</li>
</ol>
| 3 | 2016-08-01T11:13:34Z | 38,708,239 | <p>Concerning your first question, I can't say exactly why this instance is slow. But generally, <code>apply</code> does not take advantage of vectorization. Also, <code>apply</code> returns a new Series or DataFrame object, so with a very large DataFrame, you have considerable IO overhead (I cannot guarantee this is the case 100% of the time since Pandas has loads of internal implementation optimization).</p>
<p>For your first method, I assume you are trying to fill a 'value' column in <code>df</code> using the <code>p_dict</code> as a lookup table. It is about 1000x faster to use <code>pd.merge</code>:</p>
<pre><code>import string, sys
import numpy as np
import pandas as pd
##
# Part 1 - filling a column by a lookup table
##
def f1(col, p_dict):
return [p_dict[p_dict['ID'] == s]['value'].values[0] for s in col]
# Testing
n_size = 1000
np.random.seed(997)
p_dict = pd.DataFrame({'ID': [s for s in string.ascii_uppercase], 'value': np.random.randint(0,n_size, 26)})
df = pd.DataFrame({'p_id': [string.ascii_uppercase[i] for i in np.random.randint(0,26, n_size)]})
# Apply the f1 method as posted
%timeit -n1 -r5 temp = df.apply(f1, args=(p_dict,))
>>> 1 loops, best of 5: 832 ms per loop
# Using merge
np.random.seed(997)
df = pd.DataFrame({'p_id': [string.ascii_uppercase[i] for i in np.random.randint(0,26, n_size)]})
%timeit -n1 -r5 temp = pd.merge(df, p_dict, how='inner', left_on='p_id', right_on='ID', copy=False)
>>> 1000 loops, best of 5: 826 µs per loop
</code></pre>
<p>Concerning the second task, we can quickly add a new column to <code>p_dict</code> that calculates a mean where the time window starts at <code>min_week_num</code> and ends at the week for that row in <code>p_dict</code>. This requires that <code>p_dict</code> is sorted by ascending order along the <code>WEEK</code> column. Then you can use <code>pd.merge</code> again.</p>
<p>I am assuming that <code>min_week_num</code> is 0 in the following example. But you could easily modify <code>rolling_growing_mean</code> to take a different value. The <code>rolling_growing_mean</code> method will run in O(n) since it conducts a fixed number of operations per iteration.</p>
<pre><code>n_size = 1000
np.random.seed(997)
p_dict = pd.DataFrame({'WEEK': range(52), 'value': np.random.randint(0, 1000, 52)})
df = pd.DataFrame({'WEEK': np.random.randint(0, 52, n_size)})
def rolling_growing_mean(values):
out = np.empty(len(values))
out[0] = values[0]
# Time window for taking mean grows each step
for i, v in enumerate(values[1:]):
out[i+1] = np.true_divide(out[i]*(i+1) + v, i+2)
return out
p_dict['Means'] = rolling_growing_mean(p_dict['value'])
df_merged = pd.merge(df, p_dict, how='inner', left_on='WEEK', right_on='WEEK')
</code></pre>
| 0 | 2016-08-01T21:15:01Z | [
"python",
"pandas"
] |
How to return generated file download with Django REST Framework? | 38,697,529 | <p>I need to return generated file download as a Django REST Framework response. I tried the following:</p>
<pre><code>def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
res = HttpResponse(
FileWrapper(doc),
content_type='application/msword'
)
res['Content-Disposition'] = u'attachment; filename="%s_%s.zip"' % (context[u'surname'], context[u'name'])
return res
</code></pre>
<p>But it returns a msword document as <code>json</code>.</p>
<p>How do I make it start downloading as file instead?</p>
| 3 | 2016-08-01T11:19:55Z | 38,697,955 | <p>This may work for you:</p>
<pre><code>file_path = file_url
FilePointer = open(file_path,"r")
response = HttpResponse(FilePointer,content_type='application/msword')
response['Content-Disposition'] = 'attachment; filename=NameOfFile'
return response.
</code></pre>
<p>For FrontEnd code refer <a href="http://stackoverflow.com/questions/36792681/angularjs-receive-and-download-csv/36793906#36793906">this</a> </p>
| 1 | 2016-08-01T11:41:44Z | [
"python",
"django",
"ms-word",
"django-rest-framework",
"downloading"
] |
How to return generated file download with Django REST Framework? | 38,697,529 | <p>I need to return generated file download as a Django REST Framework response. I tried the following:</p>
<pre><code>def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
res = HttpResponse(
FileWrapper(doc),
content_type='application/msword'
)
res['Content-Disposition'] = u'attachment; filename="%s_%s.zip"' % (context[u'surname'], context[u'name'])
return res
</code></pre>
<p>But it returns a msword document as <code>json</code>.</p>
<p>How do I make it start downloading as file instead?</p>
| 3 | 2016-08-01T11:19:55Z | 38,703,639 | <p>I solved my problem by saving file in media folder and sending of the link of it to front-end.</p>
<pre><code>@permission_classes((permissions.IsAdminUser,))
class StudentDocxViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
p = u'docs/cards/%s/%s_%s.doc' % (datetime.now().date(), context[u'surname'], context[u'name'])
path = default_storage.save(p, doc)
return response.Response(u'/media/' + path)
</code></pre>
<p>And handled this like in my front-end (AngularJS SPA)</p>
<pre><code>$http(req).success(function (url) {
console.log(url);
window.location = url;
})
</code></pre>
| 1 | 2016-08-01T16:22:07Z | [
"python",
"django",
"ms-word",
"django-rest-framework",
"downloading"
] |
Pad numpy array with fixed array as constant | 38,697,641 | <p>I have the following code :</p>
<pre><code>x = np.array([[1]])
print x
print np.lib.pad(x,(1,1),mode='constant',constant_values=[4,8])
</code></pre>
<p>output : </p>
<pre><code>[[1]]
[[4 4 8]
[4 1 8]
[4 8 8]]
</code></pre>
<p>the problem is :
in the constant values I want to put the new padding for example : </p>
<pre><code>print np.lib.pad(x,(1,1),mode='constant',constant_values = [1,2,3,4,5,6,7,8])
</code></pre>
<p>and output like :</p>
<pre><code>[[1,2,3]
[8,1,4]
[7,6,5]]
</code></pre>
| 3 | 2016-08-01T11:25:52Z | 38,700,370 | <p>This is a reverse engineering of <a href="http://stackoverflow.com/questions/726756/print-two-dimensional-array-in-spiral-order">Print two-dimensional array in spiral order</a>:</p>
<pre><code>inner_array = np.array([3, 6, 7, 2])
outer_array = np.array([0, 23, 3, 5, 6, 8, 99, 73, 18, 42, 67, 88, 91, 12])
total_array = inner_array[::-1][np.newaxis]
i = 0
while True:
s = total_array.shape[1]
try:
total_array = np.vstack([total_array, outer_array[i:i+s]])
except ValueError:
break
try:
total_array = np.rot90(total_array, -1)
except ValueError:
pass
i += s
total_array = np.rot90(total_array, -1)
print(total_array)
</code></pre>
| 1 | 2016-08-01T13:38:34Z | [
"python",
"arrays",
"numpy"
] |
Pad numpy array with fixed array as constant | 38,697,641 | <p>I have the following code :</p>
<pre><code>x = np.array([[1]])
print x
print np.lib.pad(x,(1,1),mode='constant',constant_values=[4,8])
</code></pre>
<p>output : </p>
<pre><code>[[1]]
[[4 4 8]
[4 1 8]
[4 8 8]]
</code></pre>
<p>the problem is :
in the constant values I want to put the new padding for example : </p>
<pre><code>print np.lib.pad(x,(1,1),mode='constant',constant_values = [1,2,3,4,5,6,7,8])
</code></pre>
<p>and output like :</p>
<pre><code>[[1,2,3]
[8,1,4]
[7,6,5]]
</code></pre>
| 3 | 2016-08-01T11:25:52Z | 38,703,653 | <p>The answer is way different since it's pretty customized to my problem ( Field Of View).</p>
<pre><code>def updatevalues(self,array,elementsCount):
counter =0
R1 =Agent.GetCenterCoords(array.shape)[0]
C1 = array.shape[1]-1
coords = {'R1':R1,'R2':R1,'C1':C1,'C2':C1,'Phase':1}
array[coords['R1'],coords['C1']] = True
while counter<elementsCount:
counter +=2
self.Phases[coords['Phase']](array,coords)
def Phase1(self,array,coords):
'''
Phase 1.
During this phase we start from the max column(C1,C2) and middle Row (R1,R2)
and start moving up and down till
minimum row (R1 ) , max Row (R2) then we move to phase 2
'''
coords['R1'] -=1
coords['R2'] +=1
array[coords['R1'],coords['C1']] = True
array[coords['R2'],coords['C2']] = True
if coords['R1']==0 or coords['R2'] == array.shape[0]-1:
coords['Phase']=2
def Phase2(self,array,coords):
'''
Phase 2.
During this phase we start from the max column (C1,C2) and Min,Max Rows (R1,R2)
and start changing (C1,C2 to minimum) till
C1,C2 ==0 then we move to phase 3
'''
coords['C1'] -=1
coords['C2'] -=1
array[coords['R1'],coords['C1']] = True
array[coords['R2'],coords['C2']] = True
if coords['C1']==0 or coords['C2'] ==0:
coords['Phase']=3
def Phase3(self,array,coords):
'''
Phase 3.
During this phase we start from the minimum columns (C1,C2) and Min,Max Rows (R1,R2)
and start changing (R1,R2) toward center till R1==R2 then we break (all border got covered)
'''
coords['R1'] +=1
coords['R2'] -=1
array[coords['R1'],coords['C1']] = True
array[coords['R2'],coords['C2']] = True
if coords['R1']==coords['R2']:
coords['Phase']=4
@staticmethod
def GetCenterCoords(shape):
return (shape[0]-1)/2 , (shape[1]-1)/2
</code></pre>
<p>the solution depends on how many values we want to change on the border starting from the max row, middle column to the right then start moving in two directions simultaneously.
Sorry for the complex solution but as I told you @Ophir it's pretty customized solution for my problem. (when I put the question I used a very general forum to simplify it.)
hope this help others one day.</p>
| 0 | 2016-08-01T16:23:09Z | [
"python",
"arrays",
"numpy"
] |
Issue loading objects from model in Django | 38,697,722 | <p>I am currently writing a web application in Django for an interview.</p>
<p>On the home page I am looking to have 3 lists of various data.</p>
<p>This is the error I receive when loading the home page: </p>
<pre><code>invalid literal for int() with base 10: 'Critical'
</code></pre>
<p>This is the models.py:</p>
<pre><code>from django.db import models
from django.utils import timezone
class Status(models.Model):
status_level=models.CharField(max_length=15)
def __str__(self):
return self.status_level
class Event(models.Model):
event_status=models.ForeignKey(Status)
event_title=models.CharField(max_length=50)
event_description=models.CharField(max_length=500)
event_flag=models.CharField(max_length=10)
date_active=models.DateField(default=timezone.now())
time_active=models.TimeField(default=timezone.now())
def __str__(self):
return self.event_title
</code></pre>
<p>There are 3 status objects currently, Critical, Medium and Low.</p>
<p>Views.py:</p>
<pre><code>def index(request):
# home page
critical_list=Event.objects.filter(event_status='Critical')
medium_list=Event.objects.filter(event_status='Medium')
low_list=Event.objects.filter(event_status='Low')
context_dict={'critical':critical_list, 'medium':medium_list,'low':low_list}
return render(request, 'server_status/index.html',context_dict)
</code></pre>
<p>There's a lot of stacktrace so I shall post the two relevant lines which I believe are causing the problem:</p>
<p>The error occurs at this line:</p>
<pre><code>critical_list=Event.objects.filter(event_status='Critical')
</code></pre>
<p>And then the last line on the stacktrace:</p>
<pre><code> return int(value) ...
â¼ Local vars
Variable Value
self
<django.db.models.fields.AutoField: id>
value
'Critical'
</code></pre>
| 1 | 2016-08-01T11:29:27Z | 38,697,765 | <p>Since you appear to be trying to filter on the status_level on the Status model</p>
<pre><code>critical_list=Event.objects.filter(event_status__status_level='Critical')
</code></pre>
| 4 | 2016-08-01T11:31:33Z | [
"python",
"django"
] |
Run sqoop in python script | 38,697,820 | <p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p>
<pre><code>#!/usr/bin/python
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" "
exec (sqoopcom)
</code></pre>
<p>I got an error, Invalid syntax, how to solve it ? </p>
| 0 | 2016-08-01T11:34:42Z | 38,698,044 | <p>You need to skip " on --query param</p>
<pre>
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000"
</pre>
| 2 | 2016-08-01T11:46:25Z | [
"python",
"sqoop"
] |
Run sqoop in python script | 38,697,820 | <p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p>
<pre><code>#!/usr/bin/python
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" "
exec (sqoopcom)
</code></pre>
<p>I got an error, Invalid syntax, how to solve it ? </p>
| 0 | 2016-08-01T11:34:42Z | 38,698,081 | <p>The build in <code>exec</code> statement that you're using is for interpreting python code inside a python program.</p>
<p>What you want is to execute an external (shell) command. For that you could use <code>call</code> from the <strong>subprocess module</strong></p>
<pre><code>import subprocess
subprocess.call(["echo", "Hello", "World"])
</code></pre>
<p><a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">https://docs.python.org/3/library/subprocess.html</a></p>
| 1 | 2016-08-01T11:48:16Z | [
"python",
"sqoop"
] |
Run sqoop in python script | 38,697,820 | <p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p>
<pre><code>#!/usr/bin/python
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" "
exec (sqoopcom)
</code></pre>
<p>I got an error, Invalid syntax, how to solve it ? </p>
| 0 | 2016-08-01T11:34:42Z | 38,698,887 | <p>You can use:
Invalid syntax error noted that you haven't backslashed \"queryname\"</p>
<pre><code>#!/usr/bin/env python
import os
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" "
os.system(sqoopcom)
</code></pre>
| 0 | 2016-08-01T12:27:09Z | [
"python",
"sqoop"
] |
Do we have some inbuild function in python 2.7.9 which gets input both in integer & string using same function | 38,697,843 | <p>I am using python 2.7.9 and also i am new to stack overflow.</p>
<p><code>input()</code> is used for getting integer as input from user.<br>
<code>raw_input()</code> is used for getting string as input from user.</p>
<p>I am looking for some common function in python 2.7.9 which will allow user to input either integer or string based up on user wish</p>
<p>I am using below code:</p>
<pre><code>A=input("Enter a String")
Error:
Traceback (most recent call last):
File "C:/Users/eubcefm/Desktop/Important/Python/2407/Test.py", line 1, in <module>
A=input("Enter a String")
File "<string>", line 1, in <module>
NameError: name 'And' is not defined
</code></pre>
| 0 | 2016-08-01T11:36:32Z | 38,698,191 | <p>You can use raw_input() and try to convert it to an int.</p>
<pre><code>rawinput=raw_input("Enter a String :")
try:
value=int(rawinput)
except ValueError:
value=rawinput
print "Type is ", type(value)
print "Value is ", value
</code></pre>
| 0 | 2016-08-01T11:53:05Z | [
"python",
"input"
] |
Python scikit learn multi-class multi-label performance metrics? | 38,697,982 | <p>I ran Random Forest classifier for my multi-class multi-label output variable. I got below output.</p>
<pre><code>My y_test values
Degree Nature
762721 1 7
548912 0 6
727126 1 12
14880 1 12
189505 1 12
657486 1 12
461004 1 0
31548 0 6
296674 1 7
121330 0 17
predicted output :
[[ 1. 7.]
[ 0. 6.]
[ 1. 12.]
[ 1. 12.]
[ 1. 12.]
[ 1. 12.]
[ 1. 0.]
[ 0. 6.]
[ 1. 7.]
[ 0. 17.]]
</code></pre>
<p>Now I want to check the performance of my classifier. I found that for multiclass multilabel "Hamming loss or jaccard_similarity_score" is the good metrics. I tried to calculate it but I was getting value error.</p>
<pre><code>Error:
ValueError: multiclass-multioutput is not supported
</code></pre>
<p>Below line I tried:</p>
<pre><code>print hamming_loss(y_test, RF_predicted)
print jaccard_similarity_score(y_test, RF_predicted)
</code></pre>
<p>Thanks,</p>
| 2 | 2016-08-01T11:42:51Z | 38,699,687 | <p>To calculate the unsupported hamming loss for multiclass / multilabel, you could: </p>
<pre><code>import numpy as np
y_true = np.array([[1, 1], [2, 3]])
y_pred = np.array([[0, 1], [1, 2]])
np.sum(np.not_equal(y_true, y_pred))/float(y_true.size)
0.75
</code></pre>
<p>You can also get the <code>confusion_matrix</code> for each of the two labels like so:</p>
<pre><code>from sklearn.metrics import confusion_matrix, precision_score
np.random.seed(42)
y_true = np.vstack((np.random.randint(0, 2, 10), np.random.randint(2, 5, 10))).T
[[0 4]
[1 4]
[0 4]
[0 4]
[0 2]
[1 4]
[0 3]
[0 2]
[0 3]
[1 3]]
y_pred = np.vstack((np.random.randint(0, 2, 10), np.random.randint(2, 5, 10))).T
[[1 2]
[1 2]
[1 4]
[1 4]
[0 4]
[0 3]
[1 4]
[1 3]
[1 3]
[0 4]]
confusion_matrix(y_true[:, 0], y_pred[:, 0])
[[1 6]
[2 1]]
confusion_matrix(y_true[:, 1], y_pred[:, 1])
[[0 1 1]
[0 1 2]
[2 1 2]]
</code></pre>
<p>You could also calculate the <code>precision_score</code> like so (or the <code>recall_score</code> in a similiar way):</p>
<pre><code>precision_score(y_true[:, 0], y_pred[:, 0])
0.142857142857
</code></pre>
| 2 | 2016-08-01T13:04:09Z | [
"python",
"machine-learning",
"scikit-learn",
"precision",
"multilabel-classification"
] |
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python? | 38,698,000 | <pre><code>In [301]: string_to_write
Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
In [302]: len(string_to_write)
Out[302]: 72
In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"
In [304]: print thestring
S8CC3FF000000121
In [305]: len(thestring)
Out[305]: 18
</code></pre>
<p>I need to use serial port to communicate with a device and I need to write a string to the port. I entered <strong>thestring</strong> through keyboard while I used loop to write each of the hexadecimal characters to <strong>string_to_write</strong>. I need to convert this <strong>string_to_write</strong> into <strong>thestring</strong>. How do I make Python identify groups of four characters each as a hexadecimal.</p>
| 1 | 2016-08-01T11:44:11Z | 38,698,330 | <p>Just use the built-in encode lib for example:</p>
<pre><code>>>> "hello".encode("hex")
'68656c6c6f'
>>> "68656c6c6f".decode("hex")
'hello'
>>>
</code></pre>
| 0 | 2016-08-01T11:59:47Z | [
"python",
"python-2.7",
"serial-port",
"ascii"
] |
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python? | 38,698,000 | <pre><code>In [301]: string_to_write
Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
In [302]: len(string_to_write)
Out[302]: 72
In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"
In [304]: print thestring
S8CC3FF000000121
In [305]: len(thestring)
Out[305]: 18
</code></pre>
<p>I need to use serial port to communicate with a device and I need to write a string to the port. I entered <strong>thestring</strong> through keyboard while I used loop to write each of the hexadecimal characters to <strong>string_to_write</strong>. I need to convert this <strong>string_to_write</strong> into <strong>thestring</strong>. How do I make Python identify groups of four characters each as a hexadecimal.</p>
| 1 | 2016-08-01T11:44:11Z | 38,698,441 | <p>You need to chop <code>string_to_write</code> into strings of length 4, convert those strings to integer, then convert each of those integers to characters. Here's an efficient way to do that in Python 2 (a different approach is needed in Python 3). Note that this code assumes that all of your hex codes contain exactly 4 chars, with the leading <code>0x</code>. This script also uses <code>binascii.hexlify</code> to print the output data in a convenient format.</p>
<pre><code>from binascii import hexlify
def hex_to_bin(s):
return ''.join([chr(int(''.join(u), 16)) for u in zip(*[iter(s)] * 4)])
s2w = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
thestring = "\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"
out = hex_to_bin(s2w)
print repr(thestring)
print repr(out)
print hexlify(out)
print thestring == out
</code></pre>
<p><strong>output</strong></p>
<pre><code>'\x01S8CC3FF000000121\r'
'\x01S8CC3FF000000121\r'
01533843433346463030303030303132310d
True
</code></pre>
| 0 | 2016-08-01T12:06:15Z | [
"python",
"python-2.7",
"serial-port",
"ascii"
] |
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python? | 38,698,000 | <pre><code>In [301]: string_to_write
Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
In [302]: len(string_to_write)
Out[302]: 72
In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"
In [304]: print thestring
S8CC3FF000000121
In [305]: len(thestring)
Out[305]: 18
</code></pre>
<p>I need to use serial port to communicate with a device and I need to write a string to the port. I entered <strong>thestring</strong> through keyboard while I used loop to write each of the hexadecimal characters to <strong>string_to_write</strong>. I need to convert this <strong>string_to_write</strong> into <strong>thestring</strong>. How do I make Python identify groups of four characters each as a hexadecimal.</p>
| 1 | 2016-08-01T11:44:11Z | 38,699,052 | <p>may be you can use this as an example:</p>
<pre><code>string_to_write = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
temp = [i for i in string_to_write.split('0x') if i]
print map(lambda x: int('0x'+x, 16), temp)
</code></pre>
<p>op:</p>
<pre><code>[1, 83, 56, 67, 67, 51, 70, 70, 48, 48, 48, 48, 48, 48, 49, 50, 49, 13]
</code></pre>
| 0 | 2016-08-01T12:34:24Z | [
"python",
"python-2.7",
"serial-port",
"ascii"
] |
How to use variable in different classes in Python? | 38,698,025 | <p>Here is my code:</p>
<pre><code>class ProjectApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.filepaths = []
class StartPage(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.controller = controller
self.parent = parent
def get_file(self):
filepath = askopenfilename()
if filepath:
print(ProjectApp.filepaths)
self.parent.filepaths.append(filepath)
</code></pre>
<p>I am trying to use filepath in another class but I got the error below.</p>
<pre><code>AttributeError: type object 'ProjectApp' has no attribute 'filepaths'
</code></pre>
<p>Can you tell me where is the mistake?</p>
| 1 | 2016-08-01T11:45:11Z | 38,698,111 | <p>You need to create an instance of the ProjectApp</p>
<pre><code>myProjectApp = ProjectApp()
</code></pre>
<p>Then you will be able to call the attribute <code>filepaths</code></p>
<pre><code>print(myProjectApp.filepaths)
</code></pre>
| 2 | 2016-08-01T11:49:21Z | [
"python",
"class"
] |
How to use variable in different classes in Python? | 38,698,025 | <p>Here is my code:</p>
<pre><code>class ProjectApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.filepaths = []
class StartPage(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.controller = controller
self.parent = parent
def get_file(self):
filepath = askopenfilename()
if filepath:
print(ProjectApp.filepaths)
self.parent.filepaths.append(filepath)
</code></pre>
<p>I am trying to use filepath in another class but I got the error below.</p>
<pre><code>AttributeError: type object 'ProjectApp' has no attribute 'filepaths'
</code></pre>
<p>Can you tell me where is the mistake?</p>
| 1 | 2016-08-01T11:45:11Z | 38,698,167 | <p>filepaths is an instance attribute. I.e. filepath only exists after ProjectApp has been instantiated via the constructor call (= <strong>init</strong> ).</p>
<p>When instantiating StartPage, you should do it like that:</p>
<pre><code>app = ProjectApp() # her you create the ProjectApp instance with filepaths
start_page = StartPage(app, ....)
</code></pre>
<p>and remove print(ProjectApp.filepaths), since this will throw an error.</p>
| 1 | 2016-08-01T11:51:42Z | [
"python",
"class"
] |
How to use variable in different classes in Python? | 38,698,025 | <p>Here is my code:</p>
<pre><code>class ProjectApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.filepaths = []
class StartPage(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.controller = controller
self.parent = parent
def get_file(self):
filepath = askopenfilename()
if filepath:
print(ProjectApp.filepaths)
self.parent.filepaths.append(filepath)
</code></pre>
<p>I am trying to use filepath in another class but I got the error below.</p>
<pre><code>AttributeError: type object 'ProjectApp' has no attribute 'filepaths'
</code></pre>
<p>Can you tell me where is the mistake?</p>
| 1 | 2016-08-01T11:45:11Z | 38,699,447 | <p>This will depend of what you want. There is two kind of attribute for object:
The class attribute and the instance attribute.</p>
<h3>Class attribute</h3>
<p>The class attribute is the same object for each instance of the class.</p>
<pre><code>class MyClass:
class_attribute = []
</code></pre>
<p>Here <code>MyClass.class_attribute</code> is already define for the class and you can use it. If you create instances of <code>MyClass</code>, each instance would have access to the same <code>class_attribute</code>.</p>
<h3>Instance Attribute</h3>
<p>The instance attribute is only usable when the instance is created, and is unique for each instance of the class. You can use them only on an instance. There are defined in the method <code>__init__</code>.</p>
<pre><code>class MyClass:
def __init__(self)
self.instance-attribute = []
</code></pre>
<p>In your case <code>filepaths</code> is define as an instance attribute.
you can change your class for this, your <code>print(ProjectApp.filepaths)</code> will work.</p>
<pre><code>class ProjectApp(tk.Tk):
filepaths = []
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
</code></pre>
<p>If you need more explaination, i advice you to read <a href="https://docs.python.org/3.2/tutorial/classes.html#class-objects" rel="nofollow">this</a> part of the python documentation</p>
| 2 | 2016-08-01T12:53:10Z | [
"python",
"class"
] |
Creating custom source for reading from cloud datastore using latest python apache_beam cloud datafow sdk | 38,698,233 | <p>Recently cloud dataflow python sdk was made available and I decided to use it. Unfortunately the support to read from cloud datastore is yet to come so I have to fall back on writing custom source so that I can utilize the benefits of dynamic splitting, progress estimation etc as promised. I did study the documentation thoroughly but am unable to put the pieces together so that I can speed up my entire process.</p>
<p>To be more clear my first approach was:</p>
<ol>
<li>querying the cloud datastore</li>
<li>creating ParDo function and passing the returned query to it.</li>
</ol>
<p>But with this it took 13 minutes to iterate over 200k entries.</p>
<p>So I decided to write custom source that would read the entities efficiently. But am unable to achieve that due to my lack of understanding of putting the pieces together. Can any one please help me with how to create custom source for reading from datastore.</p>
<p>Edited:
For first approach the link to my gist is:
<a href="https://gist.github.com/shriyanka/cbf30bbfbf277deed4bac0c526cf01f1" rel="nofollow">https://gist.github.com/shriyanka/cbf30bbfbf277deed4bac0c526cf01f1</a></p>
<p>Thank you.</p>
| 0 | 2016-08-01T11:54:52Z | 38,705,127 | <p>In the code you provided, the access to Datastore happens before the pipeline is even constructed:</p>
<pre><code>query = client.query(kind='User').fetch()
</code></pre>
<p>This executes the whole query and reads all entities before the Beam SDK gets involved at all.</p>
<p>More precisely, <code>fetch()</code> returns a lazy iterable over the query results, and they <em>get iterated over</em> when you construct the pipeline, at <code>beam.Create(query)</code> - but, once again, this happens in your main program, before the pipeline starts. Most likely, this is what's taking 13 minutes, rather than the pipeline itself (but please feel free to provide a job ID so we can take a deeper look). You can verify this by making a small change to your code:</p>
<pre><code>query = list(client.query(kind='User').fetch())
</code></pre>
<p>However, I think your intention was to both <em>read</em> and <em>process</em> the entities in parallel.</p>
<p>For Cloud Datastore in particular, the custom source API is not the best choice to do that. The reason is that the underlying Cloud Datastore API itself does not currently provide the properties necessary to implement the custom source "goodies" such as progress estimation and dynamic splitting, because its querying API is very generic (unlike, say, Cloud Bigtable, which always returns results ordered by key, so e.g. you can estimate progress by looking at the current key).</p>
<p>We are currently rewriting the Java Cloud Datastore connector to use a different approach, which uses a <code>ParDo</code> to split the query and a <code>ParDo</code> to read each of the sub-queries. Please see <a href="https://github.com/apache/incubator-beam/pull/739/files" rel="nofollow">this pull request</a> for details.</p>
| 0 | 2016-08-01T17:50:20Z | [
"python",
"google-cloud-dataflow",
"apache-beam"
] |
Plot normal distribution in 3D | 38,698,277 | <p>I am trying to plot the comun distribution of two normal distributed variables. </p>
<p>The code below plots one normal distributed variable. What would the code be for plotting two normal distributed variables?</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import math
mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(-3, 3, 100)
plt.plot(x,mlab.normpdf(x, mu, sigma))
plt.show()
</code></pre>
| 1 | 2016-08-01T11:57:12Z | 38,705,297 | <p>It sounds like what you're looking for is a <a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="nofollow">Multivariate Normal Distribution</a>. This is implemented in scipy as <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html" rel="nofollow">scipy.stats.multivariate_normal</a>. It's important to remember that you are passing a covariance matrix to the function. So to keep things simple keep the off diagonal elements as zero:</p>
<pre><code>[X variance , 0 ]
[ 0 ,Y Variance]
</code></pre>
<p>Here is an example using this function and generating a 3D plot of the resulting distribution. I add the colormap to make seeing the curves easier but feel free to remove it.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D
#Parameters to set
mu_x = 0
variance_x = 3
mu_y = 0
variance_y = 15
#Create grid and multivariate normal
x = np.linspace(-10,10,500)
y = np.linspace(-10,10,500)
X, Y = np.meshgrid(x,y)
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X; pos[:, :, 1] = Y
rv = multivariate_normal([mu_x, mu_y], [[variance_x, 0], [0, variance_y]])
#Make a 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
</code></pre>
<p>Giving you this plot:
<a href="http://i.stack.imgur.com/NXF9g.png" rel="nofollow"><img src="http://i.stack.imgur.com/NXF9g.png" alt="enter image description here"></a></p>
<h1>Edit</h1>
<p>A simpler verision is avalible through <a href="http://matplotlib.org/api/mlab_api.html#matplotlib.mlab.bivariate_normal" rel="nofollow">matplotlib.mlab.bivariate_normal</a>
It takes the following arguments so you don't need to worry about matrices
<code>matplotlib.mlab.bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0)</code>
Here X, and Y are again the result of a meshgrid so using this to recreate the above plot:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import biivariate_normal
from mpl_toolkits.mplot3d import Axes3D
#Parameters to set
mu_x = 0
sigma_x = np.sqrt(3)
mu_y = 0
sigma_y = np.sqrt(15)
#Create grid and multivariate normal
x = np.linspace(-10,10,500)
y = np.linspace(-10,10,500)
X, Y = np.meshgrid(x,y)
Z = bivariate_normal(X,Y,sigma_x,sigma_y,mu_x,mu_y)
#Make a 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z,cmap='viridis',linewidth=0)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
</code></pre>
<p>Giving:
<a href="http://i.stack.imgur.com/AoyVX.png" rel="nofollow"><img src="http://i.stack.imgur.com/AoyVX.png" alt="enter image description here"></a></p>
| 1 | 2016-08-01T18:00:35Z | [
"python",
"matplotlib",
"mplot3d"
] |
Python - Mac - renamed file is created at the same level with the folder that was containing it | 38,698,298 | <p>I am trying to rename a file in a specific path, but it moves the file at the same level with the folder that was containing it before being renamed.</p>
<pre><code>import os
path_to_file = "/Users/Me/file.txt" #NOTE that in my code, file name will be randomly generated
path_before_file, file_name = os.path.split(path_to_file) # I need file_name from here, which is the file name without the rest of the path: "file.txt"
renamed_file = os.path.splitext(file_name)[0] + '_renamed' + os.path.splitext(file_name)[1] #This is how renamed file I want to look "file_renamed.txt"
renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt"
os.rename(path_to_file, renamed_file_path)
</code></pre>
<p>After renaming, "/Users/Me/file.txt" becomes "/Users/file.txt"</p>
| 0 | 2016-08-01T11:58:27Z | 38,698,603 | <pre><code>renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt"
</code></pre>
<p>Above line has a bug. Above line should be as below</p>
<pre><code>renamed_file_path = os.path.join(path_before_file, renamed_file) #"/Users/Me/file_renamed.txt"
</code></pre>
| 0 | 2016-08-01T12:14:23Z | [
"python"
] |
Python - Mac - renamed file is created at the same level with the folder that was containing it | 38,698,298 | <p>I am trying to rename a file in a specific path, but it moves the file at the same level with the folder that was containing it before being renamed.</p>
<pre><code>import os
path_to_file = "/Users/Me/file.txt" #NOTE that in my code, file name will be randomly generated
path_before_file, file_name = os.path.split(path_to_file) # I need file_name from here, which is the file name without the rest of the path: "file.txt"
renamed_file = os.path.splitext(file_name)[0] + '_renamed' + os.path.splitext(file_name)[1] #This is how renamed file I want to look "file_renamed.txt"
renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt"
os.rename(path_to_file, renamed_file_path)
</code></pre>
<p>After renaming, "/Users/Me/file.txt" becomes "/Users/file.txt"</p>
| 0 | 2016-08-01T11:58:27Z | 38,701,145 | <p>I figured out what was the problem. path_before_file was something like "Users/Me"(without slash at the end). If I do:</p>
<pre><code>renamed_file_path = os.path.join(path_before_file + '/' + renamed_file)
</code></pre>
<p>or</p>
<pre><code>renamed_file_path = path_before_file + '/' + renamed_file
</code></pre>
<p>it works. But AFAIK, you wouldn't need this when working with os.path.join()</p>
<p>This is the code that works:</p>
<pre><code>import os
path_to_file = "/Users/Me/file.txt"
path_before_file, file_name = os.path.split(path_to_file)
renamed_file = os.path.splitext(file_name)[0] + '_renamed' + os.path.splitext(file_name)[1]
renamed_file_path = path_before_file + '/' + renamed_file
os.rename(path_to_file, renamed_file_path)
</code></pre>
| 0 | 2016-08-01T14:15:26Z | [
"python"
] |
Executable called via subprocess.check_output prints on console but result is not returned | 38,698,383 | <p>On a Windows machine, I'm trying to call an external executable from Python and gather its outputs for further processing. Because a local path variable has to be set before calling the executable, I created a batch script that </p>
<ul>
<li>first calls another script to set %PATH% and </li>
<li>then calls the executable with the parameters given to it.</li>
</ul>
<p>The *.bat file looks like this:</p>
<pre><code>@echo off
call set_path.bat
@echo on
executable.exe %*
</code></pre>
<p>And the Python code like this: </p>
<pre><code>print("before call");
result = subprocess.check_output([batfile, parameters], stderr=subprocess.STDOUT, shell=True);
print("after call");
print("------- ------- ------- printing result ------- ------- ------- ");
print(result);
print("------- ------- ------- /printing result ------- ------- ------- ");
</code></pre>
<p>Now, technically, this works. The executable is called with the intended parameters, runs, finishes and produces results. I know this, because they are mockingly displayed in the very console in which the Python script is running.</p>
<p>However, the result string only contains what the batch script returns, not the executables outputs:</p>
<blockquote>
<p>before call</p>
<p>hello? yes, this is executable.exe </p>
<p>after call</p>
<p>------- ------- ------- printing result ------- ------- -------</p>
<p>C:\Users\me\Documents\pythonscript\execute\executable.exe "para1|para2|para3"</p>
<p>------- ------- ------- /printing result ------- ------- -------</p>
</blockquote>
<p>The subprocess.check_output command itself somehow prints the intended output to the console, what it returns only contains the batch file's outputs after @echo is on again.</p>
<p><strong>How can I access and save the executable's output to a string for further work?</strong> </p>
<p>Or do I have to somehow modify the batch file to catch and print the output, so that it will end upt in check_output's results? If so, how could I go about doing that?</p>
| 2 | 2016-08-01T12:02:47Z | 38,749,458 | <p>If a program writes directly to the console (e.g. by opening the <code>CONOUT$</code> device) instead of to the process standard handles, the only option is to read the console screen buffer directly. To make this simpler, start with a new, empty screen buffer. Create, size, initialize, and activate a new screen buffer via the following functions:</p>
<ul>
<li><a href="https://msdn.microsoft.com/en-us/library/ms682122" rel="nofollow"><code>CreateConsoleScreenBuffer</code></a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms683172" rel="nofollow"><code>GetConsoleScreenBufferInfoEx</code></a> (Minimum supported client: Windows Vista)</li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms686039" rel="nofollow"><code>SetConsoleScreenBufferInfoEx</code></a> (Minimum supported client: Windows Vista)</li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms686125" rel="nofollow"><code>SetConsoleWindowInfo</code></a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms682663" rel="nofollow"><code>FillConsoleOutputCharacter</code></a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms686010" rel="nofollow"><code>SetConsoleActiveScreenBuffer</code></a></li>
</ul>
<p>Make sure to request <code>GENERIC_READ | GENERIC_WRITE</code> access when calling <code>CreateConsoleScreenBuffer</code>. You'll need read access later in order to read the contents of the screen. </p>
<p>Specifically for Python, use <a href="https://docs.python.org/3/library/ctypes.html" rel="nofollow">ctypes</a> to call functions in the Windows console API. Also, if you wrap the handle with a C file descriptor via <code>msvcrt.open_osfhandle</code>, then you can pass it as the <code>stdout</code> or <code>stderr</code> argument of <code>subprocess.Popen</code>. </p>
<p>The file descriptor or handle for the screen buffer can't be read directly via <code>read</code>, <code>ReadFile</code>, or even <code>ReadConsole</code>. If you have a file descriptor, get the underlying handle via <code>msvcrt.get_osfhandle</code>. Given a screen buffer handle, call <a href="https://msdn.microsoft.com/en-us/library/ms684969" rel="nofollow"><code>ReadConsoleOutputCharacter</code></a> to read from the screen. The <code>read_screen</code> function in the sample code below demonstrates reading from the beginning of the screen buffer up to the cursor position.</p>
<p>A process needs to be attached to a console in order to use the console API. To that end, I've included a simple <code>allocate_console</code> context manager to temporarily open a console. This is useful in a GUI application, which normally isn't attached to a console.</p>
<p>The following example was tested in Windows 7 and 10, in Python 2.7 and 3.5.</p>
<h2>ctypes definitions</h2>
<pre><code>import os
import contextlib
import msvcrt
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 1
FILE_SHARE_WRITE = 2
CONSOLE_TEXTMODE_BUFFER = 1
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11)
STD_ERROR_HANDLE = wintypes.DWORD(-12)
def _check_zero(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
def _check_invalid(result, func, args):
if result == INVALID_HANDLE_VALUE:
raise ctypes.WinError(ctypes.get_last_error())
return args
if not hasattr(wintypes, 'LPDWORD'): # Python 2
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
wintypes.PSMALL_RECT = ctypes.POINTER(wintypes.SMALL_RECT)
class COORD(ctypes.Structure):
_fields_ = (('X', wintypes.SHORT),
('Y', wintypes.SHORT))
class CONSOLE_SCREEN_BUFFER_INFOEX(ctypes.Structure):
_fields_ = (('cbSize', wintypes.ULONG),
('dwSize', COORD),
('dwCursorPosition', COORD),
('wAttributes', wintypes.WORD),
('srWindow', wintypes.SMALL_RECT),
('dwMaximumWindowSize', COORD),
('wPopupAttributes', wintypes.WORD),
('bFullscreenSupported', wintypes.BOOL),
('ColorTable', wintypes.DWORD * 16))
def __init__(self, *args, **kwds):
super(CONSOLE_SCREEN_BUFFER_INFOEX, self).__init__(
*args, **kwds)
self.cbSize = ctypes.sizeof(self)
PCONSOLE_SCREEN_BUFFER_INFOEX = ctypes.POINTER(
CONSOLE_SCREEN_BUFFER_INFOEX)
LPSECURITY_ATTRIBUTES = wintypes.LPVOID
kernel32.GetStdHandle.errcheck = _check_invalid
kernel32.GetStdHandle.restype = wintypes.HANDLE
kernel32.GetStdHandle.argtypes = (
wintypes.DWORD,) # _In_ nStdHandle
kernel32.CreateConsoleScreenBuffer.errcheck = _check_invalid
kernel32.CreateConsoleScreenBuffer.restype = wintypes.HANDLE
kernel32.CreateConsoleScreenBuffer.argtypes = (
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.DWORD, # _In_ dwShareMode
LPSECURITY_ATTRIBUTES, # _In_opt_ lpSecurityAttributes
wintypes.DWORD, # _In_ dwFlags
wintypes.LPVOID) # _Reserved_ lpScreenBufferData
kernel32.GetConsoleScreenBufferInfoEx.errcheck = _check_zero
kernel32.GetConsoleScreenBufferInfoEx.argtypes = (
wintypes.HANDLE, # _In_ hConsoleOutput
PCONSOLE_SCREEN_BUFFER_INFOEX) # _Out_ lpConsoleScreenBufferInfo
kernel32.SetConsoleScreenBufferInfoEx.errcheck = _check_zero
kernel32.SetConsoleScreenBufferInfoEx.argtypes = (
wintypes.HANDLE, # _In_ hConsoleOutput
PCONSOLE_SCREEN_BUFFER_INFOEX) # _In_ lpConsoleScreenBufferInfo
kernel32.SetConsoleWindowInfo.errcheck = _check_zero
kernel32.SetConsoleWindowInfo.argtypes = (
wintypes.HANDLE, # _In_ hConsoleOutput
wintypes.BOOL, # _In_ bAbsolute
wintypes.PSMALL_RECT) # _In_ lpConsoleWindow
kernel32.FillConsoleOutputCharacterW.errcheck = _check_zero
kernel32.FillConsoleOutputCharacterW.argtypes = (
wintypes.HANDLE, # _In_ hConsoleOutput
wintypes.WCHAR, # _In_ cCharacter
wintypes.DWORD, # _In_ nLength
COORD, # _In_ dwWriteCoord
wintypes.LPDWORD) # _Out_ lpNumberOfCharsWritten
kernel32.ReadConsoleOutputCharacterW.errcheck = _check_zero
kernel32.ReadConsoleOutputCharacterW.argtypes = (
wintypes.HANDLE, # _In_ hConsoleOutput
wintypes.LPWSTR, # _Out_ lpCharacter
wintypes.DWORD, # _In_ nLength
COORD, # _In_ dwReadCoord
wintypes.LPDWORD) # _Out_ lpNumberOfCharsRead
</code></pre>
<h2>functions</h2>
<pre><code>@contextlib.contextmanager
def allocate_console():
allocated = kernel32.AllocConsole()
try:
yield allocated
finally:
if allocated:
kernel32.FreeConsole()
@contextlib.contextmanager
def console_screen(ncols=None, nrows=None):
info = CONSOLE_SCREEN_BUFFER_INFOEX()
new_info = CONSOLE_SCREEN_BUFFER_INFOEX()
nwritten = (wintypes.DWORD * 1)()
hStdOut = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
kernel32.GetConsoleScreenBufferInfoEx(
hStdOut, ctypes.byref(info))
if ncols is None:
ncols = info.dwSize.X
if nrows is None:
nrows = info.dwSize.Y
elif nrows > 9999:
raise ValueError('nrows must be 9999 or less')
fd_screen = None
hScreen = kernel32.CreateConsoleScreenBuffer(
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
None, CONSOLE_TEXTMODE_BUFFER, None)
try:
fd_screen = msvcrt.open_osfhandle(
hScreen, os.O_RDWR | os.O_BINARY)
kernel32.GetConsoleScreenBufferInfoEx(
hScreen, ctypes.byref(new_info))
new_info.dwSize = COORD(ncols, nrows)
new_info.srWindow = wintypes.SMALL_RECT(
Left=0, Top=0, Right=(ncols - 1),
Bottom=(info.srWindow.Bottom - info.srWindow.Top))
kernel32.SetConsoleScreenBufferInfoEx(
hScreen, ctypes.byref(new_info))
kernel32.SetConsoleWindowInfo(hScreen, True,
ctypes.byref(new_info.srWindow))
kernel32.FillConsoleOutputCharacterW(
hScreen, u'\0', ncols * nrows, COORD(0,0), nwritten)
kernel32.SetConsoleActiveScreenBuffer(hScreen)
try:
yield fd_screen
finally:
kernel32.SetConsoleScreenBufferInfoEx(
hStdOut, ctypes.byref(info))
kernel32.SetConsoleWindowInfo(hStdOut, True,
ctypes.byref(info.srWindow))
kernel32.SetConsoleActiveScreenBuffer(hStdOut)
finally:
if fd_screen is not None:
os.close(fd_screen)
else:
kernel32.CloseHandle(hScreen)
def read_screen(fd):
hScreen = msvcrt.get_osfhandle(fd)
csbi = CONSOLE_SCREEN_BUFFER_INFOEX()
kernel32.GetConsoleScreenBufferInfoEx(
hScreen, ctypes.byref(csbi))
ncols = csbi.dwSize.X
pos = csbi.dwCursorPosition
length = ncols * pos.Y + pos.X + 1
buf = (ctypes.c_wchar * length)()
n = (wintypes.DWORD * 1)()
kernel32.ReadConsoleOutputCharacterW(
hScreen, buf, length, COORD(0,0), n)
lines = [buf[i:i+ncols].rstrip(u'\0')
for i in range(0, n[0], ncols)]
return u'\n'.join(lines)
</code></pre>
<h2>example</h2>
<pre><code>if __name__ == '__main__':
import io
import textwrap
import subprocess
text = textwrap.dedent('''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.''')
cmd = ("python -c \""
"print('piped output');"
"conout = open(r'CONOUT$', 'w');"
"conout.write('''%s''')\"" % text)
with allocate_console() as allocated:
with console_screen(nrows=1000) as fd_conout:
stdout = subprocess.check_output(cmd).decode()
conout = read_screen(fd_conout)
with io.open('result.txt', 'w', encoding='utf-8') as f:
f.write(u'stdout:\n' + stdout)
f.write(u'\nconout:\n' + conout)
</code></pre>
<h2>output</h2>
<pre class="lang-none prettyprint-override"><code>stdout:
piped output
conout:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</code></pre>
| 1 | 2016-08-03T16:50:41Z | [
"python",
"windows",
"batch-file",
"subprocess"
] |
Create a 'standard property' for class attributes in Python | 38,698,535 | <p>I have a class, that is used to translate binary stream to human readable. I want to translate it both ways, because I send and receive binary messages. Attributes of this class are made mostly the same way - take the bytes from startbyte to stopbyte and decode them - so I made a decision to use a property to do that. But can I make a general "property" that will be used when defining my class attributes?</p>
<pre><code>class Packet(object):
def __init__(self, data):
self.data = data
def standard_getter(startbyte, stopbyte):
def getter(self):
return decode(self.data[startbyte:stopbyte])
return getter
def standard_setter(startbyte, stopbyte):
def setter(self, value):
self.data[startbyte:stopbyte] = encode(value)
return setter
# the way I define properties by now:
protocol_type = property(standard_getter(16, 18), standard_setter(16, 18))
protocol_sub_type = property(standard_getter(18, 20), standard_setter(18, 20))
# the way I would like to do it:
protocol_type = property(standard_property(16, 18))
# or
protocol_type = standard_property(16, 18)
</code></pre>
<p>I tried to define a function, that takes two arguments and returns property(getter, setter), but always I'm stuck in giving "self" instance to the function. Is there a nice way I can make it?</p>
| 1 | 2016-08-01T12:10:34Z | 38,698,612 | <p>Have your function produce both the getter and setter, and return the <code>property</code> object for those two functions:</p>
<pre><code>def standard_property(startbyte, stopbyte):
def getter(self):
return decode(self.data[startbyte:stopbyte])
def setter(self, value):
self.data[startbyte:stopbyte] = encode(value)
return property(getter, setter)
</code></pre>
<p>Then use the return value directly:</p>
<pre><code>protocol_type = standard_property(16, 18)
protocol_sub_type = standard_property(18, 20)
</code></pre>
<p>Note that the <code>standard_property()</code> function doesn't even need to live in your class; it could be a top-level function too:</p>
<pre><code>>>> def standard_property(startbyte, stopbyte):
... def getter(self):
... return decode(self.data[startbyte:stopbyte])
... def setter(self, value):
... self.data[startbyte:stopbyte] = encode(value)
... return property(getter, setter)
...
>>> encode = lambda v: list(v)
>>> decode = lambda v: ''.join(v)
>>> class Packet(object):
... def __init__(self, data):
... self.data = data
... protocol_type = standard_property(16, 18)
... protocol_sub_type = standard_property(18, 20)
...
>>> p = Packet(list('foo bar baz spam ham eggs'))
>>> p.protocol_type
' h'
>>> p.protocol_sub_type
'am'
>>> p.protocol_type = '_c'
>>> p.protocol_sub_type = 'an'
>>> ''.join(p.data)
'foo bar baz spam_can eggs'
</code></pre>
| 3 | 2016-08-01T12:14:51Z | [
"python",
"properties"
] |
module' object has no attribute 'SelectDateWidget' | 38,698,591 | <p>I'm trying to create a custom form/view in Calendarium and i keep getting an error </p>
<pre><code>AttributeError: 'module' object has no attribute 'SelectDateWidget'
</code></pre>
<p>CreateEvent within my forms.py</p>
<pre><code>class CreateEvent(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'start', 'end', 'description', 'category', 'created_by', 'rule', 'end_recurring_period']
widgets = {
'start': forms.SelectDateWidget()
}
</code></pre>
<p>EventCreateView within views.py</p>
<pre><code>class EventCreateView(EventMixin, CreateView):
form_class = CreateEvent
model = Event
</code></pre>
<p>Does anyone know why i'm getting this error</p>
<p>Extra(If Allowed): </p>
<p>Within the EventCreateView its being passed "EventMixin" which looks like this</p>
<pre><code>class EventMixin(object):
"""Mixin to handle event-related functions."""
model = Event
fields = '__all__'
@method_decorator(permission_required('calendarium.add_event'))
def dispatch(self, request, *args, **kwargs):
return super(EventMixin, self).dispatch(request, *args, **kwargs)
</code></pre>
<p>Can someone explain this to me?</p>
| 2 | 2016-08-01T12:13:50Z | 38,698,786 | <p>You are missing <code>widgets</code>:</p>
<pre><code>class CreateEvent(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'start', 'end', 'description', 'category', 'created_by', 'rule', 'end_recurring_period']
widgets = {
'start': forms.widgets.SelectDateWidget()
}
# ^^
</code></pre>
<p>On another note, I suspect the file containing that snippet is named <code>forms.py</code></p>
| 2 | 2016-08-01T12:22:57Z | [
"python",
"django",
"django-forms",
"django-views"
] |
module' object has no attribute 'SelectDateWidget' | 38,698,591 | <p>I'm trying to create a custom form/view in Calendarium and i keep getting an error </p>
<pre><code>AttributeError: 'module' object has no attribute 'SelectDateWidget'
</code></pre>
<p>CreateEvent within my forms.py</p>
<pre><code>class CreateEvent(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'start', 'end', 'description', 'category', 'created_by', 'rule', 'end_recurring_period']
widgets = {
'start': forms.SelectDateWidget()
}
</code></pre>
<p>EventCreateView within views.py</p>
<pre><code>class EventCreateView(EventMixin, CreateView):
form_class = CreateEvent
model = Event
</code></pre>
<p>Does anyone know why i'm getting this error</p>
<p>Extra(If Allowed): </p>
<p>Within the EventCreateView its being passed "EventMixin" which looks like this</p>
<pre><code>class EventMixin(object):
"""Mixin to handle event-related functions."""
model = Event
fields = '__all__'
@method_decorator(permission_required('calendarium.add_event'))
def dispatch(self, request, *args, **kwargs):
return super(EventMixin, self).dispatch(request, *args, **kwargs)
</code></pre>
<p>Can someone explain this to me?</p>
| 2 | 2016-08-01T12:13:50Z | 38,698,939 | <p>According to <a href="https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#selectdatewidget" rel="nofollow">the docs</a>, you can only import the <code>SelectDateWidget</code> widget from <code>django.forms</code> in Django 1.9+.</p>
<p>In earlier versions, you need to import it from <code>django.forms.extras.widgets</code>.</p>
<p>First, add the import:</p>
<pre><code>from django.forms.extras.widgets import SelectDateWidget
</code></pre>
<p>Then change the <code>widgets</code> in your form to:</p>
<pre><code> widgets = {
'start': SelectDateWidget(),
}
</code></pre>
| 1 | 2016-08-01T12:29:36Z | [
"python",
"django",
"django-forms",
"django-views"
] |
What is the Python equivalent of StringEntity in Java? | 38,698,621 | <p>I have the following class in Java:</p>
<pre><code>class JsonEntity extends StringEntity {
private final String string;
public JsonEntity(String string, Charset charset) {
super(string, ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), charset));
this.string = string
}
</code></pre>
<p>I have no clue how to implement the above code in Python 2.7. Is there any way I can achieve this?</p>
| 1 | 2016-08-01T12:15:13Z | 38,698,940 | <p>I don' know if I exactly get your need, however if you need to save as JSON with a particular charset in python you can do something like this:</p>
<pre><code>import json
json_string = json.dumps("your string even with wierd symbols", ensure_ascii=False).encode('utf8')
</code></pre>
<p>NB: you can change utf8 with other charsets.</p>
<p><strong>EDIT:</strong>
Anyway if you need to extend something to actually implement your json reader/writer you can extend JSONEncoder:
<a href="https://docs.python.org/2.6/library/json.html#json.JSONEncoder" rel="nofollow">https://docs.python.org/2.6/library/json.html#json.JSONEncoder</a></p>
| 0 | 2016-08-01T12:29:36Z | [
"java",
"python",
"json",
"python-2.7"
] |
Changes in environment variables are not reflected in python | 38,698,914 | <p>trying to install spark, I've some problems when I try to set the system enviroment variables. I modify the PATH using:</p>
<p>âAdvanced system settingsâ â âEnvironment Variablesâ</p>
<p>but when I call these variables from python, using the code:</p>
<pre><code>import os
path = os.environ.get('PATH', None)
print(path)
</code></pre>
<p>The path that shows python don't have the modifications that I put. Thanks</p>
| 1 | 2016-08-01T12:28:18Z | 38,699,164 | <p>Any program invoked from the command prompt will be given the environment variables that was at the time the command prompt was invoked.</p>
<p>Therefore, when you modify or add an environment variable you should restart the command prompt (cmd.exe) and then invoke python to see the changes.</p>
| 1 | 2016-08-01T12:39:46Z | [
"python",
"windows",
"environment-variables",
"windows-10"
] |
Python selenium webdriver. Find elements with specified class name | 38,698,948 | <p>I am using Selenium to parse a page containing markup that looks a bit like this:</p>
<pre><code><html>
<head><title>Example</title></head>
<body>
<div>
<span class="Fw(500) D(ib) Fz(42px)">1</span>
<span class="Fw(500) D(ib) Fz(42px) Green XYZ">2</span>
</div>
</body>
</html>
</code></pre>
<p>I want to fetch all span elements that contain the class foobar.</p>
<p>I have tried both of this (the variable wd is an instance of selenium.webdriver):</p>
<pre><code>elem = wd.find_elements_by_css_selector("span[class='Fw(500) D(ib) Fz(42px).']")
elem = wd.find_element_by_xpath("//span[starts-with(@class, 'Fw(500) D(ib) Fz(42px))]")
</code></pre>
<p>NONE OF WHICH WORK.</p>
<p>How can I select only the elements that start with <code>Fw(500) D(ib) Fz(42px)</code></p>
<p>i.e. both span elements in the sample markup given.</p>
| 0 | 2016-08-01T12:29:55Z | 38,699,017 | <p>Try as below :-</p>
<pre><code>elem = wd.find_elements_by_css_selector("span.foobar")
</code></pre>
<p>If there is space between class <code>foo</code> and <code>bar</code> then try as below :-</p>
<pre><code>elem = wd.find_elements_by_css_selector("span.foo.bar")
</code></pre>
<p><strong>Edited</strong> : If your class contains with non alphabetical charactor and you want to find element which starts with <code>Fw(500) D(ib) Fz(42px)</code> then try as below :-</p>
<pre><code>elem = wd.find_elements_by_css_selector("span[class ^= 'Fw(500) D(ib) Fz(42px)']")
</code></pre>
| 1 | 2016-08-01T12:32:46Z | [
"python",
"selenium"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.