title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
python logging: logger setLevel() is not enforced? | 38,286,641 | <pre><code>fmtter = logging.Formatter('%(asctime)s,%(msecs)05.1f (%(funcName)s) %(message)s', '%H:%M:%S')
rock_log = '%s/rock.log' % Build.path
hdlr = logging.FileHandler(rock_log, mode='w')
hdlr.setFormatter(fmtter)
hdlr.setLevel(logging.DEBUG)
rock_logger = logging.getLogger('rock')
rock_logger.addHandler(hdlr)
</c... | 1 | 2016-07-09T21:46:56Z | 38,288,245 | <p>In your case <code>rock_logger</code> is the logger and <code>hdlr</code> is the handler. When you try to log something, the logger first checks if it should handle the message (depending on it's own log level). Then it passes the message to the handler. The handler then checks the level against it's own log level a... | 2 | 2016-07-10T03:15:07Z | [
"python",
"logging"
] |
Pandas Use Loop to compare datetime in each row with all rows and saving subset of results | 38,286,700 | <p>This is my first time using Python (I've used R before), so please bear with me on this question. Basically, I'd like to use a for loop to compare the <code>datetime</code> value in each row with all other <code>datetime</code> values in the other rows in a pandas <code>pd</code> dataframe, and if the time differenc... | 0 | 2016-07-09T21:56:08Z | 38,286,938 | <p>The logic for the loop is:</p>
<pre><code>df = []
for i, row in enumerate(rows):
df.append([row])
try:
for next_row in rows[i + 1:]:
if abs(row['Time'] - next_row['Time']) < timedelta(hours=4):
df[i].append(next_row)
else:
break
except I... | 1 | 2016-07-09T22:38:09Z | [
"python",
"datetime",
"pandas",
"for-loop",
"filter"
] |
Pandas Use Loop to compare datetime in each row with all rows and saving subset of results | 38,286,700 | <p>This is my first time using Python (I've used R before), so please bear with me on this question. Basically, I'd like to use a for loop to compare the <code>datetime</code> value in each row with all other <code>datetime</code> values in the other rows in a pandas <code>pd</code> dataframe, and if the time differenc... | 0 | 2016-07-09T21:56:08Z | 38,287,134 | <p>If you want a pure pandas solution without any loops, you can do it like this:</p>
<ol>
<li>Do a cross-join of the data with itself</li>
<li>Select rows where the difference between times is < 4 hours</li>
<li>Group the data</li>
</ol>
<p>Here is an example:</p>
<pre><code># Load file
data = pd.read_csv("abc.c... | 3 | 2016-07-09T23:14:47Z | [
"python",
"datetime",
"pandas",
"for-loop",
"filter"
] |
Pandas Use Loop to compare datetime in each row with all rows and saving subset of results | 38,286,700 | <p>This is my first time using Python (I've used R before), so please bear with me on this question. Basically, I'd like to use a for loop to compare the <code>datetime</code> value in each row with all other <code>datetime</code> values in the other rows in a pandas <code>pd</code> dataframe, and if the time differenc... | 0 | 2016-07-09T21:56:08Z | 38,287,232 | <p>Starting with This: </p>
<pre><code> Origin Destination Time
0 New York Cairo 2016-03-28 00:00:00
1 New York Los Angeles 2016-03-28 02:00:00
2 Boston Hawaii 2016-03-28 04:00:00
... | 2 | 2016-07-09T23:36:20Z | [
"python",
"datetime",
"pandas",
"for-loop",
"filter"
] |
How do I scrape using Python and BeautifulSoup - Dealing with a Table using Javascript | 38,286,757 | <p>I'm trying to learn how to scrape info using Python, and unfortunately i'm having a lot of trouble here. The issue i'm dealing with is that the information I want <em>doesn't seem to be</em> contained in the page source, it only appears after you check one of the boxes. </p>
<p>The url in question is: <a href="htt... | 1 | 2016-07-09T22:07:32Z | 38,286,876 | <p>You need to post data, in particular the <code>minorcatid</code> which relates to the video cards:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
data = {"dofilter": "1",
"minorcatid": ""}
</code></pre>
<p># not necessarily essential but good to at least add a user-agent
headers = {
... | 1 | 2016-07-09T22:27:58Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
How do I delete all tweets using python-twitter? | 38,286,765 | <p>I'm using <a href="https://github.com/bear/python-twitter" rel="nofollow"><strong>python-twitter</strong></a> in my Web Application to post tweets like this:</p>
<pre><code>import twitter
twitter_api = twitter.Api(
consumer_key="BlahBlahBlah",
consumer_secret="BlahBlahBlah",
access_token_key="BlahBlahBl... | 1 | 2016-07-09T22:08:45Z | 38,286,846 | <p><code>twitter_api.PostUpdate("Hello World")</code> should return a <code>Status</code> object. That <code>Status</code> object also contains information about the status which, <a href="https://github.com/bear/python-twitter/blob/master/twitter/models.py#L397" rel="nofollow">according to their source is present as a... | 2 | 2016-07-09T22:22:19Z | [
"python",
"twitter",
"python-twitter"
] |
Design temporal data in mongodb | 38,286,776 | <p>I am using mongodb in my Python application.
I have a collection of <code>resources</code>.
The <code>resource</code> can be available/not available/reserved depending on time periods, for instance:</p>
<pre><code>id: resource1
state: available
from: 2016-01-03T15:00:00Z
to: 2016-01-03T17:00:00Z
id: resource1
... | 0 | 2016-07-09T22:10:26Z | 38,286,878 | <p>In mongodb you document will look like below:</p>
<pre><code>{
_id:ObjectId("unique hexadecimal string")
id: "resource",
state: "state",
from: ISODate("date_string"),
to: ISODate("date_string")
}
</code></pre>
<p>If you are not providing value for _id , mongodb will add a unique hexadecimal string ... | 0 | 2016-07-09T22:28:13Z | [
"python",
"mongodb",
"pymongo",
"mongoengine"
] |
Is this sleep command in my tmux script a justified hack? If so why? | 38,286,816 | <h3>NOTE</h3>
<p>I am not sure if this question is relevant here or on <strong>Meta</strong> but please go through the post before a downvote!</p>
<hr>
<p>I think the question looks a bit vague but I will dwell into this question extensively.</p>
<p>I am working with a decent number of <strong>Raspberry Pis</strong... | 0 | 2016-07-09T22:18:47Z | 38,286,875 | <p>Crontab runs <code>@reboot</code> scripts <strong>before</strong> the system is finished rebooting. If your script needs services that are not available until the reboot is complete, your script needs to either (a) test for the presence of those services before using them, or (b) don't use <code>@reboot</code>.</p>... | 2 | 2016-07-09T22:27:47Z | [
"python",
"linux",
"bash",
"tmux"
] |
ValueError: Invalid argument 'metric' passed to K.function even with newest Keras/Theano | 38,286,843 | <p>When I run the following very simple neural network in Anaconda / Python2.7 / Keras / Theano:</p>
<pre><code>import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
# import csv
csv = 'https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv'
iris = np.g... | 0 | 2016-07-09T22:21:50Z | 38,288,742 | <p>Very embarrassing. I spelled <code>metric</code> instead of <code>metrics</code> in the <code>model.compile</code> command.</p>
| 0 | 2016-07-10T04:58:48Z | [
"python",
"neural-network",
"anaconda",
"theano",
"keras"
] |
Flask does not create tables | 38,286,871 | <p>I'm trying to create database schema using flask, so I installed sqlalchemy-migrate and Flask-Migrate. and I ran python db_create.py</p>
<p>The db is already created but I can not create tables from models.py using db_create.py</p>
<p>Here is the db_create.py</p>
<pre><code>#!/usr/bin/python
from migrate.version... | -1 | 2016-07-09T22:27:19Z | 38,286,963 | <p>You create your database connection in core.py. You import that in your models module.</p>
<p>But in app.py you are creating a new db object that doesn't know anything about your models:</p>
<pre><code>db = SQLAlchemy(app)
</code></pre>
<p>That's what is being imported by your db_create script, so naturally the s... | 1 | 2016-07-09T22:42:48Z | [
"python",
"flask"
] |
Cython unable to find C functions and object from external C file | 38,286,897 | <p>Right now I am trying to load C functions using Cython into Python, similar to what is described here: <a href="http://docs.cython.org/src/userguide/external_C_code.html" rel="nofollow">http://docs.cython.org/src/userguide/external_C_code.html</a>. Let's say my C file is called temp.c, my pxd file is called decl.pxd... | 0 | 2016-07-09T22:31:29Z | 38,300,601 | <p>See <a href="http://docs.cython.org/src/userguide/external_C_code.html#implementing-functions-in-c" rel="nofollow">http://docs.cython.org/src/userguide/external_C_code.html#implementing-functions-in-c</a></p>
<p>Note that it says <code>cdef extern from "spam.c":</code> should be in .pyx and <code>cdef void order_sp... | 0 | 2016-07-11T06:41:52Z | [
"python",
"cython"
] |
Cython unable to find C functions and object from external C file | 38,286,897 | <p>Right now I am trying to load C functions using Cython into Python, similar to what is described here: <a href="http://docs.cython.org/src/userguide/external_C_code.html" rel="nofollow">http://docs.cython.org/src/userguide/external_C_code.html</a>. Let's say my C file is called temp.c, my pxd file is called decl.pxd... | 0 | 2016-07-09T22:31:29Z | 38,343,177 | <p>Just as a follow up, I solved this problem by compiling temp.c into libtemp.so, and then followed the directions here to link Cython with temp.h (the header file here) and libtemp.so: </p>
<p><a href="http://stackoverflow.com/questions/2105508/wrap-c-lib-with-cython">Wrap C++ lib with Cython</a></p>
| 0 | 2016-07-13T05:18:34Z | [
"python",
"cython"
] |
How to run python3 on web server? | 38,286,953 | <p>I have this python 3 program that I have problem running. When I run thought ssh using <code>python3 4230.py</code> it works like it should(it prints out data), but when I try to run it like <code>python 4230.py</code> it gives me lots of errors because its PY3 program. So I want to find a way on how could I make th... | 0 | 2016-07-09T22:40:57Z | 38,291,886 | <p>A summary of the extended discussion in the comment section and a more general question to 'why is my Python script not running when called from PHP, cgi, etc.?'</p>
<hr>
<p>Can you call a <em>Hello World</em> script instead of your real script? e.g.</p>
<pre><code>#!/usr/bin/env python or python3
from sys import... | 0 | 2016-07-10T12:30:44Z | [
"php",
"python",
"python-3.x",
"centos6"
] |
How do you make an IntPtr in Python? | 38,286,968 | <p>I've been translating a powershell script into python, mostly to learn how to do it. I've gotten stuck on these lines here:</p>
<pre><code>$lpTargetHandle = [IntPtr]::Zero
$CallResult = [Kernel32]::DuplicateHandle(
$ProcessInfo.hProcess, 0x4,
[Kernel32]::GetCurrentProcess(),
... | 1 | 2016-07-09T22:43:53Z | 38,289,007 | <p>According to the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms724251(v=vs.85).aspx" rel="nofollow">Windows documentation</a>, this is the function prototype:</p>
<pre><code>BOOL WINAPI DuplicateHandle(
_In_ HANDLE hSourceProcessHandle,
_In_ HANDLE hSourceHandle,
_In_ HANDLE hTa... | 1 | 2016-07-10T05:45:15Z | [
"python",
".net",
"powershell",
"ctypes",
"intptr"
] |
New random sentence printed for each iteration | 38,287,066 | <p>Having some trouble with this one...</p>
<p>I am able to randomly create a sentence with this code, but now I want to iterate through to make 10 random sentences.</p>
<pre><code>import random, pprint
#Create first list of elements
elements1 = []
#Create second list of location descriptions
prepositionList = []
... | -2 | 2016-07-09T23:02:37Z | 38,287,111 | <p>Repeat the code inside a loop:</p>
<pre><code>for i in range(<number of times to run>):
# Put here whatever you want to be executed 10 times
</code></pre>
<blockquote>
<p>A loop statement allows us to execute a statement or group of statements multiple times</p>
</blockquote>
<p>To read more about loo... | 1 | 2016-07-09T23:10:02Z | [
"python"
] |
New random sentence printed for each iteration | 38,287,066 | <p>Having some trouble with this one...</p>
<p>I am able to randomly create a sentence with this code, but now I want to iterate through to make 10 random sentences.</p>
<pre><code>import random, pprint
#Create first list of elements
elements1 = []
#Create second list of location descriptions
prepositionList = []
... | -2 | 2016-07-09T23:02:37Z | 38,288,967 | <p>How about a loop? Here's the way your code would look:</p>
<pre><code>random_sentences = []
for i in range(10):
random_sentence = (random.choice(elements1) + ' ' +
random.choice(prepositionList) + ' ' + random.choice(elements2))
random_sentences.append(random_sentence)
print random_se... | 0 | 2016-07-10T05:39:24Z | [
"python"
] |
Read set of images into 4D Numpy array with dimension (num_img,channel, dim1, dim2) | 38,287,077 | <p>I have a set of 1000 gray scale images (28x28), I want to read them into 4D numpy array (number of images, 1, img_dim1,img_dim2). Following is my code but it doesn't work properly. Any idea how I can fix the issue in the code? </p>
<pre><code>from PIL import Image
import numpy as np
import os
mypath=os.path.dirnam... | 0 | 2016-07-09T23:03:49Z | 38,314,103 | <p>The problem has been solved by using <code>append</code> and adding a new axis <code>np.newaxis</code> </p>
<pre><code>from PIL import Image
import numpy as np
import os
mypath=os.path.dirname('path/to/directory/')
def load_dataset( ) :
data =[]
for fname in os.listdir(mypath):
pathname = os.pa... | 0 | 2016-07-11T18:50:38Z | [
"python",
"arrays",
"numpy"
] |
Hoare partition not working when more than one value is equal to pivot | 38,287,201 | <p>I'm trying to write my own hoare partition function to better understand it. I thought I followed its definition and pseudo-code well but even though it seems to work as expected on many occasions, it falls apart and goes into infinite loop when a list with multiple values equal to pivot are passed in. Where is my m... | 1 | 2016-07-09T23:30:07Z | 38,287,489 | <p>You are testing for equality with pivot value in both <code>lst[left_index] >= pivot</code> and <code>lst[right_index] <= pivot</code>. This effectively prevents both indices from skipping over pivot-valued elements. Therefore, when two or more pivot-valued elements are pushed toward the middle of your list, <... | 2 | 2016-07-10T00:23:51Z | [
"python",
"algorithm",
"sorting",
"quicksort",
"hoare-logic"
] |
How do I retrieve all my posted tweets using python-twitter? | 38,287,221 | <p>I'm using <a href="https://github.com/bear/python-twitter" rel="nofollow"><strong>python-twitter</strong></a> in my Web Application to post tweets like this:</p>
<pre><code>import twitter
twitter_api = twitter.Api(
consumer_key="BlahBlahBlah",
consumer_secret="BlahBlahBlah",
access_token_key="BlahBlahBl... | 0 | 2016-07-09T23:34:26Z | 38,287,507 | <p>One approach could be like the following:</p>
<pre><code>import twitter
api = twitter.Api(consumer_key='consumer_key',
consumer_secret='consumer_secret',
access_token_key='access_token',
access_token_secret='access_token_secret')
# get user data fro... | 1 | 2016-07-10T00:29:10Z | [
"python",
"twitter",
"python-twitter"
] |
Using alembic with multiple databases | 38,287,301 | <p>I have a pretty standard flask app. It uses <code>flask_sqlalchemy</code> to manage connections to a <code>postgres</code> server and <code>alembic</code> to manage migrations.</p>
<p>Now the issue is that I'm in the process of integrating it with another project and that means that I'm trying to allow it to pull a... | 0 | 2016-07-09T23:48:57Z | 39,237,895 | <p>The steps you've taken so far are correct.</p>
<p>But, did you assign the correct <code>target_metadata</code> in <code>env.py</code> for each database?</p>
<p>If the metadata that is passed in is the same for both your databases, no different relations will be found and therefore the autogenerated script will not... | 0 | 2016-08-30T22:14:07Z | [
"python",
"postgresql",
"flask",
"flask-sqlalchemy",
"alembic"
] |
Trouble creating a nesting dictionary in Python | 38,287,392 | <p>I'm trying to create a specific nesting dictionary for an assignment (don't worry, I already have permission to post this here!), and I'm running into a strange error that I can't make sense of. The code is a bit long, so I'm just posting the area where I know the error is taking place (including the tags I've used ... | 0 | 2016-07-10T00:04:59Z | 38,287,574 | <p>difficult to guess without knowing what is csv_dict and what is assignment_dict. Here is one guess:</p>
<p>are you missing csv_step1 = {} initialization in while loop?</p>
| 0 | 2016-07-10T00:42:23Z | [
"python",
"dictionary"
] |
ValueError: Item wrong length 907 instead of 2000 | 38,287,400 | <p>I have a csv file, that has 1000 columns. I need to read only the first 100 columns. I wrote this program for that:</p>
<pre><code>import pandas as pd
list = []
for i in range (1, 100):
list.append(i)
df = pd.read_csv('piwik_37_2016-07-08.csv',dtype = "unicode")
df = df[df.columns.isin(list)]
df.to_csv('abc.cs... | -1 | 2016-07-10T00:06:22Z | 38,287,435 | <p>There are a lot of things strange about your code. For example, there is no reason to iterate over the range object and update a list just to get a list of numbers. Just use <code>list(range(1,100))</code>. </p>
<p>However, if you just need the first 100 columns in the csv, there is built-in functionality for what ... | 1 | 2016-07-10T00:12:38Z | [
"python",
"python-2.7",
"pandas"
] |
Is this slicing behavior defined? | 38,287,420 | <p>I am dealing with Python's slicing and I encountered unexpected results.</p>
<p><strong>Example:</strong></p>
<pre><code>print([1, 2, 3][0:-4:-1])
</code></pre>
<p>Returns <code>[1]</code></p>
<pre><code>print([1, 2, 3][0:-3:-1])
print([1, 2, 3][0:-2:-1])
print([1, 2, 3][0:-1:-1])
</code></pre>
<p>Each of these... | 2 | 2016-07-10T00:09:07Z | 38,287,465 | <p>In a <a href="https://docs.python.org/2/whatsnew/2.3.html#extended-slices" rel="nofollow">slice</a>, the first item (start) is inclusive. The second argument (stop) is <em>ex</em>clusive. When a stop of -3 is given, that means to go from <code>1</code>, to <code>1</code>. Since the stop is exclusive, that exclude... | 2 | 2016-07-10T00:18:27Z | [
"python",
"python-3.x",
"slice"
] |
Is this slicing behavior defined? | 38,287,420 | <p>I am dealing with Python's slicing and I encountered unexpected results.</p>
<p><strong>Example:</strong></p>
<pre><code>print([1, 2, 3][0:-4:-1])
</code></pre>
<p>Returns <code>[1]</code></p>
<pre><code>print([1, 2, 3][0:-3:-1])
print([1, 2, 3][0:-2:-1])
print([1, 2, 3][0:-1:-1])
</code></pre>
<p>Each of these... | 2 | 2016-07-10T00:09:07Z | 38,287,474 | <p>I think this is clearer if you reverse the slice and convert to regular indexing. Since python uses half-open intervals, <code>[0:-4:-1]</code> converts to <code>[1, 2, 3][-3:1]</code>. <code>-3</code> in this case corresponds to index <code>0</code>, so this converts to <code>[1, 2, 3][0:1]</code>, which is just ... | 1 | 2016-07-10T00:21:16Z | [
"python",
"python-3.x",
"slice"
] |
creating cpp files with a python script | 38,287,589 | <p>For academic reasons, I want to write a python script that will auto-generate some c++ code by script that I write creating a cpp file and writing to that file. However when I try to run something like this</p>
<pre><code>path = (wherever I want a cpp file to be created)
f = open(path, "w")
</code></pre>
<p>I get ... | -5 | 2016-07-10T00:45:29Z | 38,288,025 | <p><code>open</code> won't create a new directory, just a new file in an existing directory. So if the directory <code>/path/to/directory/</code> exists, then</p>
<pre><code>open('/path/to/directory/new_file.cpp','w')
</code></pre>
<p>will work. However, if <code>/path/to/new_directory/</code> does not yet exist, t... | 0 | 2016-07-10T02:22:04Z | [
"python"
] |
Pandas: Summarize table based on column value | 38,287,621 | <p>My Pandas Dataframe is in this format:</p>
<pre><code>A 5
A 7
A 4
B 2
B 7
C 8
</code></pre>
<p>How could I summarize to this:</p>
<pre><code>A 16
B 9
C 8
</code></pre>
| -2 | 2016-07-10T00:52:22Z | 38,287,652 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a>:</p>
<pre><code> col1 col2
0 A 5
1 A 7
2 A 4
3 B 2
4 B 7
5 C 8
df.groupby('col1')['col2'].sum()
col1
A 16
B 9
C 8
</code></pre>
<p>If you want t... | 4 | 2016-07-10T00:59:20Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Summarize table based on column value | 38,287,621 | <p>My Pandas Dataframe is in this format:</p>
<pre><code>A 5
A 7
A 4
B 2
B 7
C 8
</code></pre>
<p>How could I summarize to this:</p>
<pre><code>A 16
B 9
C 8
</code></pre>
| -2 | 2016-07-10T00:52:22Z | 38,291,155 | <p>I think you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> for that with <code>sum</code> as aggregation function:</p>
<pre><code>In [9]: df
Out[9]:
0 1
0 A 5
1 A 7
2 A 4
3 B 2
4 B 7
5 C 8
In [... | 1 | 2016-07-10T11:00:18Z | [
"python",
"pandas",
"dataframe"
] |
django: subclass name from base model | 38,287,646 | <p>Want to access my subclass name from the base model:</p>
<pre><code>class Asset(models.Model):
name = models.CharField(max_length=50, blank=False)
country = models.ForeignKey(Country)
industry = models.ForeignKey(Industry)
ric = models.CharField(max_length=50, blank=False)
notes = models.TextFie... | 2 | 2016-07-10T00:57:47Z | 38,297,563 | <p>finally i've resolved my problem in this way, this IS NOT the most elegant way to do it but it works :)</p>
<pre><code>class Asset(models.Model):
name = models.CharField(max_length=50, blank=False)
country = models.ForeignKey(Country)
industry = models.ForeignKey(Industry)
ric = models.CharField(max_length=50, blan... | 0 | 2016-07-11T00:14:38Z | [
"python",
"django",
"django-admin"
] |
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128) | 38,287,696 | <p>Posting again as the previous post had the API token in it. I am scraping data from a website: Here is the code:</p>
<pre><code>reload(sys)
sys.setdefaultencoding('utf-8-sig')
def __unicode__(self):
return unicode(self.some_field) or u''
def daterange(start_date, end_date):
for n in range(int ((end_date - s... | 0 | 2016-07-10T01:08:21Z | 38,287,763 | <p>One brute force way to remove all non-ASCII characters from a string is:</p>
<pre><code>import re
# substitute sequence of non-ASCII characters with single space
str = re.sub(r'[^\x00-\x7F]+',' ', str)
</code></pre>
<p>Hope that helps in your case</p>
| 0 | 2016-07-10T01:20:07Z | [
"python",
"python-2.7",
"pandas",
"unicode"
] |
Root to leaf path sum equal to a given number in python | 38,287,716 | <p>I wrote the following code for this problem in python which seems to work. </p>
<p>I understand that in python everything is bound to an object. So, in this case, wouldn't my <code>currSum</code> reflect the updated value as we go back up the recursion stack (I mean say we go to process the right child after we hav... | 0 | 2016-07-10T01:12:12Z | 38,287,757 | <p>Short answer: No.</p>
<p>Longer answer: The statement <code>currSum = currSum + node.data</code>, which is the only one that makes any kind of change to <code>currSum</code>, does <em>not</em> alter the object that that variable refers to; rather, it creates a <em>new</em> object and has <code>curium</code> point t... | 0 | 2016-07-10T01:18:49Z | [
"python",
"tree"
] |
scrapy python code to list urls not appears to work as hoped | 38,287,853 | <p>I am trying to write some code to scrap the website of a UK housebuilder to record a list of houses for sale.</p>
<p>I am starting on the page <a href="http://www.persimmonhomes.com/sitemap" rel="nofollow">http://www.persimmonhomes.com/sitemap</a> and I have written one part of the code to list all the urls of the ... | 1 | 2016-07-10T01:39:11Z | 38,287,879 | <p>You just need to fix your <code>allowed_domains</code> property:</p>
<pre><code>allowed_domains = ["persimmonhomes.com"]
</code></pre>
<p>(tested - worked for me).</p>
| 1 | 2016-07-10T01:47:29Z | [
"python",
"scrapy"
] |
How to read data sent to an XBee on Windows? | 38,288,026 | <p>How can I read the data I am sending to my XBee connected to my Windows machine?</p>
<p>I want to see if the data is being sent correctly, because my code is compiling correctly in IDLE, but if I try to read the serial console in XCTU it says the port is currently being occupied. Any ideas on how to read the data I... | 0 | 2016-07-10T02:22:55Z | 38,288,178 | <p>You have both XBees connected, while communicating to one in the python code, you have the other in the serial console in XCTU. Writing to the port will display the message.</p>
| 0 | 2016-07-10T02:59:42Z | [
"python",
"xbee"
] |
How to read data sent to an XBee on Windows? | 38,288,026 | <p>How can I read the data I am sending to my XBee connected to my Windows machine?</p>
<p>I want to see if the data is being sent correctly, because my code is compiling correctly in IDLE, but if I try to read the serial console in XCTU it says the port is currently being occupied. Any ideas on how to read the data I... | 0 | 2016-07-10T02:22:55Z | 38,296,906 | <p>Are you trying to open COM3 in XCTU? You won't be able to do that since you have it open in Python. Is that XBee module paired with one on another serial port where you'd be able to see the output?</p>
<p>You might want to add a delay between the <code>ser.write()</code> and <code>ser.close()</code> calls to ensu... | 0 | 2016-07-10T22:14:49Z | [
"python",
"xbee"
] |
How to read data sent to an XBee on Windows? | 38,288,026 | <p>How can I read the data I am sending to my XBee connected to my Windows machine?</p>
<p>I want to see if the data is being sent correctly, because my code is compiling correctly in IDLE, but if I try to read the serial console in XCTU it says the port is currently being occupied. Any ideas on how to read the data I... | 0 | 2016-07-10T02:22:55Z | 38,844,780 | <p>Have you considered using the Python-Xbee library also? It makes deciding packerts easier:</p>
<p><a href="https://github.com/nioinnovation/python-xbee" rel="nofollow">https://github.com/nioinnovation/python-xbee</a></p>
<p>This library also has support for Zigbee.</p>
<p>Jim</p>
| 0 | 2016-08-09T07:38:47Z | [
"python",
"xbee"
] |
Get value in list on Python | 38,288,110 | <p>See the code:</p>
<pre><code>mult = [lambda x, i=i:x*i for i in range(4)]
for v in mult:
print(v)
</code></pre>
<p>But my return value is:</p>
<pre><code><function <listcomp>.<lambda> at 0x7fd8b26b9d08>
<function <listcomp>.<lambda> at 0x7fd8b26b9d90>
<function <listc... | -2 | 2016-07-10T02:43:50Z | 38,288,126 | <p>you just create 4 functions with different i</p>
<pre><code>a = [lambda x, i=i:x*i for i in range(4)]
for func in a:
print func(1)
0
1
2
3
</code></pre>
| 2 | 2016-07-10T02:46:18Z | [
"python",
"lambda",
"list-comprehension"
] |
Python - Replacing warnings with a simple message | 38,288,203 | <p>I have built a few off-the-shelf classifiers from <code>sklearn</code> and there are some expected scenarios where I know the classifier is bound to perform badly and not predict anything correctly. The sklearn.svm package runs without an error but raises the following warning.</p>
<pre><code>~/anaconda/lib/python3... | 0 | 2016-07-10T03:07:21Z | 38,288,462 | <p>Suppressing all warnings is easy with <code>-Wignore</code> (see <a href="https://docs.python.org/3/using/cmdline.html?highlight=isolated#cmdoption-W" rel="nofollow">warning flag docs</a>)</p>
<p>The <code>warnings</code> module can do some finer-tuning with filters (ignore just your warning type).</p>
<p>Capturin... | 1 | 2016-07-10T04:06:15Z | [
"python",
"warnings",
"suppress"
] |
PyMongo authentication failing | 38,288,204 | <p>I set up a database with mongolab where the db had the same name as the collection. I decided I didnt like this deleted it and made a better naming scheme. I added a new user/password to for the new db and tried to authenticated. It keeps failing. Not sure why. I have double check my credentials and they are correct... | 0 | 2016-07-10T03:07:49Z | 38,295,046 | <p>Nothing wrong with the code... the db user set up entered the incorrect password the same twice in the setup box so it was accepted then when the code was trying to use the actual correct answer it wouldn't work for obvious reasons. thanks all for looking</p>
| 0 | 2016-07-10T18:15:26Z | [
"python",
"mongodb",
"authentication",
"nosql",
"pymongo"
] |
How to append values to python list instead of replacing the values with latest value | 38,288,214 | <p>Hi the following is my python/django code:</p>
<pre><code>values = Record.objects.filter(record_id__in=[1,2,3], is_main_record=True)
if values .filter(status='open'):
all_item = ['sasi', 'kuttu','vava']
for item in items:
values1 = values.filter(set=mask, status='open')
print values1
</code></... | 1 | 2016-07-10T03:10:01Z | 38,288,271 | <pre><code>jobs = []
values = Record.objects.filter(record_id__in=[1,2,3], is_main_record=True, status='open', set__in=['sasi', 'kuttu','vava'])
if values.exists():
all_item = ['sasi', 'kuttu','vava']
for mask in all_item:
for x in values:
data = {'item' : x.item, 'device': x.device, 'log': x.lo... | 0 | 2016-07-10T03:21:17Z | [
"python",
"django",
"dictionary"
] |
If statement acting like while statement python3 | 38,288,412 | <p>For some reason, this code: </p>
<pre><code> def display_jan_appointments():
for item in appointment_dates:
if item[0:2] == "01" and item[3:5] == "01" and not adding:
pygame.draw.ellipse(screen, BLUE, [915, 275, 20, 20])
jan_1_index.append(appointment_date... | 0 | 2016-07-10T03:54:48Z | 38,288,626 | <p>Two issues with the code - <code>list.index</code> will always return the index of the <em>first</em> match - so effectively, you'll get repeated indices. The other issue (which is hard to tell from your code) is that likely something is mutating <code>appointment_dates</code>...</p>
<p>The Pythonic way to do this ... | 2 | 2016-07-10T04:37:47Z | [
"python",
"python-3.x"
] |
Python: The fatest way to compare 2 text file? | 38,288,540 | <p>I have 2 file: File A contains 200 000 lines; File B contains 4 000 000 lines. So, I want to compare these files and print the lines which aren't in File B.</p>
<p>For example:
File A:</p>
<pre><code> 1
2
3
</code></pre>
<p>File B:</p>
<pre><code> 1
4
5
6
7
</code></pre>
<p>The output:</p>... | 1 | 2016-07-10T04:19:37Z | 38,288,562 | <p>A faster way would be to open the file once and use a set:</p>
<pre><code>with open('C:/A.txt') as a:
with open('C:/B.txt') as b:
lines = set(b)
for line in a:
if line not in lines:
print(line)
</code></pre>
<p>Maybe a better way would be something like this:</p>
<pre><code>wit... | 1 | 2016-07-10T04:23:07Z | [
"python",
"windows",
"file",
"python-3.x"
] |
Python: The fatest way to compare 2 text file? | 38,288,540 | <p>I have 2 file: File A contains 200 000 lines; File B contains 4 000 000 lines. So, I want to compare these files and print the lines which aren't in File B.</p>
<p>For example:
File A:</p>
<pre><code> 1
2
3
</code></pre>
<p>File B:</p>
<pre><code> 1
4
5
6
7
</code></pre>
<p>The output:</p>... | 1 | 2016-07-10T04:19:37Z | 38,288,577 | <p>Create a set just of the hashes of lines in file B - and compare the lines in A with those in this set - </p>
<p>Such a set will take about about one hundred megabytes of memory, therefore should fit in memory in a notebook or workstation:</p>
<pre><code>linesB = {hash(line) for line in open("fileB"))}
for line in... | 2 | 2016-07-10T04:26:07Z | [
"python",
"windows",
"file",
"python-3.x"
] |
Python: The fatest way to compare 2 text file? | 38,288,540 | <p>I have 2 file: File A contains 200 000 lines; File B contains 4 000 000 lines. So, I want to compare these files and print the lines which aren't in File B.</p>
<p>For example:
File A:</p>
<pre><code> 1
2
3
</code></pre>
<p>File B:</p>
<pre><code> 1
4
5
6
7
</code></pre>
<p>The output:</p>... | 1 | 2016-07-10T04:19:37Z | 38,288,629 | <p>You could use the <code>set difference</code> operation to get all the lines that do not match in these files.</p>
<pre><code>with open('A.txt') as a:
contentA = set(a)
with open('B.txt') as b:
contentB = set(b)
print(contentA - contentB)
</code></pre>
<p>Edit:
The reverse operation, to print contents o... | 1 | 2016-07-10T04:38:10Z | [
"python",
"windows",
"file",
"python-3.x"
] |
PySide: Setting setDisabled(True) for a child menu entry not working in Mac | 38,288,554 | <p>I am creating a system tray application in Mac (El Capitan 10.11.3) using Pyside. However, I am not able to set certain menu entry as disabled, particularly when its a <strong>child menu</strong>. The <code>setDisabled(True)</code> works for <strong>parent menu</strong> entry though.</p>
<p>The same code works in U... | 0 | 2016-07-10T04:21:31Z | 38,293,659 | <p><a href="http://doc.qt.io/qt-4.8/qaction.html#setDisabled" rel="nofollow">http://doc.qt.io/qt-4.8/qaction.html#setDisabled</a>
the name of the method is same with qmenu.But qmenu's set disabled is inherite from qwidget while qaction's method is only for itself and it's not for the user interface. also qaction is abs... | 0 | 2016-07-10T15:47:31Z | [
"python",
"osx",
"qt",
"pyqt",
"pyside"
] |
PySide: Setting setDisabled(True) for a child menu entry not working in Mac | 38,288,554 | <p>I am creating a system tray application in Mac (El Capitan 10.11.3) using Pyside. However, I am not able to set certain menu entry as disabled, particularly when its a <strong>child menu</strong>. The <code>setDisabled(True)</code> works for <strong>parent menu</strong> entry though.</p>
<p>The same code works in U... | 0 | 2016-07-10T04:21:31Z | 38,361,305 | <pre><code>#This is the example code for Setting setDisabled(True) for a child .
#If your are not expecting this answer, sorry.
#It is PyQt4, but you can try with PySide with small changes.
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Window (QtGui.QWidget):
def __init__(self, parent=None):[!... | 0 | 2016-07-13T20:40:37Z | [
"python",
"osx",
"qt",
"pyqt",
"pyside"
] |
Can't display a normal image in matplotlib, it keeps displaying with the jet colormap | 38,288,624 | <p>I have code that displays the MISER regions of an image:</p>
<pre><code>import numpy as np
import cv2
import sys
import matplotlib.pyplot as plt
imp1 = sys.argv[1]
img1 = cv2.imread(imp1)
mser = cv2.MSER()
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
vis = img1.copy()
regions = mser.detect(gray, None)
hulls = [... | 3 | 2016-07-10T04:37:02Z | 38,288,884 | <p>The imshow docs says that cmap is ignored when image has RGB information.</p>
<p>You can consider creating a gray level image</p>
<pre><code>newimg = numpy.sum(img, 2)
</code></pre>
<p>Then</p>
<pre><code>ax.imshow(newimg, cmap='gray')
</code></pre>
| 0 | 2016-07-10T05:26:47Z | [
"python",
"opencv",
"matplotlib",
"rgb",
"colormap"
] |
Can't display a normal image in matplotlib, it keeps displaying with the jet colormap | 38,288,624 | <p>I have code that displays the MISER regions of an image:</p>
<pre><code>import numpy as np
import cv2
import sys
import matplotlib.pyplot as plt
imp1 = sys.argv[1]
img1 = cv2.imread(imp1)
mser = cv2.MSER()
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
vis = img1.copy()
regions = mser.detect(gray, None)
hulls = [... | 3 | 2016-07-10T04:37:02Z | 38,302,393 | <p>You data is stored as 64 bit numpy arrays, from the <a href="http://matplotlib.org/users/image_tutorial.html" rel="nofollow">docs</a>,</p>
<blockquote>
<p>For RGB and RGBA images, matplotlib supports float32 and uint8 data types</p>
</blockquote>
<p>You either need it in this format or need to specify a colormap... | 1 | 2016-07-11T08:30:16Z | [
"python",
"opencv",
"matplotlib",
"rgb",
"colormap"
] |
Python low-level vs high-level performance (running time analysis of palindrome functions) | 38,288,645 | <p>I am trying to find the most efficient way to check whether the given string is palindrome or not.<br>
Firstly, I tried brute force which has running time of the order O(N). Then I optimized the code a little bit by making only n/2 comparisons instead of n. </p>
<p>Here is the code: </p>
<pre><code>def palindrom... | 2 | 2016-07-10T04:40:00Z | 38,289,376 | <p>Your slicing-based solution is still O(n), the constant got smaller (that's your multiplier). It's faster, because less stuff is done in Python and more stuff is done in C. The bytecode shows it all. </p>
<pre><code>In [1]: import dis
In [2]: %paste
def palindrome(a):
length=len(a)
iterator=0
while ite... | 2 | 2016-07-10T06:48:21Z | [
"python",
"python-2.7"
] |
Pandas: replace list of values from list of columns | 38,288,711 | <p>I've got a many row, many column dataframe with different 'placeholder' values needing substitution (in a subset of columns). I've read many examples in the forum using nested lists or dictionaries, but haven't had luck with variations..</p>
<pre><code># A test dataframe
df = pd.DataFrame({'Sample':['alpha','beta',... | 3 | 2016-07-10T04:52:25Z | 38,288,867 | <p>You can set the <code>Sample</code> column as index and then replace values on the whole data frame based on conditions:</p>
<pre><code>df = df.set_index('Sample')
df[df < -1] = np.nan
df[(df < 0) & (df > -1)] = 0.05
</code></pre>
<p>Which gives:</p>
<pre><code># element1 element2 ele... | 3 | 2016-07-10T05:23:40Z | [
"python",
"pandas",
"replace"
] |
Pandas: replace list of values from list of columns | 38,288,711 | <p>I've got a many row, many column dataframe with different 'placeholder' values needing substitution (in a subset of columns). I've read many examples in the forum using nested lists or dictionaries, but haven't had luck with variations..</p>
<pre><code># A test dataframe
df = pd.DataFrame({'Sample':['alpha','beta',... | 3 | 2016-07-10T04:52:25Z | 38,297,653 | <p>Here is the successful answer as suggested by @Psidom.</p>
<p>The solution involves taking a slice out of the dataframe, applying the function, then reincorporates the amended slice:</p>
<pre><code>df1 = df.loc[:, headings]
df1[df1 < -1] = np.nan
df1[(df1 < 0)] = 0.05
df.loc[:, headings] = df1
</code></pre>... | 1 | 2016-07-11T00:30:01Z | [
"python",
"pandas",
"replace"
] |
Python equivalent for Ruby combination method | 38,288,735 | <p>Is there <strong><em>idiomatic python way</em></strong> to list all combinations of specific size from a list?</p>
<p>The following code works in ruby (<a href="http://ruby-doc.org/core-1.9.3/Array.html#method-i-combination" rel="nofollow">here</a>), I wonder if there is python equivalent for this:</p>
<pre><code>... | 1 | 2016-07-10T04:57:30Z | 38,288,760 | <p><a href="https://docs.python.org/2.7/library/itertools.html#itertools.combinations">The <code>itertools</code> module has a <code>combinations</code></a> method which does this for you.</p>
<pre><code>itertools.combinations(a, len)
</code></pre>
<p>Demo:</p>
<pre><code>>>> a = [1, 2, 3, 4]
>>> i... | 5 | 2016-07-10T05:01:13Z | [
"python",
"arrays",
"ruby"
] |
How to redirect the output of my program into a .txt file using Linux | 38,288,828 | <p>I need to redirect the output of a function into a .txt file.
I'm using the function <em>printClassTree()</em> from the library <em>ontospy</em>.
The code of my program is very simple:</p>
<pre><code>import ontospy
g = ontospy.Graph("/home/gabsbelini/Documentos/ontologiaTeste.owl")
g.printClassTree()
</code></pre>
... | 0 | 2016-07-10T05:15:01Z | 38,288,838 | <p>try tee:</p>
<pre><code>python myprogram.py | tee file.txt
</code></pre>
<p>or from python</p>
<pre><code>with open('file.txt', 'w') as fh:
fh.write(g.printClassTree())
</code></pre>
<p>EDIT
In case is going to <code>stderr</code> you can try:</p>
<p>python myprogram.py 2>&1 | tee file.txt</p>
<p>EDIT... | 0 | 2016-07-10T05:17:15Z | [
"python",
"linux",
"python-2.7"
] |
Redis - how to RPUSH/LPUSH an empty list | 38,288,839 | <p>We'd like to RPUSH/LPUSH a key with an empty list.<br/>
This is for consistency reasons: when the key is read with LRANGE than whether the list is empty or not, the rest of the code behaves the same.<br/>
<br/>
Why the fact that if a key has an empty list it is deleted is a problem? <br/>
Because we are using Redis ... | 0 | 2016-07-10T05:17:27Z | 38,289,365 | <p>Empty lists do not exist in Redis - a list must have one or more items. Empty lists (e.g. as a result of popping a non-empty one) are automatically removed.</p>
| 1 | 2016-07-10T06:45:31Z | [
"python",
"caching",
"redis",
"push",
"empty-list"
] |
Subsequent Google links python beautifulsoup: How To? | 38,288,847 | <p>How would you go about grabbing the first link off google using beautiful soup and requests with Python 2.7? And <strong>if</strong> the first link isn't the link I want <strong>then</strong> grab the second link off google, and <strong>if</strong> <em>that</em> link isn't the link then the third, etc. </p>
<p>Or i... | -1 | 2016-07-10T05:18:44Z | 38,294,426 | <p>Instead grabbing just the first one grab all of them into a list:</p>
<pre><code>cites = soup.find_all('cite')
</code></pre>
<p>Use a for loop to go through them looking for the one you want:</p>
<pre><code>for cite in cites:
</code></pre>
<p>Then just check if 'www.yelp.com/biz' is in the link:</p>
<pre><code>... | 0 | 2016-07-10T17:08:06Z | [
"python",
"web-scraping",
"beautifulsoup",
"python-requests",
"scraper"
] |
Custom Python module not importing | 38,288,860 | <p>I can't seem to get past this and do not quite understand what is happening. I have a directory with two class files in it. Using the REPL from within that directory I can import both files and execute their logic. From their parent directory which main() is ran from however, only one class file is visible, pagetabl... | 0 | 2016-07-10T05:23:07Z | 38,289,033 | <p>The solution as I suspected was a pathing issue and more specifically in relation to how the modules interact once imported into the parent file, pagingsimulation.py.</p>
<p>So to resolve this issue it had nothing to do with __init__.py but rather how I was accessing page.py from within pagetable.py</p>
<p>So pagi... | 0 | 2016-07-10T05:49:56Z | [
"python",
"debugging",
"import",
"module",
"runtime-error"
] |
How to manipulate a python dictionary by adding object from other tables | 38,288,881 | <p>Hi I have the following to create the data structure (List of dictionaries)</p>
<pre><code>jobs = []
values = Record.objects.filter(record_id__in=[1,2,3], is_main_record=True, status='open', set__in=['sasi', 'kuttu','vava'])
if values.exists():
all_item = ['sasi', 'kuttu','vava']
for mask in all_item:
... | 0 | 2016-07-10T05:26:16Z | 38,289,558 | <p>You can add a new field to your dictionary. It will be independent of your database.</p>
<p>The way will be kind of:</p>
<pre><code>for job in jobs:
// DO YOUR STUFF...
job['owner'] = newValue;
</code></pre>
<p>You are adding another field to that specific job. You can check or recover or whatever you want before... | 0 | 2016-07-10T07:13:16Z | [
"python",
"mysql",
"django",
"dictionary",
"data-manipulation"
] |
how to unpack a list while returning it? | 38,288,883 | <pre><code>def function(inputlist, outputlist,**kwargs):
def f(*inputlist, **kwargs):
return outputlist
return f
</code></pre>
<p>will return a list, But I want the return value to be seperate values.</p>
| -1 | 2016-07-10T05:26:45Z | 38,289,758 | <p>Suppose you have <code>n</code> value in <code>outputlist</code>. Then instead of</p>
<pre><code>return outputlist
</code></pre>
<p>you'd like to</p>
<pre><code>return outputlist[0], outputlist[1], ..., outputlist[n]
</code></pre>
<p>Obviously</p>
<pre><code>return *outputlist
</code></pre>
<p>does not work an... | 0 | 2016-07-10T07:42:58Z | [
"python"
] |
Python telnetlib read_until returns cut off string | 38,288,887 | <h1><strong>[Python telnetlib read_until recv problem]</strong></h1>
<p>"read_until" function returns cut off string with long commands.<br>
The commands ran perfectly, but it does not show full texts.<br>
How can I fix this? Please help.</p>
<p><strong># my code</strong></p>
<pre><code>tn = telnetlib.Telnet(ip, 23,... | 2 | 2016-07-10T05:27:57Z | 38,712,350 | <p>The issue appears to be occurring due to line-wrapping.
I found a solution where setting the window size width to near the max value allows long lines to be received without line-wrapping applied by the telnet server.</p>
<p>(See the <em>Window Size Option</em> RFC for details on setting the option <a href="https:/... | 0 | 2016-08-02T05:28:13Z | [
"python",
"telnet",
"telnetlib"
] |
Python and background running program with 'shortcut keys' | 38,288,914 | <p>I'm looking for a way to allow a program to run in the background while during other tasks, and still be able execute commands by input from the user, in the form a short-cut keys.</p>
<p>For example: if I'm browsing a homepage and press shift-f a method will execute in a background running python program.</p>
| 0 | 2016-07-10T05:32:27Z | 38,289,229 | <p>You could use <a href="https://tronche.com/gui/x/xlib/display/opening.html" rel="nofollow"><code>Xlib.display</code></a> to capture keyboard input even when your application is not in focus.</p>
<p>Here is a very basic example:</p>
<pre><code>from Xlib.display import Display
from pprint import pprint
import time
... | 1 | 2016-07-10T06:24:58Z | [
"python"
] |
In Python, is None a unique object? | 38,288,926 | <p>In my test code, why the <code>print</code> results for tuple and None are different? It seems that a, b point to the same object <code>None</code>, but c, d point to different objects, though their values are the same (both equal to <code>(a,b)</code>). </p>
<p>I know that <code>is</code> keyword checks for the ob... | 2 | 2016-07-10T05:34:05Z | 38,288,955 | <p><a href="https://docs.python.org/2/library/constants.html#None"><code>None</code> object is a singleton in python.</a> Hence the result. </p>
<p>Whereas for <code>c</code> and <code>d</code>, it creates separate tuples.</p>
<p>From your example:</p>
<pre><code>>>> id(None)
4454442584
>>> id(a)
4... | 6 | 2016-07-10T05:38:00Z | [
"python",
"object",
"nonetype"
] |
In Python, is None a unique object? | 38,288,926 | <p>In my test code, why the <code>print</code> results for tuple and None are different? It seems that a, b point to the same object <code>None</code>, but c, d point to different objects, though their values are the same (both equal to <code>(a,b)</code>). </p>
<p>I know that <code>is</code> keyword checks for the ob... | 2 | 2016-07-10T05:34:05Z | 38,288,959 | <p><a href="https://docs.python.org/2/c-api/none.html" rel="nofollow"><code>None</code></a> is a singleton object: only one instance of it can ever exist. So objects referencing <code>None</code> will always have the same identity, and two or more of such objects will always pass the identity (object equality) test:</... | 4 | 2016-07-10T05:38:11Z | [
"python",
"object",
"nonetype"
] |
In Python, is None a unique object? | 38,288,926 | <p>In my test code, why the <code>print</code> results for tuple and None are different? It seems that a, b point to the same object <code>None</code>, but c, d point to different objects, though their values are the same (both equal to <code>(a,b)</code>). </p>
<p>I know that <code>is</code> keyword checks for the ob... | 2 | 2016-07-10T05:34:05Z | 38,289,055 | <p>The 'is' operator compares the objects behind the variables as you figured out.</p>
<pre><code>a=None
b=None
print(a is b)
>True #both None are the same instanciations or objects
</code></pre>
<p>The None Object in Python is a singleton (<a href="https://docs.python.org/2/c-api/none.html" rel="nofollow">https:/... | 1 | 2016-07-10T05:54:46Z | [
"python",
"object",
"nonetype"
] |
Python Spyder initializing Hello World Kivi app once? | 38,289,017 | <p>Does anyone know why Python's 2.7 Spyder is successfully initializing the 'Hello World' Kivy app just once, i.e. hitting F5 brings the window app, but when I close it and hit F5 again, it says the following error:</p>
<pre><code>[INFO ] [Base ] Start application main loop
[ERROR ] [B... | 1 | 2016-07-10T05:47:58Z | 38,289,771 | <p>Actually the sample program is just a minimum structure for you to try out how the interactive UI can be created in such a simple way.</p>
<p>And the in <code>TestApp</code>, it actually didn't implment the <code>event listerners</code> to handle the close event. And when you create your actual project, you should ... | 2 | 2016-07-10T07:44:57Z | [
"python",
"python-2.7",
"kivy",
"spyder"
] |
CALL with CURL an API through Python | 38,289,153 | <p>I am working with an API for license plate recognition ; and i get this curl command :</p>
<p>How to implement such call with curl in PYTHON?</p>
<pre><code>curl "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1?url=https%3A%2F%2Fwww.havenondemand.com%2Fsample-content%2Fvideos%2Fgb-plates.mp4&am... | -1 | 2016-07-10T06:11:07Z | 38,289,307 | <p>In Python, using the <code>requests</code> module is a much better option. Install it first:</p>
<pre><code>pip install requests
</code></pre>
<p>Then do this: </p>
<pre><code>import requests
API_URL = "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1"
data = {
"url": "https://www.havenon... | 0 | 2016-07-10T06:36:38Z | [
"python",
"curl"
] |
CALL with CURL an API through Python | 38,289,153 | <p>I am working with an API for license plate recognition ; and i get this curl command :</p>
<p>How to implement such call with curl in PYTHON?</p>
<pre><code>curl "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1?url=https%3A%2F%2Fwww.havenondemand.com%2Fsample-content%2Fvideos%2Fgb-plates.mp4&am... | -1 | 2016-07-10T06:11:07Z | 38,289,333 | <p>There are multiple options. You could start with <a href="https://github.com/HPE-Haven-OnDemand/havenondemand-python" rel="nofollow">urllib2</a> (or any other HTTP library like requests). A better option could be to directly use the python client library for <a href="https://github.com/HPE-Haven-OnDemand/havenondema... | 0 | 2016-07-10T06:40:38Z | [
"python",
"curl"
] |
Python Printing Alternative | 38,289,186 | <p>I'm using Python in Jupyter to write Cellular Automata, and in the end I'm basically plotting a huge (such as 100*100) array/list. The problem is that the array can't be plotted as a square in Jupyter since each row is splitted due to the large size of the matrix, and is there any way (saving as certain format?) to ... | 0 | 2016-07-10T06:15:27Z | 38,289,497 | <p>You can save your array like this:</p>
<pre><code>array = numpy.random.randint(2, size=(100,100))
numpy.savetxt('array.csv', array, delimiter=';', fmt='%1d')
</code></pre>
<p>This saves your array to a file called array.csv which you can open with any editor or office suite.</p>
| 0 | 2016-07-10T07:04:27Z | [
"python",
"jupyter",
"cellular-automata"
] |
Python dictionary automatically converting hexadecimals into decimals? | 38,289,209 | <p>I am working on a little Python method that needs to read a dictionary from another file that will represent the key, and values.</p>
<p>But it seems I am running into a problem with the representation of the number values that I am sending over. For example, some keys in my dictionary would look like this :</p>
<... | 2 | 2016-07-10T06:20:14Z | 38,289,233 | <blockquote>
<p>Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?</p>
</blockquote>
<p>They were not originally stored in hexadecimal. Python does not track any information about base; whether you type <code>0x1000</code> or <... | 6 | 2016-07-10T06:25:35Z | [
"python",
"dictionary",
"hex",
"decimal"
] |
Python dictionary automatically converting hexadecimals into decimals? | 38,289,209 | <p>I am working on a little Python method that needs to read a dictionary from another file that will represent the key, and values.</p>
<p>But it seems I am running into a problem with the representation of the number values that I am sending over. For example, some keys in my dictionary would look like this :</p>
<... | 2 | 2016-07-10T06:20:14Z | 38,289,295 | <p>Python stores the numbers the same way, the only thing that changes is the formatting. Your issue is how the numbers are being formatted, not represented, thus, you fix your problem with string formatting:</p>
<pre><code>>>> d = {k:v for k,v in zip('abcdefg',range(1,5000,313))}
>>> d
{'e': 1253, '... | 2 | 2016-07-10T06:35:10Z | [
"python",
"dictionary",
"hex",
"decimal"
] |
greedy regex error in python while searching html tags | 38,289,273 | <p>I am new to <code>python</code> <code>regex</code></p>
<p>I know how to use <code>'?'</code> to solve the greedy problem
and the below example shows how it works:</p>
<pre><code>str2=' "anupam""behera" '
match2=re.search(r'".*?"',str2)
print match2.group()'
</code></pre>
<p>I get output <code>"anupam"</code></p>
... | 1 | 2016-07-10T06:31:14Z | 38,289,437 | <p>To address your question, you need to be more specific, like:</p>
<pre><code>r'<a href="(.*?)"\s.*?>(.*)</a>'
</code></pre>
<p>However, don't use regex to parse html/xml as noted in this <a href="http://stackoverflow.com/a/1732454/62138">famous answer</a>.</p>
<p>Use a parser like lxml. See how easy a... | 4 | 2016-07-10T06:56:42Z | [
"python",
"regex",
"regex-greedy"
] |
Django all-auth remove asking password twice in signup form | 38,289,442 | <p>I wanted to remove asking password twice from the django all-auth signup page. According to its manual <a href="http://django-allauth.readthedocs.io/en/latest/configuration.html" rel="nofollow">here</a>, i added the following to my settings</p>
<pre><code>ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
</code></pre>
<... | 0 | 2016-07-10T06:57:13Z | 38,990,453 | <p>This question was posted the 10th of July. The setting was renamed (in a backwards compatible manner though). The version where <code>ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE</code> became available was 0.26.0. So, likely you are using an older version where this setting is still named <code>ACCOUNT_SIGNUP_PASSWORD_VERIF... | 1 | 2016-08-17T07:22:31Z | [
"python",
"django",
"django-allauth"
] |
python logging: multiple loggers error | 38,289,690 | <p>I have objects called Job which has it's own logger (each Job need to have a log file which is represented by logging.getLogger())</p>
<p>The problem is I create thousands of Jobs (~4000) and they all want to create a logger.</p>
<pre><code>Traceback (most recent call last):
File "/u/lib/btool/Job.py", line 151,... | 0 | 2016-07-10T07:32:14Z | 38,289,807 | <p>Here's a custom file handler that stores the log message and then closes the file. </p>
<pre><code>import logging
class MyFileHandler(logging.Handler):
def __init__(self, filename):
self.filename = filename
super().__init__()
def emit(self, record):
log_text = self.format(record)
... | 1 | 2016-07-10T07:51:09Z | [
"python",
"logging"
] |
Django form for a table of checkboxes | 38,289,692 | <p>I'm trying to create a table-scheduler where people can pick the timeslots where they're free. I'm using django with a postgresql database. I have the below model:</p>
<pre><code>class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, unique=True)
name = models.CharField(ma... | 0 | 2016-07-10T07:33:09Z | 38,294,878 | <p>I would simply use two <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#datetimefield" rel="nofollow">datetime fields</a> and the render the table with slots in the front-end with javascript. You would have to have a <code>start_time</code> and an <code>end_time</code> field.</p>
<p>This simplifies... | 0 | 2016-07-10T17:56:46Z | [
"python",
"django",
"django-forms"
] |
flask html input format | 38,289,730 | <p>I am trying to read a file in using python/Flask and display it at the click of a button. To view the file, a return function like this works fine:</p>
<pre><code>return redirect(url_for('uploaded_file',filename=filename))
</code></pre>
<p>But I am trying to implement in HTML to view file at a click. Something lik... | 0 | 2016-07-10T07:39:27Z | 38,290,163 | <p>The action attribute should go on <code><form></code>, not <code><input></code>. The value of action should just be the URL of your route which accepts the file. Assuming you're using Jinja2, something like this:</p>
<p>Jinja2:</p>
<pre><code><form action="{{url_for('upload')}}" enctype="multipart/f... | 1 | 2016-07-10T08:45:44Z | [
"python",
"flask"
] |
flask html input format | 38,289,730 | <p>I am trying to read a file in using python/Flask and display it at the click of a button. To view the file, a return function like this works fine:</p>
<pre><code>return redirect(url_for('uploaded_file',filename=filename))
</code></pre>
<p>But I am trying to implement in HTML to view file at a click. Something lik... | 0 | 2016-07-10T07:39:27Z | 38,299,052 | <p>This code worked for me to pass filename to html form input. </p>
<p>python:</p>
<pre><code>...
return render_template('view.html', cat = filename)
</code></pre>
<p>html (view.html):</p>
<pre><code><!doctype html>
<form action="{{url_for('uploaded_file', filename=cat)}}" enctype="multipart/form-data">... | 0 | 2016-07-11T04:11:10Z | [
"python",
"flask"
] |
Mocking no ssl installed | 38,289,748 | <p>I am trying to test the compatibility wrapper for library against the possibility that Python was compiled without SSL support.</p>
<p>The problem is that this is detected using the following statement.</p>
<pre><code>try:
import ssl
except ImportError:
ssl = None
</code></pre>
<p>How would I go about moc... | 0 | 2016-07-10T07:41:35Z | 38,290,018 | <p>You can assign Mock() to the ssl module:</p>
<pre><code>import sys
sys.modules['ssl'] = Mock()
</code></pre>
<p>Before running the code where ssl gets imported.</p>
| 1 | 2016-07-10T08:21:56Z | [
"python",
"unit-testing",
"ssl"
] |
How to match both pattern under one regex? | 38,289,874 | <p>Raw Data:</p>
<pre><code># Case 1
1980 (reprint 1987)
# Case 2
1980 (1987 reprint)
</code></pre>
<p>Capture Group:</p>
<pre><code>{
publish: 1980,
reprint: 1987
}
</code></pre>
<p>Requirement:</p>
<ol>
<li>Match "reprint" and thus treat its year segment as reprint.</li>
<li>First matching year is alway... | 3 | 2016-07-10T08:00:53Z | 38,289,916 | <p>Maybe just:</p>
<pre><code>(?P<publish>\d{4}).*(?:reprint )?(?P<reprint>\d{4})(?: reprint)?
</code></pre>
<p><a href="https://regex101.com/r/lX7hK5/1" rel="nofollow">https://regex101.com/r/lX7hK5/1</a></p>
<p>This will assume that the reprint can appear before or after the date, but your raw data sugg... | 1 | 2016-07-10T08:07:18Z | [
"python",
"regex"
] |
How to match both pattern under one regex? | 38,289,874 | <p>Raw Data:</p>
<pre><code># Case 1
1980 (reprint 1987)
# Case 2
1980 (1987 reprint)
</code></pre>
<p>Capture Group:</p>
<pre><code>{
publish: 1980,
reprint: 1987
}
</code></pre>
<p>Requirement:</p>
<ol>
<li>Match "reprint" and thus treat its year segment as reprint.</li>
<li>First matching year is alway... | 3 | 2016-07-10T08:00:53Z | 38,289,944 | <p>All you need is specifying the parenthesis and mixing both regexes:</p>
<pre><code>r'(?P<publish>\d{4})\s\(.*(?P<reprint>\d{4}).*\)
</code></pre>
<p>Demo:</p>
<pre><code>>>> [i.groupdict() for i in re.finditer(r'(?P<publish>\d{4})\s\(.*(?P<reprint>\d{4}).*\)', s)]
[{'reprint': '19... | 1 | 2016-07-10T08:11:41Z | [
"python",
"regex"
] |
How to match both pattern under one regex? | 38,289,874 | <p>Raw Data:</p>
<pre><code># Case 1
1980 (reprint 1987)
# Case 2
1980 (1987 reprint)
</code></pre>
<p>Capture Group:</p>
<pre><code>{
publish: 1980,
reprint: 1987
}
</code></pre>
<p>Requirement:</p>
<ol>
<li>Match "reprint" and thus treat its year segment as reprint.</li>
<li>First matching year is alway... | 3 | 2016-07-10T08:00:53Z | 38,289,952 | <p>You can use this single regex with alternation. <code>reprint</code> group will match if it is followed by <code>\sreprint</code> (asserted by a positive lookahead) or if it preceded by <code>reprint\s</code> (asserted by a positive lookbehind).</p>
<pre><code>(?P<publish>\d{4}).*?(?P<reprint>(?:\d{4}(?... | 3 | 2016-07-10T08:12:36Z | [
"python",
"regex"
] |
django concrete inheritance, __str__(self) in parent fails to pick attribute from child | 38,289,889 | <p>In Django, I am using concrete inheritance as follows:</p>
<p>The Client class is a concrete parent, having the common fields. A client can be an Individual, or a Partnership, or a Company...</p>
<p><strong><em>Note: Yes I have read up on disadvantages of concrete inheritance, but my database is going to be small,... | 0 | 2016-07-10T08:03:15Z | 38,289,924 | <p>This is the wrong way round. If your method is referencing an attribute that only exists on the child model, then it should be on that child model. As a bonus, that makes the logic a lot simpler:</p>
<pre><code>class Client:
def name(self):
return self.First_Name + " " + self.Last_Name
class Individual... | 0 | 2016-07-10T08:08:41Z | [
"python",
"django",
"inheritance",
"django-models",
"django-admin"
] |
Extracting required Variables from Event Log file using Python | 38,289,890 | <p><a href="http://i.stack.imgur.com/zSGWk.png" rel="nofollow"><img src="http://i.stack.imgur.com/zSGWk.png" alt="enter image description here"></a></p>
<p>sample first row of event log file ,here i have successfully extracted evrything apart from last key value pair which is attribute-</p>
<pre><code>{"event_type":"... | 1 | 2016-07-10T08:03:26Z | 38,290,032 | <p><strong>Edit</strong></p>
<p>The data, after your edit, now appears to be JSON data. You can still use <code>literal_eval</code> as below, or you could use the <a href="https://docs.python.org/3/library/json.html#module-json" rel="nofollow"><code>json</code></a> module:</p>
<pre><code>import json
with open('event... | 2 | 2016-07-10T08:23:27Z | [
"python",
"pandas",
"text-parsing",
"string-parsing",
"text-extraction"
] |
Extracting required Variables from Event Log file using Python | 38,289,890 | <p><a href="http://i.stack.imgur.com/zSGWk.png" rel="nofollow"><img src="http://i.stack.imgur.com/zSGWk.png" alt="enter image description here"></a></p>
<p>sample first row of event log file ,here i have successfully extracted evrything apart from last key value pair which is attribute-</p>
<pre><code>{"event_type":"... | 1 | 2016-07-10T08:03:26Z | 38,299,276 | <p>This might not be the most efficient way to convert nested json records in a text file (delimited by line) to DataFrame object, but it kinda does the job.</p>
<pre><code>import pandas as pd
import json
from pandas.io.json import json_normalize
with open('path_to_your_text_file.txt', 'rb') as f:
data = f.readli... | 0 | 2016-07-11T04:40:16Z | [
"python",
"pandas",
"text-parsing",
"string-parsing",
"text-extraction"
] |
Python - Classes - Self Not Defined | 38,290,054 | <p>Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.</p>
<p>I'm guessing it's probably something easy</p>
<pre><code>import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b... | -1 | 2016-07-10T08:27:35Z | 38,290,086 | <ol>
<li><p>Your indention is wrong, but I assume this is only a copy-pasting issue.</p></li>
<li><p>That <code>start(self)</code> at the bottom doesn't make sense,<br>
and indeed <code>self</code> is not defined there. You should create an instance of the class, and then call its <code>start</code> method:</p>
<pre><... | 4 | 2016-07-10T08:33:15Z | [
"python",
"class",
"self"
] |
Python - Classes - Self Not Defined | 38,290,054 | <p>Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.</p>
<p>I'm guessing it's probably something easy</p>
<pre><code>import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b... | -1 | 2016-07-10T08:27:35Z | 38,290,129 | <p>You have two problems: </p>
<ol>
<li>you miss indentation on every class-function</li>
<li>you must create an object of the class before you can call any of its functions</li>
</ol>
<p>Your class should look like this</p>
<pre><code>import random
class KeyGenerator():
def __init__(self):
length = 0
... | 0 | 2016-07-10T08:40:39Z | [
"python",
"class",
"self"
] |
Using PyTables to index a 500 GB HDF5 file | 38,290,058 | <p>I would like to dump a keyed 500GB-800GB table into HDF5, and then then retrieve rows matching specific keys.</p>
<p>For an HDF5 file, items like all the data access uses an integer "row" number, so seems like I would have to implement a 'key to row number map" outside of HDF5. </p>
<p>Would this work? Do I need t... | 0 | 2016-07-10T08:28:36Z | 38,305,850 | <p>Assume that you have defined this record type in PyTables</p>
<pre><code>class Record(tables.IsDescription):
row = tables.Int32Col()
col1 = tables.Int32Col()
col2 = tables.Float64Col()
col3 = tables.Float64Col()
</code></pre>
<p>A regular range query might look like this: </p>
<pre><code>result = ... | 2 | 2016-07-11T11:31:32Z | [
"python",
"bigdata",
"hdf5",
"pytables",
"h5py"
] |
Slicing a string in Python without brackets | 38,290,094 | <p>Let's say I have a string like <code>num = "12345"</code>; how do I print it as one character like <code>1</code> or <code>2</code> without using brackets (<code>print(num[0])</code>)?</p>
| 0 | 2016-07-10T08:34:40Z | 38,290,111 | <p>The brackets are probably the correct way to do this, why do not want you to use it?</p>
<p>Anyway, you can <a href="https://www.python.org/dev/peps/pep-3132/" rel="nofollow">unpack your string</a> (only work with Python 3 as @DeepSpace precised), like this:</p>
<pre><code>letter, *_ = num
print(letter)
# "1"
</co... | 1 | 2016-07-10T08:37:27Z | [
"python",
"string",
"slice"
] |
Slicing a string in Python without brackets | 38,290,094 | <p>Let's say I have a string like <code>num = "12345"</code>; how do I print it as one character like <code>1</code> or <code>2</code> without using brackets (<code>print(num[0])</code>)?</p>
| 0 | 2016-07-10T08:34:40Z | 38,290,223 | <p>Another abuse of Python functions. </p>
<p>You could iterate over the string and only print values which are in a certain position.</p>
<pre><code>num = '12345'
values = (0, 1)
for i, n in enumerate(num):
if i in values:
print(n)
</code></pre>
| 0 | 2016-07-10T08:53:31Z | [
"python",
"string",
"slice"
] |
Slicing a string in Python without brackets | 38,290,094 | <p>Let's say I have a string like <code>num = "12345"</code>; how do I print it as one character like <code>1</code> or <code>2</code> without using brackets (<code>print(num[0])</code>)?</p>
| 0 | 2016-07-10T08:34:40Z | 38,290,245 | <p>Using iterators:</p>
<pre><code>chars = iter("12345")
print(next(chars)) # 1
print(next(chars)) # 2
</code></pre>
| 0 | 2016-07-10T08:57:13Z | [
"python",
"string",
"slice"
] |
Slicing a string in Python without brackets | 38,290,094 | <p>Let's say I have a string like <code>num = "12345"</code>; how do I print it as one character like <code>1</code> or <code>2</code> without using brackets (<code>print(num[0])</code>)?</p>
| 0 | 2016-07-10T08:34:40Z | 38,290,293 | <p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice()</code></a>:</p>
<pre><code>>>> from itertools import islice
>>> num = '123456'
>>> ''.join(islice(num, 0, 1)) # same as num[0]
'1'
>>> n = 4
>&g... | 0 | 2016-07-10T09:05:40Z | [
"python",
"string",
"slice"
] |
How can I convert Spark dataframe column to Numpy array efficiently? | 38,290,117 | <p>I have a Spark dataframe with around 1 million rows. I am using pyspark and have to apply box-cox transformation from scipy library on each column of the dataframe. But the box-cox function allows only 1-d numpy array as input. How can I do this efficiently? </p>
<p>Is numpy array distributed on spark or it collect... | 0 | 2016-07-10T08:39:18Z | 38,295,303 | <p>The dataframes/RDD in Spark allow abstracting from how the processing is distributed.</p>
<p>To do what you require, I think a UDF can be very useful. Here you can see an example of its use:</p>
<p><a href="http://stackoverflow.com/questions/29479872/functions-from-python-packages-for-udf-of-spark-dataframe">Funct... | 0 | 2016-07-10T18:42:58Z | [
"python",
"numpy",
"pyspark"
] |
How to return multiple forloop results (Django) | 38,290,146 | <p>I have function to return list of hotels:</p>
<pre><code>def search_result(request):
......
for hotels in json_data.get('hotelList'):
hotel = hotels.get('localizedName')
print hotel
return HttpResponse(hotel)
</code></pre>
<p>in console it prints whole list:</p>
<pre><code> ....
... | 0 | 2016-07-10T08:42:52Z | 38,290,155 | <p>You need to build a list and then return it.</p>
<pre><code>def search_result(request):
......
results = []
for hotels in json_data.get('hotelList'):
results.append(hotels.get('localizedName'))
return HttpResponse(results)
</code></pre>
<p>To display the contents properly, you need to us... | 3 | 2016-07-10T08:44:12Z | [
"python",
"django"
] |
How to return multiple forloop results (Django) | 38,290,146 | <p>I have function to return list of hotels:</p>
<pre><code>def search_result(request):
......
for hotels in json_data.get('hotelList'):
hotel = hotels.get('localizedName')
print hotel
return HttpResponse(hotel)
</code></pre>
<p>in console it prints whole list:</p>
<pre><code> ....
... | 0 | 2016-07-10T08:42:52Z | 38,290,164 | <p>Have you tried to return the whole list instead the content of last read and assigned hotel?</p>
<pre><code>json_data.get('hotelList')
</code></pre>
| 3 | 2016-07-10T08:45:55Z | [
"python",
"django"
] |
IndexError when creating squared list | 38,290,320 | <p>Would you please consider the following code?</p>
<pre><code>start_list = [5, 3, 1, 2, 4]
square_list = []
for i in start_list:
square_list.append(start_list[i]**2)
print square_list
</code></pre>
<p>This code was meant to iterate over start_list and append each number squared to square list. So the output is ... | 1 | 2016-07-10T09:09:22Z | 38,290,325 | <p>You are using the <em>values</em> in <code>start_list</code> as <em>indices</em>. The first such value is <code>5</code>, but you don't have a <code>start_list[5]</code>, giving you an <code>IndexError</code>. A Python <code>for</code> loop is a type of <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofol... | 1 | 2016-07-10T09:10:35Z | [
"python",
"append"
] |
IndexError when creating squared list | 38,290,320 | <p>Would you please consider the following code?</p>
<pre><code>start_list = [5, 3, 1, 2, 4]
square_list = []
for i in start_list:
square_list.append(start_list[i]**2)
print square_list
</code></pre>
<p>This code was meant to iterate over start_list and append each number squared to square list. So the output is ... | 1 | 2016-07-10T09:09:22Z | 38,290,366 | <p>You are using the values of start_list as positions of elements in start_list. The looping statement</p>
<pre><code>for i in start_list
square_list.append(start_list[i]**2)
print square_list
</code></pre>
<p>gives all values in start_list and then searches for elements with those values as indexes in start_lis... | 2 | 2016-07-10T09:16:23Z | [
"python",
"append"
] |
IndexError when creating squared list | 38,290,320 | <p>Would you please consider the following code?</p>
<pre><code>start_list = [5, 3, 1, 2, 4]
square_list = []
for i in start_list:
square_list.append(start_list[i]**2)
print square_list
</code></pre>
<p>This code was meant to iterate over start_list and append each number squared to square list. So the output is ... | 1 | 2016-07-10T09:09:22Z | 38,291,178 | <p>You could just use a list comprehension also :</p>
<pre><code>squarelist = [i**2 for i in start_list]
</code></pre>
<p>Or even this:</p>
<pre><code>squarelist = list(map(lambda x: x**2, start_list))
</code></pre>
| 0 | 2016-07-10T11:02:41Z | [
"python",
"append"
] |
IndexError when creating squared list | 38,290,320 | <p>Would you please consider the following code?</p>
<pre><code>start_list = [5, 3, 1, 2, 4]
square_list = []
for i in start_list:
square_list.append(start_list[i]**2)
print square_list
</code></pre>
<p>This code was meant to iterate over start_list and append each number squared to square list. So the output is ... | 1 | 2016-07-10T09:09:22Z | 38,291,343 | <p>You can use multiple sol:</p>
<pre><code>squarelist = [x**2 for x in start_list]
</code></pre>
<p>Or :</p>
<pre><code>squarelist = map(lambda x : x**2 , start_list)
</code></pre>
<p>Or : </p>
<pre><code>squarelist = []
for x in start_list :
squarelist.append(x**2)
</code></pre>
<p>Or </p>
<pre><code>squa... | 0 | 2016-07-10T11:23:13Z | [
"python",
"append"
] |
Strip out spaces in EXIF file (.txt file) with Python | 38,290,401 | <p>I have .txt files (one per image) that is formatted as can be seen below. I cannot figure out how to extract the information, without spaces, I am interested in.</p>
<pre><code>ExifTool Version Number : 10.20
File Name : R0010023.tiff
Directory : C:/gtag/wf1313
Fi... | 0 | 2016-07-10T09:21:39Z | 38,290,433 | <p>You have several options; the top two would be:</p>
<ul>
<li><p>split a line on <code>:</code>, <em>then</em> strip the parts:</p>
<pre><code>name, value = line.split(':', 1)
name, value = name.strip(), value.strip()
</code></pre>
<p>Note the second argument to <code>str.split()</code> as well; this limits the nu... | 0 | 2016-07-10T09:25:56Z | [
"python",
"dictionary",
"gps",
"exif",
"exiftool"
] |
Strip out spaces in EXIF file (.txt file) with Python | 38,290,401 | <p>I have .txt files (one per image) that is formatted as can be seen below. I cannot figure out how to extract the information, without spaces, I am interested in.</p>
<pre><code>ExifTool Version Number : 10.20
File Name : R0010023.tiff
Directory : C:/gtag/wf1313
Fi... | 0 | 2016-07-10T09:21:39Z | 38,293,784 | <p>Why not just have Exiftool output the info you want in the format you want directly. If the separator between the each piece of data is a tab (which it sort of looks like it might be), you can just specify the tags you want and the <a href="http://www.sno.phy.queensu.ca/~phil/exiftool/exiftool_pod.html#t" rel="nofo... | 0 | 2016-07-10T16:00:58Z | [
"python",
"dictionary",
"gps",
"exif",
"exiftool"
] |
webbrowser, opening chrome and internet explore for different url | 38,290,468 | <pre><code>url = 'http://www.google.org/'
chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
webbrowser.get(chrome_path)
webbrowser.open(url)
</code></pre>
<p>above will open chrome, which is what I want. </p>
<p>However if I change the url to <code>url = 'reddit</code> it will open inte... | 0 | 2016-07-10T09:30:53Z | 38,290,657 | <p>Do this: </p>
<pre><code>>>> import webbrowser
>>> browser = webbrowser.get()
>>> browser.open('http://google.com')
True
>>> browser.open_new_tab('http://yahoo.com')
True
>>>
</code></pre>
<p>The <code>webbrowser.get()</code> call will get you a browser controller objec... | 1 | 2016-07-10T09:57:12Z | [
"python",
"python-webbrowser"
] |
Python - Remove duplicate pandas data frames from dictionary | 38,290,470 | <p>I have a dictionary containing pandas data frames that have the same column names, and I'd like to remove duplicate data frames with identical values and row ids.</p>
<p>Let's assume this is my dictionary of data frames:</p>
<pre><code>>>> dd[0]
Origin Destination Ti... | 3 | 2016-07-10T09:31:11Z | 38,292,369 | <h3>One liner</h3>
<pre><code>{k: v.unstack() for k, v in pd.DataFrame({k: v.stack() for k, v in dd.iteritems()}).T.drop_duplicates().iterrows()}
</code></pre>
<h3>Explained version</h3>
<pre><code># iterate through key, value pairs of dictionary,
# stacking each dataframe into a series so that we
# can pass the res... | 2 | 2016-07-10T13:26:02Z | [
"python",
"pandas",
"dictionary",
"duplicates"
] |
Autochange values of a variable outside a while loop in Python | 38,290,538 | <p>I do not really know how to correctly ask this question so please bear with me. So,</p>
<pre><code>b=1
a=b
while (a<10):
b+=1
#a=b
print a, b
</code></pre>
<p>This returns an infinite loop UNLESS I remove the #. What I am asking is this: is there a way to UPDATE the value of var a without having t... | 0 | 2016-07-10T09:39:54Z | 38,290,688 | <p>You need to create separate function, and parameterize the formula. Try something like this:</p>
<pre><code>def calculate_value(oats=50, egg_whites=4, green_apple=1):
oats_value = (8*9+11*4+60*4)*oats_min/100
egg_whites_value = (0.1*9+3.6*4+0.2*4)*egg_whites
green_apple = (0.3*9+0.5+4+20.6*4)*green_apple ... | 0 | 2016-07-10T10:00:36Z | [
"python",
"loops",
"variables",
"while-loop"
] |
Autochange values of a variable outside a while loop in Python | 38,290,538 | <p>I do not really know how to correctly ask this question so please bear with me. So,</p>
<pre><code>b=1
a=b
while (a<10):
b+=1
#a=b
print a, b
</code></pre>
<p>This returns an infinite loop UNLESS I remove the #. What I am asking is this: is there a way to UPDATE the value of var a without having t... | 0 | 2016-07-10T09:39:54Z | 38,290,708 | <p>In python Integers are copied by value, instead of reference. So if you want to copy by reference you have to define those in a python list.try this code</p>
<pre><code>#python 3.4
b=[1]
a=b
while (a[0]<10):
b[0]=b[0]+1
#a=b
print(a[0], b[0])
</code></pre>
| 0 | 2016-07-10T10:02:30Z | [
"python",
"loops",
"variables",
"while-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.