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):
... | 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)... | 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):
... | 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>```<... | 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(base6... | 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 ... | 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:
... | 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:
no... | 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:
... | 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... | 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:
... | 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>>>>... | 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 a... | -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_t... | 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>
<... | 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), ... | 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
f... | -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] )*
... | 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
f... | -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>
... | 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>
... | 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 t... | 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"] ... | 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"] ... | 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... | 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>imp... | -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" ... | 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>imp... | -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... | 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>imp... | -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/ge... | 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.d... | -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... | 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 = temperat... | 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> wor... | 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 = temperat... | 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>... | 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 = temperat... | 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(ro... | 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?... | 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... | 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.micr... | 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... | 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 linu... | 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... | 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:/... | 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></... | 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/fu... | 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></... | 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 be... | 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></... | 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> Yo... | 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 scrip... | 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... | -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 i... | 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.s... | 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</... | 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 | 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 ... | 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 r... | 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 serve... | 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 r... | 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</c... | 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 pat... | 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 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>d... | 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>d... | 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 s... | 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('... | 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 s... | 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... | 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 ... | 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", "S... | -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, r... | 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"""
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-... | 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-... | 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 th... | 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-... | 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... | 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?... | 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="nofol... | 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?... | 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?... | 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(utimest... | 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 ... | 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(utimest... | 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)<... | 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(utimest... | 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 exp... | 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... | 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 ... | 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':'... | 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 = Beautifu... | 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... | 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)
... | -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... | 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)
... | -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,
... | 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']
fo... | 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:... | 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 unres... | 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 ... | 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 ... | 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 ... | 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... | 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 ca... | 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 ca... | 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 ca... | 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])+... | 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/pyt... | 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])+... | 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 = (... | 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])+... | 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>"s... | 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... | 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 h... | 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... | 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... | 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 '{},{}'.forma... | 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 fi... | 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 co... | 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... | 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 singl... | 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... | 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] ....[x... | 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]-... | 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] ....[x... | 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]},
... | 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"><i... | 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 ... | 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>impo... | 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 ... | 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>
<... | 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)
... | 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>l... | 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><... | 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 f... | 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><cod... | 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 ... | 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://... | -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>... | 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 variab... | 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>... | 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>... | 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(... | 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... | 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 p... | 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><cod... | 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.dateti... | 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><cod... | 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), ... | 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><cod... | 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_st... | 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'v... | 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 ser... | 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... | 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... | 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 f... | 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... | 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._... | 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(... | 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._... | 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 M... | 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._... | 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._... | 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... | 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.