title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Selectively feeding python csv class with lines | 39,850,173 | <p>I have a csv file with a few patterns. I only want to selectively load lines into the csv reader class of python. Currently, csv only takes a file object. Is there a way to get around this?<br>
In other words, what I need is:</p>
<pre><code>with open('filename') as f:
for line in f:
if condition(line):
record = csv.reader(line)
</code></pre>
<p>But, currently, csv class fails if it is given a line instead of a file object.</p>
| 0 | 2016-10-04T10:40:59Z | 39,853,176 | <p>Found a solution: As csv expects object which supports __next__(), I'm using a <strong>StringIO</strong> class to convert string to StringIO object which in turn handles __next__() and returns one line everytime for csv reader class.</p>
<pre><code>with open('filename') as f:
for line in f:
if condition(line):
record = csv.reader(StringIO.StringIO(line))
</code></pre>
| 0 | 2016-10-04T13:07:18Z | [
"python",
"csv"
]
|
Selectively feeding python csv class with lines | 39,850,173 | <p>I have a csv file with a few patterns. I only want to selectively load lines into the csv reader class of python. Currently, csv only takes a file object. Is there a way to get around this?<br>
In other words, what I need is:</p>
<pre><code>with open('filename') as f:
for line in f:
if condition(line):
record = csv.reader(line)
</code></pre>
<p>But, currently, csv class fails if it is given a line instead of a file object.</p>
| 0 | 2016-10-04T10:40:59Z | 39,855,040 | <p>```</p>
<pre><code>with open("xx.csv") as f:
csv = f.readlines()
print(csv[0])
</code></pre>
<p>```</p>
<p>â_â Life is short,your need pandas</p>
<p>pip install pandas</p>
<p>```</p>
<pre><code>import pandas as pd
df = pd.read_csv(filepath or url)
df.ix[0]
df.ix[1]
df.ix[1:3]
</code></pre>
<p>```</p>
| 0 | 2016-10-04T14:33:44Z | [
"python",
"csv"
]
|
Python - base64 - comparing user input vs stored PIN | 39,850,252 | <p>I am having problems when checking if the inputted pin(check_pin) == correct pin (pin)</p>
<p>the test outputs of the check_pin and pin are the same, but it does not see them as equivalent (line 4) </p>
<p>code: </p>
<pre><code>pin_check = input("Please input your 4 digit PIN number: ")
print("g"+str(base64.b64encode(bytes(pin_check, "utf-8"))))
print(pin)
if "g"+str(base64.b64encode(bytes(pin_check, "utf-8"))) == pin:
y = 0
else:
v = v + 1
y = int(y) - 1
print("Incorrect PIN,",y,"attempts remaining.\n")
</code></pre>
<p>Outputs:</p>
<pre><code>Please input your 4 digit PIN number: 1234 [user input, correct pin[1234]]
gb'MTIzNA==' [stored pin]
gb'MTIzNA==' [user input pin]
Incorrect PIN, 2 attempts remaining. [it should set y = 0, not print this line]
</code></pre>
<p>Stored pin: Pin.txt consists of several lines of: gb'MTIzNA=='</p>
<pre><code> import linecache
fo = open("Pin.txt", "r")
pin = linecache.getline('Pin.txt', int(card_no))
print(pin)
fo.close()
</code></pre>
| 0 | 2016-10-04T10:44:48Z | 39,852,054 | <p>Given how you read from the file, notice that <code>linecache.getline</code> will also read the newline character at the end of the line. So the content of <code>pin</code> is actually <code>"gb'MTIzNA=='\n"</code> and that's not equal to the base64-encoded value for <code>pin_check</code>.</p>
<p>The fact that in your sample output you have an extra newline between the third and fifth line shows just that (as the second line, judging from the code, is actually the encoded user input pin).</p>
<p>What you might want to do is</p>
<pre><code>pin = linecache.getline('Pin.txt', int(card_no)).strip()
</code></pre>
<p>that is, strip the line you just read.</p>
| 0 | 2016-10-04T12:14:44Z | [
"python",
"base64"
]
|
Python: Monkeypatching a method of an object | 39,850,270 | <p>I'm hitting an API in python through requests' Session class. I'm making GET & POST method call using requests.Session().</p>
<p>On every call(GET/POST) failure, I want to notify another process. I can do this by creating a utility method as follows:</p>
<pre><code>s = request.Session()
def post():
try:
s.post(URL,data,headers)
except:
notify_another_process()
</code></pre>
<p>And call this method instead of <code>requests.Session().post</code> directly. </p>
<p>But, I want to monkeypatch this code to <code>requests.Session().post</code> and want the additional functionality of notifying the other process in the <code>requests.Session().post</code> method call itself. How can I achieve this?</p>
<p><strong>EDIT 1 :</strong></p>
<p>requests.Session()'s post method has the following signature:</p>
<pre><code>def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **kwargs)
</code></pre>
<p>If I somehow try to make my a custom post like the following:</p>
<pre><code>def post_new(self, url, data=None, json=None, **kwargs):
try:
s.post(url,data, json,kwargs)
except:
notify_another_process()
</code></pre>
<p>and do a patch as follows:</p>
<pre><code>requests.post = post_new
</code></pre>
<p>This isn't really a good monkeypatching because I'm not using <code>self</code> but <code>session's object</code> inside <code>session.post</code>.</p>
| 3 | 2016-10-04T10:45:49Z | 39,850,892 | <p>This should resolve this. You basically save the old function with different name and give your function as the default post.</p>
<pre><code>setattr(requests, 'old_post', requests.post)
def post(url, data=None, json=None, **kwargs):
try:
requests.old_post(url, data, json, kwargs)
except:
notify_another_process()
setattr(requests, 'post', post)
</code></pre>
| 1 | 2016-10-04T11:17:36Z | [
"python",
"python-decorators",
"monkeypatching"
]
|
Python: Monkeypatching a method of an object | 39,850,270 | <p>I'm hitting an API in python through requests' Session class. I'm making GET & POST method call using requests.Session().</p>
<p>On every call(GET/POST) failure, I want to notify another process. I can do this by creating a utility method as follows:</p>
<pre><code>s = request.Session()
def post():
try:
s.post(URL,data,headers)
except:
notify_another_process()
</code></pre>
<p>And call this method instead of <code>requests.Session().post</code> directly. </p>
<p>But, I want to monkeypatch this code to <code>requests.Session().post</code> and want the additional functionality of notifying the other process in the <code>requests.Session().post</code> method call itself. How can I achieve this?</p>
<p><strong>EDIT 1 :</strong></p>
<p>requests.Session()'s post method has the following signature:</p>
<pre><code>def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **kwargs)
</code></pre>
<p>If I somehow try to make my a custom post like the following:</p>
<pre><code>def post_new(self, url, data=None, json=None, **kwargs):
try:
s.post(url,data, json,kwargs)
except:
notify_another_process()
</code></pre>
<p>and do a patch as follows:</p>
<pre><code>requests.post = post_new
</code></pre>
<p>This isn't really a good monkeypatching because I'm not using <code>self</code> but <code>session's object</code> inside <code>session.post</code>.</p>
| 3 | 2016-10-04T10:45:49Z | 39,851,381 | <p>You're almost there, but you should use the self argument</p>
<pre><code>def post_new(self, url, data=None, json=None, **kwargs):
try:
return self.request('POST', url, data=data, json=json, **kwargs)
except:
notify_another_process()
</code></pre>
<p>Then set the post function to port_new</p>
<pre><code>requests.post = post_new
</code></pre>
| 1 | 2016-10-04T11:41:34Z | [
"python",
"python-decorators",
"monkeypatching"
]
|
Python: Monkeypatching a method of an object | 39,850,270 | <p>I'm hitting an API in python through requests' Session class. I'm making GET & POST method call using requests.Session().</p>
<p>On every call(GET/POST) failure, I want to notify another process. I can do this by creating a utility method as follows:</p>
<pre><code>s = request.Session()
def post():
try:
s.post(URL,data,headers)
except:
notify_another_process()
</code></pre>
<p>And call this method instead of <code>requests.Session().post</code> directly. </p>
<p>But, I want to monkeypatch this code to <code>requests.Session().post</code> and want the additional functionality of notifying the other process in the <code>requests.Session().post</code> method call itself. How can I achieve this?</p>
<p><strong>EDIT 1 :</strong></p>
<p>requests.Session()'s post method has the following signature:</p>
<pre><code>def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **kwargs)
</code></pre>
<p>If I somehow try to make my a custom post like the following:</p>
<pre><code>def post_new(self, url, data=None, json=None, **kwargs):
try:
s.post(url,data, json,kwargs)
except:
notify_another_process()
</code></pre>
<p>and do a patch as follows:</p>
<pre><code>requests.post = post_new
</code></pre>
<p>This isn't really a good monkeypatching because I'm not using <code>self</code> but <code>session's object</code> inside <code>session.post</code>.</p>
| 3 | 2016-10-04T10:45:49Z | 39,852,190 | <p>This is the answer which worked for me. It is inspired by the answers mentioned by <a href="http://stackoverflow.com/users/2648166/siddharth-gupta">Siddharth</a> & <a href="http://stackoverflow.com/users/2154798/lafferc">lafferc</a> both. This is on top of what both of them mentioned.</p>
<pre><code>>>> import requests
>>> def post(self, url, data=None, json=None, **kwargs):
... try:
... raise Exception()
... except:
... print "notifying another process"
...
>>> setattr(requests.Session, 'post_old', requests.Session.post)
>>> setattr(requests.Session, 'post', post)
>>> s = requests.Session()
>>> s.post("url")
notifying another process
</code></pre>
| 1 | 2016-10-04T12:20:43Z | [
"python",
"python-decorators",
"monkeypatching"
]
|
Dynamically allocate variables on a for loop in python | 39,850,356 | <p>On the code below, the list 'anos' shall be defined by the user and can take an arbitrary number of years. </p>
<p>However, for each year within the 'anos' list, a new variable has to be assigned at the beginning of FOR loop. If anos = ['2008', '2009], then the for loop would be: for [a,b].. and the data += would also only use a and b.</p>
<p>Is it possible to dynamically allocate such variables depending on the number of items with the 'anos' list? Does the FOR function accept it or do I have to resort to another tool in itertools?</p>
<pre><code>def gv(var):
dd, aa, bb, cc, anos = {}, [], {}, {}, ['2006','2007','2008','2009','2010','2011','2012','2013','2014','2015']
for i in anos:
resp = requests.get('http://www.sidra.ibge.gov.br/api/values/t/1612/n3/all/v/'+var+'/p/' + i + '/C81/2713/f/c')
dd[i] = json.loads(resp.text.encode('utf8'))
anos_tuple = tuple((dd[i]) for i in anos) #ie: (dd['2006], dd['2007']...)
for [a,b,c,d,e,f,g,h,i,j] in zip(*anos_tuple): # uma letra para cada ano
data = a['D1C']
data += ','.join([a['V'], b['V'], c['V'], d['V'], e['V'],
f['V'], g['V'], h['V'], i['V'], j['V']])
</code></pre>
| -1 | 2016-10-04T10:50:50Z | 39,851,043 | <blockquote>
<p>If anos = ['2008', '2009], then the for loop would be: for [a,b].. and the data += would also only use a and b</p>
</blockquote>
<p>So the list [a,b ] can become [a, b, c ] when there are 3 years and so on.</p>
<p>In that case, translate your last for loop into</p>
<pre><code>for row in zip(*anos_tuple):
# a is row[0]
data = row[0]['D1C']
# a['V'], b['V'] etc is row[0]['V'], row[1]['V']
data += ','.join([ i['V'] for i in row ])
</code></pre>
| 1 | 2016-10-04T11:25:30Z | [
"python",
"loops",
"tuples",
"itertools"
]
|
Avoid Duplicate entry error | 39,850,379 | <p>I'm using <code>MySQLdb</code>to insert records in my database, I created a table with an <code>UNIQUE KEY</code> on the <code>domain field</code>.<br></p>
<p>I would like to avoid the error : <code>IntegrityError: (1062, "Duplicate entry 'xxxxx.com' for key 'domain'")</code>.<br></p>
<p>How can I do that ?</p>
<p><strong>My code is here :</strong></p>
<pre><code>try:
CONN = MySQLdb.connect(host=SQL_HOST,
user=SQL_USER,
passwd=SQL_PASSWD,
db=SQL_DB)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
cursor = CONN.cursor()
def insert_table(domain, trust_flow, citation_flow, ref_domains, ext_back_links):
sql = "INSERT INTO %s (domain, TrustFlow, CitationFlow, RefDomains, ExtBackLinks) values('%s','%s','%s','%s','%s')" % (SQL_TABLE, domain, trust_flow, citation_flow, ref_domains, ext_back_links)
if cursor.execute(sql):
CONN.commit()
</code></pre>
| 0 | 2016-10-04T10:51:55Z | 39,850,433 | <p>Try using <a href="http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html" rel="nofollow">INSERT ... ON DUPLCATE KEY UPDATE</a></p>
<pre><code>INSERT INTO %s (domain, TrustFlow, CitationFlow, RefDomains, ExtBackLinks) values('%s','%s','%s','%s','%s')
ON DUPLICATE KEY UPDATE TrustFlow = VALUES(TrustFlow), CitationFlow = VALUES(CitationFlow) ....
</code></pre>
| 2 | 2016-10-04T10:54:29Z | [
"python",
"mysql",
"python-2.7",
"scrapy"
]
|
Syntax of importing multiple classes from a module | 39,850,390 | <p>I'm reading some code which contains the following import statement:</p>
<pre><code>from threading import local as thread_local, Event, Thread
</code></pre>
<p>At first this syntax puzzled me, but I think it is equivalent to:</p>
<pre><code>from threading import local as thread_local
from threading import Event
from threading import Thread
</code></pre>
<p>Can anyone confirm whether this is the case?</p>
| -1 | 2016-10-04T10:52:32Z | 39,850,466 | <p>You can check this on the official documentation. Here's the <a href="https://docs.python.org/3/reference/simple_stmts.html#import" rel="nofollow">documentation for the <code>import</code> syntax</a>:</p>
<blockquote>
<pre><code>import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*
| "from" relative_module "import" identifier ["as" name]
( "," identifier ["as" name] )*
| "from" relative_module "import" "(" identifier ["as" name]
( "," identifier ["as" name] )* [","] ")"
| "from" module "import" "*"
module ::= (identifier ".")* identifier
relative_module ::= "."* module | "."+
name ::= identifier
</code></pre>
</blockquote>
<p>Note how you always have the <code>import module ["as" name]</code> and <code>identifier ["as" name]</code>, including in the list definition:</p>
<pre><code>( "," identifier ["as" name] )*
</code></pre>
<p>This means a comma <code>,</code> followed by an identifier, optionally assigned with <code>as</code> to a name and the <code>)*</code> means "this group can be repeated zero or more times, which includes the example you provided.</p>
<p>This is also explained on the same page a bit later on:</p>
<blockquote>
<p>The <code>from</code> form uses a slightly more complex process:</p>
<ol>
<li>find the module specified in the <code>from</code> clause, loading and initializing it if necessary;</li>
<li>for each of the identifiers specified in the import clauses:
<ol>
<li>check if the imported module has an attribute by that name</li>
<li>if not, attempt to import a submodule with that name and then check the imported module again for that attribute</li>
<li>if the attribute is not found, <code>ImportError</code> is raised.</li>
<li>otherwise, <strong>a reference to that value is stored in the local namespace, using the name in the <code>as</code> clause if it is present, otherwise
using the attribute name</strong></li>
</ol></li>
</ol>
</blockquote>
| 2 | 2016-10-04T10:55:48Z | [
"python"
]
|
Syntax of importing multiple classes from a module | 39,850,390 | <p>I'm reading some code which contains the following import statement:</p>
<pre><code>from threading import local as thread_local, Event, Thread
</code></pre>
<p>At first this syntax puzzled me, but I think it is equivalent to:</p>
<pre><code>from threading import local as thread_local
from threading import Event
from threading import Thread
</code></pre>
<p>Can anyone confirm whether this is the case?</p>
| -1 | 2016-10-04T10:52:32Z | 39,850,518 | <p>Yes, it is.</p>
<p>Check out all the ways that one can import a module in python:
<a href="https://docs.python.org/2/reference/simple_stmts.html#the-import-statement" rel="nofollow">https://docs.python.org/2/reference/simple_stmts.html#the-import-statement</a></p>
| 0 | 2016-10-04T10:57:44Z | [
"python"
]
|
Closing authentication popup selenium | 39,850,462 | <p>Is there possibility to close popup authentication window via <strong>selenium</strong></p>
<p>I wrote something like thath: </p>
<pre><code>def Alert():
alert = driver.switch_to_alert()
alert.dismiss()
</code></pre>
<p>I do not need to authenticate this session. Simple closure of window is enought. </p>
<p>Authentication is granted by domain user im logged into :)</p>
<p>@Edit i do not need to log in i just need to close the window</p>
| 0 | 2016-10-04T10:55:42Z | 39,850,731 | <p>Pass proxy user name & password in the URL that you are trying to access in the following manner:</p>
<p><code>driver.get("http://username:password@www.yourAppURL.com/")</code></p>
| 0 | 2016-10-04T11:08:54Z | [
"python",
"selenium",
"popup"
]
|
Closing authentication popup selenium | 39,850,462 | <p>Is there possibility to close popup authentication window via <strong>selenium</strong></p>
<p>I wrote something like thath: </p>
<pre><code>def Alert():
alert = driver.switch_to_alert()
alert.dismiss()
</code></pre>
<p>I do not need to authenticate this session. Simple closure of window is enought. </p>
<p>Authentication is granted by domain user im logged into :)</p>
<p>@Edit i do not need to log in i just need to close the window</p>
| 0 | 2016-10-04T10:55:42Z | 39,851,269 | <p>If you only close window from multiple try like this </p>
<pre><code># Show all windows
print(driver.window_handles)
# Switch last open window
driver.switch_to_window(driver.window_handles[len(driver.window_handles) - 1])
# Close last open window
driver.close()
</code></pre>
| 0 | 2016-10-04T11:36:39Z | [
"python",
"selenium",
"popup"
]
|
How does one populate a row in pandas python | 39,850,550 | <p>I have initialised a dataframe in python to simulate a matrix</p>
<pre><code> llist = ["this", "is", "a","sentence"]
df = pd.DataFrame(columns = llist, index = llist)
</code></pre>
<p>Now I want to populate a row as follows </p>
<pre><code> test = [1,0,0,0]
df.iloc[[1]] = test
</code></pre>
<p>this throws up the following error</p>
<blockquote>
<p>ValueError: cannot set using a list-like indexer with a different length than the value</p>
</blockquote>
<p>When I set the value as below it populates the row with the same value </p>
<pre><code> test = [1]
df.iloc[[1]] = test
</code></pre>
<p>Can someone tell me why this happens and the most efficient way of populating a row with a list of different values? </p>
| 2 | 2016-10-04T10:59:42Z | 39,850,582 | <p>I think you need remove one <code>[]</code>:</p>
<pre><code>test = [1,0,0,0]
df.iloc[1] = test
print (df)
this is a sentence
this NaN NaN NaN NaN
is 1 0 0 0
a NaN NaN NaN NaN
sentence NaN NaN NaN NaN
</code></pre>
| 2 | 2016-10-04T11:01:34Z | [
"python",
"list",
"pandas",
"dataframe",
"append"
]
|
Pandas: Filter in rows that have a Null/None/NaN value in any of several specific columns | 39,850,632 | <p>I have a csv file which has a lot of strings called <code>"NULL"</code> in it, in several columns.</p>
<p>I would like to select (filter in) rows that have a <code>"NULL"</code> value in <em>any</em> of <em>several specific</em> columns.</p>
<p>Example:</p>
<blockquote>
<pre><code>["Firstname"] ["Lastname"] ["Profession"]
"Jeff" "Goldblum" "NULL"
"NULL" "Coltrane" "Musician"
"Richard" "NULL" "Physicist"
</code></pre>
</blockquote>
<p>Here, I would like to filter in (select) rows in <code>df</code> that have the value <code>"NULL"</code> in the column <code>"Firstname"</code> <em>or</em> <code>"Lastname"</code> â but not if the value is <code>"NULL"</code> in <code>"Profession"</code>.</p>
<p>This manages to filter in strings (not <code>None</code>) in one column:</p>
<pre><code>df = df[df["Firstname"].str.contains("NULL", case=False)]
</code></pre>
<p><br>
I have however attempted to convert the <code>"NULL"</code> strings to <code>None</code> via:</p>
<pre><code>df = df.where((pd.notnull(df)), None)
df.columns = df.columns.str.lower()
</code></pre>
<p>Given the above <code>str.contains</code> filtering, perhaps it's easier to filter in <code>"NULL"</code> strings before converting to <code>None</code>?</p>
| 0 | 2016-10-04T11:03:42Z | 39,850,686 | <p>you can try:</p>
<pre><code>df.replace(to_replace="NULL", value = None)
</code></pre>
<p>to replace all the occurence of <code>"NULL"</code> to <code>None</code></p>
| 1 | 2016-10-04T11:07:07Z | [
"python",
"pandas",
"filtering"
]
|
Pandas: Filter in rows that have a Null/None/NaN value in any of several specific columns | 39,850,632 | <p>I have a csv file which has a lot of strings called <code>"NULL"</code> in it, in several columns.</p>
<p>I would like to select (filter in) rows that have a <code>"NULL"</code> value in <em>any</em> of <em>several specific</em> columns.</p>
<p>Example:</p>
<blockquote>
<pre><code>["Firstname"] ["Lastname"] ["Profession"]
"Jeff" "Goldblum" "NULL"
"NULL" "Coltrane" "Musician"
"Richard" "NULL" "Physicist"
</code></pre>
</blockquote>
<p>Here, I would like to filter in (select) rows in <code>df</code> that have the value <code>"NULL"</code> in the column <code>"Firstname"</code> <em>or</em> <code>"Lastname"</code> â but not if the value is <code>"NULL"</code> in <code>"Profession"</code>.</p>
<p>This manages to filter in strings (not <code>None</code>) in one column:</p>
<pre><code>df = df[df["Firstname"].str.contains("NULL", case=False)]
</code></pre>
<p><br>
I have however attempted to convert the <code>"NULL"</code> strings to <code>None</code> via:</p>
<pre><code>df = df.where((pd.notnull(df)), None)
df.columns = df.columns.str.lower()
</code></pre>
<p>Given the above <code>str.contains</code> filtering, perhaps it's easier to filter in <code>"NULL"</code> strings before converting to <code>None</code>?</p>
| 0 | 2016-10-04T11:03:42Z | 39,850,736 | <p>I think you need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a> <code>NULL</code> string to <code>NaN</code>. Then check all <code>NaN</code> values in selected columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow"><code>isnull</code></a> and select all rows where is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a> <code>True</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>df = df.replace("NULL", np.nan)
print (df[['Firstname','Lastname']].isnull())
Firstname Lastname
0 False False
1 True False
2 False True
print (df[df[['Firstname','Lastname']].isnull().any(1)])
Firstname Lastname Profession
1 NaN Coltrane Musician
2 Richard NaN Physicist
</code></pre>
| 1 | 2016-10-04T11:09:00Z | [
"python",
"pandas",
"filtering"
]
|
Make a Tuple from two dictionaries | 39,850,893 | <p>Suppose I have the dictionaries:</p>
<pre><code>a={1:2,2:3}
</code></pre>
<p>and:</p>
<pre><code>b={3:4,4:5}
</code></pre>
<p>I want to make a tuple such that:</p>
<pre><code>t=({1:2,2:3},{3:4,4:5})
</code></pre>
| -3 | 2016-10-04T11:17:37Z | 39,850,928 | <p>Just put them in a <code>tuple</code> literal:</p>
<pre><code>t = (a, b) # or t = a, b
</code></pre>
<p>Now, <code>print(t)</code> returns <code>({1: 2, 2: 3}, {3: 4, 4: 5})</code>.</p>
| 3 | 2016-10-04T11:18:57Z | [
"python",
"dictionary",
"tuples"
]
|
Extracting data from multiple files with python | 39,850,920 | <p>I'm trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only succeeded in creating a df with all of the X,Y and Z data in the same column. This is my code: </p>
<pre><code>import pandas as pd
import numpy as np
import os
import fnmatch
path = os.getcwd()
file_list = os.listdir(path)
InfoDF = pd.DataFrame()
for file in file_list:
try:
if fnmatch.fnmatch(file, '*.txt'):
filedata = open(file, 'r')
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
except Exception as e:
print(e)
</code></pre>
<p>What am i doing wrong? </p>
| -1 | 2016-10-04T11:18:25Z | 39,850,990 | <p>I think you need <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> for select all files, create list of <code>DataFrames</code> <code>dfs</code> in <code>list comprehension</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p>
<pre><code>files = glob.glob('*.txt')
dfs = [pd.read_csv(fp, delim_whitespace=True, names=['X','Y','Z']) for fp in files]
df = pd.concat(dfs, ignore_index=True)
</code></pre>
| 1 | 2016-10-04T11:22:45Z | [
"python",
"numpy",
"dataframe"
]
|
Extracting data from multiple files with python | 39,850,920 | <p>I'm trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only succeeded in creating a df with all of the X,Y and Z data in the same column. This is my code: </p>
<pre><code>import pandas as pd
import numpy as np
import os
import fnmatch
path = os.getcwd()
file_list = os.listdir(path)
InfoDF = pd.DataFrame()
for file in file_list:
try:
if fnmatch.fnmatch(file, '*.txt'):
filedata = open(file, 'r')
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
except Exception as e:
print(e)
</code></pre>
<p>What am i doing wrong? </p>
| -1 | 2016-10-04T11:18:25Z | 39,851,059 | <pre><code>df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
</code></pre>
<p>this line replace <code>df</code> at each iteration of the loop, that's why you only have the last one at the end of your program.</p>
<p>what you can do is to save all your dataframe in a list and concatenate them at the end</p>
<pre><code>df_list = []
for file in file_list:
try:
if fnmatch.fnmatch(file, '*.txt'):
filedata = open(file, 'r')
df_list.append(pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'}))
df = pd.concat(df_list)
</code></pre>
<p>alternatively, you can write it:</p>
<pre><code>df_list = pd.concat([pd.read_table(open(file, 'r'), delim_whitespace=True, names={'X','Y','Z'}) for file in file_list if fnmatch.fnmatch(file, '*.txt')])
</code></pre>
| 2 | 2016-10-04T11:26:09Z | [
"python",
"numpy",
"dataframe"
]
|
Extracting data from multiple files with python | 39,850,920 | <p>I'm trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only succeeded in creating a df with all of the X,Y and Z data in the same column. This is my code: </p>
<pre><code>import pandas as pd
import numpy as np
import os
import fnmatch
path = os.getcwd()
file_list = os.listdir(path)
InfoDF = pd.DataFrame()
for file in file_list:
try:
if fnmatch.fnmatch(file, '*.txt'):
filedata = open(file, 'r')
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
except Exception as e:
print(e)
</code></pre>
<p>What am i doing wrong? </p>
| -1 | 2016-10-04T11:18:25Z | 39,851,344 | <ul>
<li>As camilleri mentions above, you are overwriting <code>df</code> in your loop</li>
<li>Also there is no point catching a general exception</li>
</ul>
<p><strong>Solution</strong>: Create an empty dataframe <code>InfoDF</code> before the loop and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow">append</a> or <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">concat</a> to populate it with smaller <code>df</code>s</p>
<pre><code>import pandas as pd
import numpy as np
import os
import fnmatch
path = os.getcwd()
file_list = os.listdir(path)
InfoDF = pd.DataFrame(columns={'X','Y','Z'}) # create empty dataframe
for file in file_list:
if fnmatch.fnmatch(file, '*.txt'):
filedata = open(file, 'r')
df = pd.read_table(filedata, delim_whitespace=True, names={'X','Y','Z'})
InfoDF.append(df, ignore_index=True)
print InfoDF
</code></pre>
| 0 | 2016-10-04T11:40:10Z | [
"python",
"numpy",
"dataframe"
]
|
Sqlite python insert into table error | 39,850,938 | <p>having trouble with these two functions
was wondering if people could tell me where I am going wrong
this is a separate function as part of a spider that searches through a website of house prices </p>
<pre><code>def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE houses (id, address, postcode, bedrooms) VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id, date, sale_price) VALUES'
'(%d %s %s)' %(id, sale_price, str(date)))
d.commit()
d.close()
</code></pre>
<p>here is the error raised:</p>
<pre><code>Traceback (most recent call last):
File "/Users/saminahbab/Documents/House_Prices/final_spider.py", line 186, in <module>
final_function(link_set=areas,id_counter=40)
File "/Users/s/Documents/House_Prices/final_spider.py", line 158, in final_function
page_stripper(link=(root+page), id_counter=id_counter)
File "/Users/s/Documents/House_Prices/final_spider.py", line 79, in page_stripper
save_house_to_db(id=float(id_counter), address=address, postcode=postcode, bedrooms=bedrooms)
File "/Users/s/Documents/House_Prices/final_spider.py", line 25, in save_house_to_db
d.execute('INSERT INTO TABLE houses VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
sqlite3.OperationalError: near "TABLE": syntax error
</code></pre>
<p>and for reference here is the execute for the databse </p>
<pre><code># conn = sqlite3.connect('houses_in_london.db')
# database = conn.cursor()
# database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
# 'postcode TEXT, bedrooms TEXT)')
#
# database.execute('CREATE TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id INTEGER '
# ' REFERENCES houses(id), date TEXT, sale_price INTEGER )')
</code></pre>
<p>as always, thank you for the support </p>
| -2 | 2016-10-04T11:19:35Z | 39,851,382 | <p>You have many issues:</p>
<ul>
<li><a href="https://www.sqlite.org/lang_insert.html" rel="nofollow">INSERT-clause</a> has no TABLE keyword</li>
<li>You're trying to pass variables to an SQL query using string formatting; don't do it, ever â use placeholders, or <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">face the consequences</a></li>
<li>Your VALUES-clause is missing commas between the value-expressions</li>
<li>The <a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow">sqlite3 module</a> uses "?" as a placeholder instead of percent formatters</li>
<li>"transaction_id NOT NULL AUTO_INCREMENT" is not a valid column name</li>
<li>"AUTO_INCREMENT" <a href="http://stackoverflow.com/questions/508627/auto-increment-in-sqlite-problem-with-python">is not valid SQLite syntax</a> and you probably meant for transaction_id to be <code>INTEGER PRIMARY KEY</code> â also <a href="https://www.sqlite.org/autoinc.html" rel="nofollow">AUTOINCREMENT should usually not be used</a></li>
</ul>
<p>The below functions fix some of the errors, barring the DDL-corrections to the <code>transactions</code> table.</p>
<pre><code>def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# Remove the TABLE "keyword"
d.execute('INSERT INTO houses (id, address, postcode, bedrooms) '
'VALUES (?, ?, ?, ?)', (id, address, postcode, bedrooms))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# This here expects that you've fixed the table definition as well
d.execute('INSERT INTO transactions (house_id, date, sale_price) '
'VALUES (?, ?, ?)', (id, sale_price, date))
d.commit()
d.close()
</code></pre>
| 1 | 2016-10-04T11:41:35Z | [
"python",
"database",
"sqlite"
]
|
property not working as intended | 39,851,062 | <p>I'm trying to follow a tutorial on <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, and have written the following script:</p>
<pre><code>class Celsius:
def __init__(self, temperature = 0):
self.temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
c = Celsius()
print c.temperature
c.temperature = 100
print c.temperature
</code></pre>
<p>When I run the script, I simply see the two temperature values:</p>
<pre><code>0
100
</code></pre>
<p>However, I would expect the <code>Getting value</code> and <code>Setting value</code> print statements to be visible as well. Is the <code>property</code> somehow not working properly?</p>
| 1 | 2016-10-04T11:26:19Z | 39,851,204 | <p>What you're trying to do only works in new-style classes. To declare a new-style class in Python 2, you need to have</p>
<pre><code>class Celsius(object):
</code></pre>
<p>instead of</p>
<pre><code>class Celsius:
</code></pre>
<p>In Python 3, all classes are new-style, so the plain <code>class Celsius</code> works fine.</p>
| 2 | 2016-10-04T11:33:58Z | [
"python"
]
|
property not working as intended | 39,851,062 | <p>I'm trying to follow a tutorial on <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, and have written the following script:</p>
<pre><code>class Celsius:
def __init__(self, temperature = 0):
self.temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
c = Celsius()
print c.temperature
c.temperature = 100
print c.temperature
</code></pre>
<p>When I run the script, I simply see the two temperature values:</p>
<pre><code>0
100
</code></pre>
<p>However, I would expect the <code>Getting value</code> and <code>Setting value</code> print statements to be visible as well. Is the <code>property</code> somehow not working properly?</p>
| 1 | 2016-10-04T11:26:19Z | 39,851,249 | <p>The code should work as is, but you're mixing Python 2 syntax with Python 3. </p>
<hr>
<p>If you turn the <code>print</code> statements outside the class into <em>function calls</em>, the code works fine as valid Python 3.</p>
<p>If you'll run this as Python 2 code, then you have to inherit your class from <code>object</code> and keep every other thing as is.</p>
<hr>
<p>Choose one.</p>
| 1 | 2016-10-04T11:35:28Z | [
"python"
]
|
property not working as intended | 39,851,062 | <p>I'm trying to follow a tutorial on <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, and have written the following script:</p>
<pre><code>class Celsius:
def __init__(self, temperature = 0):
self.temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
c = Celsius()
print c.temperature
c.temperature = 100
print c.temperature
</code></pre>
<p>When I run the script, I simply see the two temperature values:</p>
<pre><code>0
100
</code></pre>
<p>However, I would expect the <code>Getting value</code> and <code>Setting value</code> print statements to be visible as well. Is the <code>property</code> somehow not working properly?</p>
| 1 | 2016-10-04T11:26:19Z | 39,851,414 | <p>you need define class as this:</p>
<pre><code>class Celsius(object):
balabala
balabala
</code></pre>
| 1 | 2016-10-04T11:43:15Z | [
"python"
]
|
get row and column of matrix | 39,851,083 | <p>I wonder where how to get row and column of this matrix. I want to loop through each element[row][column], but I have no idea how to get these.</p>
<pre><code>imaginary_axis = 100
real_axis = 1
mixed_matrix = [[0 for j in xrange(imaginary_axis)] for i in xrange(real_axis)]
for row in mixed_matrix[0]:
print(row)
for column in mixed_matrix:
print(column)
check(mixed_matrix[row][column])
</code></pre>
<p>This throws an error. How can I get this to work?</p>
<pre class="lang-none prettyprint-override"><code>TypeError: list indices must be integers, not list
</code></pre>
<p>I know why I get this error, but I do not know how I can get the column right.</p>
| 0 | 2016-10-04T11:27:23Z | 39,851,185 | <p>I think, that you can use smth like <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow">enumerate()</a></p>
<p>Cause in your example your <code>column</code> is a list, but as i can see - you want the number of element in this list.</p>
<p>I edit my answer:</p>
<p>What do you want? Magic? There is no magic. You have matrix, like this:
[[1, 2, 3]]</p>
<p>There is a list inside list.
You want to iterate by elements?</p>
<p><code>for lst in matrix:
for element in lst:
print(element)</code></p>
<p>Or you can zip your lists in ONE list and iterate by element in that list.</p>
<p>If you want access by index - you should use it.
You should have two loops, the number of your lists is the number of rows, the number of your elements in list - is number of columns.</p>
<p>And you need smth lile:</p>
<pre><code>for row in range(0, len(mixed_matrix)):
# mixed_matrix[row] - is your FIRST list
for column in range(0, len(mixed_matrix[row])):
print(mixed_matrix[row][column])
</code></pre>
| 0 | 2016-10-04T11:33:12Z | [
"python"
]
|
Get python executable full path from C++ | 39,851,169 | <p>I have a program, written in C++. I would like to get full path to python executable from it. For example, if I open Windows command prompt (cmd.exe) and type python, it use python executable from <code>PATH</code>. So, i would like to have a function <code>get_exec_path("python")</code> whick returns something like <code>C:\Python27\python.exe</code>. <code>C:\Python27\</code> is in my <code>PATH</code>.
I need this for calling python scripts from C++ code. Embedding python in C++ is a bad idea for my purposes. I used to call it like this:</p>
<pre><code>std::system("start \"\" /WAIT python myscript.py --arg1 arg1 --arg2 arg2")
</code></pre>
<p>but this method shows command prompt window, I would like some kind of background work. For this purpose I used <code>CreateProcess</code> with second argument <code>"C:\Python27\python.exe myscript.py --arg1 arg1 --arg2 arg2"</code>. So, I need full path to python executable from <code>PATH</code> variable.</p>
| 0 | 2016-10-04T11:32:23Z | 39,851,693 | <p>You're asking the wrong question.</p>
<p>Instead of trying to bypass the shell (and reinventing the <code>PATH</code> variable while doing so), <em>use it to your advantage</em> by passing the proper flags to <code>start</code> for hiding the command prompt window.</p>
<p>According to <a href="https://technet.microsoft.com/en-gb/library/bb491005.aspx" rel="nofollow">the documentation</a>, that's <code>/b</code>:</p>
<blockquote>
<p>Starts an application without opening a new Command Prompt window.</p>
</blockquote>
| 2 | 2016-10-04T11:57:53Z | [
"python",
"c++"
]
|
Get python executable full path from C++ | 39,851,169 | <p>I have a program, written in C++. I would like to get full path to python executable from it. For example, if I open Windows command prompt (cmd.exe) and type python, it use python executable from <code>PATH</code>. So, i would like to have a function <code>get_exec_path("python")</code> whick returns something like <code>C:\Python27\python.exe</code>. <code>C:\Python27\</code> is in my <code>PATH</code>.
I need this for calling python scripts from C++ code. Embedding python in C++ is a bad idea for my purposes. I used to call it like this:</p>
<pre><code>std::system("start \"\" /WAIT python myscript.py --arg1 arg1 --arg2 arg2")
</code></pre>
<p>but this method shows command prompt window, I would like some kind of background work. For this purpose I used <code>CreateProcess</code> with second argument <code>"C:\Python27\python.exe myscript.py --arg1 arg1 --arg2 arg2"</code>. So, I need full path to python executable from <code>PATH</code> variable.</p>
| 0 | 2016-10-04T11:32:23Z | 39,852,071 | <p>There are some solutions, that could help you.</p>
<ul>
<li><p>Get from windows registry using C++ tools. Replace {ver} with actual version. "3.5" was in my case.</p>
<p>HKCU\SOFTWARE\Python\PythonCore\{ver}\InstallPath\ExecutablePath</p></li>
<li><p>Use where.exe utility to perform PATH search. It works like linux "which".</p>
<p>C:\Users\admin>where python<br>
C:\Users\admin\AppData\Local\Programs\Python\Python35\python.exe</p></li>
</ul>
| 0 | 2016-10-04T12:15:44Z | [
"python",
"c++"
]
|
Get python executable full path from C++ | 39,851,169 | <p>I have a program, written in C++. I would like to get full path to python executable from it. For example, if I open Windows command prompt (cmd.exe) and type python, it use python executable from <code>PATH</code>. So, i would like to have a function <code>get_exec_path("python")</code> whick returns something like <code>C:\Python27\python.exe</code>. <code>C:\Python27\</code> is in my <code>PATH</code>.
I need this for calling python scripts from C++ code. Embedding python in C++ is a bad idea for my purposes. I used to call it like this:</p>
<pre><code>std::system("start \"\" /WAIT python myscript.py --arg1 arg1 --arg2 arg2")
</code></pre>
<p>but this method shows command prompt window, I would like some kind of background work. For this purpose I used <code>CreateProcess</code> with second argument <code>"C:\Python27\python.exe myscript.py --arg1 arg1 --arg2 arg2"</code>. So, I need full path to python executable from <code>PATH</code> variable.</p>
| 0 | 2016-10-04T11:32:23Z | 39,852,822 | <p>As you a showing a Windows Python path, this answer will focus on Windows and is <strong>not</strong> portable.</p>
<p>A function from the shwlapi does exactly what you want: </p>
<pre><code>BOOL PathFindOnPath(
_Inout_ LPTSTR pszFile,
_In_opt_ LPCTSTR *ppszOtherDirs
);
</code></pre>
<p>Its <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb773594%28v=vs.85%29.aspx" rel="nofollow">documentation</a> says:</p>
<blockquote>
<p>PathFindOnPath searches for the file specified by pszFile. If no directories are specified in ppszOtherDirs, it attempts to find the file by searching standard directories such as System32 and the directories specified in the PATH environment variable.</p>
</blockquote>
<p>To find for python.exe you could do:</p>
<pre><code>char path[MAX_PATH] = "python.exe";
BOOL cr = ::PathFindOnPathA(path, NULL);
if (! cr) {
//process error ...
}
// path now contains the full path
</code></pre>
<p>BEWARE: you must include shlwapi.h and link shlwapi.lib ...</p>
| 0 | 2016-10-04T12:50:35Z | [
"python",
"c++"
]
|
How do I know when I can/should use `with` keyword? | 39,851,196 | <p>In C#, when an object implements <code>IDisposable</code>, <code>using</code> should be used to guarantee that resources will be cleaned if an exception is thrown. For instance, instead of:</p>
<pre class="lang-cs prettyprint-override"><code>var connection = new SqlConnection(...);
...
connection.Close();
</code></pre>
<p>one needs to write:</p>
<pre class="lang-cs prettyprint-override"><code>using (var connection = new SqlConnection(...))
{
...
}
</code></pre>
<p>Therefore, just by looking at the signature of the class, I know exactly whether or not I should initialize the object inside a <code>using</code>.</p>
<p>In Python 3, a similar construct is <code>with</code>. Similarly to C#, it ensures that the resources will be cleaned up automatically when exiting the <code>with</code> context, even if a error is raised.</p>
<p>However, I'm not sure how should I determine whether <code>with</code> should be used or not for a specific class. For instance, <a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">an example from <code>psycopg</code></a> doesn't use <code>with</code>, which may mean that:</p>
<ul>
<li>I shouldn't either, or:</li>
<li>The example is written for Python 2, or:</li>
<li>The authors of the documentation were unaware of <code>with</code> syntax, or:</li>
<li>The authors decided not to handle exceptional cases for the sake of simplicity.</li>
</ul>
<p>In general, how should I determine whether <code>with</code> should be used when initializing an instance of a specific class (assuming that documentation says nothing on the subject, and that I have access to source code)?</p>
| 2 | 2016-10-04T11:33:40Z | 39,851,324 | <p><code>with</code> is for use with context managers.
At the code level, a context manager must define two methods:</p>
<ul>
<li><code>__enter__(self)</code></li>
<li><code>__exit__(self, type, value, traceback)</code>.</li>
</ul>
<p>Be aware that there are class decorators which can turn otherwise simple classes/functions into context managers - see <a href="https://docs.python.org/2.7/library/contextlib.html" rel="nofollow">contextlib</a> for some examples</p>
| 2 | 2016-10-04T11:39:15Z | [
"python",
"python-3.x",
"with-statement"
]
|
How do I know when I can/should use `with` keyword? | 39,851,196 | <p>In C#, when an object implements <code>IDisposable</code>, <code>using</code> should be used to guarantee that resources will be cleaned if an exception is thrown. For instance, instead of:</p>
<pre class="lang-cs prettyprint-override"><code>var connection = new SqlConnection(...);
...
connection.Close();
</code></pre>
<p>one needs to write:</p>
<pre class="lang-cs prettyprint-override"><code>using (var connection = new SqlConnection(...))
{
...
}
</code></pre>
<p>Therefore, just by looking at the signature of the class, I know exactly whether or not I should initialize the object inside a <code>using</code>.</p>
<p>In Python 3, a similar construct is <code>with</code>. Similarly to C#, it ensures that the resources will be cleaned up automatically when exiting the <code>with</code> context, even if a error is raised.</p>
<p>However, I'm not sure how should I determine whether <code>with</code> should be used or not for a specific class. For instance, <a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">an example from <code>psycopg</code></a> doesn't use <code>with</code>, which may mean that:</p>
<ul>
<li>I shouldn't either, or:</li>
<li>The example is written for Python 2, or:</li>
<li>The authors of the documentation were unaware of <code>with</code> syntax, or:</li>
<li>The authors decided not to handle exceptional cases for the sake of simplicity.</li>
</ul>
<p>In general, how should I determine whether <code>with</code> should be used when initializing an instance of a specific class (assuming that documentation says nothing on the subject, and that I have access to source code)?</p>
| 2 | 2016-10-04T11:33:40Z | 39,851,760 | <h3>Regarding when you <em>should</em> use it:</h3>
<p>No one forces you to use the <code>with</code> statement, it's just syntactic sugar that's there to make your life easier. If you use it or not is totally up to you but, it is generally recommended to do so. (We're forgetful and <code>with ...</code> looks ways better than explicit initialize resource/finalize recourse calls).</p>
<h3>When you <em>can</em> use it:</h3>
<p>When you <em>can</em> use it boils down to examining if it defines the context manager protocol. This could be as simple as trying to use <code>with</code> and seeing that it fails :-)</p>
<p>If you dynamically need to check if an object <em>is</em> a context manager, you have two options.</p>
<p>First, wait for the stable release of <code>Python 3.6</code> which defines an <code>ABC</code> for context managers, <code>ContextManager</code>, which can be used in <code>issubclass/isinstance</code> checks:</p>
<pre><code>>>> from typing import ContextManager
>>> class foo:
... def __enter__(self): pass
... def __exit__(self): pass
...
>>> isinstance(foo(), ContextManager)
True
>>> class foo2: pass
...
>>> isinstance(foo2(), ContextManager)
False
</code></pre>
<p>Or, create your own little function to check for it:</p>
<pre><code>def iscontext(inst):
cls = type(inst)
return (any("__enter__" in vars(a) for a in cls.__mro__) and
any("__exit__" in vars(a) for a in cls.__mro__))
</code></pre>
<p>As a final note, the <code>with</code> statement is present in <code>Python 2</code> and in <code>3</code>, the use case you saw probably just wasn't aware of it :-).</p>
| 2 | 2016-10-04T12:01:03Z | [
"python",
"python-3.x",
"with-statement"
]
|
How do I know when I can/should use `with` keyword? | 39,851,196 | <p>In C#, when an object implements <code>IDisposable</code>, <code>using</code> should be used to guarantee that resources will be cleaned if an exception is thrown. For instance, instead of:</p>
<pre class="lang-cs prettyprint-override"><code>var connection = new SqlConnection(...);
...
connection.Close();
</code></pre>
<p>one needs to write:</p>
<pre class="lang-cs prettyprint-override"><code>using (var connection = new SqlConnection(...))
{
...
}
</code></pre>
<p>Therefore, just by looking at the signature of the class, I know exactly whether or not I should initialize the object inside a <code>using</code>.</p>
<p>In Python 3, a similar construct is <code>with</code>. Similarly to C#, it ensures that the resources will be cleaned up automatically when exiting the <code>with</code> context, even if a error is raised.</p>
<p>However, I'm not sure how should I determine whether <code>with</code> should be used or not for a specific class. For instance, <a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">an example from <code>psycopg</code></a> doesn't use <code>with</code>, which may mean that:</p>
<ul>
<li>I shouldn't either, or:</li>
<li>The example is written for Python 2, or:</li>
<li>The authors of the documentation were unaware of <code>with</code> syntax, or:</li>
<li>The authors decided not to handle exceptional cases for the sake of simplicity.</li>
</ul>
<p>In general, how should I determine whether <code>with</code> should be used when initializing an instance of a specific class (assuming that documentation says nothing on the subject, and that I have access to source code)?</p>
| 2 | 2016-10-04T11:33:40Z | 39,851,863 | <p>You should use <code>with</code> whenever you need to perform some similar action before and after executing the statement. For example:</p>
<ul>
<li><em>Want to execute SQL query?</em> You need to open and close the connections safely.Use <code>with</code>.</li>
<li><em>Want to perform some action on file?</em> You have to open and close the file safely. Use <code>with</code></li>
<li><em>Want to store some data in temporary file to perform some task?</em> You need to create the directory, and clean it up once you are done. Use <code>with</code>, and so on. . . </li>
</ul>
<p>Everything you want to perform before the query execution, add it to the <code>__enter__()</code> method. And the action to be performed after, add it to the <code>__exit__()</code> method.</p>
<p>One of the nice thing about <code>with</code> is, <em><code>__exit__</code> is executed even if the code within <code>with</code> raises any <code>Exception</code></em></p>
| 0 | 2016-10-04T12:05:43Z | [
"python",
"python-3.x",
"with-statement"
]
|
Is it possible to use the selected lines of a one2many list in a function? | 39,851,220 | <p>Ive been using the module â<code>web_o2m_delete_multi</code>â that lets me select multiple lines in <code>one2many</code> list view and delete them all.</p>
<p>Is there a way to use the selected lines in a python function? I tried <code>active_ids</code> but itâs not working.</p>
| 1 | 2016-10-04T11:34:33Z | 39,851,575 | <p>You can get these selected record ids in <code>ids</code> instead of <code>active_ids</code>.</p>
| 0 | 2016-10-04T11:51:41Z | [
"python",
"openerp",
"odoo-8"
]
|
Calling a setuptools entry point from within the library | 39,851,300 | <p>I have a setuptools-based Python (3.5) project with multiple scripts as entry points similar to the following:</p>
<pre><code>entry_points={
'console_scripts': [
'main-prog=scripts.prog:main',
'prog-viewer=scripts.prog_viewer:main'
]}
</code></pre>
<p>So there is supposed to be a main script, run as <code>main-prog</code> and an auxiliary script <code>prog-viewer</code> (which does some Tk stuff).</p>
<p>The problem is that I want to be able to run the <code>prog-viewer</code> in a <code>Popen</code> subprocess from <code>main-prog</code> (or rather form my library) without having to resort to manually figuring out the paths and then adapt to the different OS. Also, what do I do when my PATH contains a script with the same name that does not belong to my library? Can I tell my program to <code>Popen(scripts.prog_viewer:main)</code>?</p>
| 0 | 2016-10-04T11:37:51Z | 39,851,506 | <p>You could run a python command with Popen, for example:</p>
<pre><code>Popen('python -c "from scripts.prog import main; main()"', shell=True)
</code></pre>
| 1 | 2016-10-04T11:47:58Z | [
"python",
"setuptools",
"packaging"
]
|
Calculate correlation for discrete-like values from two columns of DataFrame in Pandas | 39,851,353 | <p>Here's the code snippet:</p>
<pre><code>df = pd.DataFrame(data=[1,1,2,2,3,3,3], columns =list('A'))
def m(x):
if x == 1:
return 2
if x == 2:
return 3
if x == 3:
return 1
return -1
df['B'] = df['A'].map(m)
print df.head(n=10)
A B
0 1 2
1 1 2
2 2 3
3 2 3
4 3 1
5 3 1
6 3 1
</code></pre>
<p>As we can see, column B is created by mapping value from column A, thus they should have correlation of value 1, but what I got from below is all not satisfying. Could anyone give me some idea on how to calculate correlation of discrete data for two columns? Great thanks!</p>
<pre><code>df['A'].cov(df['B'])
-0.47619047619047611
df['A'].corr(df['B'], method='spearman')
-0.68000000000000016
df['A'].corr(df['B'], method='kendall')
-0.50000000000000011
df['A'].corr(df['B'])
-0.58823529411764708
</code></pre>
| -1 | 2016-10-04T11:40:27Z | 39,852,615 | <p>The values in the 5th row move in the opposite direction, that's why you get a correlation of <code>-0.58823529411764708</code>. You can see that in column A the 4th value is 2 and then the 5th value is 3 so your series is increasing in this column. Instead in column B the 4th value is 3 and then the fifth value is 1 so your series is decreasing. There is no problem with your calculation. If you calculate the correlation til the 4th row you will get a correlation coefficient = 1 because values in both columns move to the same direction.</p>
<p>You can find a nice explanation of correlation in this post: <a href="http://stats.stackexchange.com/questions/29713/what-is-covariance-in-plain-language">http://stats.stackexchange.com/questions/29713/what-is-covariance-in-plain-language</a></p>
| 1 | 2016-10-04T12:40:47Z | [
"python",
"pandas",
"dataframe",
"statistics",
"correlation"
]
|
Django - How to filter dropdown based on user id? | 39,851,362 | <p>I'm not sure how to filter dropdown based on user id.</p>
<p>Not I want for user id 2.</p>
<p><a href="http://i.stack.imgur.com/iJ4Zm.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJ4Zm.png" alt="enter image description here"></a></p>
<p>I want exactly like this for user id 2.</p>
<p><a href="http://i.stack.imgur.com/1XF7A.png" rel="nofollow"><img src="http://i.stack.imgur.com/1XF7A.png" alt="enter image description here"></a></p>
<p>Model</p>
<pre><code>@python_2_unicode_compatible # only if you need to support Python 2
class PredefinedMessage(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length=50)
list_description = models.CharField(max_length=50)
def __str__(self):
return self.list_name
class PredefinedMessageDetail(models.Model):
predefined_message_detail = models.ForeignKey(PredefinedMessage)
message = models.CharField(max_length=5000)
</code></pre>
<p>View</p>
<pre><code>class PredefinedMessageDetailForm(ModelForm):
class Meta:
model = PredefinedMessageDetail
fields = ['predefined_message_detail', 'message']
exclude = ('user',)
def predefined_message_detail_update(request, pk, template_name='predefined-message/predefined_message_detail_form.html'):
if not request.user.is_authenticated():
return redirect('home')
predefined_message_detail = get_object_or_404(PredefinedMessageDetail, pk=pk)
form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail)
if form.is_valid():
form.save()
return redirect('predefined_message_list')
return render(request, template_name, {'form':form})
</code></pre>
<p>html file</p>
<pre><code>{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
</code></pre>
| 0 | 2016-10-04T11:40:49Z | 39,852,489 | <p>You can do it in view itself using</p>
<pre><code>form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail)
form.fields["predefined_message_detail"].queryset= PredefinedMessage.objects.filter(user=request.user)
</code></pre>
<p>But filtering happens based on <code>request.user</code> so it should be logged in.Consider that also. Hope this helps</p>
| 1 | 2016-10-04T12:34:37Z | [
"python",
"django"
]
|
Extract rows as column from pandas data frame after melt | 39,851,416 | <p>I'm working with pandas and I have this table:</p>
<pre><code>ID 1-May-2016 1-Jun-2016 20-Jul-2016 Class
1 0.2 0.52 0.1 H
2 0.525 0.20 0.01 L
...
</code></pre>
<p>and I'd like to obtain this table:</p>
<pre><code>ID Date Value Class
1 1-May-2016 0.2 H
1 1-Jun-2016 0.52 H
...
2 1-May-2016 0.525 L
...
</code></pre>
<p>I tried:</p>
<pre><code>pandas.melt(df,id_vars["ID"], var_name = "Class")
</code></pre>
<p>and I obtain almost what I'd like:</p>
<pre><code>ID Class Value
1 1-May-2016 0.2
1 1-Jun-2016 0.52
...
1 Class L
2 Class H
</code></pre>
<p>except that the bottom part of the table contains the information that should be considered as an "extra" column.
Is this the right process/approach? If yes, how can I "shift" the bottom part of the table to be a column that contains the class of my samples?</p>
| 1 | 2016-10-04T11:43:19Z | 39,851,465 | <p>You need add <code>Class</code> to <code>id_vars</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a>:</p>
<pre><code>print (pd.melt(df,id_vars=["ID", 'Class'], var_name = "Date", value_name='Vals'))
ID Class Date Vals
0 1 H 1-May-2016 0.200
1 2 L 1-May-2016 0.525
2 1 H 1-Jun-2016 0.520
3 2 L 1-Jun-2016 0.200
4 1 H 20-Jul-2016 0.100
5 2 L 20-Jul-2016 0.010
</code></pre>
<p>Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> if necessary:</p>
<pre><code>print (pd.melt(df,id_vars=["ID", 'Class'], var_name = "Date", value_name='Vals')
.sort_values(['ID', 'Class']))
ID Class Date Vals
0 1 H 1-May-2016 0.200
2 1 H 1-Jun-2016 0.520
4 1 H 20-Jul-2016 0.100
1 2 L 1-May-2016 0.525
3 2 L 1-Jun-2016 0.200
5 2 L 20-Jul-2016 0.010
</code></pre>
<p>Another possible solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p>
<pre><code>print (df.set_index(["ID", 'Class'])
.stack()
.reset_index(name='Vals')
.rename(columns={'level_2':'Date'}))
ID Class Date Vals
0 1 H 1-May-2016 0.200
1 1 H 1-Jun-2016 0.520
2 1 H 20-Jul-2016 0.100
3 2 L 1-May-2016 0.525
4 2 L 1-Jun-2016 0.200
5 2 L 20-Jul-2016 0.010
</code></pre>
| 2 | 2016-10-04T11:45:47Z | [
"python",
"pandas",
"pivot-table",
"melt"
]
|
Access django server on VirtualBox/Vagrant machine from host browser? | 39,851,495 | <p>I have a Django web server on a VirtualBox/Vagrant machine running "bento/centos-6.7-i386".
I have followed this guide to create a Django project: <a href="https://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/dev/intro/tutorial01/</a></p>
<p>I have a web server running at <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> inside my guest machine. This is the first time I am running a Django web server. It is supposed to be a hello world app.
How can I access this web application from my host browser?
I tried adding this line - config.vm.network "private_network", ip: "55.55.55.5" in the vagrant file and then trying to run the "python manage.py runserver 0.0.0.0:80" command as per 1 of the solutions explained in previous discussions by others but I couldnt access the site from my host browser using 55.55.55.5:8000.
How can I access the web server from my browser?
Kindly help me,I'm quite new to vagrant.
Following given is my Vagrant File:</p>
<pre><code># -- mode: ruby --
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "bento/centos-6.7-i386"
config.vm.network "forwarded_port", guest: 8000, host: 8000
config.vm.network "forwarded_port", guest: 8080, host: 8080
config.vm.network "forwarded_port", guest: 5000, host: 5000
config.vm.network "private_network", ip: "10.10.10.10"
end
</code></pre>
| 1 | 2016-10-04T11:47:33Z | 39,852,005 | <p>You're forwarding port 8000 on the guest to 8000 on the host. Try:</p>
<pre><code>python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>Then in your browser visit: <a href="http://localhost:8000" rel="nofollow">http://localhost:8000</a></p>
<p>That'll leave port 80 free if you end up wanting to run a web server for testing as well. Good luck!</p>
| 0 | 2016-10-04T12:12:37Z | [
"python",
"django",
"vagrant"
]
|
Access django server on VirtualBox/Vagrant machine from host browser? | 39,851,495 | <p>I have a Django web server on a VirtualBox/Vagrant machine running "bento/centos-6.7-i386".
I have followed this guide to create a Django project: <a href="https://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/dev/intro/tutorial01/</a></p>
<p>I have a web server running at <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> inside my guest machine. This is the first time I am running a Django web server. It is supposed to be a hello world app.
How can I access this web application from my host browser?
I tried adding this line - config.vm.network "private_network", ip: "55.55.55.5" in the vagrant file and then trying to run the "python manage.py runserver 0.0.0.0:80" command as per 1 of the solutions explained in previous discussions by others but I couldnt access the site from my host browser using 55.55.55.5:8000.
How can I access the web server from my browser?
Kindly help me,I'm quite new to vagrant.
Following given is my Vagrant File:</p>
<pre><code># -- mode: ruby --
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "bento/centos-6.7-i386"
config.vm.network "forwarded_port", guest: 8000, host: 8000
config.vm.network "forwarded_port", guest: 8080, host: 8080
config.vm.network "forwarded_port", guest: 5000, host: 5000
config.vm.network "private_network", ip: "10.10.10.10"
end
</code></pre>
| 1 | 2016-10-04T11:47:33Z | 39,852,578 | <p>if you are using below line in your <code>Vagrantfile</code> for port forwarding </p>
<pre><code>config.vm.network "forwarded_port", guest: 8000, host: 8000
</code></pre>
<p>It means you will be able to access your guest application which running at port <code>8000</code> in your host browser at port <code>8000</code>. so you will be able access by hitting <code>http://127.0.0.1:8000</code> or <code>http://localhost:8000</code> in your host.</p>
<p>why you are forcing your app to run on <code>0.0.0.0</code> ? .
it is not required , or if you want to access with guest IP address then there is no sense to use port forwarding. </p>
<p>if you changed this configuration in <code>Vagrantfile</code> after provision then don`t forget to reload</p>
<pre><code>vagrant reload
</code></pre>
| 1 | 2016-10-04T12:38:55Z | [
"python",
"django",
"vagrant"
]
|
Using pip on Windows installed with both python 2.7 and 3.5 | 39,851,566 | <p>I am using Windows 10. Currently, I have python 2.7 installed. I would like to install python 3.5 as well. However, if I have both 2.7 and 3.5 installed, when I run <code>pip</code>, how do I get the direct the package to be installed to the desired python version?</p>
| 0 | 2016-10-04T11:51:11Z | 39,852,126 | <p>You will have to use the absolute path of <code>pip</code>.</p>
<p>E.g: if I installed python 3 to <code>C:\python35</code>, I would use:
<code>C:\> python35\Scripts\pip.exe install packagename</code></p>
<p>Or if you're on linux, use <code>pip3 install packagename</code></p>
<p>If you don't specify a full path, it will use whichever <code>pip</code> is in your <code>path</code>.</p>
| 1 | 2016-10-04T12:17:59Z | [
"python",
"python-2.7",
"python-3.x",
"pip"
]
|
Using pip on Windows installed with both python 2.7 and 3.5 | 39,851,566 | <p>I am using Windows 10. Currently, I have python 2.7 installed. I would like to install python 3.5 as well. However, if I have both 2.7 and 3.5 installed, when I run <code>pip</code>, how do I get the direct the package to be installed to the desired python version?</p>
| 0 | 2016-10-04T11:51:11Z | 39,852,599 | <p>The answer from Farhan.K will work. However, I think a more convenient way would be to rename <code>python35\Scripts\pip.exe</code> to <code>python35\Scripts\pip3.exe</code> assuming python 3 is installed in <code>C:\python35</code>.</p>
<p>After renaming, you can use <code>pip3</code> when installing packages to python v3 and <code>pip</code> when installing packages to python v2. Without the renaming, your computer will use whichever pip is in your path.</p>
| 2 | 2016-10-04T12:39:42Z | [
"python",
"python-2.7",
"python-3.x",
"pip"
]
|
Do not write None or empty lines in Spark (Python) | 39,851,601 | <p>I am new in Spark, but I have had some experience in Hadoop. I've trying to adapt a python code I use in Hadoop streaming that filters out some tweets in JSON format.</p>
<p>Normally, my function has a condition that prints to stdout the tweet if the condition is true and prints nothing otherwise.</p>
<pre><code>def filter(tweet):
if criteria(tweet) is True:
print json.dumps(tweet)
</code></pre>
<p>This way, the final output file will contain only the tweets I want.</p>
<p>However, when trying to use Spark, I had to change the <code>print</code> statement with a <code>return</code> so I return the tweet if the condition is True, and <code>None</code> otherwise. </p>
<pre><code>def filter(tweet):
if criteria(tweet) is True:
return json.dumps(tweet)
</code></pre>
<p>The problem appears when trying to save the results to disk. Using <code>saveAsTextFile</code> method of Pyspark, it saves not only the tweets I want but also the <code>None</code> I return when condition is False.</p>
<p>How can I avoid writing <code>None</code> to the file so I only save the desired tweets?</p>
<p>Many thanks in advance.</p>
<p>Jorge</p>
| 0 | 2016-10-04T11:52:50Z | 39,851,935 | <p>If you are using your function in a map, it will not reduce the number of elements you have. To filter elements, you must to use the <code>filter</code> method to test if an element is <code>None</code> after you <code>map</code>.</p>
| 0 | 2016-10-04T12:09:18Z | [
"python",
"hadoop",
"apache-spark",
"pyspark"
]
|
Do not write None or empty lines in Spark (Python) | 39,851,601 | <p>I am new in Spark, but I have had some experience in Hadoop. I've trying to adapt a python code I use in Hadoop streaming that filters out some tweets in JSON format.</p>
<p>Normally, my function has a condition that prints to stdout the tweet if the condition is true and prints nothing otherwise.</p>
<pre><code>def filter(tweet):
if criteria(tweet) is True:
print json.dumps(tweet)
</code></pre>
<p>This way, the final output file will contain only the tweets I want.</p>
<p>However, when trying to use Spark, I had to change the <code>print</code> statement with a <code>return</code> so I return the tweet if the condition is True, and <code>None</code> otherwise. </p>
<pre><code>def filter(tweet):
if criteria(tweet) is True:
return json.dumps(tweet)
</code></pre>
<p>The problem appears when trying to save the results to disk. Using <code>saveAsTextFile</code> method of Pyspark, it saves not only the tweets I want but also the <code>None</code> I return when condition is False.</p>
<p>How can I avoid writing <code>None</code> to the file so I only save the desired tweets?</p>
<p>Many thanks in advance.</p>
<p>Jorge</p>
| 0 | 2016-10-04T11:52:50Z | 39,852,142 | <p>Quite elegant solution, which avoids chaining <code>filter</code> and <code>map</code>, is to use <code>flatMap</code>:</p>
<pre><code>def filter(tweet):
return [json.dumps(tweet)] if criteria(tweet) is True else []
some_rdd.flatMap(filter)
</code></pre>
| 0 | 2016-10-04T12:18:41Z | [
"python",
"hadoop",
"apache-spark",
"pyspark"
]
|
QWidget delete file on destroy | 39,851,691 | <p>I'd like to <strong>automatically</strong> delete a temporary file when my QWidget is destroyed (for example, at the end of the program).</p>
<p>I tried to handle it with the <strong>destroyed</strong> signal, but it doesn't work, my callback function is never executed.</p>
<p>Source code:</p>
<pre><code>import sys
from os import remove
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__(flags=Qt.Window)
self.setAttribute(Qt.WA_DeleteOnClose, True)
with open('temporary_file.txt', 'w') as f:
f.write("Hello World!")
self.destroyed.connect(self._on_destroyed)
@pyqtSlot(name='_on_destroyed')
def _on_destroyed(self):
print("Never executed.")
remove('temporary_file.txt')
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-10-04T11:57:42Z | 39,853,354 | <p>You should use <a href="http://doc.qt.io/qt-5/qwidget.html#closeEvent" rel="nofollow"><code>closeEvent</code></a> for this:</p>
<pre><code>class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__(flags=Qt.Window)
self.setAttribute(Qt.WA_DeleteOnClose, True)
with open('temporary_file.txt', 'w') as f:
f.write("Hello World!")
def closeEvent(self, event):
print('close event')
remove('temporary_file.txt')
</code></pre>
| 0 | 2016-10-04T13:14:08Z | [
"python",
"qt",
"pyqt"
]
|
QWidget delete file on destroy | 39,851,691 | <p>I'd like to <strong>automatically</strong> delete a temporary file when my QWidget is destroyed (for example, at the end of the program).</p>
<p>I tried to handle it with the <strong>destroyed</strong> signal, but it doesn't work, my callback function is never executed.</p>
<p>Source code:</p>
<pre><code>import sys
from os import remove
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__(flags=Qt.Window)
self.setAttribute(Qt.WA_DeleteOnClose, True)
with open('temporary_file.txt', 'w') as f:
f.write("Hello World!")
self.destroyed.connect(self._on_destroyed)
@pyqtSlot(name='_on_destroyed')
def _on_destroyed(self):
print("Never executed.")
remove('temporary_file.txt')
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-10-04T11:57:42Z | 39,856,630 | <p>The solution is trivial: replace <code>_on_destroyed</code> with <code>__del__(self)</code>, and remove the slot annotation. That's really all there's to it.</p>
<p>Alas, you don't need to do that. Use a <code>QTemporaryFile</code> member and it will be automatically removed upon destruction.</p>
| 0 | 2016-10-04T15:46:40Z | [
"python",
"qt",
"pyqt"
]
|
Pandas pivoting on timestap table returns unexpected result | 39,851,743 | <p>I have a DataFrame with two columns: <code>ts</code> (timestamp) and <code>n</code> (number)</p>
<p>timestamps begin at <code>2016-07-15</code>:</p>
<pre><code>In [1]: d.head()
Out[1]:
ts n
0 2016-07-15 00:04:09.444 12
1 2016-07-15 00:05:01.633 12
2 2016-07-15 00:05:03.173 31
3 2016-07-15 00:05:03.970 12
4 2016-07-15 00:05:04.258 23
</code></pre>
<p>now, I pivot:</p>
<pre><code>pd.pivot_table(d, columns='n', values='ts', aggfunc=lambda x: (np.min(x) - pd.Timestamp('2016-07-15')).days)
</code></pre>
<p>I expect to see column with integers represent days but instead I see:</p>
<pre><code>n
12 1970-01-01
23 1970-01-01
31 1970-01-01
Name: ts, dtype: datetime64[ns]
</code></pre>
<p>What am O missing here? and is there a better way to achieve the same (trying to get the offset in days for the first appearance of <code>n</code> in the table)</p>
| 2 | 2016-10-04T12:00:22Z | 39,851,921 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and add custom function with <code>apply</code>:</p>
<pre><code>print (d.groupby('n')['ts'].apply(lambda x: (x.min() - pd.Timestamp('2016-07-15')).days))
n
12 0
23 0
31 0
Name: ts, dtype: int64
</code></pre>
<p>In your code you get <code>0</code> too, but values are converted to <code>datetime</code> (<code>1970-01-01</code>), because <code>dtype</code> of <code>ts</code> was <code>datetime</code> before.</p>
<p>I think then need cast <code>datetime</code> to <code>int</code>, but first convert to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a>:</p>
<pre><code>s = pd.pivot_table(d, columns='n',
values='ts',
aggfunc=lambda x: (np.min(x) - pd.Timestamp('2016-07-15')).days)
s = s.values.astype(int)
print (s)
n
12 0
23 0
31 0
Name: ts, dtype: int64
</code></pre>
| 1 | 2016-10-04T12:08:34Z | [
"python",
"datetime",
"pandas",
"time-series",
"pivot-table"
]
|
Get query result from python | 39,851,819 | <p>I have code in Python that want to get results from this query but got errors : </p>
<pre><code>AttributeError: 'Future' object has no attribute 'fetchone'
</code></pre>
<p>here is my code: </p>
<pre><code> domain = bid_request["site"]["domain"]
site = yield self.db.execute('SELECT "Id", "State", "LastAccess", "Domain", "RubricId", '
'"IgnoreInInterests", "PriceCPM" '
'FROM whis2011."RtbActiveSites" '
'WHERE "Domain" = \'%s\' '
'ORDER BY "Id" DESC limit 1;' % domain).fetchone()
self.add_header('Content-Type', 'text/html; charset=utf-8')
if len(site) > 0: .....
</code></pre>
<p>Also, I need "site" variable because as you see I'll use it latter.
How I can fix it?</p>
<p>Thanks</p>
| -1 | 2016-10-04T12:03:42Z | 39,852,965 | <p>It's seems if I use "fetchall()" instead of "fetchone()" it will be work!</p>
| 0 | 2016-10-04T12:56:52Z | [
"python",
"database"
]
|
Filling Excel cells using openpyxl | 39,851,862 | <p>in my new department i have to code with python and openpyxl. I have to fill cells of an excel sheet with test runs and the result(passed/failed).
This is all i got so far. I am not getting any errors but the sheet is still empty.. Any help would be nice. Thanks in advance. </p>
<pre><code>def create_report(self, root, now):
tests = (
['Discover DTC time', 'failed'],
['Drucksensor_DTC_Startup', 'failed'],
['Drucksensor_DTC_Runtime', 'passed'],
)
wb = xl.Workbook()
ws = wb.active
ws.title = 'ExcelSummaryReport.xlsx'
row = 1
col = 0
for i in range(row, ws.max_row):
for j in range(col, ws.max_col):
ws.cell(row=i + 1, col=j).value = tests[i]
wb.save('ExcelSummaryReport.xlsx')
</code></pre>
| 0 | 2016-10-04T12:05:39Z | 39,851,987 | <p>If you are creating a new worksheet, it doesn't have any rows or columns, so <code>max_row</code> and <code>max_col</code> are 0, and your loop does nothing. How many rows/columns to fill looks like it should be determined by the data (<code>tests</code>).</p>
| 0 | 2016-10-04T12:11:51Z | [
"python",
"excel",
"pycharm",
"openpyxl"
]
|
IPython console not showing some outputs but showing others? | 39,851,911 | <p>Win 7, x64, Python 2.7, Anaconda 4.2.0, IPython 5.1.0</p>
<p>I am working through some <code>multiprocessing</code> tutorials & hit a problem straight away whilst working in an IPython console. The code below...</p>
<pre><code>import multiprocessing
print 'hello'
def worker():
"""worker function"""
print 'Worker'
return
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
</code></pre>
<p>I am expecting...</p>
<pre><code>hello
worker
worker
worker
worker
worker
</code></pre>
<p>but I am getting..</p>
<pre><code>hello
</code></pre>
<p>Why is the output from the <code>worker</code> function not being displayed in the IPython console?</p>
<p>EDIT: When run from the Anaconda command line it exits with a syntax error on the <code>print 'Worker'</code> line but when run from a Python console runs as expected if I keep pressing enter.</p>
<p>EDIT 2: Now works in Anaconda command window (I had the wrong Python installed). The issue appears not just limited to this code. Any print statement in any parallelized functions do not appear in the IPython console. </p>
| 0 | 2016-10-04T12:08:04Z | 39,853,683 | <p>Try this:</p>
<pre><code>for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
p.join()
</code></pre>
<p>I suspect that ipython is ending the child processes when the main process/function is done, and the <code>join</code> should help prevent that.</p>
| 0 | 2016-10-04T13:30:20Z | [
"python",
"ipython",
"python-multiprocessing"
]
|
Django doesn't keep User logged in between views | 39,851,919 | <p>I am quite new to web programming and django especially. I am trying to implement symple login service using Ajax. The user seems to be logged in succesfully however when the view is changed he uppears ulogged again. </p>
<p>Appreciate any help.
Thanks.</p>
<p>Login template:</p>
<pre><code><form class="login-form" action="">
{% csrf_token %}
<input type="text" id="usernamelog" />
<input type="password" id="pwdlogin" />
<button onclick="login(event)">login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
</code></pre>
<p>Login Ajax:</p>
<pre><code>function login(e) {
e.preventDefault();
var username = $("#usernamelog").val();
var pwd = $("#pwdlogin").val();
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url : "/loginscript/",
type : "post",
data : {
username: username,
password : pwd,
}
}).done(function(data) {
if (data == "good") {
document.getElementById('usernamelog').value ="good";
window.location='../ehealth'
}else{
document.getElementById('usernamelog').value ="bad";
}
});
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
</code></pre>
<p>Loginscript view:</p>
<pre><code>def loginscript(request):
#c = {}
#c.update(csrf(request))
print >> sys.stderr,"script entered"
username = request.POST['username']
password = request.POST['password']
print >> sys.stderr, username
user = authenticate(username=username, password=password)
if user is not None:
login(request=request,user=user)
if User.is_authenticated:
print >> sys.stderr,"should be good actually"
else:
print >> sys.stderr, "Still not"
return HttpResponse("good")
else:
print >> sys.stderr,"Should be bad"
return HttpResponse("bad")
</code></pre>
<p>Ehealth view:</p>
<pre><code>def index(request):
check=User.is_authenticated
if check!=True:
return redirect('http://127.0.0.1:8000/login/')
template="index.html"
return render (request=request, template_name=template)
</code></pre>
<p>The log I get: </p>
<pre><code>Hey we are in login
[04/Oct/2016 14:02:42] "GET /login/ HTTP/1.1" 200 6881
script entered
Andrey
should be good actually
[04/Oct/2016 14:02:46] "POST /loginscript/ HTTP/1.1" 200 4
[04/Oct/2016 14:02:46] "GET /ehealth/ HTTP/1.1" 302 0
Hey we are in login
</code></pre>
<p>So the user is logged in and then redirected back to login page as unlogged</p>
| 0 | 2016-10-04T12:08:28Z | 39,852,098 | <p>Use this code snippet:</p>
<pre><code> def index(request):
if not request.user.is_authenticated():
return redirect('http://127.0.0.1:8000/login/')
template="index.html"
return render (request=request, template_name=template)
</code></pre>
| 2 | 2016-10-04T12:16:45Z | [
"python",
"ajax",
"django",
"csrf"
]
|
Django doesn't keep User logged in between views | 39,851,919 | <p>I am quite new to web programming and django especially. I am trying to implement symple login service using Ajax. The user seems to be logged in succesfully however when the view is changed he uppears ulogged again. </p>
<p>Appreciate any help.
Thanks.</p>
<p>Login template:</p>
<pre><code><form class="login-form" action="">
{% csrf_token %}
<input type="text" id="usernamelog" />
<input type="password" id="pwdlogin" />
<button onclick="login(event)">login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
</code></pre>
<p>Login Ajax:</p>
<pre><code>function login(e) {
e.preventDefault();
var username = $("#usernamelog").val();
var pwd = $("#pwdlogin").val();
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url : "/loginscript/",
type : "post",
data : {
username: username,
password : pwd,
}
}).done(function(data) {
if (data == "good") {
document.getElementById('usernamelog').value ="good";
window.location='../ehealth'
}else{
document.getElementById('usernamelog').value ="bad";
}
});
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
</code></pre>
<p>Loginscript view:</p>
<pre><code>def loginscript(request):
#c = {}
#c.update(csrf(request))
print >> sys.stderr,"script entered"
username = request.POST['username']
password = request.POST['password']
print >> sys.stderr, username
user = authenticate(username=username, password=password)
if user is not None:
login(request=request,user=user)
if User.is_authenticated:
print >> sys.stderr,"should be good actually"
else:
print >> sys.stderr, "Still not"
return HttpResponse("good")
else:
print >> sys.stderr,"Should be bad"
return HttpResponse("bad")
</code></pre>
<p>Ehealth view:</p>
<pre><code>def index(request):
check=User.is_authenticated
if check!=True:
return redirect('http://127.0.0.1:8000/login/')
template="index.html"
return render (request=request, template_name=template)
</code></pre>
<p>The log I get: </p>
<pre><code>Hey we are in login
[04/Oct/2016 14:02:42] "GET /login/ HTTP/1.1" 200 6881
script entered
Andrey
should be good actually
[04/Oct/2016 14:02:46] "POST /loginscript/ HTTP/1.1" 200 4
[04/Oct/2016 14:02:46] "GET /ehealth/ HTTP/1.1" 302 0
Hey we are in login
</code></pre>
<p>So the user is logged in and then redirected back to login page as unlogged</p>
| 0 | 2016-10-04T12:08:28Z | 39,852,102 | <p><code>User.is_authenticated</code> is always true by definition, because you're calling it on the class. You need to check the method on the actual user instance: in your login view that is <code>user</code>, but in the index view that will be <code>request.user</code>.</p>
<p>However an even easier way to check the authentication in the index view is to use the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator" rel="nofollow"><code>login_required</code> decorator</a>.</p>
| 2 | 2016-10-04T12:16:49Z | [
"python",
"ajax",
"django",
"csrf"
]
|
Django doesn't keep User logged in between views | 39,851,919 | <p>I am quite new to web programming and django especially. I am trying to implement symple login service using Ajax. The user seems to be logged in succesfully however when the view is changed he uppears ulogged again. </p>
<p>Appreciate any help.
Thanks.</p>
<p>Login template:</p>
<pre><code><form class="login-form" action="">
{% csrf_token %}
<input type="text" id="usernamelog" />
<input type="password" id="pwdlogin" />
<button onclick="login(event)">login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
</code></pre>
<p>Login Ajax:</p>
<pre><code>function login(e) {
e.preventDefault();
var username = $("#usernamelog").val();
var pwd = $("#pwdlogin").val();
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url : "/loginscript/",
type : "post",
data : {
username: username,
password : pwd,
}
}).done(function(data) {
if (data == "good") {
document.getElementById('usernamelog').value ="good";
window.location='../ehealth'
}else{
document.getElementById('usernamelog').value ="bad";
}
});
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
</code></pre>
<p>Loginscript view:</p>
<pre><code>def loginscript(request):
#c = {}
#c.update(csrf(request))
print >> sys.stderr,"script entered"
username = request.POST['username']
password = request.POST['password']
print >> sys.stderr, username
user = authenticate(username=username, password=password)
if user is not None:
login(request=request,user=user)
if User.is_authenticated:
print >> sys.stderr,"should be good actually"
else:
print >> sys.stderr, "Still not"
return HttpResponse("good")
else:
print >> sys.stderr,"Should be bad"
return HttpResponse("bad")
</code></pre>
<p>Ehealth view:</p>
<pre><code>def index(request):
check=User.is_authenticated
if check!=True:
return redirect('http://127.0.0.1:8000/login/')
template="index.html"
return render (request=request, template_name=template)
</code></pre>
<p>The log I get: </p>
<pre><code>Hey we are in login
[04/Oct/2016 14:02:42] "GET /login/ HTTP/1.1" 200 6881
script entered
Andrey
should be good actually
[04/Oct/2016 14:02:46] "POST /loginscript/ HTTP/1.1" 200 4
[04/Oct/2016 14:02:46] "GET /ehealth/ HTTP/1.1" 302 0
Hey we are in login
</code></pre>
<p>So the user is logged in and then redirected back to login page as unlogged</p>
| 0 | 2016-10-04T12:08:28Z | 39,852,186 | <p>There are quite a number of problems with your code.</p>
<ol>
<li><p>You're calling (no not calling, I'll get to that) <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated" rel="nofollow"><code>is_authenticated</code></a> from the user class (<em>Capital U</em> in <code>User</code>) and not from the user instance which you're trying to log in i.e. <code>user.is_authenticated</code>.</p></li>
<li><p>The <code>is_authenticated</code> attribute is a method in versions of Django < 1.10. If you're with a version less than 1.10, you should call the method using double parenthesis</p></li>
</ol>
| 1 | 2016-10-04T12:20:28Z | [
"python",
"ajax",
"django",
"csrf"
]
|
Iterate through all rows Smartsheet API Python | 39,851,922 | <p>I am trying to iterate through all the rows in a sheet, but it seems that simply using .rows is limited to returning 100 items.</p>
<pre><code>for temp_row in inventory.rows:
x += 1
print x #X will always return <= 100
</code></pre>
<p>No matter how many items I have in there.</p>
<p>What am I doing wrong?</p>
<p>Edit: Just to clarify, I am trying to do something to every row, not count them, that is just an example of how i noticed it is only grabbing 100 rows.</p>
| 1 | 2016-10-04T12:08:43Z | 39,854,715 | <p>Sounds like perhaps the SDK is utilizing <em>paging</em> when executing the <strong>Get Sheet</strong> operation -- i.e., it's only returning the first page of results in the response, which defaults to 100 rows. As described in the <a href="http://smartsheet-platform.github.io/api-docs/?python#get-sheet" rel="nofollow">API docs</a>, page size defaults to 100 rows in the <strong>Get Sheet</strong> response, unless specified otherwise by the request. (In the docs, see the description for the <strong>pageSize</strong> and <strong>page</strong> parameters.) </p>
<p>I'd suggest that you review the SDK for the ability to specify <strong>pageSize</strong> and/or <strong>page</strong> when calling the <strong>Get Sheet</strong> operation.</p>
| 0 | 2016-10-04T14:18:38Z | [
"python",
"smartsheet-api"
]
|
Iterate through all rows Smartsheet API Python | 39,851,922 | <p>I am trying to iterate through all the rows in a sheet, but it seems that simply using .rows is limited to returning 100 items.</p>
<pre><code>for temp_row in inventory.rows:
x += 1
print x #X will always return <= 100
</code></pre>
<p>No matter how many items I have in there.</p>
<p>What am I doing wrong?</p>
<p>Edit: Just to clarify, I am trying to do something to every row, not count them, that is just an example of how i noticed it is only grabbing 100 rows.</p>
| 1 | 2016-10-04T12:08:43Z | 39,862,677 | <p>By default, get_sheet will return a page with 100 rows. Include the flag: <code>includeAll=true</code> to return all rows.</p>
<p>See the <a href="http://smartsheet-platform.github.io/api-docs/?python#paging" rel="nofollow">documentation on paging</a> for more info.</p>
| 0 | 2016-10-04T22:23:14Z | [
"python",
"smartsheet-api"
]
|
Iterate through all rows Smartsheet API Python | 39,851,922 | <p>I am trying to iterate through all the rows in a sheet, but it seems that simply using .rows is limited to returning 100 items.</p>
<pre><code>for temp_row in inventory.rows:
x += 1
print x #X will always return <= 100
</code></pre>
<p>No matter how many items I have in there.</p>
<p>What am I doing wrong?</p>
<p>Edit: Just to clarify, I am trying to do something to every row, not count them, that is just an example of how i noticed it is only grabbing 100 rows.</p>
| 1 | 2016-10-04T12:08:43Z | 39,862,714 | <p>It is important to note that when making the request to the Smartsheet API directly rather than via the Python SDK the default response is to include all rows of the sheet without needing to include <code>page</code> or <code>pageSize</code> parameters.</p>
| 0 | 2016-10-04T22:27:05Z | [
"python",
"smartsheet-api"
]
|
Replacing different substrings without clear pattern in python | 39,852,123 | <p>I need to replace part of some queries (strings) which <strong>don't</strong> always have the same substring to replace. </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """
</code></pre>
<p>I want to replace the part regarding date after <em>group by</em>. </p>
<p>This part could be any of the following strings:</p>
<pre><code>'YEAR(utimestamp), MONTH(utimestamp), DAY(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp),'
'YEAR(utimestamp),'
</code></pre>
<p>My idea is to search for "<em>(utimestamp),</em>" and get the part from the left (YEAR, DAY, WEEK or MONTH) searching for the first blank space in the left. After having those removed I want to insert another substring, but how can I insert this substring now that I have blank spaces where the new substring should go.</p>
<p>I thought of getting the index everytime I removed a string and once there's no more to remove insert the substring there but I think I'm complicating things.</p>
<p>Is there an easier, neat way of doing this? Am I missing something?</p>
<p><strong>EXAMPLE:</strong></p>
<p>Input string that needs replacement:</p>
<p>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """</p>
<p>or </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), id """
</code></pre>
<p>or</p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp), id """
</code></pre>
<p>etc.</p>
<p>Desired result:</p>
<pre><code>query_replaced = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by MY_COOL_STRING, id """
</code></pre>
<p>If should work for all those cases (and more, the ones stated before)</p>
<p>Following @Efferalgan answer I came up with this:</p>
<pre><code>query_1 = query.split("group by")[0]
utimestamp_list = query.split("(utimestamp)")
l = len(utimestamp_list)
query_2 = utimestamp_list[l-1]
query_3 = query_1 + " group by MY_COOL_STRING" + query_2
</code></pre>
| 2 | 2016-10-04T12:17:52Z | 39,852,317 | <p>You may use <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a> of regex to achieve it:</p>
<pre><code>>>> import re
>>> replace_with = 'HELLO'
>>> new_string = re.sub('group by\s\w+\(utimestamp\)', "group_by"+replace_with, query)
# Value of new_string: SELECT as utimestamp, sum(value) as value
# from table
# where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
# group by HELLO, HELLO, id
</code></pre>
<p>where <code>replace_with</code> is the content you need to update with the pattern <code>'\w+\(utimestamp\)'</code> and <code>query</code> is the string you mentioned in the code.</p>
<p>Here, <code>\w+</code> means alphabets with occurence of one or more, whereas <code>\(utimestamp\)</code> along with that denotes, words followed by the string <code>(utimestamp)</code>.</p>
<p><strong>EDIT</strong>:</p>
<p>As is mentioned in the comment, to replace all instances of the <code>timestamp</code> in the <code>query</code>, regex expression should be like:</p>
<pre><code>re.sub('group by\s\w+\(utimestamp\)(,\s*\w+\(utimestamp\))*', "group_by" + replace_with, query)
# Returned Value:
# SELECT DATE(utimestamp) as utimestamp, sum(value) as value from table
# where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
# group by HELLO, id
</code></pre>
| 0 | 2016-10-04T12:26:01Z | [
"python",
"string",
"replace"
]
|
Replacing different substrings without clear pattern in python | 39,852,123 | <p>I need to replace part of some queries (strings) which <strong>don't</strong> always have the same substring to replace. </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """
</code></pre>
<p>I want to replace the part regarding date after <em>group by</em>. </p>
<p>This part could be any of the following strings:</p>
<pre><code>'YEAR(utimestamp), MONTH(utimestamp), DAY(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp),'
'YEAR(utimestamp),'
</code></pre>
<p>My idea is to search for "<em>(utimestamp),</em>" and get the part from the left (YEAR, DAY, WEEK or MONTH) searching for the first blank space in the left. After having those removed I want to insert another substring, but how can I insert this substring now that I have blank spaces where the new substring should go.</p>
<p>I thought of getting the index everytime I removed a string and once there's no more to remove insert the substring there but I think I'm complicating things.</p>
<p>Is there an easier, neat way of doing this? Am I missing something?</p>
<p><strong>EXAMPLE:</strong></p>
<p>Input string that needs replacement:</p>
<p>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """</p>
<p>or </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), id """
</code></pre>
<p>or</p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp), id """
</code></pre>
<p>etc.</p>
<p>Desired result:</p>
<pre><code>query_replaced = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by MY_COOL_STRING, id """
</code></pre>
<p>If should work for all those cases (and more, the ones stated before)</p>
<p>Following @Efferalgan answer I came up with this:</p>
<pre><code>query_1 = query.split("group by")[0]
utimestamp_list = query.split("(utimestamp)")
l = len(utimestamp_list)
query_2 = utimestamp_list[l-1]
query_3 = query_1 + " group by MY_COOL_STRING" + query_2
</code></pre>
| 2 | 2016-10-04T12:17:52Z | 39,852,346 | <p>From what you asked, I would go for</p>
<pre><code>query = query.split("group by")[0] + " group by MY_COOL_STRING" + query.split("(utimestamp)")[-1]
</code></pre>
<p>It concatenates the part before the <code>group by</code>, then <code>MY_COOL_STRING</code> and then first thing before the first <code>(utimestamp)</code>.</p>
| 0 | 2016-10-04T12:27:56Z | [
"python",
"string",
"replace"
]
|
Replacing different substrings without clear pattern in python | 39,852,123 | <p>I need to replace part of some queries (strings) which <strong>don't</strong> always have the same substring to replace. </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """
</code></pre>
<p>I want to replace the part regarding date after <em>group by</em>. </p>
<p>This part could be any of the following strings:</p>
<pre><code>'YEAR(utimestamp), MONTH(utimestamp), DAY(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp),'
'YEAR(utimestamp), MONTH(utimestamp),'
'YEAR(utimestamp),'
</code></pre>
<p>My idea is to search for "<em>(utimestamp),</em>" and get the part from the left (YEAR, DAY, WEEK or MONTH) searching for the first blank space in the left. After having those removed I want to insert another substring, but how can I insert this substring now that I have blank spaces where the new substring should go.</p>
<p>I thought of getting the index everytime I removed a string and once there's no more to remove insert the substring there but I think I'm complicating things.</p>
<p>Is there an easier, neat way of doing this? Am I missing something?</p>
<p><strong>EXAMPLE:</strong></p>
<p>Input string that needs replacement:</p>
<p>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """</p>
<p>or </p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), id """
</code></pre>
<p>or</p>
<pre><code>query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp), id """
</code></pre>
<p>etc.</p>
<p>Desired result:</p>
<pre><code>query_replaced = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value
from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by MY_COOL_STRING, id """
</code></pre>
<p>If should work for all those cases (and more, the ones stated before)</p>
<p>Following @Efferalgan answer I came up with this:</p>
<pre><code>query_1 = query.split("group by")[0]
utimestamp_list = query.split("(utimestamp)")
l = len(utimestamp_list)
query_2 = utimestamp_list[l-1]
query_3 = query_1 + " group by MY_COOL_STRING" + query_2
</code></pre>
| 2 | 2016-10-04T12:17:52Z | 39,853,528 | <p>If I'm not mistaken, you don't want to get rid of the <code>(utimestamp)</code> part, only the <code>YEAR</code>, <code>MONTH</code>, etc. Or maybe I got it wrong but this solution is trivial to adapt in that case: just adapt the <code>rep</code> dict to cover your needs.</p>
<p>In any case, I would use regular expressions for that. This should take care of what you want (I think) in a single pass and in a (fairly) simple way.</p>
<pre class="lang-python prettyprint-override"><code>import re
rep = {
'YEAR': 'y',
'MONTH': 'm',
'WEEK': 'w',
'DAY': 'd',
}
query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by YEAR(utimestamp), MONTH(utimestamp), id """
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
replaced = pattern.sub(lambda m: rep[re.escape(m.group(0))], query)
print("Processed query: {}\n".format(replaced))
</code></pre>
<p>That's just the basic example. Here's a more complete one with comments explaining what the code does, including a test at the end for all the possible patterns you mentioned:</p>
<pre class="lang-python prettyprint-override"><code>import re
# Several possible patterns like you mentioned.
# Only used for testing further down.
patterns = [
'YEAR(utimestamp), MONTH(utimestamp), DAY(utimestamp)',
'YEAR(utimestamp), MONTH(utimestamp), WEEK(utimestamp)',
'YEAR(utimestamp), MONTH(utimestamp)',
'YEAR(utimestamp)'
]
# These are the several patterns to be matched and their replacements.
# The keys are the patterns to match and the values are what you want
# to replace them with.
rep = {
'YEAR': 'y',
'MONTH': 'm',
'WEEK': 'w',
'DAY': 'd',
}
# The query string template, where we'll replace {} with each of the patterns.
query = """ SELECT DATE(utimestamp) as utimestamp, sum(value) as value from table
where utimestamp BETWEEN '2000-06-28 00:00:00' AND '2000-07-05 00:00:00'
group by {}, id """
# A dictionary with escaped patterns (the keys) suitable for use in regex.
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
# We join each possible pattern (the keys in the rep dict) with | so that the
# regex engine considers them all when matching, i.e., "hey, regex engine,
# please match YEAR or MONTH or WEEK or DAY". This builds the matching patter
# we'll use and we also pre-compile the regex to make it faster.
pattern = re.compile("|".join(rep.keys()))
# This is the trick part: we're using pattern.sub() to replace our pattern from
# above with what we want (the values in the rep dict). We're telling the regex
# engine to call a function for each occurrence of the pattern in order to get
# the value we're replacing it with. In our case, we want to get the value from
# the rep dict, using the key which is the found match. m is the match object,
# m.group(0) is the first match, re.escape() escapes the value and we finally
# use this as the key to fetch the value from the rep dict.
q = query.format(patterns[0])
print("Query: {}\n".format(q))
replaced = pattern.sub(lambda m: rep[re.escape(m.group(0))], q)
print("Processed query: {}\n".format(replaced))
# Now to test it with the examples you gave let's iterate over the patterns
# dict, form a new query string using each of them and run the regex against
# each one.
print("###########################")
print("Test each pattern:\n")
print("---------------------------")
for p in patterns:
q = query.format(p)
print("Pattern: {}".format(p))
print("Original query: {}\n".format(q))
replaced = pattern.sub(lambda m: rep[re.escape(m.group(0))], q)
print("Processed query: {}\n".format(replaced))
print("---------------------------\n")
</code></pre>
<p>You can read more about how <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a> works.</p>
| 0 | 2016-10-04T13:23:05Z | [
"python",
"string",
"replace"
]
|
Curses breaks a time.sleep() when terminal's size has been changed | 39,852,148 | <p>I faced with behavior which I cannot understand.</p>
<pre><code>import curses
import time
myscreen = curses.initscr()
y, x = myscreen.getmaxyx()
i = 0
while y >= 24 and x >= 80 and i <= 23:
myscreen.addstr(i, 0, 'Python curses in action!')
myscreen.refresh()
y, x = myscreen.getmaxyx()
i += 1
time.sleep(1)
curses.endwin()
</code></pre>
<p>This code will write 24 strings with 1 second interval and it's ok.
But when I will begin to change size of terminal window during execution, strings will appear on screen much faster then 1 string per second.
Could you please explain this behavior and maybe get advice how to "protect" my time.sleep()?
Thanks.</p>
<p>P.S. without curses sleep() works fine.</p>
| 0 | 2016-10-04T12:18:53Z | 39,852,401 | <p>From the documentation of <code>time.sleep()</code>:</p>
<blockquote>
<p>Suspend execution of the current thread for the given number of
seconds. The argument may be a floating point number to indicate a
more precise sleep time. <strong>The actual suspension time may be less than
that requested because any caught signal will terminate the sleep()
following execution of that signalâs catching routine</strong>. Also, the
suspension time may be longer than requested by an arbitrary amount
because of the scheduling of other activity in the system.</p>
</blockquote>
| 0 | 2016-10-04T12:30:29Z | [
"python",
"python-2.7",
"ncurses",
"python-curses"
]
|
How to 'react' to the response of a request using Python | 39,852,178 | <p>I am using Python requests to get information from the mobile website of the german railways company (<a href="https://mobile.bahn.de/bin/mobil/query.exe/dox" rel="nofollow">https://mobile.bahn.de/bin/mobil/query.exe/dox</a>')</p>
<p>For instance: </p>
<pre><code>import requests
query = {'S':'Stuttgart Hbf', 'Z':'München Hbf'}
rsp = requests.get('https://mobile.bahn.de/bin/mobil/query.exe/dox', params=query)
</code></pre>
<p>which in this case gives the correct page.</p>
<p>However, using the following query:</p>
<pre><code>query = {'S':'Cottbus', 'Z':'München Hbf'}
</code></pre>
<p>It gives another response, where the user is required to choose one of the given options (The server is confused about the starting stations, since there are many beginning with 'Cottbus')</p>
<p>Now, my question is: given this response, how can I choose one of the given options, and then repeat the request without getting this error ? </p>
<p>I tried to look at the cookies, to use a session instead of a simple get request. But nothing worked so far.</p>
<p>I hope you can help me.</p>
<p>Thanks.</p>
| 1 | 2016-10-04T12:20:19Z | 39,856,528 | <p>You can use Beautifulsoup to parse the response and get the options if there is a select on the response: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
query = {'S': u'Cottbus', 'Z': u'München Hbf'}
rsp = requests.get('https://mobile.bahn.de/bin/mobil/query.exe/dox', params=query)
soup = BeautifulSoup(rsp.content, 'lxml')
# check if has choice dropdown
if soup.find('select'):
# Get list of tuples with text and input values that you will nee do use in the next POST request
options_value = [(option['value'], option.text) for option in soup.find_all('option')]
</code></pre>
| 0 | 2016-10-04T15:41:37Z | [
"python",
"python-requests"
]
|
dopy.manager.DoError: Unable to authenticate you | 39,852,205 | <p>I'm trying to configure a Virtual Machine(with Vagrant and Ansible), that needs a file.py to the full correct configuration of this machine (according to the book that I'm studying),I'm was using the DigitalOcean API V2, but as I have no a valid credit card my account is bloked,so I had to change DigitalOcean to AWS,as the company where I work have an account with AWS,now I take the 'client id' and 'api key' from AWS VM,so the foregoing problems returned...when I try use the "python file.py" command the output says again: </p>
<blockquote>
<p>dopy.manager.DoError: Unable to authenticate you.</p>
</blockquote>
<pre><code>**the file.py:**
"""
dependencias:
sudo pip install dopy pyopenssl ndg-httpsclient pyasn1
"""
import os
from dopy.manager import DoManager
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
api_version = os.getenv("DO_API_VERSION")
api_token=os.getenv("DO_API_KEY")
#do = DoManager(cliend_id, api_key)
do = DoManager(None, api_token, api_version=2)
keys = do.all_ssh_keys()
print "ssh key name\tid"
for key in keys:
print "%s\t%d" % (key["name"], key["id"])
print "Image name\tid"
imgs = do.all_images()
for img in imgs:
if img["slug"] == "ubuntu-14-04-x64":
print "%s\t%d" % (img["name"], img["id"])
print "Region name\tid"
regions = do.all_regions()
for region in regions:
if region["slug"] == "nyc2":
print "%s\t%d" % (region["slug"], region["id"])
print "Size name\tid"
sizes = do.sizes()
for size in sizes:
if size["slug"] == "512mb":
print "%s\t%d" % (size["slug"], size["id"])
</code></pre>
<p>I appreciate any help. </p>
| 0 | 2016-10-04T12:21:18Z | 39,852,470 | <p>Try to remove quotes from api_token:</p>
<pre><code>do = DoManager(None, api_token, api_version=2)
</code></pre>
<p>Otherwise your token is always literal string <em>api_token</em>, not a variable api_token.</p>
| 1 | 2016-10-04T12:33:40Z | [
"python",
"vagrant",
"ansible"
]
|
It is not safe to use pixmaps outside the GUI thread | 39,852,240 | <p>rebz! This code is not working - icon full transperent. I'll never know what to do.</p>
<pre><code>class SystemTrayIcon:
def __init__(self, icon_app, icon_pause, icon_work, parent=None):
self.STATUS_WORK = 2
self.STATUS_PAUSE = 1
self.STATUS_APP = 0
self.tray = QSystemTrayIcon(icon_app, parent)
api.gui.connector.connect_slot(object_name=)
self.icons = {
0:icon_app,
1:icon_pause,
2:icon_work
}
self.menu = QMenu(parent)
self.tray.setContextMenu(self.menu)
print self.tray.thread()
# self.set_status(2)
def set_status(self, status):
self.tray.setIcon(self.icons[status])
</code></pre>
<p>I call method <strong>set_status</strong> in second thread. Help me please (:</p>
| -2 | 2016-10-04T12:22:42Z | 39,852,881 | <p>I'm assuming the title...</p>
<blockquote>
<p>It is not safe to use pixmaps outside the GUI thread</p>
</blockquote>
<p>is the error/warning message you see when the code runs.</p>
<p>In general, no, it's not safe to manipulate a <code>QPixmap</code> on any thread other that that on which the <code>QApplication</code> itself was instantiated. This is because the <code>QPixmap</code> implementation is (for most Os's) tightly bound to the underlying graphics system.</p>
<p>If you have code on a non-gui thread that wants to change/set an icon then use a queued signal or similar mechanism.</p>
| 0 | 2016-10-04T12:53:20Z | [
"python",
"multithreading",
"qt"
]
|
It is not safe to use pixmaps outside the GUI thread | 39,852,240 | <p>rebz! This code is not working - icon full transperent. I'll never know what to do.</p>
<pre><code>class SystemTrayIcon:
def __init__(self, icon_app, icon_pause, icon_work, parent=None):
self.STATUS_WORK = 2
self.STATUS_PAUSE = 1
self.STATUS_APP = 0
self.tray = QSystemTrayIcon(icon_app, parent)
api.gui.connector.connect_slot(object_name=)
self.icons = {
0:icon_app,
1:icon_pause,
2:icon_work
}
self.menu = QMenu(parent)
self.tray.setContextMenu(self.menu)
print self.tray.thread()
# self.set_status(2)
def set_status(self, status):
self.tray.setIcon(self.icons[status])
</code></pre>
<p>I call method <strong>set_status</strong> in second thread. Help me please (:</p>
| -2 | 2016-10-04T12:22:42Z | 39,872,091 | <p>solved a problem:</p>
<pre><code>class SystemTrayIcon:
def __init__(self, icon_app, icon_pause, icon_work, parent=None):
self.STATUS_APP = 0
self.STATUS_PAUSE = 1
self.STATUS_WORK = 2
self.tray = QSystemTrayIcon(icon_app, parent)
self.icons = {
0:icon_app,
1:icon_pause,
2:icon_work
}
self.menu = QMenu(parent)
self.tray.setContextMenu(self.menu)
print self.tray.thread()
self.tray.connect(self.tray, SIGNAL("change_status(int)"), self.set_status)
# self.set_status(2)
def set_status(self, status):
self.tray.setIcon(self.icons[status])
</code></pre>
<p>and another thread:
<code>tray.emit(SIGNAL("change_status(int)"), STATUS_PAUSE)</code></p>
| 0 | 2016-10-05T10:55:45Z | [
"python",
"multithreading",
"qt"
]
|
Scan range of IP with ping command and give specific result | 39,852,367 | <p>hello i want to create a ping script on python where it will ping 3 ips and give me out only the result if the server is alive i want to give me the packet loss and generate if the ms time is less than 100 . I have no pythong expert skills</p>
| 0 | 2016-10-04T12:28:59Z | 39,852,605 | <p>Just Change the hostname with List and provide the ip address in the code given in the another StackOverflow thread</p>
<p><a href="http://stackoverflow.com/questions/26468640/python-function-to-test-ping">Check out this</a> </p>
<p>Sample Code</p>
<pre><code>import subprocess
hosts = ['link1','link2','link3']
for host in hosts:
result = subprocess.check_output("ping google.com")
print result
# do some process on result
</code></pre>
| 0 | 2016-10-04T12:40:12Z | [
"python",
"windows",
"cmd",
"ip",
"ping"
]
|
WxPython - Binding an Event to a Randomly changing value - Algorithm Required | 39,852,416 | <p>I have a textBox on my WxPython GUI, where I am displaying a changing value (Which changes every 100 mS). I have two buttons - Button A, Button B. </p>
<p>Initial condition: Textbox has a value of between 2000-3000. Button A is enabled, Button B is disabled.</p>
<p>I need the following sequence of events to go on:
The user presses the Button A. After approximately 20 seconds or some user defined time (completely variable based on the user/ type of work he is doing), the textBox value goes under less 50. </p>
<p>Once the textBox value goes less than 50 - Button B should be enabled. </p>
<p>Currently this is my following code, where I am pressing the Button A - waiting for the textBox value to less than 50. Then enable the Button B - and it is not working. The button B is not getting enabled. I tried using other means, but they are leaving to an unresponsive GUI. My Button A is - DONE, Button B is START. textBox is pressure_text_control.</p>
<pre><code>def OnDone(self, event):
self.WriteToController([0x04],'GuiMsgIn')
self.status_text.SetLabel('PRESSURE CALIBRATION DONE \n DUMP PRESSURE')
self.led1.SetBackgroundColour('GREY')
self.add_pressure.Disable()
while self.pressure_text_control.GetValue() < 50:
wx.CallAfter(self.StartEnable, 'Enabling start button')
#self.start.Enable()
def StartEnable(self):
self.start.Enable()
</code></pre>
| 0 | 2016-10-04T12:31:15Z | 39,877,045 | <p>You haven't supplied sufficient code to be able to see what is going on.<br>
We don't know for example if <code>self.pressure_text_control.GetValue() < 50</code> is in fact less than 50, given that you say the value is changing every 100mS.</p>
<p>If your issue is really about the fact that the GUI becomes unresponsive, then investigate <code>wx.Timer()</code><br>
See:<br>
<a href="http://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/" rel="nofollow">http://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/</a></p>
<p>The Timer class allows you to execute code at specified intervals, which allows you to process one or more periodic events (you can declare multiple <code>timers</code>), as long as they are not long or blocking processes, yet leave the GUI responsive.</p>
<p>mocked up as follows:</p>
<pre><code> self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.check, self.timer)
def StartmyButton(self):
self.start.Enable()
self.timer.Start(100)
def check(self, event):
"check you input here and process any results"
</code></pre>
| 0 | 2016-10-05T14:41:45Z | [
"python",
"wxpython"
]
|
Why isn't there a simple group_by in Django? | 39,852,536 | <p>I have a model:</p>
<pre><code>class Person(models.MyModel):
department = models.ForeignKey('Department')
start_date = models.DateField()
class Department(models.SomeModel):
name = models.CharField()
</code></pre>
<p>I want, in my template, to be able to create a simple table where I can group people by two attributes: <code>department__name</code> and <code>start_date</code>.</p>
<p>In this way, people with the same department name which started in the same date would be displayed in the same row.</p>
<p>I know there is a template tag called <code>regroup</code>, but I can only give three arguments, and only one of them can be the <code>grouper</code>.</p>
<p>Well, I thought I could do this query in my <code>view.py</code> with something like this: </p>
<pre><code>Person.objects.all().group_by('start_date','department__name')
</code></pre>
<p>But I was wrong. There is no such method.</p>
<p>Any way to achieve this in a simple way?</p>
<h3>Edit 1</h3>
<p>By the same attribute I mean the classe's objects. For example:</p>
<p>Let's suppose this is the database:</p>
<p>Name | Department | Start date</p>
<p>Bob | Sales | 12-12-2012</p>
<p>Sara | Sales | 12-12-2012</p>
<p>John | Finance | 13-11-2012</p>
<p>Then the of the following function would be something like this:</p>
<p>function: </p>
<pre><code>Person.objects.all().group_by('department__name', 'start_date')
</code></pre>
<p>output: </p>
<p>Sales | 12-12-2012 | Bob, Sara</p>
<p>Finance | 13-11-2012 | John</p>
<p>This way, Sara and John have been grouped by department <strong>AND</strong> start date.</p>
| 0 | 2016-10-04T12:36:45Z | 39,853,918 | <p>The way you can do your group_by in django is using <code>values</code> and <code>aggregate</code>.</p>
<p>For example, you can achieve the result you want by making it like this:</p>
<pre><code>Person.objects.all().values('department__name', 'start_date').annotate(Count('start_date'))
</code></pre>
<p>However I believe you can not get all the names in a single string, and AFAIK you also could not do it in a simple <code>GROUP BY</code> on mysql, for example.</p>
<p>EDIT: just now I've understood that you want to group_by two values, so you would do something like:</p>
<pre><code> Person.objects.all().values('department__name', 'start_date')\
.annotate(Count('start_date'))\
.annotate(Count('department__name'))\
.values_list('department__name','start_date')
</code></pre>
| 0 | 2016-10-04T13:42:13Z | [
"python",
"django"
]
|
Why isn't there a simple group_by in Django? | 39,852,536 | <p>I have a model:</p>
<pre><code>class Person(models.MyModel):
department = models.ForeignKey('Department')
start_date = models.DateField()
class Department(models.SomeModel):
name = models.CharField()
</code></pre>
<p>I want, in my template, to be able to create a simple table where I can group people by two attributes: <code>department__name</code> and <code>start_date</code>.</p>
<p>In this way, people with the same department name which started in the same date would be displayed in the same row.</p>
<p>I know there is a template tag called <code>regroup</code>, but I can only give three arguments, and only one of them can be the <code>grouper</code>.</p>
<p>Well, I thought I could do this query in my <code>view.py</code> with something like this: </p>
<pre><code>Person.objects.all().group_by('start_date','department__name')
</code></pre>
<p>But I was wrong. There is no such method.</p>
<p>Any way to achieve this in a simple way?</p>
<h3>Edit 1</h3>
<p>By the same attribute I mean the classe's objects. For example:</p>
<p>Let's suppose this is the database:</p>
<p>Name | Department | Start date</p>
<p>Bob | Sales | 12-12-2012</p>
<p>Sara | Sales | 12-12-2012</p>
<p>John | Finance | 13-11-2012</p>
<p>Then the of the following function would be something like this:</p>
<p>function: </p>
<pre><code>Person.objects.all().group_by('department__name', 'start_date')
</code></pre>
<p>output: </p>
<p>Sales | 12-12-2012 | Bob, Sara</p>
<p>Finance | 13-11-2012 | John</p>
<p>This way, Sara and John have been grouped by department <strong>AND</strong> start date.</p>
| 0 | 2016-10-04T12:36:45Z | 39,854,345 | <p>This isn't what SQL group by is -- in SQL you would have to choose which of Bob or Sara would be returned for the Sales - 12/12 row, you couldn't have both. I'd do this processing in Python, there's no real SQL for what you want.</p>
<p>For instance, keep a dictionary of (department name, date) tuples and a list of names as values:</p>
<pre><code>from collections import defaultdict
table = defaultdict(list)
for department, date, name in Person.objects.values_list(
'department__name', 'start_date', 'name'):
table[(department, date)].append(name)
</code></pre>
| 1 | 2016-10-04T14:01:25Z | [
"python",
"django"
]
|
Delete all characters after a backslash in python? | 39,852,551 | <p>I have a for loop that changes the string current_part.
Current_part should have a format of 1234 but sometimes it has the format of 1234/gg</p>
<p>Other formats exist but in all of them, anything after the backlash need to be deleted.</p>
<p>I found a similar example below so I tried it but it didn't work. How can I fix this? Thanks</p>
<p><code>current_part = re.sub(r"\B\\\w+", "", str(current_part))</code></p>
| 0 | 2016-10-04T12:37:25Z | 39,852,575 | <p>No need for regexes here, why don't you simply go for <code>current_part = current_part.split('/')[0]</code> ?</p>
| 3 | 2016-10-04T12:38:44Z | [
"python"
]
|
Delete all characters after a backslash in python? | 39,852,551 | <p>I have a for loop that changes the string current_part.
Current_part should have a format of 1234 but sometimes it has the format of 1234/gg</p>
<p>Other formats exist but in all of them, anything after the backlash need to be deleted.</p>
<p>I found a similar example below so I tried it but it didn't work. How can I fix this? Thanks</p>
<p><code>current_part = re.sub(r"\B\\\w+", "", str(current_part))</code></p>
| 0 | 2016-10-04T12:37:25Z | 39,852,612 | <p>Find the position of '/' and replace your string with all characters preceding '/'</p>
<pre><code>st = "12345/gg"
n = st.find('/');
st = st[:n]
print(st)
</code></pre>
| 1 | 2016-10-04T12:40:46Z | [
"python"
]
|
Delete all characters after a backslash in python? | 39,852,551 | <p>I have a for loop that changes the string current_part.
Current_part should have a format of 1234 but sometimes it has the format of 1234/gg</p>
<p>Other formats exist but in all of them, anything after the backlash need to be deleted.</p>
<p>I found a similar example below so I tried it but it didn't work. How can I fix this? Thanks</p>
<p><code>current_part = re.sub(r"\B\\\w+", "", str(current_part))</code></p>
| 0 | 2016-10-04T12:37:25Z | 39,852,633 | <p>You can split your string using <code>string.split()</code></p>
<p>for example:</p>
<pre><code>new_string = current_part.split("/")[0]
</code></pre>
| 1 | 2016-10-04T12:41:39Z | [
"python"
]
|
How to access an array using raw_input in python | 39,852,590 | <p>So, I have a python script which requires an input from the terminal. I have 20 different arrays and I want to print the array based on the input.</p>
<p>This is the code minus the different arrays.</p>
<pre><code>homeTeam = raw_input()
awayTeam = raw_input()
a = (homeTeam[0])+(awayTeam[3])/2
b = (hometeam[1])+(awayTeam[2])/2
</code></pre>
<p>So, effectively what I want to happen is that homeTeam/awayTeam will take the data of the array that is typed. </p>
<p>Thanks</p>
| 0 | 2016-10-04T12:39:27Z | 39,852,744 | <p>You may take input as the comma separated (or anything unique you like) string. And call <code>split</code> on that unique identifier to get <code>list</code> (In Python <a href="https://docs.python.org/2/library/array.html" rel="nofollow"><code>array</code></a> and <a href="https://www.tutorialspoint.com/python/python_lists.htm" rel="nofollow"><code>list</code></a> are different).</p>
<p>Below is the example:</p>
<pre><code>>>> my_string = raw_input()
a, b, c, d
>>> my_list = my_string.split(', ')
>>> my_list
['a', 'b', 'c', 'd']
</code></pre>
<p>Since you are having your <code>list</code> now, you already know what you need to do with it.</p>
<p><em>Alternatively</em>, you may also extract list from raw_input by using <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofollow"><code>eval</code></a>. But it is highly recommended not to use eval. Read: <a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">Is using eval in Python a bad practice?</a></p>
<p>Below is the example:</p>
<pre><code>>>> my_list = eval(raw_input())
[1, 2, 3, 4, 5]
>>> my_list[2]
3
</code></pre>
| 1 | 2016-10-04T12:46:15Z | [
"python",
"arrays"
]
|
How to access an array using raw_input in python | 39,852,590 | <p>So, I have a python script which requires an input from the terminal. I have 20 different arrays and I want to print the array based on the input.</p>
<p>This is the code minus the different arrays.</p>
<pre><code>homeTeam = raw_input()
awayTeam = raw_input()
a = (homeTeam[0])+(awayTeam[3])/2
b = (hometeam[1])+(awayTeam[2])/2
</code></pre>
<p>So, effectively what I want to happen is that homeTeam/awayTeam will take the data of the array that is typed. </p>
<p>Thanks</p>
| 0 | 2016-10-04T12:39:27Z | 39,852,793 | <p>You can take raw_input() as string and then you can use split function to make it array. While doing arithmetic stuff you need to do type casting. for example,</p>
<pre><code>homeTeam = raw_input() ### 1,2,3,4
homeTeam = homeTeam.split(",")
awayTeam = raw_input() ### 5,6,7,8
awayTeam = awayTeam.split(",")
a = (int(homeTeam[0]) + int(awayTeam[3]))/2
b = (int(hometeam[1]) + int(awayTeam[2]))/2
</code></pre>
| 0 | 2016-10-04T12:49:13Z | [
"python",
"arrays"
]
|
How to access an array using raw_input in python | 39,852,590 | <p>So, I have a python script which requires an input from the terminal. I have 20 different arrays and I want to print the array based on the input.</p>
<p>This is the code minus the different arrays.</p>
<pre><code>homeTeam = raw_input()
awayTeam = raw_input()
a = (homeTeam[0])+(awayTeam[3])/2
b = (hometeam[1])+(awayTeam[2])/2
</code></pre>
<p>So, effectively what I want to happen is that homeTeam/awayTeam will take the data of the array that is typed. </p>
<p>Thanks</p>
| 0 | 2016-10-04T12:39:27Z | 39,852,809 | <p>Instead of 20 individual arrays you could use a dictionary.</p>
<pre><code>d = {"team1": "someValue",
"team2": "anotherValue",
...
}
</code></pre>
<p>Then you can retrieve the values of a team by its name:</p>
<pre><code>x = raw_input("team1")
</code></pre>
<p><code>d[x]</code> will now return <code>"someValue"</code>. </p>
<p>In your particular case, you can use arrays for the values of the dictionary, for example:</p>
<pre><code>d = {"team1": [value1, value2, ...],
"team2": [...],
...
}
</code></pre>
<p>Now <code>d[x]</code> returns the array <code>[value1, value2, ...]</code>.</p>
<h2>Complete example</h2>
<p>Finally, you could wrap all of this into a single function f:</p>
<pre><code>def f():
homeTeam = d[raw_input("Enter home team: ")]
awayTeam = d[raw_input("Enter away team: ")]
a = (homeTeam[0] + awayTeam[3])/2
b = (homeTeam[1] + awayTeam[2])/2
return a, b
</code></pre>
<p>By calling <code>f()</code> the user will be prompted for two team names. And the function will return the values of both teams in form of a tuple.</p>
| 0 | 2016-10-04T12:50:13Z | [
"python",
"arrays"
]
|
Save all files before running custom command in Sublime3 | 39,852,604 | <p>This is a derivative of this question I made some days ago <a href="http://stackoverflow.com/q/39734390/1391441">Save file before running custom command in Sublime3</a>.</p>
<p>I've setup a custom keybind in Sublime Text 3:</p>
<pre><code>{
"keys": ["f5"],
"command": "project_venv_repl"
}
</code></pre>
<p>to run the <code>project_venv_repl.py</code> script (see <a href="http://stackoverflow.com/a/25002696/1391441">here</a> to learn what it does):</p>
<pre class="lang-py prettyprint-override"><code>import sublime_plugin
class ProjectVenvReplCommand(sublime_plugin.TextCommand):
"""
Starts a SublimeREPL, attempting to use project's specified
python interpreter.
"""
def run(self, edit, open_file='$file'):
"""Called on project_venv_repl command"""
# Save all files before running REPL <---- THESE TWO LINES
for open_view in self.view.window().views():
open_view.run_command("save")
cmd_list = [self.get_project_interpreter(), '-i', '-u']
if open_file:
cmd_list.append(open_file)
self.repl_open(cmd_list=cmd_list)
# Other functions...
</code></pre>
<p>This runs the opened file in a <a href="https://github.com/wuub/SublimeREPL" rel="nofollow">SublimeREPL</a> when the <code>f5</code> key is pressed. The two lines below <code># Save all files before running REPL</code> should save all opened files with unsaved changes, before running the REPL (as stated in the <a href="http://stackoverflow.com/a/39734918/1391441">answer</a> to my previous question).</p>
<p>The lines work, ie: they save the files. But they also display two consecutive <em>Save</em> pop-ups, asking me to save the REPL (?):</p>
<pre><code>*REPL* [/home/gabriel/.pyenv/versions/test-env/bin/python -i -u /home/gabriel/Github/test/test.py]
</code></pre>
<p><code>test.py</code> is the file from where the script <code>project_venv_repl</code> was called. After I cancel both pop-ups, the script is executed correctly.</p>
<p>How can I get the <code>project_venv_repl</code> script to save all opened files with unsaved changes before executing, <em>without</em> displaying these annoying <em>Save</em> pop-ups?</p>
<p>(The idea behind all this is to mimic the behavior of <code>Ctrl+B</code>, which will save all unsaved files prior to building the script)</p>
| 1 | 2016-10-04T12:39:59Z | 39,853,064 | <p>The trick is to only save for files that are dirty and exist on disk.</p>
<pre><code># Write out every buffer (active window) with changes and a file name.
window = sublime.active_window()
for view in window.views():
if view.is_dirty() and view.file_name():
view.run_command('save')
</code></pre>
<p>I had a similar issue with <a href="https://github.com/gerardroche/sublime-phpunit" rel="nofollow">PHPUNITKIT</a>.</p>
<blockquote>
<p><strong>save_all_on_run: Only save files that exist on disk and have dirty buffers</strong></p>
<p>Note: the "save_all_on_run" option no longer saves files that don't
exist on disk.</p>
<p>The reason for this change is trying to save a file that doesn't exist
on disk prompts the user with a "save file" dialog, which is generally
not desired behaviour.</p>
<p>Maybe another option "save_all_on_run_strict" option can be added
later that will try to save even the files that don't exist on disk.</p>
<p><a href="https://github.com/gerardroche/sublime-phpunit/commit/3138e2b75a8fbb7a5cb8d7dacabc3cf72a77c1bf" rel="nofollow">https://github.com/gerardroche/sublime-phpunit/commit/3138e2b75a8fbb7a5cb8d7dacabc3cf72a77c1bf</a></p>
</blockquote>
| 1 | 2016-10-04T13:01:56Z | [
"python",
"sublimetext3"
]
|
Create dictionary with join in python | 39,852,686 | <p>Each row of my document contains a dictionary of informations :</p>
<pre><code>{'O':34, 'D': 75, '2015-01':{'c':30,'f':90},'2016-01':{'c':100,'f':78,'r':90.5}}
</code></pre>
<p>The expected is :</p>
<pre><code>{'2015-01,c':30,'2015-01,f':90,'2016-01,c':100....}
</code></pre>
<p>I tried this in python :</p>
<pre><code>for row in cursor:
d = dict((''.join([l,',',row[l].keys()]),row[l].values())
for l in row.keys - ['O','D'])
</code></pre>
<p>But I got this error :
TypeError: sequence item 2: expected str instance, dict_keys found
Any help please.
Thank you</p>
| 1 | 2016-10-04T12:44:03Z | 39,852,850 | <p>I suggest this :</p>
<pre><code>row = {'O':34, 'D': 75, '2015':{'c':30,'f':90},'2016':{'c':100,'f':78,'r':90.5}}
dic = {}
for key in row :
if key != 'O' and key != 'D':
subdic = row[key]
for subkey in subdic :
dic[key+","+subkey] = subdic[subkey]
print dic
</code></pre>
| 0 | 2016-10-04T12:51:53Z | [
"python",
"dictionary",
"join"
]
|
Create dictionary with join in python | 39,852,686 | <p>Each row of my document contains a dictionary of informations :</p>
<pre><code>{'O':34, 'D': 75, '2015-01':{'c':30,'f':90},'2016-01':{'c':100,'f':78,'r':90.5}}
</code></pre>
<p>The expected is :</p>
<pre><code>{'2015-01,c':30,'2015-01,f':90,'2016-01,c':100....}
</code></pre>
<p>I tried this in python :</p>
<pre><code>for row in cursor:
d = dict((''.join([l,',',row[l].keys()]),row[l].values())
for l in row.keys - ['O','D'])
</code></pre>
<p>But I got this error :
TypeError: sequence item 2: expected str instance, dict_keys found
Any help please.
Thank you</p>
| 1 | 2016-10-04T12:44:03Z | 39,852,882 | <p>Assuming your nesting is always one level deep, you could do following:</p>
<pre><code>d = {'O':34, 'D': 75, '2015':{'c':30,'f':90},'2016':{'c':100,'f':78,'r':90.5}}
def join_dict(d):
for k, v in d.items():
if isinstance(v, dict):
for k2, v2 in v.items():
yield '{},{}'.format(k, k2), v2
result = {k: v for k, v in join_dict(d)}
print(result)
# {'2016,f': 78, '2016,r': 90.5, '2016,c': 100, '2015,f': 90, '2015,c': 30}
</code></pre>
| 4 | 2016-10-04T12:53:22Z | [
"python",
"dictionary",
"join"
]
|
Copying file from Vcentre datastore to VM | 39,852,697 | <p>I use salt-stack and pyvmomi module to communicate with vcenter and create the VM. On this newly created VM I want to copy files(around 1 GB) from vcenter Datastore. InitiateFileTransferToGuest can be used to upload the file to VM but how can we copy files from datastore to vm ?</p>
| 0 | 2016-10-04T12:44:27Z | 39,958,510 | <p>The hackiest way I can think of is: </p>
<ol>
<li>Save the 1GB file as .iso {either use MagicIso or inbuilt tools of
linux}. </li>
<li>Now place the file in datastore.</li>
<li>Now when creating the vm,you need to set the cdrom to point to file-data instead of empty string. </li>
<li>You can either edit the vmx file or provide the vmx options
while creating itself </li>
</ol>
<blockquote>
<pre><code> ide1:0.deviceType = "cdrom-image"
ide1:0.fileName = "/vmfs/volumes/5034a864-xxxxxx/data.iso"
ide1:0.present = "TRUE"
</code></pre>
</blockquote>
<ol start="5">
<li>After powering on the guest, depending upon the guest, you can add a batch/shell to copy to its disk.</li>
<li>If required, you can use Invoke-VMScript powercli cmdlet to do operation 5 for you.</li>
</ol>
<p>Cheers,
zXi</p>
| 0 | 2016-10-10T12:39:08Z | [
"python",
"salt-stack",
"vsphere",
"vcenter",
"pyvmomi"
]
|
Call one method with several threads in python | 39,852,777 | <p>I have about 4 input text files that I want to read them and write all of them into one separate file.
I use two threads so it runs faster! <br>
Here is my questions and code in python:<br><br>
1-Does each thread has its own version of variables such as "lines" inside the function "writeInFile"?<br><br>
2-Since I copied some parts of the code from Tutorialspoint, I don't understand what is "while 1: pass" in the last line. Can you explain? link to the main code: <a href="http://www.tutorialspoint.com/python/python_multithreading.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_multithreading.htm</a> <br><br>
3-Does it matter what delay I put for the threads? <br><br>
4-If I have about 400 input text files and want to do some operations on them before writing all of them into a separate file, how many threads I can use? <br><br>
5- If assume I use 10 threads, is it better to have the inputs in different folders (10 folders with 40 input text files each) and for each thread call one folder OR I use what I already done in the below code in which I ask each thread to read one of the 400 input text files if they have not been read before by other threads? <br><br></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>processedFiles=[] # this list to check which file in the folder has already been read by one thread so the other thread don't read it
#Function run by the threads
def writeInFile( threadName, delay):
for file in glob.glob("*.txt"):
if file not in processedFiles:
processedFiles.append(file)
f = open(file,"r")
lines = f.readlines()
f.close()
time.sleep(delay)
#open the file to write in
f = open('myfile','a')
f.write("%s \n" %lines)
f.close()
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
f = open('myfile', 'r+')
f.truncate()
start = timeit.default_timer()
thread.start_new_thread( writeInFile, ("Thread-1", 0, ) )
thread.start_new_thread( writeInFile, ("Thread-2", 0, ) )
stop = timeit.default_timer()
print stop - start
except:
print "Error: unable to start thread"
while 1:
pass</code></pre>
</div>
</div>
</p>
| 0 | 2016-10-04T12:47:53Z | 39,853,531 | <ol>
<li>Yes. Each of the local variables is on the thread's stack and are not shared between threads.</li>
<li>This loop allows the parent thread to wait for each of the child threads to finish and exit before termination of the program. The actual construct you should use to handle this is <code>join</code> and not a while loop. See <a href="http://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading">what is the use of join() in python threading</a>. </li>
<li>In practice, yes, especially if the threads are writing to a common set of files (e.g., both thread 1 and thread2 will be reading/writing to the same file). Depending on the hardware, the size of the files and the amount of data you re trying to write, different delays may make your program feel more responsive to the user than not. The best bet is to start with a simple value and adjust it as you see the program work in a real-world setting.</li>
<li>While you can technically use as many threads as you want, you generally wonât get any performance benefits over 1 thread per core per CPU. </li>
<li>Different folders wonât matter as much for only 400 files. If youâre talking about 4,000,000 files, than it might matter for instances when you want to do ls on those directories. What will matter for performance is whether each thread is working on it's own file or whether two or more threads might be operating on the same file. </li>
</ol>
<hr>
<p>General thought: while it is a more advanced architecture, you may want to try to learn/use celery for these types of tasks in a production environment <a href="http://www.celeryproject.org/" rel="nofollow">http://www.celeryproject.org/</a>.</p>
| 0 | 2016-10-04T13:23:17Z | [
"python",
"multithreading"
]
|
Iterate through and compare customer data from two .csv files, export single file with most recent updated customer information (Python) | 39,852,789 | <p>I have two .csv files with the following customer information as headers:</p>
<p>First name<br>
Last name<br>
Email<br>
Phone number<br>
Street name<br>
House number<br>
City<br>
Zip code<br>
Country<br>
Date -- last time customer information was updated </p>
<p>I want to go through both files, and export a single file with the most recent customer information.</p>
<p>For example,</p>
<p>File 1 contains the following for a single customer:</p>
<p>First name - John<br>
Last name - Smith<br>
Email - jsmith@verizon.net<br>
Phone number - 123 456 7890<br>
Street name - Baker St<br>
House number - 50<br>
City - London<br>
Zip code - 12345<br>
Country - England<br>
Date - 01-06-2016 (DD-MM-YYYY) </p>
<p>And file 2 contains the following information for the same customer:</p>
<p>First name - John<br>
Last name - Smith<br>
Email - jsmith@gmail.com<br>
Phone number - 098 765 4321<br>
Street name - Baker St<br>
House number - 50<br>
City - London<br>
Zip code - 12345<br>
Country - England<br>
Date - 01-10-2016 </p>
<p>I want to use the information for this customer from file 2 in the exported file.</p>
<p>Any suggestions how to go about doing this in Python?</p>
<p>Thanks!</p>
| 0 | 2016-10-04T12:48:56Z | 39,853,001 | <p>I suggest you to use pandas. You may create two DataFrame's and after that you may update first frame by the second. I found a question which looks similar like your(<a href="http://stackoverflow.com/questions/7971513/using-one-data-frame-to-update-another"><code>http://stackoverflow.com/questions/7971513/using-one-data-frame-to-update-another</code></a> ) I hope that it can help you.</p>
| 0 | 2016-10-04T12:59:17Z | [
"python",
"csv"
]
|
Perform operation on each cell of one column with each cell of other columns in pandas | 39,852,808 | <p>I have a data frame(df) consisting of more than 1000 columns. Each cell consists of a list.
e.g.</p>
<pre><code> 0 1 2 .... n
0 [1,2,3] [3,7,9] [1,2,1] ....[x,y,z]
1 [2,5,6] [2,3,1] [3,3,3] ....[x1,y1,z1]
2 None [2,0,1] [2,2,2] ....[x2,y2,z2]
3 None [9,5,9] None ....None
</code></pre>
<p>This list is actually the dimensions. I need to find the euclidean distance of each cell in column 0 with every other cell in column 1 and store the minimum.
Similarly from column 0 to column 2 and then to column 3 so on..</p>
<h2>Example</h2>
<pre><code>distance of df[0][0] from df[1][0], df[1][1], df[1][2]
then of df[0][1] from df[1][0], df[1][1], df[1][2] and so on...
</code></pre>
<p>Currently i am doing it with help of for loops but it is taking a lot of time for large data.
Following is the implementation::</p>
<pre><code>for n in range(len(df.columns)):
for m in range(n+1,len(df.columns)):
for q in range(df.shape[0]):
min1=9999
r=0
while(r<df.shape[0]):
if(df[n][q] is not None or df[m][r] is not None):
dist=distance.euclidean(df[n][q],df[m][r])
if(d<min1):
min1=d
if(min1==0): *#because distance can never be less than zero*
break
r=r+1
</code></pre>
<p>Is there any other way to do this?</p>
| 0 | 2016-10-04T12:50:10Z | 39,853,905 | <p>You can use pandas apply. The example below will do the distance between 0 and 1 and create a new column.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'0':[[1,2,3],[2,5,6]],'1':[[3,7,9],[2,3,1]]})
def eucledian(row):
x = np.sqrt((row[0][0]-row[1][0])**2)
y = np.sqrt((row[0][1]-row[1][1])**2)
z = np.sqrt((row[0][2]-row[1][2])**2)
return [x,y,z]
df['dist0-1'] = df.apply(eucledian,axis=1)
</code></pre>
<p>With this said I highly recommend to unroll your variables to separate columns, e.g. 0.x, 0.y, 0.z, etc and then use numpy to operate directly on columns. This will be much faster if you have a large amount of data.</p>
| 0 | 2016-10-04T13:41:43Z | [
"python",
"pandas",
"dataframe"
]
|
Perform operation on each cell of one column with each cell of other columns in pandas | 39,852,808 | <p>I have a data frame(df) consisting of more than 1000 columns. Each cell consists of a list.
e.g.</p>
<pre><code> 0 1 2 .... n
0 [1,2,3] [3,7,9] [1,2,1] ....[x,y,z]
1 [2,5,6] [2,3,1] [3,3,3] ....[x1,y1,z1]
2 None [2,0,1] [2,2,2] ....[x2,y2,z2]
3 None [9,5,9] None ....None
</code></pre>
<p>This list is actually the dimensions. I need to find the euclidean distance of each cell in column 0 with every other cell in column 1 and store the minimum.
Similarly from column 0 to column 2 and then to column 3 so on..</p>
<h2>Example</h2>
<pre><code>distance of df[0][0] from df[1][0], df[1][1], df[1][2]
then of df[0][1] from df[1][0], df[1][1], df[1][2] and so on...
</code></pre>
<p>Currently i am doing it with help of for loops but it is taking a lot of time for large data.
Following is the implementation::</p>
<pre><code>for n in range(len(df.columns)):
for m in range(n+1,len(df.columns)):
for q in range(df.shape[0]):
min1=9999
r=0
while(r<df.shape[0]):
if(df[n][q] is not None or df[m][r] is not None):
dist=distance.euclidean(df[n][q],df[m][r])
if(d<min1):
min1=d
if(min1==0): *#because distance can never be less than zero*
break
r=r+1
</code></pre>
<p>Is there any other way to do this?</p>
| 0 | 2016-10-04T12:50:10Z | 39,854,125 | <p>since you don't tell me how to handle Nond in the distance calculation, I just give a example. You need to handle the exception of None type yourself.</p>
<pre><code>import pandas as pd
import numpy as np
from scipy.spatial.distance import pdist
df = pd.DataFrame([{'a':[1,2,3], 'b':[3,7,9], 'c':[1,2,1]},
{'a':[2,5,6], 'b':[2,3,1], 'c':[3,3,3]}])
df.apply(distance, axis=1).apply(min, axis=1)
</code></pre>
| 0 | 2016-10-04T13:51:46Z | [
"python",
"pandas",
"dataframe"
]
|
Intensity-weighted minimal path between 2 points in grayscale image | 39,852,896 | <p>I want to determine minimum path between two specific points in an image, i.e. the path for which sum of distances between adjacent pixels weighted by pixel intensity (greyscale) will be minimized. For instance, this picture shows the input image</p>
<p><a href="http://i.stack.imgur.com/6hR24.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/6hR24.jpg" alt="original image"></a></p>
<p>and this is the (hand-drawn) minimal path in red, from UL to LR corner (black boundaries serve as zero-weight padding):</p>
<p><a href="http://i.stack.imgur.com/6Y2Wb.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/6Y2Wb.jpg" alt="example minimum path"></a></p>
<p>I found that matlab has the <a href="http://%20https://www.mathworks.com/help/images/ref/graydist.html" rel="nofollow">graydist</a> function just for this; is there something similar in ndimage/scikit-image/whatever? I found <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.distance_transform_edt.html#scipy.ndimage.morphology.distance_transform_edt" rel="nofollow">scipy.ndimage.morphology.distance_transform_edt</a> but I am not sure if and how to use it for this purpose. It is OK if the algorithm returns only one of non-unique minima.</p>
<p>I am not interested in implementation hints, it is a fairly straightforward task algorithmically (at least the naive implementation using e.g. dynamic programming), I am looking for (combination of) already coded routines to accomplish this.</p>
| 3 | 2016-10-04T12:53:59Z | 39,861,270 | <p>This type of dynamic programming is available in scikit-image as <code>route_through_array</code> and <code>shortest_path</code>: <a href="http://scikit-image.org/docs/dev/api/skimage.graph.html" rel="nofollow">http://scikit-image.org/docs/dev/api/skimage.graph.html</a></p>
| 4 | 2016-10-04T20:33:54Z | [
"python",
"numpy",
"scipy",
"scikit-image",
"ndimage"
]
|
constrained linear regression / quadratic programming python | 39,852,921 | <p>I have a dataset like this:</p>
<pre><code>import numpy as np
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
</code></pre>
<p>and want to fit a constrained linear regression</p>
<p>y = b1*a + b2*b + b3*c</p>
<p>where all b's sum to one and are positive: b1+b2+b3=1</p>
<p>A similar problem in R is specified here:</p>
<p><a href="http://stats.stackexchange.com/questions/21565/how-do-i-fit-a-constrained-regression-in-r-so-that-coefficients-total-1">http://stats.stackexchange.com/questions/21565/how-do-i-fit-a-constrained-regression-in-r-so-that-coefficients-total-1</a></p>
<p>How can I do this in python?</p>
| 0 | 2016-10-04T12:55:29Z | 39,853,507 | <p><strong>EDIT</strong>:
<em>These two approaches are very general and can work for small-medium scale instances. For a more efficient approach, check the answer of</em> <strong>chthonicdaemon</strong> (using customized preprocessing and scipy's optimize.nnls).</p>
<h2>Using scipy</h2>
<h3>Code</h3>
<pre><code>import numpy as np
from scipy.optimize import minimize
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
def loss(x):
return np.sum(np.square((np.dot(x, m) - y)))
cons = ({'type': 'eq',
'fun' : lambda x: np.sum(x) - 1.0})
x0 = np.zeros(m.shape[0])
res = minimize(loss, x0, method='SLSQP', constraints=cons,
bounds=[(0, np.inf) for i in range(m.shape[0])], options={'disp': True})
print(res.x)
print(np.dot(res.x, m.T))
print(np.sum(np.square(np.dot(res.x, m) - y)))
</code></pre>
<h3>Output</h3>
<pre><code>Optimization terminated successfully. (Exit mode 0)
Current function value: 18.817792344
Iterations: 5
Function evaluations: 26
Gradient evaluations: 5
[ 0.7760881 0. 0.2239119]
[ 1.87173571 2.11955951 4.61630834]
18.817792344
</code></pre>
<h3>Evaluation</h3>
<ul>
<li>It's obvious that the model-capabilitites / model-complexity is not enough to obtain a good performance (high loss!)</li>
</ul>
<h2>Using general-purpose QP/SOCP-optimization modelled by cvxpy</h2>
<p>Advantages:</p>
<ul>
<li>cvxpy prooves, that the problem is convex</li>
<li>convergence for convex optimization problems is guaranteed (might be also true for the above)</li>
<li>in general: better accuracy</li>
<li>in general: more robust in regards to numerical instabilities (solver is only able to solve SOCPs; not non-convex models like the SLSQP-approach above!)</li>
</ul>
<h3>Code</h3>
<pre><code>import numpy as np
from cvxpy import *
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
X = Variable(m.shape[0])
constraints = [X >= 0, sum_entries(X) == 1.0]
product = m.T * diag(X)
diff = sum_entries(product, axis=1) - y
problem = Problem(Minimize(norm(diff)), constraints)
problem.solve(verbose=True)
print(problem.value)
print(X.value)
</code></pre>
<h3>Output</h3>
<pre><code>ECOS 2.0.4 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS
It pcost dcost gap pres dres k/t mu step sigma IR | BT
0 +0.000e+00 -0.000e+00 +2e+01 5e-01 1e-01 1e+00 4e+00 --- --- 1 1 - | - -
1 +2.451e+00 +2.539e+00 +4e+00 1e-01 2e-02 2e-01 8e-01 0.8419 4e-02 2 2 2 | 0 0
2 +4.301e+00 +4.306e+00 +2e-01 5e-03 7e-04 1e-02 4e-02 0.9619 1e-02 2 2 2 | 0 0
3 +4.333e+00 +4.334e+00 +2e-02 4e-04 6e-05 1e-03 4e-03 0.9326 2e-02 2 1 2 | 0 0
4 +4.338e+00 +4.338e+00 +5e-04 1e-05 2e-06 4e-05 1e-04 0.9698 1e-04 2 1 1 | 0 0
5 +4.338e+00 +4.338e+00 +3e-05 8e-07 1e-07 3e-06 7e-06 0.9402 7e-03 2 1 1 | 0 0
6 +4.338e+00 +4.338e+00 +7e-07 2e-08 2e-09 6e-08 2e-07 0.9796 1e-03 2 1 1 | 0 0
7 +4.338e+00 +4.338e+00 +1e-07 3e-09 4e-10 1e-08 3e-08 0.8458 2e-02 2 1 1 | 0 0
8 +4.338e+00 +4.338e+00 +7e-09 2e-10 2e-11 9e-10 2e-09 0.9839 5e-02 1 1 1 | 0 0
OPTIMAL (within feastol=1.7e-10, reltol=1.5e-09, abstol=6.5e-09).
Runtime: 0.000555 seconds.
4.337947939 # needs to be squared to be compared to scipy's output!
# as we are using l2-norm (outer sqrt) instead of sum-of-squares
# which is nicely converted to SOCP-form and easier to
# tackle by SOCP-based solvers like ECOS
# -> does not change the solution-vector x, only the obj-value
[[ 7.76094262e-01]
[ 7.39698388e-10]
[ 2.23905737e-01]]
</code></pre>
| 3 | 2016-10-04T13:22:05Z | [
"python",
"scipy",
"linear-regression",
"quadratic-programming"
]
|
constrained linear regression / quadratic programming python | 39,852,921 | <p>I have a dataset like this:</p>
<pre><code>import numpy as np
a = np.array([1.2, 2.3, 4.2])
b = np.array([1, 5, 6])
c = np.array([5.4, 6.2, 1.9])
m = np.vstack([a,b,c])
y = np.array([5.3, 0.9, 5.6])
</code></pre>
<p>and want to fit a constrained linear regression</p>
<p>y = b1*a + b2*b + b3*c</p>
<p>where all b's sum to one and are positive: b1+b2+b3=1</p>
<p>A similar problem in R is specified here:</p>
<p><a href="http://stats.stackexchange.com/questions/21565/how-do-i-fit-a-constrained-regression-in-r-so-that-coefficients-total-1">http://stats.stackexchange.com/questions/21565/how-do-i-fit-a-constrained-regression-in-r-so-that-coefficients-total-1</a></p>
<p>How can I do this in python?</p>
| 0 | 2016-10-04T12:55:29Z | 39,857,307 | <p>You can get a good solution to this with a little bit of math and <code>scipy.optimize.nnls</code>:</p>
<p>First we do the math:</p>
<p>If </p>
<p>y = b1*a + b2*b + b3*c and b1 + b2 + b3 = 1, then b3 = 1 - b1 - b2. </p>
<p>If we substitute and simplify we end up with </p>
<p>y - c = b1(a - c) + b2(b - c)</p>
<p>Now, we don't have any equality constraints and nnls can solve directly:</p>
<pre><code>import scipy.optimize
A = np.vstack([a - c, b - c]).T
(b1, b2), norm = scipy.optimize.nnls(A, y - c)
b3 = 1 - b1 - b2
</code></pre>
<p>This recovers the same solution as obtained in the other answer using cvxpy.</p>
<pre><code>b1 = 0.77608809648662802
b2 = 0.0
b3 = 0.22391190351337198
norm = 4.337947941595865
</code></pre>
<p>This approach can be generalised to an arbitrary number of dimensions as follows. Assume that we have a matrix B constructed with a, b, c from the original question arranged in the columns. Any additional dimensions will get added to this.</p>
<p>Now, we can do</p>
<pre><code>A = B[:, :-1] - B[:, -1:]
bb, norm = scipy.optimize.nnls(A, y - B[:, -1])
bi = np.append(bb, 1 - sum(bb))
</code></pre>
| 3 | 2016-10-04T16:20:50Z | [
"python",
"scipy",
"linear-regression",
"quadratic-programming"
]
|
Drawing a fractal tree in Python, not sure how to proceed | 39,853,005 | <p>I have this so far in python </p>
<pre><code>import turtle
import math
t = turtle.Turtle()
t.shape("turtle")
t.lt(90)
lv = 11
l = 100
s = 17
t.penup()
t.bk(l)
t.pendown()
t.fd(l)
def draw_tree(l, level):
l = 3.0/4.0*l
t.lt(s)
t.fd(l)
level +=1
if level<lv:
draw_tree(l, level)
t.bk(l)
t.rt(2*s)
t.fd(l)
if level<=lv:
draw_tree(l, level)
t.bk(l)
t.lt(s)
level -=1
t.speed(100)
draw_tree(l, 2)
</code></pre>
<p>But I'm kind of stuck on how to proges, because I need to reach for building this tree. This is what I'm trying to produce:</p>
<p><a href="http://i.stack.imgur.com/6w23I.png" rel="nofollow"><img src="http://i.stack.imgur.com/6w23I.png" alt="Fractal tree"></a></p>
<p>Can any one tell me what I am doing wrong?</p>
| 0 | 2016-10-04T12:59:21Z | 39,857,545 | <p>Your code is basically correct, you mostly need to adjust your parameters. The example tree you're trying to match is larger than what you are drawing (likely reduced in that image) so increase your <code>l</code> parameter. The example tree has a couple more levels of recursion than yours so increase your <code>lv</code> parameter.</p>
<p>Finally, you need to reset the pen width based on the recursion level (and unset it on your way out.) The following rework of your code does this but needs further fine tuning:</p>
<pre><code>import turtle
t = turtle.Turtle(shape="turtle")
t.lt(90)
lv = 13
l = 120
s = 17
t.width(lv)
t.penup()
t.bk(l)
t.pendown()
t.fd(l)
def draw_tree(l, level):
width = t.width() # save the current pen width
t.width(width * 3.0 / 4.0) # narrow the pen width
l = 3.0 / 4.0 * l
t.lt(s)
t.fd(l)
if level < lv:
draw_tree(l, level + 1)
t.bk(l)
t.rt(2 * s)
t.fd(l)
if level < lv:
draw_tree(l, level + 1)
t.bk(l)
t.lt(s)
t.width(width) # restore the previous pen width
t.speed("fastest")
draw_tree(l, 2)
turtle.done()
</code></pre>
| 2 | 2016-10-04T16:35:17Z | [
"python",
"turtle-graphics",
"fractals"
]
|
Dealing with SciPy fmin_bfgs precision loss | 39,853,010 | <p>I'm currently trying to solve numerically a minimization problem and I tried to use the optimization library available in SciPy. </p>
<p>My function and derivative are a bit too complicated to be presented here, but they are based on the following functions, the minimization of which do not work either:</p>
<pre><code>def func(x):
return np.log(1 + np.abs(x))
def grad(x):
return np.sign(x) / (1.0 + np.abs(x))
</code></pre>
<p>When calling the fmin_bfgs function (and initializing the descent method to x=10), I get the following message:</p>
<pre><code>Warning: Desired error not necessarily achieved due to precision loss.
Current function value: 2.397895
Iterations: 0
Function evaluations: 24
Gradient evaluations: 22
</code></pre>
<p>and the output is equal to 10 (i.e. initial point). I suppose that this error may be caused by two problems:</p>
<ul>
<li><p>The objective function is not convex: however I checked with other non-convex functions and the method gave me the right result.</p></li>
<li><p>The objective function is "very flat" when far from the minimum because of the log. </p></li>
</ul>
<p>Are my suppositions true? Or does the problem come from anything else?
Whatever the error can be, what can I do to correct this? In particular, is there any other available minimization method that I could use?</p>
<p>Thanks in advance.</p>
| 0 | 2016-10-04T12:59:30Z | 39,853,267 | <p><code>abs(x)</code> is always somewhat dangerous as it is non-differentiable. Most solvers expect problems to be smooth. Note that we can drop the <code>log</code> from your objective function and then drop the <code>1</code>, so we are left with minimizing <code>abs(x)</code>. Often this can be done better by the following.</p>
<p>Instead of <code>min abs(x)</code> use </p>
<pre><code>min t
-t <= x <= t
</code></pre>
<p>Of course this requires a solver that can solve (linearly) constrained NLPs.</p>
| 1 | 2016-10-04T13:10:29Z | [
"python",
"scipy",
"mathematical-optimization"
]
|
Python/Django: how exactly works the ugettext_lazy function with operator %? | 39,853,066 | <p>I am using python 2.7 and had issue with lines like:
<code>LOG.warning(_("text"))</code></p>
<p>This won't work as LOG.warning is expecting a string (str) and ugettext_lazy only knows how to render unicode.</p>
<p>Now the solution I found was to force unicode rendering before calling the logger:</p>
<pre><code> text = 'Test trans'
LOG.warning(u"%s" % _(text))
</code></pre>
<p>However, I was surprised to noticed that theses code also work:</p>
<pre><code>LOG.warning(_(Test trans %(test)s.') % {'test': 1})
LOG.warning(_('Test trans %s.') % 1)
</code></pre>
<p>Can somebody explain why ?
Does the "%" operator calls for unicode rendering before replacing the variable ?</p>
<p>Thanks in advance.</p>
| 1 | 2016-10-04T13:02:00Z | 39,853,794 | <p>The <code>u</code> prefix in <a href="https://docs.djangoproject.com/en/1.10/ref/utils/#django.utils.translation.ugettext_lazy" rel="nofollow"><code>ugettext_lazy</code></a> means that the return value of this function is a Unicode string. The <code>_lazy</code> suffix means that the return value becomes lazy, that is, the return value only becomes a Unicode string at the absolutely last opportunity, when a string operation is done on it.</p>
<p>Try running this under <code>python2 manage.py shell</code> to see what I mean:</p>
<pre><code>>>> from django.utils.translation import ugettext_lazy as _
>>> _("hi")
<django.utils.functional.__proxy__ object at 0x10fa23b10>
>>> _("hi") + ""
u'hi'
>>> _("hi %s") % "hello"
u'hi hello'
</code></pre>
<p>I'm assuming that your assumption that <code>LOG.warning</code> only accepts non-Unicode strings and lazy strings is correct. In your case, maybe you have your logging configured to do nothing with warning log messages, and so the lazy strings that you are passing to <code>LOG.warning</code> are never evaluated and never converted to normal non-lazy Unicode strings.</p>
<p>Compare with <a href="https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.translation.ugettext" rel="nofollow"><code>ugettext</code></a> and <a href="https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.translation.gettext_lazy" rel="nofollow"><code>gettext_lazy</code></a>, and you'll see what I mean.</p>
<p>By the way, I highly recommend upgrading to Python 3, the way it deals with Unicode is much clearer and easy to follow in general than Python 2.</p>
| 1 | 2016-10-04T13:35:52Z | [
"python",
"django",
"python-2.7",
"unicode",
"translation"
]
|
python- using splinter to open and login webpage failed, helpï¼ï¼ | 39,853,143 | <p><a href="https://idmsa.apple.com/IDMSWebAuth/signin?appIdKey=990d5c9e38720f4e832a8009a0fe4cad7dd151f99111dbea0df5e2934f267ec8&language=HK-en&segment=R409&grpcode=g001&view=6&rv=1&paramcode=h006&path=%2Fgeniusbar%2FR409%2Fen_HK&path2=%2Fgeniusbar%2FR409%2Fen_HK" rel="nofollow">https://idmsa.apple.com/IDMSWebAuth/signin?appIdKey=990d5c9e38720f4e832a8009a0fe4cad7dd151f99111dbea0df5e2934f267ec8&language=HK-en&segment=R409&grpcode=g001&view=6&rv=1&paramcode=h006&path=%2Fgeniusbar%2FR409%2Fen_HK&path2=%2Fgeniusbar%2FR409%2Fen_HK</a></p>
<p>I want to auto login this website,but it's doesn't work not matter browser.fill or <code>find_by_name</code> or <code>find_by_id</code></p>
<p>below was the information of input:</p>
<pre><code><input type="email" class="si-text-field" id="appleId" can-field="accountName" autocomplete="off" autocorrect="off" autocapitalize="off" aria-required="true" required="required" aria-labelledby="appleIdFieldLabel" spellcheck="false" autofocus="" placeholder="Apple ID">
<input type="password" id="pwd" aria-required="true" required="required" can-field="password" autocomplete="off" class="si-password si-text-field " placeholder="Password">
</code></pre>
<p>but when I use code below,it doesn't work, I don't know any special of the login form, </p>
<pre><code> browser.fill("appleId","***")
browser.fill("pwd","***")
splinter.exceptions.ElementDoesNotExist: no elements could be found with name "appleId"
</code></pre>
| -1 | 2016-10-04T13:05:46Z | 39,853,210 | <p>The form is inside an <code>iframe</code>, <em>switch</em> to it before filling the login and password:</p>
<pre><code>with browser.get_iframe('aid-auth-widget-iFrame') as iframe:
browser.find_by_id("appleId").type("your login")
browser.find_by_id("pwd").type("your password")
</code></pre>
| 0 | 2016-10-04T13:08:24Z | [
"python",
"login",
"splinter"
]
|
How to set argparse arguments from python script | 39,853,278 | <p>I have a <code>main</code> function specified as entry point in my package's <code>setup.py</code> which uses the <code>argparse</code> package in order to pass command line arguments (see <a href="http://stackoverflow.com/questions/2853088/setuptools-not-passing-arguments-for-entry-points">discussion here</a>):</p>
<pre><code># file with main routine specified as entry point in setup.py
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('a', type=str, help='mandatory argument a')
args = parser.parse_args()
</code></pre>
<p>Ideally, I would like to use the same <code>main</code> function in the package's tests as suggested <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html" rel="nofollow">here</a>. In the latter context, I would like to call the <code>main</code> function from within the test class and set (some of) the command line arguments prior to the function call (which otherwise will fail, due to missing arguments).</p>
<pre><code># file in the tests folder calling the above main function
class TestConsole(TestCase):
def test_basic(self):
set_value_of_a()
main()
</code></pre>
<p>Is that possible?</p>
| 0 | 2016-10-04T13:10:48Z | 39,853,711 | <p>The <strong>argparse</strong> module actually reads input variables from special variable, which is called <strong>ARGV</strong> (short from <strong>ARG</strong>ument <strong>V</strong>ector). This variable is usually accessed by reading <strong>sys.argv</strong> from <strong>sys</strong> module.</p>
<p>This variable is a ordinary list, so you can append your command-line parameters to it like this:</p>
<pre><code>import sys
sys.argv.extend(['-a', SOME_VALUE])
main()
</code></pre>
<p>However, messing with sys.argv at runtime is not a good way of testing.
A much more cleaner way to replace the <strong>sys.argv</strong> for some limited scope is using <strong>unittest.mock.patch</strong> context manager, like this:</p>
<pre><code>with unittest.mock.patch('sys.argv'. ['-a', SOME_VALUE]):
main()
</code></pre>
<p><a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch" rel="nofollow" title="Read more about unittest.mock.patch in docmentation">Read more about unittest.mock.patch in documentation</a></p>
<p>Also, check this SO question:</p>
<p><a href="http://stackoverflow.com/questions/18668947/how-do-i-set-sys-argv-so-i-can-unit-test-it">How do I set sys.argv so I can unit test it?</a></p>
| 0 | 2016-10-04T13:31:51Z | [
"python",
"argparse",
"setup.py",
"entry-point"
]
|
How to set argparse arguments from python script | 39,853,278 | <p>I have a <code>main</code> function specified as entry point in my package's <code>setup.py</code> which uses the <code>argparse</code> package in order to pass command line arguments (see <a href="http://stackoverflow.com/questions/2853088/setuptools-not-passing-arguments-for-entry-points">discussion here</a>):</p>
<pre><code># file with main routine specified as entry point in setup.py
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('a', type=str, help='mandatory argument a')
args = parser.parse_args()
</code></pre>
<p>Ideally, I would like to use the same <code>main</code> function in the package's tests as suggested <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html" rel="nofollow">here</a>. In the latter context, I would like to call the <code>main</code> function from within the test class and set (some of) the command line arguments prior to the function call (which otherwise will fail, due to missing arguments).</p>
<pre><code># file in the tests folder calling the above main function
class TestConsole(TestCase):
def test_basic(self):
set_value_of_a()
main()
</code></pre>
<p>Is that possible?</p>
| 0 | 2016-10-04T13:10:48Z | 39,854,094 | <p>Add <code>kwargs</code> to <code>main</code> and if they're <code>None</code>, you set them to the <code>parse_args</code>.</p>
| 0 | 2016-10-04T13:50:02Z | [
"python",
"argparse",
"setup.py",
"entry-point"
]
|
How to set argparse arguments from python script | 39,853,278 | <p>I have a <code>main</code> function specified as entry point in my package's <code>setup.py</code> which uses the <code>argparse</code> package in order to pass command line arguments (see <a href="http://stackoverflow.com/questions/2853088/setuptools-not-passing-arguments-for-entry-points">discussion here</a>):</p>
<pre><code># file with main routine specified as entry point in setup.py
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('a', type=str, help='mandatory argument a')
args = parser.parse_args()
</code></pre>
<p>Ideally, I would like to use the same <code>main</code> function in the package's tests as suggested <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html" rel="nofollow">here</a>. In the latter context, I would like to call the <code>main</code> function from within the test class and set (some of) the command line arguments prior to the function call (which otherwise will fail, due to missing arguments).</p>
<pre><code># file in the tests folder calling the above main function
class TestConsole(TestCase):
def test_basic(self):
set_value_of_a()
main()
</code></pre>
<p>Is that possible?</p>
| 0 | 2016-10-04T13:10:48Z | 39,854,264 | <p>@William Fernandes: Just for the sake of completeness, I'll post the full solution in the way that was suggested by (checking for an empty dict not <code>kwargs is None</code>):</p>
<pre><code>def main(**kwargs):
a = None
if not kwargs:
parser = argparse.ArgumentParser()
parser.add_argument('a', type=str, help='mandatory argument a')
args = parser.parse_args()
a = args.a
else:
a = kwargs.get('a')
print(a)
</code></pre>
<p>From within the test class the <code>main</code> function can then be called with arguments:</p>
<pre><code># file in the tests folder calling the above main function
class TestConsole(TestCase):
def test_basic(self):
main(a=42)
</code></pre>
<p>The call from the command line without <code>kwargs</code> then requires the specification of the command line argument <code>a=...</code>. </p>
| 0 | 2016-10-04T13:58:00Z | [
"python",
"argparse",
"setup.py",
"entry-point"
]
|
Explode a row to multiple rows in pandas dataframe | 39,853,311 | <p>I have a dataframe with the following header: </p>
<pre><code>id, type1, ..., type10, location1, ..., location10
</code></pre>
<p>and I want to convert it as follows: </p>
<pre><code>id, type, location
</code></pre>
<p>I managed to do this using embedded for loops but it's very slow: </p>
<pre><code>new_format_columns = ['ID', 'type', 'location']
new_format_dataframe = pd.DataFrame(columns=new_format_columns)
print(data.head())
new_index = 0
for index, row in data.iterrows():
ID = row["ID"]
for i in range(1,11):
if row["type"+str(i)] == np.nan:
continue
else:
new_row = pd.Series([ID, row["type"+str(i)], row["location"+str(i)]])
new_format_dataframe.loc[new_index] = new_row.values
new_index += 1
</code></pre>
<p>Any suggestions for improvement using native pandas features? </p>
| 2 | 2016-10-04T13:12:07Z | 39,853,371 | <p>You can use <code>lreshape</code>:</p>
<pre><code>types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]
print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'type1': {0: 1, 1: 4},
'id': {0: 'a', 1: 'a'},
'type10': {0: 1, 1: 8},
'location1': {0: 2, 1: 9},
'location10': {0: 5, 1: 7}})
print (df)
id location1 location10 type1 type10
0 a 2 5 1 1
1 a 9 7 4 8
types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]
print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))
id Location Type
0 a 2 1
1 a 9 4
2 a 5 1
3 a 7 8
</code></pre>
<hr>
<p>Another solution with double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a>:</p>
<pre><code>print (pd.concat([pd.melt(df, id_vars='id', value_vars=types, value_name='type'),
pd.melt(df, value_vars=location, value_name='Location')], axis=1)
.drop('variable', axis=1))
id type Location
0 a 1 2
1 a 4 9
2 a 1 5
3 a 8 7
</code></pre>
| 4 | 2016-10-04T13:14:59Z | [
"python",
"pandas",
"explode",
"reshape",
"melt"
]
|
How to convert string date with timezone to datetime? | 39,853,321 | <p>I have date in string:</p>
<pre><code>Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)
</code></pre>
<p>and I use (according to <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a>):</p>
<pre><code>datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z')
</code></pre>
<p>but I get error:</p>
<pre><code>ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%S %z %Z'
</code></pre>
<p>How to do it correctly?</p>
| 3 | 2016-10-04T13:12:52Z | 39,853,445 | <p>python datetime can't parse the <code>GMT</code> part (You might want to specify it manually in your format). You can use <code>dateutil</code> instead:</p>
<pre><code>In [16]: s = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'
In [17]: from dateutil import parser
In [18]: parser.parse(s)
Out[18]: d = datetime.datetime(2016, 10, 4, 12, 13, tzinfo=tzoffset(u'CEST', -7200))
In [30]: d.utcoffset()
Out[30]: datetime.timedelta(-1, 79200)
In [31]: d.tzname()
Out[31]: 'CEST'
</code></pre>
| 2 | 2016-10-04T13:18:59Z | [
"python",
"date"
]
|
How to convert string date with timezone to datetime? | 39,853,321 | <p>I have date in string:</p>
<pre><code>Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)
</code></pre>
<p>and I use (according to <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a>):</p>
<pre><code>datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z')
</code></pre>
<p>but I get error:</p>
<pre><code>ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%S %z %Z'
</code></pre>
<p>How to do it correctly?</p>
| 3 | 2016-10-04T13:12:52Z | 39,853,448 | <p>%z is the <code>+0200</code>, <code>%Z</code> is <code>CEST</code>. Therefore:</p>
<pre><code>>>> s = "Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)"
>>> datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=datetime.timezone(datetime.timedelta(0, 7200), 'CEST'))
</code></pre>
<p>I also replaced your <code>%m</code> with <code>%d</code>; <code>%m</code> is the month, numerically, so in your case <code>04</code> would be parsed as April.</p>
| 2 | 2016-10-04T13:19:12Z | [
"python",
"date"
]
|
How to convert string date with timezone to datetime? | 39,853,321 | <p>I have date in string:</p>
<pre><code>Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)
</code></pre>
<p>and I use (according to <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a>):</p>
<pre><code>datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z')
</code></pre>
<p>but I get error:</p>
<pre><code>ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%S %z %Z'
</code></pre>
<p>How to do it correctly?</p>
| 3 | 2016-10-04T13:12:52Z | 39,853,569 | <p>Simpler way to achieve this without taking care of <code>datetime</code> formatting identifiers will be the usage of <a href="http://dateutil.readthedocs.io/en/latest/parser.html" rel="nofollow"><code>dateutil.parser()</code></a>. For example:</p>
<pre><code>>>> import dateutil.parser
>>> date_string = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'
>>> dateutil.parser.parse(date_string)
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=tzoffset(u'CEST', -7200))
</code></pre>
| 1 | 2016-10-04T13:24:45Z | [
"python",
"date"
]
|
IndexError: list index out of range in a matrix | 39,853,324 | <p>I've been trying to create a Procedurally Generated Dungeon, as seen in <a href="http://www.gamasutra.com/blogs/AAdonaac/20150903/252889/Procedural_Dungeon_Generation_Algorithm.php" rel="nofollow">this article</a>. But that was a little to hard for me to understand the working this type of algorithm. So instead, I've been using <a href="https://gamedevelopment.tutsplus.com/tutorials/create-a-procedurally-generated-dungeon-cave-system--gamedev-10099" rel="nofollow">this</a> as a guide to at least understand the room placement.</p>
<p>The program used in the article is made in Java, so I made some adaptations to my "reality", and tried to emulate the same results in Python 3.5.</p>
<p>My code is as follows:</p>
<pre><code>from random import randint
class Room:
"""docstring for Room"""
def __init__(self, x, y, w, h):
"""[summary]
[description]
Arguments:
x {int} -- bottom-left horizontal anchorpoint of the room
y {int} -- bottom-left vertical anchor point of the room
w {int} -- width of the room
h {int} -- height of the room
"""
self.x1 = x
self.x2 = x + w
self.y1 = y
self.y2 = y + h
self.w = w
self.h = h
self.center = ((self.x1 + self.x2)/2, (self.y1 + self.y2)/2)
def intersects(self, room):
"""[summary]
Verifies if the rooms overlap
Arguments:
room {Room} -- a room object
"""
return(self.x1 <= room.x2 and self.x2 >= room.x1 and \
self.y1 <= room.y2 and self.y2 >= room.y1)
def __str__(self):
room_info = ("Coords: (" + str(self.x1) + ", " + str(self.y1) +
") | (" + str(self.x2) + ", " + str(self.y2) + ")\n")
room_info += ("Center: " + str(self.center) + "\n")
return(room_info)
MIN_ROOM_SIZE = 10
MAX_ROOM_SIZE = 20
MAP_WIDTH = 400
MAP_HEIGHT = 200
MAX_NUMBER_ROOMS = 20
dungeon_map = [[None] * MAP_WIDTH for i in range(MAP_HEIGHT)]
# print(dungeon_map)
def crave_room(room):
"""[summary]
"saves" a room in the dungeon map by making everything inside it's limits 1
Arguments:
room {Room} -- the room to crave in the dungeon map
"""
for x in xrange(min(room.x1, room.x2), max(room.x1, room.x2) + 1):
for y in xrange(min(room.y1, room.y2), max(room.y1, room.y2) + 1):
print(x, y) # debug
dungeon_map[x][y] = 1
print("Done") # dungeon
def place_rooms():
rooms = []
for i in xrange(0, MAX_NUMBER_ROOMS):
w = MIN_ROOM_SIZE + randint(0, MAX_ROOM_SIZE - MIN_ROOM_SIZE + 1)
h = MIN_ROOM_SIZE + randint(0, MAX_ROOM_SIZE - MIN_ROOM_SIZE + 1)
x = randint(0, MAP_WIDTH - w) + 1
y = randint(0, MAP_HEIGHT - h) + 1
new_room = Room(x, y, w, h)
fail = False
for other_room in rooms:
if new_room.intersects(other_room):
fail = True
break
if not fail:
print(new_room)
crave_room(new_room) # WIP
new_center = new_room.center
# rooms.append(new_room)
if len(rooms) != 0:
prev_center = rooms[len(rooms) - 1].center
if(randint(0, 1) == 1):
h_corridor(prev_center[0], new_center[0], prev_center[1])
v_corridor(prev_center[1], new_center[1], prev_center[0])
else:
v_corridor(prev_center[1], new_center[1], prev_center[0])
h_corridor(prev_center[0], new_center[0], prev_center[1])
if not fail:
rooms.append(new_room)
for room in rooms:
print(room)
def h_corridor(x1, x2, y):
for x in xrange(min(x1, x2), max(x1, x2) + 1):
dungeon_map[x][y] = 1
def v_corridor(y1, y2, x):
for y in xrange(min(y1, y2), max(y1, y2) + 1):
dungeon_map[x][y] = 1
place_rooms()
</code></pre>
<p>but whenever I run it, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "/home/user/dungeon.py", line 114, in <module>
place_rooms()
File "/home/user/dungeon.py", line 87, in place_rooms
crave_room(new_room)
File "/home/user/dungeon.py", line 65, in crave_room
dungeon_map[x][y] = 1
IndexError: list index out of range
</code></pre>
<p>For what I understood from my code, the <code>crave_room</code> function should work correctly, since I'm using the <code>min</code> and <code>max</code> functions. And since the <code>h_corridor</code> and <code>v_corridor</code> functions work in a similar way They present the same kind of problem.</p>
<p>I'm not sure if the problem is happening due the fact that I'm using a matrix as a substitute to the canvas used in the original article. I was suspecting a local/global variable problem, but I don't think that's the problem. I'm afraid I'm making a very stupid mistake and not seeing it.</p>
<p>Any code improvement tips or suggestions about better data structures to use will be welcome, and if anyone has, a more clearer/simpler article in the subject, preferably on Python, I saw a lot of the related posts in here, but I'm still kind of lost.</p>
<p>Thanks for any help. :D</p>
| 1 | 2016-10-04T13:13:02Z | 39,854,214 | <p>You have your <code>dungeon_map</code> declared incorrectly:</p>
<pre><code>dungeon_map = [[None] * MAP_WIDTH] * MAP_HEIGHT
</code></pre>
<p>The correct way should be:</p>
<pre><code>dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH
</code></pre>
<p>Now that you done that, let's take a look at the second, more serious problem. Let's have an experiment in smaller scale (smaller map):</p>
<pre><code>MAP_WIDTH = 4
MAP_HEIGHT = 2
dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH
print('\nBefore Assignment:')
print(dungeon_map)
dungeon_map[2][1] = 'y'
print('\nAfter Assignment:')
print(dungeon_map)
</code></pre>
<p>In this experiment, we created a 4 column x 2 row matrix and we alter the value of one cell, so let's take a look at the output:</p>
<pre><code>Before Assignment:
[[None, None], [None, None], [None, None], [None, None]]
After Assignment:
[[None, 'y'], [None, 'y'], [None, 'y'], [None, 'y']]
</code></pre>
<p>What is going on? Essentially, you declare the same list, <code>MAP_WIDTH</code> times. The declaration line below is convenient and clever, but incorrect:</p>
<pre><code>dungeon_map = [[None] * MAP_HEIGHT] * MAP_WIDTH
</code></pre>
<p>The correct way to declare such a matrix is:</p>
<pre><code>dungeon_map = [[None for x in range(MAP_HEIGHT)] for y in range(MAP_WIDTH)]
</code></pre>
| 1 | 2016-10-04T13:56:04Z | [
"python",
"matrix",
"indexoutofboundsexception",
"python-3.5",
"procedural-generation"
]
|
Call function inside other function odoo | 39,853,421 | <p>I want call function 2 inside function 1.</p>
<p>Function 2 need parameter (num2 and num3), after call in source I don't get any error but nothing happened aslo.</p>
<pre><code>def function_1(self, cr, uid, ids, num1, num2, num3, context=None):
res = {}
if num1:
res['sum'] = num1 + num2
return {'value': res}
self.function_2(cr, uid, ids, num2, num3, context)
def function_2(self, cr, uid, ids, num2,num3, context=None):
res = {}
if num2:
res['sum2'] = num2 + num3
return {'value': res}
</code></pre>
<p>What is problem here or any other solution?</p>
| 0 | 2016-10-04T13:17:32Z | 39,863,431 | <p>You don't need <code>self</code> in <code>function_2</code> and you also need the <code>return</code> keyword, because after <code>function_2</code> evaluates and returns it's value to the caller which is <code>function_1</code>, <code>function_1</code> also has to return that result to it's caller. if you don't add a return statement <code>function_1</code> would end up returning <code>None</code> to it's caller.</p>
<pre><code>def function_1(self, cr, uid, ids, num1, num2, num3, context=None):
# i'll place the function definition at the top (personal preference)
def function_2(cr, uid, ids, num2,num3, context=None):
res = {}
if num2:
res['sum2'] = num2 + num3
return {'value': res}
res = {}
if num1:
res['sum'] = num1 + num2
return {'value': res}
return function_2(cr, uid, ids, num2, num3, context=context)
</code></pre>
<p>Personally i don't see the need to have a nested function. i would have written it like this.</p>
<pre><code>def function_1(self, cr, uid, ids, num1, num2, num3, context=None):
res = {}
if num1:
res['sum'] = num1 + num2
return {'value': res}
elif num2:
res['sum2'] = num2 + num3
return {'value': res}
else:
pass # return some default value here
</code></pre>
| 0 | 2016-10-04T23:53:04Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
]
|
Creating an object with more than 1 foreign key in a Django project with multiple databases causing error | 39,853,446 | <p>In my Django project, I have 2 databases. Everything works perfectly except for when I try to create a model with 2 foreign keys. The database router locks up and gives me a <code>Cannot assign "<FKObject: fk_object2>": the current database router prevents this relation.</code> even if both foreign keys come from the same database and I've yet to save the object in question. Code below</p>
<pre><code>1 fk_object1 = FKObject.objects.using("database2").get(pk=1)
2 fk_object2 = FKObject.objects.using("database2").get(pk=2)
3
4 object = Object()
5 object.fk_object1 = fk_object1
6 object.fk_object2 2 = fk_object2
7 object.save(using="database2")
</code></pre>
<p>The problem arises on line 6, before the object is even saved into the database so I'm assuming that Django somehow calls <code>Object()</code> with <code>database1</code> even though it hasn't been specified yet.</p>
<p>Does anyone know how to deal with this?</p>
| 0 | 2016-10-04T13:19:02Z | 39,871,804 | <p>So I ended up finding a work around as such:</p>
<p>As it turns out, my suspicions were only partially true. Calling <code>Model()</code> does not cause Django to assume it is to use the default database but setting a foreign key does. This would explain why my code would error out at line 6 and not at line 5 as by this point in time, Django already assumes that you're using the default database and as <code>fk_object2</code> is called from <code>database2</code>, it errors out for fear of causing an inter-database relation.</p>
<p>To get around this, I used <code>threading.current_thread()</code> as so:</p>
<pre><code>class Command(BaseCommand):
current_thread().db_name = "database2"
def handle(self, **args, **kwargs):
# Do work here
class DatabaseRouter(object):
db_thread = threading.current_thread()
def db_for_read(self, model, **hints):
try:
print("Using {}".format(db_thread.db_name))
return db_thread.db_name
except AttributeError:
return "default"
def db_for_write(self, model, **hints):
try:
print("Using {}".format(db_thread.db_name))
return db_thread.db_name
except AttributeError:
return "default"
</code></pre>
<p>This way, my 2nd database is used every time, thereby avoiding any possible relation inconsistencies.</p>
| 1 | 2016-10-05T10:41:54Z | [
"python",
"django",
"python-3.x",
"django-models"
]
|
Implementing a property using the double asterisk (**) | 39,853,606 | <p>Following <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, I'm familiar with the following method of implementing a property in Python:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
</code></pre>
<p>I'm now reading some code in which the double asterisk (<code>**</code>) is used in defining the property. If I adapt it to my own example, it seems to be like this:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
def fget(self):
print("Getting value")
return self._temperature
def fset(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(**temperature())
</code></pre>
<p>However, if I try to run this code and instantiate a class through <code>c = Celsius()</code>, I get</p>
<pre><code>TypeError: type object argument after ** must be a mapping, not NoneType
</code></pre>
<p>I understand that <code>fget</code> and <code>fset</code> are keyword arguments of <code>property</code>, so I would expect what comes out of <code>**temperature()</code> to be something like <code>fget=fget, fset=fset</code>, but I am not sure what is going wrong here or how to dissect it further. Any ideas?</p>
| 0 | 2016-10-04T13:26:39Z | 39,853,757 | <p>You should <code>return</code> the nested functions and then unpack them according from the function call:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
...
return fget, fset
temperature = property(*temperature())
</code></pre>
<p>If you insist on using <code>**</code>, then you'll be returning a mapping/dictionary from your function which will then be <em>unpacked</em> as keyword arguments.</p>
<pre><code>def temperature():
...
return {'fget': fget, 'fset': fset}
temperature = property(**temperature())
</code></pre>
| 2 | 2016-10-04T13:33:58Z | [
"python",
"properties"
]
|
Implementing a property using the double asterisk (**) | 39,853,606 | <p>Following <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, I'm familiar with the following method of implementing a property in Python:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
</code></pre>
<p>I'm now reading some code in which the double asterisk (<code>**</code>) is used in defining the property. If I adapt it to my own example, it seems to be like this:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
def fget(self):
print("Getting value")
return self._temperature
def fset(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(**temperature())
</code></pre>
<p>However, if I try to run this code and instantiate a class through <code>c = Celsius()</code>, I get</p>
<pre><code>TypeError: type object argument after ** must be a mapping, not NoneType
</code></pre>
<p>I understand that <code>fget</code> and <code>fset</code> are keyword arguments of <code>property</code>, so I would expect what comes out of <code>**temperature()</code> to be something like <code>fget=fget, fset=fset</code>, but I am not sure what is going wrong here or how to dissect it further. Any ideas?</p>
| 0 | 2016-10-04T13:26:39Z | 39,853,814 | <p>You are getting that error because the <code>temperature()</code> call returns <code>None</code>, which you then attempt to unpack as if it were a dictionary, using <code>**</code>. So to get that code working you need to return an appropriate dictionary containing the setter & getter methods.</p>
<p>I prefer Moses' solution, but you <em>could</em> pass the methods with a dict instead of a tuple if you really want. Eg,</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
def fget(self):
print("Getting value")
return self._temperature
def fset(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
return {'fget': fget, 'fset': fset}
temperature = property(**temperature())
# Test
a = Celsius()
a.temperature = 20
print(a.temperature)
</code></pre>
<p><strong>output</strong></p>
<pre><code>Setting value
Getting value
20
</code></pre>
| 1 | 2016-10-04T13:36:38Z | [
"python",
"properties"
]
|
Implementing a property using the double asterisk (**) | 39,853,606 | <p>Following <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, I'm familiar with the following method of implementing a property in Python:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
</code></pre>
<p>I'm now reading some code in which the double asterisk (<code>**</code>) is used in defining the property. If I adapt it to my own example, it seems to be like this:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
def fget(self):
print("Getting value")
return self._temperature
def fset(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(**temperature())
</code></pre>
<p>However, if I try to run this code and instantiate a class through <code>c = Celsius()</code>, I get</p>
<pre><code>TypeError: type object argument after ** must be a mapping, not NoneType
</code></pre>
<p>I understand that <code>fget</code> and <code>fset</code> are keyword arguments of <code>property</code>, so I would expect what comes out of <code>**temperature()</code> to be something like <code>fget=fget, fset=fset</code>, but I am not sure what is going wrong here or how to dissect it further. Any ideas?</p>
| 0 | 2016-10-04T13:26:39Z | 39,853,846 | <p>Indeed I had missed the <code>return</code> statement in the function definition of <code>temperature</code>. The original code actually contains the line</p>
<pre><code>return locals()
</code></pre>
<p>Adding this line makes the property work as intended.</p>
| 0 | 2016-10-04T13:38:21Z | [
"python",
"properties"
]
|
Implementing a property using the double asterisk (**) | 39,853,606 | <p>Following <a href="http://www.programiz.com/python-programming/property" rel="nofollow">http://www.programiz.com/python-programming/property</a>, I'm familiar with the following method of implementing a property in Python:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature, set_temperature)
</code></pre>
<p>I'm now reading some code in which the double asterisk (<code>**</code>) is used in defining the property. If I adapt it to my own example, it seems to be like this:</p>
<pre><code>class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def temperature():
def fget(self):
print("Getting value")
return self._temperature
def fset(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(**temperature())
</code></pre>
<p>However, if I try to run this code and instantiate a class through <code>c = Celsius()</code>, I get</p>
<pre><code>TypeError: type object argument after ** must be a mapping, not NoneType
</code></pre>
<p>I understand that <code>fget</code> and <code>fset</code> are keyword arguments of <code>property</code>, so I would expect what comes out of <code>**temperature()</code> to be something like <code>fget=fget, fset=fset</code>, but I am not sure what is going wrong here or how to dissect it further. Any ideas?</p>
| 0 | 2016-10-04T13:26:39Z | 39,854,237 | <p>The <code>temperature</code> method you are defining does not have a return statement, so it implicitly returns <code>None</code>, this the <code>...,not NoneType</code> in your error message. The method does have two sub-methods, but that does not cause it to return them in any form, I think you are missing a line such as ( untested ):</p>
<pre><code>return { "fget": fget, "fset": fset }
</code></pre>
<p>You could also use a list and a single <code>*</code>.</p>
<p>That being said, it's a best practice to avoid <code>*</code> and <code>**</code> magic, there's also a <a href="http://pylint-messages.wikidot.com/messages:w0142" rel="nofollow">pylint rule</a> to discourage it. </p>
| 0 | 2016-10-04T13:57:01Z | [
"python",
"properties"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.