title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Under which circumstances do equal strings share the same reference? | 11,611,750 | 8 | 2012-07-23T11:35:27Z | 11,611,774 | 8 | 2012-07-23T11:37:37Z | [
"python",
"string",
"reference",
"immutability"
] | I have searched the web and stack overflow questions but been unable to find an answer to this question. The observation that I've made is that in Python 2.7.3, if you assign two variables the same single character string, e.g.
```
>>> a = 'a'
>>> b = 'a'
>>> c = ' '
>>> d = ' '
```
Then the variables will share the ... | The details of when strings are cached and reused are implementation-dependent, can change from Python version to Python version and cannot be relied upon. If you want to check strings for equality, use `==`, not `is`.
In CPython (the most commonly-used Python implementation), string literals that occur in the source ... |
Modify wiki page (Confluence) programmatically | 11,611,865 | 2 | 2012-07-23T11:43:52Z | 18,776,841 | 9 | 2013-09-13T01:30:10Z | [
"python",
"html",
"urllib2"
] | I'd like to modify a wiki page (Confluence by Atlassian - JIRA editors) programmatically (in python). What I tried so far is to simulate user behaviour:
1. click on Edit button
2. change content of a `textarea` input
3. submit changes with Save button
Part 1 is ok since I have the URL corresponding to an edit of the ... | ```
# write to a confluence page
import xmlrpclib
CONFLUENCE_URL = "https://intranet.example.com/confluence/rpc/xmlrpc"
CONFLUENCE_LOGIN = "a confluence username here"
CONFLUENCE_PASSWORD = "confluence pwd for username"
# get this from the page url while editing
# e.g. ../editpage.action?pageId=132350005 <-- here
PA... |
in OR condition which side evaluate first in python? | 11,612,763 | 3 | 2012-07-23T12:42:14Z | 11,612,810 | 11 | 2012-07-23T12:44:47Z | [
"python",
"performance"
] | ```
if cpu_expensive_condition() or simple_condition():
do_something()
```
out of two condition in OR statement in above python code which will be evaluate first ? , and is it compulsory that both will be evaluate ? | > The expression `x or y` first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Quoted from [Python Language Reference](http://docs.python.org/reference/expressions.html#boolean-operations) |
Add items to a dictionary of lists | 11,613,284 | 4 | 2012-07-23T13:14:53Z | 11,613,314 | 7 | 2012-07-23T13:16:49Z | [
"python",
"dictionary"
] | Suppose the following toyset (from a CSV file where column names are the "keys" and I'm only interested in some rows that I put in "data"):
```
keys = ['k1', 'k2', 'k3', 'k4']
data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
```
I want to get a dictionary with a list for each column, like this:
... | You are running into the issue [explained in this answer](http://stackoverflow.com/questions/11509721/how-do-i-initialize-a-dictionary-of-empty-lists-in-python/11509759#11509759): You dictionary is initialised with *the same list object* resued for all values. Simply use
```
dict(zip(keys, zip(*data)))
```
instead. T... |
A safe, atomic file-copy operation | 11,614,815 | 7 | 2012-07-23T14:43:12Z | 11,614,863 | 10 | 2012-07-23T14:46:04Z | [
"python",
"concurrency"
] | I need to copy a file from one location to another, and I need to throw an exception (or at least somehow recognise) if the file already exists at the destination (no overwriting).
I can check first with os.path.exists() but it's extremely important that the file cannot be created in the small amount of time between c... | There is no way to do this; file copy operations are never atomic and there is no way to make them.
But you can write the file under a random, temporary name and then *rename* it. Rename operations have to be atomic. ~~If the file already exists, the rename will fail and you'll get an error.~~
**[EDIT2]** `rename()` ... |
Why use multiple arguments to log instead of interpolation? | 11,615,053 | 9 | 2012-07-23T14:54:57Z | 11,615,199 | 11 | 2012-07-23T15:02:57Z | [
"python",
"logging",
"interpolation"
] | Python's logging functions allow you to pass them multiple arguments that they can interpolate for you. So you have a choice:
```
logger.info("Something %s this way comes!" % "wicked")
```
or
```
logger.info("Something %s this way comes!", "wicked")
```
But why choose one over the other? Is it simply a matter of le... | It's a matter of performance :
* When you do the interpolation in your code, this code will be executed each time you call the logger (event if the logger or the log level is not activated)
* When you let the logger do the interpolation, it will do the interpolation only if the logger and log level is activated. |
Python interpreters uses up to 130% of my CPU. How is that possible? | 11,615,449 | 2 | 2012-07-23T15:17:49Z | 11,615,490 | 9 | 2012-07-23T15:20:03Z | [
"python",
"linux",
"multithreading",
"load"
] | I am currently doing some **I/O intensive load-testing** using python. All my program does is to send HTTP requests as fast as possible to my target server.
To manage this, I use **up to 20 *threads*** as I'm essentially bound to I/O and remote server limitations.
According to 'top', *CPython* uses a **peak of 130% C... | 100 percent in top refer to a single core. On a dual-core machine, you have up to 200 per cent available.
A single single-threaded process can only make use of a single core, so it is limited to 100 percent. Since your process has several threads, nothing is stopping it from making use of both cores.
The GIL only pre... |
Python: Start new command prompt on Windows and wait for it finish/exit | 11,615,455 | 11 | 2012-07-23T15:18:26Z | 11,615,580 | 18 | 2012-07-23T15:25:05Z | [
"python",
"windows"
] | I don't understand why it's so hard to do this on Windows.
I want to spawn a bunch of command prompt windows which will run other scripts. The reason I want this is so I can see all the output from each script neatly (if I have them just be threads/subprocesses in the main window I can't view all the output properly).... | Upon reading your comment to my previous answer what you need is:
```
os.system("start /wait cmd /c {command}")
```
Keep [the windows command reference](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true) always at hand! |
Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python | 11,615,504 | 18 | 2012-07-23T15:20:43Z | 11,617,682 | 23 | 2012-07-23T17:45:03Z | [
"python",
"pandas"
] | I'm starting using Python and I have a simple question related with csv files and parsing datetime.
I have a csv file that look like this:
```
YYYYMMDD, HH, X
20110101, 1, 10
20110101, 2, 20
20110101, 3, 30
```
I would like to read it using pandas (read\_csv) and have it in a dataframe indexed by the dat... | If you pass a list to `index_col`, it means you want to create a hierarchical index out of the columns in the list.
In addition, the `parse_dates` keyword can be set to either True or a list/dict. If True, then it tries to parse individual columns as dates, otherwise it combines columns to parse a single date column.
... |
Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python | 11,615,504 | 18 | 2012-07-23T15:20:43Z | 18,527,067 | 8 | 2013-08-30T07:15:45Z | [
"python",
"pandas"
] | I'm starting using Python and I have a simple question related with csv files and parsing datetime.
I have a csv file that look like this:
```
YYYYMMDD, HH, X
20110101, 1, 10
20110101, 2, 20
20110101, 3, 30
```
I would like to read it using pandas (read\_csv) and have it in a dataframe indexed by the dat... | I am doing this all the time, so I tested different ways for speed.
The fastest I found is the following, approx. 3 times faster than Chang She's solution, at least in my case, when taking the total time of file parsing and date parsing into account:
First, parse the data file using pd.read\_csv withOUT parsing dates.... |
Multivariate normal density in Python? | 11,615,664 | 27 | 2012-07-23T15:30:20Z | 11,615,969 | 7 | 2012-07-23T15:48:49Z | [
"python",
"numpy",
"scipy"
] | Is there any python package that allows the efficient computation of the multivariate normal pdf?
I doesn't seem to be included in Numpy/Scipy, and surprisingly a Google search didn't turn up anything useful. | In the common case of a diagonal covariance matrix, the multivariate PDF can be obtained by simply multiplying the univariate PDF values returned by a `scipy.stats.norm` instance. If you need the general case, you will probably have to code this yourself (which shouldn't be hard). |
Multivariate normal density in Python? | 11,615,664 | 27 | 2012-07-23T15:30:20Z | 14,831,639 | 16 | 2013-02-12T11:37:14Z | [
"python",
"numpy",
"scipy"
] | Is there any python package that allows the efficient computation of the multivariate normal pdf?
I doesn't seem to be included in Numpy/Scipy, and surprisingly a Google search didn't turn up anything useful. | I just made one for my purposes so I though I'd share. It's built using "the powers" of numpy, on the formula of the non degenerate case from <http://en.wikipedia.org/wiki/Multivariate_normal_distribution> and it aso validates the input.
Here is the code along with a sample run
```
from numpy import *
import math
# c... |
Multivariate normal density in Python? | 11,615,664 | 27 | 2012-07-23T15:30:20Z | 20,901,747 | 27 | 2014-01-03T10:43:07Z | [
"python",
"numpy",
"scipy"
] | Is there any python package that allows the efficient computation of the multivariate normal pdf?
I doesn't seem to be included in Numpy/Scipy, and surprisingly a Google search didn't turn up anything useful. | The multivariate normal is now available on `SciPy 0.14.0.dev-16fc0af`:
```
from scipy.stats import multivariate_normal
var = multivariate_normal(mean=[0,0], cov=[[1,0],[0,1]])
var.pdf([1,0])
``` |
scapy get packet's arrivals time | 11,615,892 | 4 | 2012-07-23T15:44:24Z | 11,707,946 | 8 | 2012-07-29T08:55:18Z | [
"python",
"packet-sniffers",
"scapy"
] | Is there a way to get the packet's arrivals time using scapy? Using scapy to read the pcap file and I want to know all the packet's arrivals time because as we know wireshark can see it. So I guess there must be a way. Anyone know? | use `pkt.time`
```
[mpenning@tsunami icinga-1.7.1]$ sudo python
[sudo] password for mpenning:
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from scapy.all import sniff
WARNING: No route found for IPv6 destination :: (no... |
Django: My models.py file seems to have trouble syncing to the database. | 11,616,371 | 7 | 2012-07-23T16:13:25Z | 11,616,394 | 14 | 2012-07-23T16:15:06Z | [
"python",
"database",
"django",
"terminal",
"syncdb"
] | I tried setting up a simple models.py file as part of this tutorial that I was following online. When I tried the syncdb command, I got the following errors:
```
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/co... | The problem is
```
email = models.EmailField
```
Change it to
```
email = models.EmailField()
```
This is because attributes of Django model classes are modified by the metaclass of `django.db.models.Model` rather than assigned directly as standard attributes, so that they can transparently talk to the database and... |
Python: List Comprehensions vs. map | 11,616,599 | 7 | 2012-07-23T16:28:22Z | 11,616,687 | 10 | 2012-07-23T16:35:20Z | [
"python",
"performance"
] | Referring to this [Python List Comprehension Vs. Map](http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map) question, can someone explain why List Comprehensions gives better results over `map` when list comprehension does not call a function, even when there is no lambda function in the `map` bu... | All your timing results can be explained by theses facts:
1. CPython has a rather high function call overhead.
2. `map(f, it)` is slightly faster than `[f(x) for x in it]`.
The first version of your code does not define a function at all, so there is no function call overhead. The second version needs to define a fun... |
What are the advantages of concurrent.futures over multiprocessing in Python? | 11,617,619 | 15 | 2012-07-23T17:40:39Z | 11,618,234 | 10 | 2012-07-23T18:23:12Z | [
"python",
"multithreading",
"multiprocessing",
"concurrent.futures"
] | I'm writing an app in Python and I need to run some tasks simultaneously. The module multiprocessing offers the class Process and the concurrent.futures module has the class ProcessPoolExecutor. Both seem to use multiple processes to execute their tasks, but their APIs are different. Why should I use one over the other... | The motivations for concurrent.futures are covered in the [PEP](http://www.python.org/dev/peps/pep-3148/).
In my practical experience concurrent.futures provides a more convenient programming model for long-running task submission and monitoring situations. A program I recently wrote using concurrent.futures involved ... |
How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file? | 11,617,719 | 19 | 2012-07-23T17:48:01Z | 11,618,291 | 19 | 2012-07-23T18:28:02Z | [
"python",
"matplotlib",
"bar-chart"
] | I use Python 2.7 and matplotlib. I have a \*.txt data file :
```
0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014
```
first column of my file (numbers) should be on axis Y in my bar chart, and the second column f... | This code will do what you're looking for. It's based on examples found [here](http://scienceoss.com/bar-plot-with-custom-axis-labels/) and [here](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar).
The `autofmt_xdate()` call is particularly useful for making the x-axis labels readable.
```
... |
How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file? | 11,617,719 | 19 | 2012-07-23T17:48:01Z | 11,618,384 | 27 | 2012-07-23T18:34:13Z | [
"python",
"matplotlib",
"bar-chart"
] | I use Python 2.7 and matplotlib. I have a \*.txt data file :
```
0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014
```
first column of my file (numbers) should be on axis Y in my bar chart, and the second column f... | You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.
Here is a complete example from your data that shows a bar of for each requir... |
Django: Multiple url patterns starting at the root spread across files | 11,618,105 | 8 | 2012-07-23T18:15:29Z | 11,618,280 | 21 | 2012-07-23T18:27:02Z | [
"python",
"django",
"django-urls"
] | I am wondering if it is possible to have the standard url patterns spread across multiple files (in this case the project-wide `urls.py` and several apps-specific `urls.py`).
Imagine that the project `urls.py` look like this (got this working):
```
from django.conf.urls import patterns, include, url
admin.autodiscove... | Sure. URLs are processed in order, and two includes can have the same prefix - if one doesn't succeed in matching, processing will just move on to the next one.
```
urlpatterns = patterns('',
url(r'^user/', include('registration.urls')),
url(r'^user/', include('profile.urls')),
)
``` |
python: check if a hostname is resolved | 11,618,118 | 10 | 2012-07-23T18:16:06Z | 11,618,198 | 24 | 2012-07-23T18:21:08Z | [
"python",
"hostname"
] | How can I have a function in python that returns 1 if the a hostname resolves and 0 if a hostname does not.
I couldn't find anything useful, any thoughts?
Thanks, | You can use [`socket.gethostbyname()`](http://docs.python.org/library/socket.html#socket.gethostbyname) for this:
```
>>> import socket
>>> socket.gethostbyname('google.com')
'74.125.224.198'
>>> socket.gethostbyname('foo') # no host 'foo' exists on the network
Traceback (most recent call last):
File "<std... |
Why can't you re-import in Python? | 11,618,687 | 3 | 2012-07-23T18:56:24Z | 11,618,688 | 10 | 2012-07-23T18:56:24Z | [
"python",
"import"
] | There are plenty of questions and answers regarding re-imports on SO, but it all seems very counter-intuitive without knowing the mechanisms behind it.
If you import a module, change the contents, then try to import it again, you'll find that the second import has no effect:
```
>>> import foo # foo.py contains: b... | When you import a module, it is cached in [`sys.modules`](http://docs.python.org/library/sys.html?highlight=sys.modules#sys.modules). Any attempt to import the same module again within the same session simply returns the already existing module contained there. This speeds up the overall experience when a module is imp... |
Is there a way to cancel gevent.spawn_later()? | 11,618,714 | 4 | 2012-07-23T18:57:41Z | 11,625,016 | 7 | 2012-07-24T06:04:23Z | [
"python",
"gevent"
] | If you call gevent.spawn\_later(), is there a way to cancel this scheduled function before it occurs? | Yes, use `kill()` method.
```
g = gevent.spawn_later(5, function)
g.kill()
``` |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 12,037,133 | 348 | 2012-08-20T11:51:48Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | `pg_config` is in `postgresql-devel` (`libpq-dev` in Debian/Ubuntu, `libpq-devel` on Cygwin/Babun.) |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 12,037,460 | 13 | 2012-08-20T12:16:12Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | Try to add it to PATH:
```
PATH=$PATH:/usr/pgsql-9.1/bin/ ./pip install psycopg2
``` |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 14,424,226 | 115 | 2013-01-20T11:51:21Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | Have you installed python-dev?
If you already have, try also installing libpq-dev
```
sudo apt-get install libpq-dev python-dev
```
From the article: [How to install psycopg2 under virtualenv](http://web.archive.org/web/20140615091953/http://goshawknest.wordpress.com/2011/02/16/how-to-install-psycopg2-under-virtualen... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 14,779,572 | 34 | 2013-02-08T19:04:05Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | ```
apt-get build-dep python-psycopg2
``` |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 17,482,690 | 24 | 2013-07-05T06:46:03Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | Just to sum up, I also faced exactly same problem. After reading a lot of stackoverflow posts and online blogs, the final solution which worked for me is this:
1) PostgreSQL(development or any stable version) should be installed before installing psycopg2.
2) The pg\_config file (this file normally resides in the bin... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 18,589,463 | 17 | 2013-09-03T10:04:48Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | UPDATE /etc/yum.repos.d/CentOS-Base.repo, [base] and [updates] sections
ADD exclude=postgresql\*
```
curl -O http://yum.postgresql.org/9.1/redhat/rhel-6-i386/pgdg-centos91-9.1-4.noarch.rpmr
rpm -ivh pgdg-centos91-9.1-4.noarch.rpm
yum install postgresql
yum install postgresql-devel
PATH=$PATH:/usr/pgsql-9.1/bin... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 20,860,520 | 15 | 2013-12-31T16:45:25Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | Ali's solution worked for me but I was having trouble finding the bin folder location. A quick way to find the path on Mac OS X is to open psql (there's a quick link in the top menu bar). This will open a separate terminal window and on the second line the path of your Postgres installation will appear like so:
```
My... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 24,645,416 | 126 | 2014-07-09T04:28:14Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | On Mac OS X, I solved it with
```
brew install postgresql
``` |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 24,684,701 | 30 | 2014-07-10T19:26:28Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | Also on OSX. Installed Postgress.app from <http://postgresapp.com/> but had the same issue.
I found `pg_config` in that app's contents and added the dir to `$PATH`.
It was at `/Applications/Postgres.app/Contents/Versions/9.3/bin`. So this worked: `export PATH="/Applications/Postgres.app/Contents/Versions/9.3/bin:$PAT... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 27,043,037 | 10 | 2014-11-20T15:16:26Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | This is what worked for me on CentOS, first install:
```
sudo yum install postgresql postgresql-devel python-devel
```
On Ubuntu just use the equivilent apt-get packages.
```
sudo apt-get install postgresql postgresql-dev python-dev
```
And now include the path to your postgresql binary dir with you pip install, th... |
pg_config executable not found | 11,618,898 | 304 | 2012-07-23T19:09:40Z | 29,276,961 | 14 | 2015-03-26T11:11:46Z | [
"python",
"pip",
"psycopg2"
] | I am having trouble installing psycopg2. I get the following error when I try to `pip install psycopg2`:
```
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_c... | For those running OS X, this solution worked for me:
1) Install Postgres.app:
<http://www.postgresql.org/download/macosx/>
2) Then open the Terminal and run this command, replacing where it says {{version}} with the Postgres version number:
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/{{version}}/... |
PyDev Offline install | 11,619,746 | 8 | 2012-07-23T20:10:07Z | 11,620,013 | 7 | 2012-07-23T20:27:26Z | [
"python",
"windows",
"eclipse",
"pydev"
] | I have a windows machine which has no connection to the internet. It's also not possible to connect this machine to the internet due security reasons.
How can I install `PyDev` without internet connection? | From [PyDev](http://pydev.org/manual_101_install.html) use [SourceForge download](http://sourceforge.net/projects/pydev/files/) and install manually via these instructions:
```
Installing with the zip file
The available locations for the zip files are:
Sourceforge download
After downloading the zip file:
Eclipse 3.... |
print series of prime numbers in python | 11,619,942 | 8 | 2012-07-23T20:22:35Z | 11,619,990 | 7 | 2012-07-23T20:25:16Z | [
"python",
"primes",
"series"
] | I am trying to learn Python programming, I'm pretty new at this. I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code. Hope someone could help me out with this. Here's what i wrote, it prints all the odd numbers instead of primes.
```
for num in ra... | `break` ends the loop that it is currently in. So, you are only ever checking if it divisible by 2, giving you all odd numbers.
```
for num in range(2,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
```
that being said, there are much better ways to find primes i... |
print series of prime numbers in python | 11,619,942 | 8 | 2012-07-23T20:22:35Z | 11,620,052 | 17 | 2012-07-23T20:31:02Z | [
"python",
"primes",
"series"
] | I am trying to learn Python programming, I'm pretty new at this. I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code. Hope someone could help me out with this. Here's what i wrote, it prints all the odd numbers instead of primes.
```
for num in ra... | You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n).
If `n` is divisible by any of the numbers, it is not prime. If a number is prime, print it.
```
for num in range(1,101):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
... |
What do numbers starting with 0 mean in python? | 11,620,151 | 28 | 2012-07-23T20:38:18Z | 11,620,174 | 34 | 2012-07-23T20:40:01Z | [
"python"
] | When I type small integers with a 0 in front into python, they give weird results. Why is this?
```
>>> 011
9
>>> 0100
64
>>> 027
23
```
Note: Python version 2.7.3
I have tested this in Python 3.0, and apparently this is now an error. So it is something version-specific.
Edit: they are apparently still integers:
``... | These are numbers represented in base 8 (octal numbers).
For example,
`011` is equal to `8**1 + 8**0` = 9,
`0100` is equal to `8**2` = 64,
`027` is equal to `2*8**1 + 7*8**0` = 16 + 7 = 23. |
What do numbers starting with 0 mean in python? | 11,620,151 | 28 | 2012-07-23T20:38:18Z | 11,620,194 | 20 | 2012-07-23T20:41:33Z | [
"python"
] | When I type small integers with a 0 in front into python, they give weird results. Why is this?
```
>>> 011
9
>>> 0100
64
>>> 027
23
```
Note: Python version 2.7.3
I have tested this in Python 3.0, and apparently this is now an error. So it is something version-specific.
Edit: they are apparently still integers:
``... | In Python 2 (and a few more programming languages), these represent [octal numbers](http://en.wikipedia.org/wiki/Octal).
In Python 3, `011` no longer works and you would use `0o11` instead.
*In response to edit*: and they are regular integers. They are just specified different way; and they are automatically converte... |
Removing nan values from an array | 11,620,914 | 47 | 2012-07-23T21:36:54Z | 11,620,945 | 16 | 2012-07-23T21:39:59Z | [
"python",
"arrays",
null
] | I want to figure out how to remove nan values from my array. It looks something like this:
```
x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration
```
I'm relatively new to python so I'm still learning. Any tips? | Try this:
```
import math
print [value for value in x if not math.isnan(value)]
```
For more, read on [List Comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). |
Removing nan values from an array | 11,620,914 | 47 | 2012-07-23T21:36:54Z | 11,620,982 | 94 | 2012-07-23T21:42:30Z | [
"python",
"arrays",
null
] | I want to figure out how to remove nan values from my array. It looks something like this:
```
x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration
```
I'm relatively new to python so I'm still learning. Any tips? | If you're using numpy for your arrays, you can also use
```
x = x[numpy.logical_not(numpy.isnan(x))]
```
Equivalently
```
x = x[~numpy.isnan(x)]
```
[Thanks to chbrown for the added shorthand]
**Explanation**
The inner function, `numpy. isnan` returns a boolean/logical array which is has the value `True` everywhe... |
Removing nan values from an array | 11,620,914 | 47 | 2012-07-23T21:36:54Z | 29,679,784 | 13 | 2015-04-16T15:46:36Z | [
"python",
"arrays",
null
] | I want to figure out how to remove nan values from my array. It looks something like this:
```
x = [1400, 1500, 1600, nan, nan, nan ,1700] #Not in this exact configuration
```
I'm relatively new to python so I'm still learning. Any tips? | ```
filter(lambda v: v==v, x)
```
works both for lists and numpy array
since v!=v only for NaN |
Google Appengine sending emails: [Error] unauthorized sender | 11,621,019 | 10 | 2012-07-23T21:45:09Z | 11,621,263 | 20 | 2012-07-23T22:06:40Z | [
"python",
"google-app-engine",
"email"
] | I'm trying to use google app engine's mail service on my site. It's showing some error whenever I visit the page that sends the email. The error says that I am using an unauthorized sender for the message. Here's the code that sends the email:
```
mail.send_mail(sender="myapp@appspot.gserviceaccount.com",
to=inpu... | What is myapp@appspot.gserviceaccount.com? You might not be able to send mail from that address.
> App Engine applications can send email messages on behalf of the app's
> administrators, and on behalf of users with Google Accounts.
>
> The email address of the sender, the From address. The sender address
> must be on... |
Indexing a pandas dataframe by integer | 11,621,165 | 7 | 2012-07-23T21:57:01Z | 11,622,565 | 9 | 2012-07-24T00:38:29Z | [
"python",
"pandas"
] | I can't seem to find an elegant way to [index](http://pandas.pydata.org/pandas-docs/stable/indexing.html) a [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/dsintro.html) by an integer index.
In the following example I want to get the value 'a' from the first element of the `'A'` column.
```
import panda... | You get an error with `df['A'].ix[0]` because your indexing doesn't start at 0, it starts at 10. You can get the value you want with either of the following
```
df['A'].ix[10]
df['A'].irow(0)
```
The first uses by the correct index. The second command, which I suspect is what you want, finds the value by the row numb... |
How to get the records from the current month in App Engine (Python) Datastore? | 11,621,525 | 2 | 2012-07-23T22:35:43Z | 11,621,790 | 7 | 2012-07-23T23:01:45Z | [
"python",
"google-app-engine",
"datetime",
"gae-datastore"
] | Given the following entity:
```
class DateTest(db.Model):
dateAdded = db.DateTimeProperty()
#...
```
What would be the best way to get the records from the current month? | There are a few ways you can do this. For example, using `Query`:
```
import datetime
from google.appengine.ext import db
q = db.Query(DateTest)
# This month
month = datetime.datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
q.filter('dateAdded >= ', month)
results = q.fetch(10)
``` |
How to determine whether a year is a leap year in Python? | 11,621,740 | 11 | 2012-07-23T22:57:19Z | 11,621,816 | 13 | 2012-07-23T23:05:32Z | [
"python",
"python-2.7"
] | I am trying to make a simple calculator to determine whether or not a certain year is a leap year.
By definition, a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred.
Here is my code:
```
def leapyr(n):
if n%4==0 and n%100!=0:
if n%400==0:
print n,... | You test three different things on n:
```
n % 4
n % 100
n % 400
```
For 1900:
```
1900 % 4 == 0
1900 % 100 == 0
1900 % 400 == 300
```
So 1900 doesn't enter the `if` clause because `1900 % 100 != 0` is `False`
But 1900 also doesn't enter the `else` clause because `1900 % 4 != 0` is also `False`
This means that exe... |
How to determine whether a year is a leap year in Python? | 11,621,740 | 11 | 2012-07-23T22:57:19Z | 11,622,584 | 43 | 2012-07-24T00:40:47Z | [
"python",
"python-2.7"
] | I am trying to make a simple calculator to determine whether or not a certain year is a leap year.
By definition, a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred.
Here is my code:
```
def leapyr(n):
if n%4==0 and n%100!=0:
if n%400==0:
print n,... | ```
import calendar
print calendar.isleap(1900)
```
Python provides this functionality already in the library module 'calendar'. |
How to determine whether a year is a leap year in Python? | 11,621,740 | 11 | 2012-07-23T22:57:19Z | 30,714,165 | 9 | 2015-06-08T16:10:51Z | [
"python",
"python-2.7"
] | I am trying to make a simple calculator to determine whether or not a certain year is a leap year.
By definition, a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred.
Here is my code:
```
def leapyr(n):
if n%4==0 and n%100!=0:
if n%400==0:
print n,... | As a one-liner:
```
def is_leap_year(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
```
It's similar to the [@mark's answer](http://stackoverflow.com/a/11622506/244297), but short circuits at the first test (note the parenthesis). |
Blank label_suffix across entire Django project | 11,622,513 | 11 | 2012-07-24T00:33:00Z | 11,622,672 | 11 | 2012-07-24T00:53:57Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I'd like to eliminate the colon (:) that is automatically added to form labels across my entire Django project. I'd like to avoid adding `label_suffix=''` to every form in the project.
Is there a simple way to override it everywhere? | It would probably be best to extend Django's `Form` class, override the default, and extend all of your forms from it, like so:
```
from django import forms
class MySiteForm(forms.Form):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(MySiteForm, self).__init__(*ar... |
Boto connect_xxx method and connection pools | 11,622,548 | 11 | 2012-07-24T00:36:19Z | 11,623,341 | 10 | 2012-07-24T02:36:23Z | [
"python",
"amazon-web-services",
"flask",
"boto"
] | If I call boto.connect\_xxx, where xxx is some service (dynamodb, s3, etc) multiple times, does it create a new connection pool each time? What I'd like to do is something like this (example in Flask):
```
@app.before_request
def before_request():
g.db = connect_dynamodb()
```
to make sure I always connect, but I... | The best approach is to call the connect\_xxx method once when your application starts and rely on boto to manage the connection from then on. The only exception to that rule is if you are using multiple threads. In that case, each thread should create it's own connection since boto uses httplib which is not threadsafe... |
WTForms create variable number of fields | 11,622,592 | 6 | 2012-07-24T00:41:49Z | 11,662,445 | 7 | 2012-07-26T04:42:02Z | [
"python",
"wtforms"
] | How I would dynamically create a few form fields with different questions, but the same answers?
```
from wtforms import Form, RadioField
from wtforms.validators import Required
class VariableForm(Form):
def __init__(formdata=None, obj=None, prefix='', **kwargs):
super(VariableForm, self).__init__(formda... | It was [in the docs](http://wtforms.simplecodes.com/docs/1.0.1/specific_problems.html) all along.
```
def my_view():
class F(MyBaseForm):
pass
F.username = TextField('username')
for name in iterate_some_model_dynamically():
setattr(F, name, TextField(name.title()))
form = F(request.PO... |
Large, persistent DataFrame in pandas | 11,622,652 | 67 | 2012-07-24T00:50:49Z | 11,622,769 | 59 | 2012-07-24T01:10:50Z | [
"python",
"pandas",
"sas"
] | I am exploring switching to python and pandas as a long-time SAS user.
However, when running some tests today, I was surprised that python ran out of memory when trying to `pandas.read_csv()` a 128mb csv file. It had about 200,000 rows and 200 columns of mostly numeric data.
With SAS, I can import a csv file into a S... | In principle it shouldn't run out of memory, but there are currently memory problems with `read_csv` on large files caused by some complex Python internal issues (this is vague but it's been known for a long time: <http://github.com/pydata/pandas/issues/407>).
At the moment there isn't a perfect solution (here's a ted... |
Large, persistent DataFrame in pandas | 11,622,652 | 67 | 2012-07-24T00:50:49Z | 12,193,309 | 58 | 2012-08-30T08:57:26Z | [
"python",
"pandas",
"sas"
] | I am exploring switching to python and pandas as a long-time SAS user.
However, when running some tests today, I was surprised that python ran out of memory when trying to `pandas.read_csv()` a 128mb csv file. It had about 200,000 rows and 200 columns of mostly numeric data.
With SAS, I can import a csv file into a S... | Wes is of course right! I'm just chiming in to provide a little more complete example code. I had the same issue with a 129 Mb file, which was solved by:
```
from pandas import *
tp = read_csv('large_dataset.csv', iterator=True, chunksize=1000) # gives TextFileReader, which is iterable with chunks of 1000 rows.
df =... |
Large, persistent DataFrame in pandas | 11,622,652 | 67 | 2012-07-24T00:50:49Z | 28,371,706 | 24 | 2015-02-06T17:46:34Z | [
"python",
"pandas",
"sas"
] | I am exploring switching to python and pandas as a long-time SAS user.
However, when running some tests today, I was surprised that python ran out of memory when trying to `pandas.read_csv()` a 128mb csv file. It had about 200,000 rows and 200 columns of mostly numeric data.
With SAS, I can import a csv file into a S... | This is an older thread, but I just wanted to dump my workaround solution here. I initially tried the `chunksize` parameter (even with quite small values like 10000), but it didn't help much; had still technical issues with the memory size (my CSV was ~ 7.5 Gb).
Right now, I just read chunks of the CSV files in a for-... |
Is there a better way to broadcast arrays? | 11,622,692 | 6 | 2012-07-24T00:57:03Z | 11,623,423 | 7 | 2012-07-24T02:48:31Z | [
"python",
"numpy",
"numpy-broadcasting"
] | I want to broadcast an array `b` to the shape it would take if it were in an arithmetic operation with another array `a`.
For example, if `a.shape = (3,3)` and `b` was a scalar, I want to get an array whose shape is `(3,3)` and is filled with the scalar.
One way to do this is like this:
```
>>> import numpy as np
>>... | If you just want to fill an array with a scalar, `fill` is probably the best choice. But it sounds like you want something more generalized. Rather than using `broadcast` you can use `broadcast_arrays` to get the result that (I think) you want.
```
>>> a = numpy.arange(9).reshape(3, 3)
>>> numpy.broadcast_arrays(a, 1)... |
Python Data structure index Start at 1 instead of 0? | 11,623,264 | 7 | 2012-07-24T02:27:15Z | 11,623,319 | 29 | 2012-07-24T02:34:40Z | [
"python",
"data-structures"
] | I have a weird question: I have this list of 64 numbers that will never change:
```
(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 11... | Just insert a `0` at the beginning of the structure:
```
(0, 2, 4, 6, 8, ...)
``` |
Python: convert string to byte array | 11,624,190 | 20 | 2012-07-24T04:29:42Z | 11,624,266 | 22 | 2012-07-24T04:39:51Z | [
"python"
] | Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g.
```
str = "ABCD"
```
I'm trying to get my output to be
```
array('B', [41, 42, 43, 44])
```
Is there a straightforward way to accomplish this? | encode function can help you here, encode returns an encoded version of the string
```
In [44]: str = "ABCD"
In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']
```
or you can use array module
```
In [49]: import array
In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])... |
Python: convert string to byte array | 11,624,190 | 20 | 2012-07-24T04:29:42Z | 29,169,004 | 14 | 2015-03-20T14:32:55Z | [
"python"
] | Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g.
```
str = "ABCD"
```
I'm trying to get my output to be
```
array('B', [41, 42, 43, 44])
```
Is there a straightforward way to accomplish this? | Just use a `bytearray()` which is a list of bytes.
Python2:
```
s = "ABCD"
b = bytearray()
b.extend(s)
```
Python3:
```
s = "ABCD"
b = bytearray()
b.extend(map(ord, s))
```
By the way, don't use `str` as a variable name since that is builtin. |
Python: Iterating through a set so we don't compare the same objects multiple times? | 11,624,362 | 3 | 2012-07-24T04:52:37Z | 11,624,445 | 7 | 2012-07-24T05:03:30Z | [
"python",
"comparison",
"set",
"iteration"
] | So I'm writing a game. Here's how the collision detection works; there's an invisible grid, and objects (or, rather, their references) are added and removed from cells based on where they are. Collision comparisons are only done between objects in the same cell.
The references are stored in a Python `set` that is owne... | If your goal is to just compare all the unique combinations of the set, you could make use of [`itertools.combinations`](http://docs.python.org/library/itertools.html#itertools.combinations)
```
from itertools import combinations
for i, j in combinations(self.objects, 2):
if pygame.sprite.collide_rect(i, j):
... |
Avoiding Python sum default start arg behavior | 11,624,955 | 9 | 2012-07-24T05:57:43Z | 11,625,314 | 8 | 2012-07-24T06:29:16Z | [
"python",
"sum"
] | I am working with a Python object that implements `__add__`, but does not subclass `int`. `MyObj1 + MyObj2` works fine, but `sum([MyObj1, MyObj2])` led to a `TypeError`, because`sum()` first attempts `0 + MyObj`. In order to use `sum()`, my object needs `__radd__` to handle `MyObj + 0` **or** I need to provide an empty... | Instead of `sum`, use:
```
import operator
reduce(operator.add, seq)
```
Reduce is generally more flexible than sum - you can provide any binary function, not only `add`, and you can *optionally* provide an initial element while `sum` always uses one.
---
Also note: *(Warning: maths rant ahead)*
Providing support ... |
C++ or Python for an Extensive Math Program? | 11,625,450 | 2 | 2012-07-24T06:41:11Z | 11,625,521 | 8 | 2012-07-24T06:47:32Z | [
"c++",
"python",
"math"
] | I'm debating whether to use C++ or Python for a largely math-based program.
Both have great math libraries, but which language is generally faster for complex math? | You could also consider a hybrid approach. Python is generally easier and faster to develop in, specially for things like user interface, input/output etc.
C++ should certainly be faster for some math operations (although if your problem can be formulated in terms of vector operations or linear algebra than numpy prov... |
Iterate across lines in two files in sequence | 11,626,201 | 3 | 2012-07-24T07:37:13Z | 11,626,373 | 7 | 2012-07-24T07:48:02Z | [
"python"
] | I have two files, and I want to perform some line-wise operation across both of them (one by one). I am now using two loops to achieve this. Is there a way to do it in a single loop (in python 2.7):
```
for fileName in [fileNam1,fileName2]:
for line in open(fileName):
do something
``` | As has been pointed out `itertools.chain` is an option, however there's also another useful standard module which avoids having to explicitly use `open`...
```
import fileinput
for line in fileinput.input(['file1.txt', 'file2.txt']):
print line
```
This also has some handy functions for line number and filename e... |
i can not find QString in PySide 1.1.0 | 11,626,430 | 8 | 2012-07-24T07:51:02Z | 11,626,445 | 13 | 2012-07-24T07:52:03Z | [
"python",
"qt",
"pyside",
"qstring"
] | i want to use QString and QStringList, but in PySide 1.1.0, they are not in modules, and not in documents.so, what can i do to use them.thank you.Not just QString and QStringList, i can not find QTableModel, QListModel and etc too. | You don't need QString or QStringList: you can use Python's native types anywhere they would be needed in C++/Qt.
More details about this can be found [**here**](http://pyside.org/docs/pseps/psep-0101.html).
For example,
* `QString` → `unicode` (`str` in Python 3)
* `QVariant` → whatever type
* `QByteArray` → `bytes... |
How to straighten a rotated rectangle area of an image using opencv in python? | 11,627,362 | 12 | 2012-07-24T08:52:24Z | 11,627,903 | 28 | 2012-07-24T09:26:42Z | [
"python",
"image-processing",
"opencv"
] | The following picture will tell you what I want.
I have the information of the rectangles in the image, width, height, center point and rotation degree. Now, I want to write a script to cut them out and save them as image, but straighten them. As in I want to go from the rectangle shown inside the image to the rectang... | You can use the `GetQuadrangleSubPix` function to extract a rotated patch, after defining a suitable transformation matrix, as in the following function (where `theta` is defined in radians):
```
from cv2 import cv
import numpy as np
def subimage(image, centre, theta, width, height):
output_image = cv.CreateImage(... |
Automatic python code formatting in sublime | 11,628,338 | 9 | 2012-07-24T09:52:38Z | 11,708,239 | 9 | 2012-07-29T09:45:19Z | [
"python",
"sublimetext"
] | I am trying to find some package that would auto format python code when using sublime.
There is PythonTidy, but when I use PackageController it says install completed but the package is not installed (does not appear in preferences).
I did try following the instructions in:
<https://github.com/witsch/SublimePythonTi... | Try doing the following in command line (a bit brute force):
1. Navigate into the `Packages/PythonTidy` folder,
usually `~/.config/sublime-text-2/Packages/PythonTidy`
or `~/.config/sublime-text-2/Packages/SublimePythonTidy`
* If it's non-existent reinstalling using `Package Control`
2. Inside there should... |
Is there a way to check a number against all numbers in a list? | 11,630,004 | 3 | 2012-07-24T11:35:24Z | 11,630,016 | 8 | 2012-07-24T11:36:03Z | [
"python",
"list",
"python-2.7"
] | I was wondering whether you could check a number against all numbers in a list, for example:
```
if n % mylist == 0:
print "Not Prime"
```
And if you're wondering, this is a continuation of [this question](http://stackoverflow.com/questions/11629570/boolean-check-not-working-in-function "Previous Question"), I ho... | ```
if any(n % x == 0 for x in mylist):
print "Not Prime"
``` |
advanced string formatting vs template strings | 11,630,106 | 31 | 2012-07-24T11:41:31Z | 11,630,449 | 11 | 2012-07-24T12:02:33Z | [
"python",
"string-formatting"
] | I was wondering if there is a advantage of using [template strings](http://docs.python.org/library/string.html#template-strings) instead of the new [advanced string formatting](http://docs.python.org/library/string.html#string-formatting)? | Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of [PEP 292](http://www.python.org/dev/peps/pep-0292/) compares templates to Python's `%`-style string formatting:
> Python currently supports a string substitution syntax based on
> C's `printf()` '%' ... |
Unable to get a setting from settings file in django | 11,631,194 | 6 | 2012-07-24T12:47:32Z | 11,631,244 | 13 | 2012-07-24T12:51:27Z | [
"python",
"django",
"settings"
] | I've a setting say `gi` in `settings.py` file. I've created a separate python file (i.e. I'm not using it in views) and used import statement as:
```
from django.conf import settings
```
but when I try to access `settings.gi`, it says that `'Settings' object has no attribute 'gi'`. What's missing? :s | From the Django docs on [creating your own settings](https://docs.djangoproject.com/en/dev/topics/settings/#creating-your-own-settings) states:
> Setting names are in all uppercase.
Try renaming the setting to `GI`. |
Combining the values in two dictionaries into a list | 11,632,154 | 3 | 2012-07-24T13:41:43Z | 11,632,185 | 8 | 2012-07-24T13:42:53Z | [
"python",
"list",
"dictionary"
] | In python if I have two dictionaries, specifically Counter objects that look like so
```
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
```
Can I combine these dictionaries so that the results is a dictionary of lists, as follows:
```
c3 = ... | ```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
for k,v in c.iteritems():
c3.setdefault(k, []).append(v)
```
`c3` is now: `{'item1': [4, 6], 'item2': [2, 2], 'item3': [... |
SQLAlchemy introspect column type with inheritance | 11,632,513 | 8 | 2012-07-24T13:59:00Z | 11,634,753 | 13 | 2012-07-24T15:57:26Z | [
"python",
"inheritance",
"sqlalchemy",
"introspection"
] | Considering this code (and using SQLAlchemy 0.7.7):
```
class Document(Base):
__tablename__ = 'document'
__table_args__ = {
'schema': 'app'
}
id = Column(types.Integer, primary_key=True)
nom = Column(types.Unicode(256), nullable=False)
date = Column(types.Date())
type_document = C... | The ORM has allowed you to define classes in an inheritance pattern that corresponds to a JOIN of two tables. This structure is full service, and can also be used to find out basic things like the types of attributes on columns, pretty much directly:
```
type = Arrete.date.property.columns[0].type
```
note that this ... |
Python: SyntaxError: keyword can't be an expression | 11,633,421 | 10 | 2012-07-24T14:46:50Z | 11,633,447 | 12 | 2012-07-24T14:48:17Z | [
"python",
"syntax",
"syntax-error",
"keyword"
] | In a Python script I call a function from `rpy2`, but I get this error:
```
#using an R module
res = DirichletReg.ddirichlet(np.asarray(my_values),alphas,
log=False, sum.up=False)
SyntaxError: keyword can't be an expression
```
What exactly went wrong here? | `sum.up` is not a valid keyword argument name. Keyword arguments must be valid identifiers. You should look in the documentation of the library you are using how this argument *really* is called â maybe `sum_up`? |
Django: How does view get multiple values from url? | 11,633,500 | 7 | 2012-07-24T14:51:04Z | 11,633,616 | 14 | 2012-07-24T14:57:06Z | [
"python",
"django"
] | It's about passing values from URL to view in django.
URL like this:
http:///boards/?**board**=picture&**board**=girls
I want get both values "picture" and "girls" that all belongs to **board**.
Store these values to a list or something.
Obviously, request.GET.get('board') can't get two values.
Does anybody get a w... | `It's request.GET.getlist('board')` - it's stated in the Django docs at <https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict> |
How to apply a modifier in Python, creating a new mesh? | 11,633,595 | 3 | 2012-07-24T14:55:57Z | 11,676,809 | 8 | 2012-07-26T19:39:53Z | [
"python",
"blender"
] | Let's say I have a bpy.types.Object containing a bpy.types.Mesh data field; how can I apply one of the modifiers associated with the object, in order to obtain a NEW bpy.types.Mesh, possibly contained within a NEW bpy.types.Object, thus leaving the original scene unchaged?
I'm interested in applying the EdgeSplit modi... | I suppose you're using the 2.6 API.
```
bpy.ops.object.modifier_apply (modifier='EdgeSplit')
```
...applies to the currently active object its Edge Split modifier. Note that it's **object**.modifier\_apply (...)
You can use
```
bpy.context.scene.objects.active = my_object
```
to set the active object. Note that it... |
How to apply a modifier in Python, creating a new mesh? | 11,633,595 | 3 | 2012-07-24T14:55:57Z | 14,483,593 | 7 | 2013-01-23T15:48:06Z | [
"python",
"blender"
] | Let's say I have a bpy.types.Object containing a bpy.types.Mesh data field; how can I apply one of the modifiers associated with the object, in order to obtain a NEW bpy.types.Mesh, possibly contained within a NEW bpy.types.Object, thus leaving the original scene unchaged?
I'm interested in applying the EdgeSplit modi... | There is another way, which seems better suited for custom exporters: Call the `to_mesh` method on the object you want to export. It gives you a copy of the object's mesh with all the modifiers applied. Use it like this:
```
mesh = your_object.to_mesh(scene = bpy.context.scene, apply_modifiers = True, settings = 'PREV... |
Most efficient way to assign a value of zero to multiple variables at once | 11,634,190 | 5 | 2012-07-24T15:27:16Z | 11,634,236 | 7 | 2012-07-24T15:29:24Z | [
"python"
] | I'm trying to initiate the variables at zero, so it currently looks like this
```
x1,y1,x2,y2=(0,0,0,0)
```
It works, but just seems a little redundant. Is there a cleaner way? | That is effectively unpacking a tuple. You can do:
```
x1 = y1 = x2 = y2 = 0
```
**Just don't do this with mutable objects!** |
Simple nested for loop not working correctly | 11,635,054 | 4 | 2012-07-24T16:14:44Z | 11,635,081 | 8 | 2012-07-24T16:16:06Z | [
"python",
"file-io",
"for-loop"
] | I can't see the problem here and it is driving me insane. I'm looping through 2 text files. Some lines in each file match and some don't. What I am doing is looping over file1. For each line in that file, loop over file2 and compare each element to see if they are the same. What's happening is my loop is stopping after... | You cannot loop through a file and then loop through the same file again without seeking to the start.
Either re-open file2, call `.seek(0)` on file2 or load all lines into a list and loop over that instead.
In your specific case, using a `set` for the names is probably going to be the fastest:
```
names = set(name.... |
Why is there a length limit to python's eval? | 11,635,211 | 20 | 2012-07-24T16:23:55Z | 11,639,789 | 15 | 2012-07-24T21:44:01Z | [
"python",
"segmentation-fault",
"eval"
] | I'm not advocating that this would ever be a good idea, but I've found that you can crash Python (2.7 and 3.2 checked) by running `eval` on a large enough input string:
```
def kill_python(N):
S = '+'.join((str(n) for n in xrange(N)))
return eval(S)
```
On my computer `S` can be generated just fine, but for v... | This issue is caused by a stack overflow (sic!) in the CPython compiler. An easy way to reproduce the same issue is
```
>>> code = compile("1" + "+1" * 1000000, "", "eval")
Segmentation fault
```
which proves that the segfault is happening at the compile stage, not during evaluation. (Of course this is also easy to c... |
Why doesn't Python call instance method __init__() on instance creation but calls class-provided __init__() instead? | 11,635,489 | 11 | 2012-07-24T16:41:30Z | 11,635,543 | 7 | 2012-07-24T16:45:03Z | [
"python",
"object",
"methods",
"instances"
] | I'm overring the `__new__()` method of a class to return a class instance which has a specific `__init__()` set. Python seems to call the class-provided `__init__()` method instead of the instance-specific method, although the Python documentation at
<http://docs.python.org/reference/datamodel.html>
says:
> Typical ... | Various special methods (including `__init__`, but also operator overloads such as `__add__`, etc.) are [always accessed via the class rather than the instance](http://docs.python.org/dev/reference/datamodel.html#special-lookup). Not only that, but they can't be accessed via a `__getattr__` or `__getattribute__` method... |
Why doesn't Python call instance method __init__() on instance creation but calls class-provided __init__() instead? | 11,635,489 | 11 | 2012-07-24T16:41:30Z | 11,635,545 | 7 | 2012-07-24T16:45:14Z | [
"python",
"object",
"methods",
"instances"
] | I'm overring the `__new__()` method of a class to return a class instance which has a specific `__init__()` set. Python seems to call the class-provided `__init__()` method instead of the instance-specific method, although the Python documentation at
<http://docs.python.org/reference/datamodel.html>
says:
> Typical ... | Special methods on new-style classes are looked up on the instance's type, not on the instance itself. This is [documented behaviour](http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes):
> For new-style classes, implicit invocations of special methods are only guaranteed to wor... |
Complex matlab-like data structure in python (numpy/scipy) | 11,637,045 | 7 | 2012-07-24T18:27:33Z | 11,637,157 | 10 | 2012-07-24T18:35:01Z | [
"python",
"matlab",
"numpy"
] | I have data currently structured as following in Matlab
```
item{i}.attribute1(2,j)
```
Where item is a cell from i = 1 .. n each containing the data structure of multiple attributes each a matrix of size 2,j where j = 1 .. m. The number of attributes is not fixed.
I have to translate this data structure to python, ... | I've often seen the following conversion approaches:
matlab array -> python numpy array
matlab cell array -> python list
matlab structure -> python dict
So in your case that would correspond to a python list containing dicts, which themselves contain numpy arrays as entries
`item[i]['attribute1'][2,j]`
**Note**
... |
Iterate over object attributes in python | 11,637,293 | 47 | 2012-07-24T18:44:55Z | 11,637,457 | 78 | 2012-07-24T18:54:44Z | [
"python",
"oop",
"attributes",
"iteration"
] | I have a python object with several attributes and methods. I want to iterate over object attributes.
```
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
```
I want to generate a dictionary containing all of the objects attributes and their ... | Assuming you have a class such as
```
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
```
calling `dir` on the object gives you back all the attributes of that object, including python special attributes. Although some object attrib... |
Iterate over object attributes in python | 11,637,293 | 47 | 2012-07-24T18:44:55Z | 20,214,464 | 20 | 2013-11-26T10:29:39Z | [
"python",
"oop",
"attributes",
"iteration"
] | I have a python object with several attributes and methods. I want to iterate over object attributes.
```
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
```
I want to generate a dictionary containing all of the objects attributes and their ... | in general put a `__iter__` method in your *class* and iterate through the object attributes or put this mixin class in your class.
```
class IterMixin(object):
def __iter__(self):
for attr, value in self.__dict__.iteritems():
yield attr, value
```
Your class:
```
>>> class YourClass(IterMixi... |
datetime objects format | 11,637,329 | 2 | 2012-07-24T18:46:37Z | 11,637,399 | 15 | 2012-07-24T18:51:10Z | [
"python"
] | I am trying to use datetime objects, including `datetime.month`, `datetime.day`, and `datetime.hour`.
The problem is that these objects (say `datetime.month`) give values as 1, 2, 3, and so on to 12. Instead, I need these in the format 01,02,03 and so on to 12. There's a similar issue with days and months.
How can I ... | You can print the individual attributes using string formatting:
```
print ('%02d' % (mydate.month))
```
Or more recent string formatting (introduced in python 2.6):
```
print ('{0:02d}'.format(a.month)) # python 2.7+ -- '{:02d}' will work
```
Note that even:
```
print ('{0:%m}'.format(a)) # python 2.7+ -- '{:%m... |
Pandas join/merge/concat two dataframes | 11,637,384 | 18 | 2012-07-24T18:50:11Z | 11,637,456 | 13 | 2012-07-24T18:54:43Z | [
"python",
"pandas"
] | I am having issues with joins in pandas and I am trying to figure out what is wrong.
Say I have a dataframe x:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1941 entries, 2004-10-19 00:00:00 to 2012-07-23 00:00:00
Data columns:
close 1941 non-null values
high 1941 non-null values
low 1941 non... | It sounds like maybe you want `pandas.concat`? `merge` and `join` do, well, joins, which means they will give you something based around the Cartesian product of the two inputs, but it sounds like you just want to paste them together into one big table.
Edit: did you try concat with `axis=1`? It seems to do what you'r... |
Pandas join/merge/concat two dataframes | 11,637,384 | 18 | 2012-07-24T18:50:11Z | 11,639,358 | 19 | 2012-07-24T21:10:36Z | [
"python",
"pandas"
] | I am having issues with joins in pandas and I am trying to figure out what is wrong.
Say I have a dataframe x:
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1941 entries, 2004-10-19 00:00:00 to 2012-07-23 00:00:00
Data columns:
close 1941 non-null values
high 1941 non-null values
low 1941 non... | Does your index have duplicates `x.index.is_unique`? If so would explain the behavior you're seeing:
```
In [16]: left
Out[16]:
a
2000-01-01 1
2000-01-01 1
2000-01-01 1
2000-01-02 2
2000-01-02 2
2000-01-02 2
In [17]: right
Out[17]:
b
2000-01-01 3
2000-01-01 3
2000-01-01 3
2000-01-02... |
Modify INI file with Python | 11,637,467 | 11 | 2012-07-24T18:55:10Z | 11,637,494 | 23 | 2012-07-24T18:57:08Z | [
"python",
"configparser"
] | I have an INI file I need to modify using Python. I was looking into the `ConfigParser` module but am still having trouble. My code goes like this:
```
config= ConfigParser.RawConfigParser()
config.read('C:\itb\itb\Webcams\AMCap1\amcap.ini')
config.set('Video','Path','C:\itb\itb')
```
But when looking at the `amcap.i... | ConfigParser does not automatically write back to the file on disk. Use the [`.write()` method](http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.write) for that; it takes an open file object as it's argument.
```
config= ConfigParser.RawConfigParser()
config.read(r'C:\itb\itb\Webcams\AMCap... |
Python : INPUT a microtime float, RESULT a formatted datetime | 11,639,348 | 2 | 2012-07-24T21:09:59Z | 11,639,369 | 7 | 2012-07-24T21:12:10Z | [
"python",
"datetime",
"time",
"floating-point"
] | I'm so confused with the Python time and datetime methods. Can someone maybe help me?
I just want to achieve a conversion from a microtime Float to a formatted string in this format:
```
mt = 1342993416.0
start_time_format = '%Y-%m-%d %H:%M:%S'
// Some time or datetime magic here..
OUTPUT >> The file's date is: 201... | Use the [`.fromtimestamp()` class method](http://docs.python.org/library/datetime.html#datetime.datetime.fromtimestamp):
```
>>> import datetime
>>> mt = 1342993416.0
>>> datetime.datetime.fromtimestamp(mt)
datetime.datetime(2012, 7, 22, 23, 43, 36)
```
then use the [`strftime` method](http://docs.python.org/library/... |
PANDAS plot multiple Y axes | 11,640,243 | 24 | 2012-07-24T22:30:16Z | 11,643,893 | 36 | 2012-07-25T06:28:37Z | [
"python",
"pandas"
] | I know pandas supports a secondary Y axis, but Im curious if anyone knows a way to put a tertiary Y axis on plots... currently I am achieving this with numpy+pyplot ... but it is slow with large data sets.
this is to plot different measurements with distinct units on the same graph for easy comparison (eg Relative Hum... | I think this might work:
```
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
df = DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])
fig, ax = plt.subplots()
ax2, ax3 = ax.twinx(), ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.25))
ax3.set_frame_on(True)... |
regexps: variable-length lookbehind-assertion alternatives | 11,640,447 | 34 | 2012-07-24T22:52:34Z | 11,640,500 | 26 | 2012-07-24T22:57:50Z | [
"php",
"javascript",
"python",
"regex",
"perl"
] | Is there any implementation of regular expressions, that supports variable-length lookbehind-assertion?
```
/(?<!foo.*)bar/
```
How can I write a r.e. that has the same meaning but uses no lookbehind-assertion?
Is there any chances that this type of assertion will be implemented someday?
**Update #1**
Things are m... | Most of the time, you can avoid variable length lookbehinds by using `\K`.
```
s/(?<=foo.*)bar/moo/s;
```
would be
```
s/foo.*\Kbar/moo/s;
```
Negative lookbehinds are a little trickier.
```
s/(?<!foo.*)bar/moo/s;
```
would be
```
s/^(?:(?!foo).)*\Kbar/moo/s;
```
because `(?:(?!STRING).)*` is to `STRING` as `[^... |
regexps: variable-length lookbehind-assertion alternatives | 11,640,447 | 34 | 2012-07-24T22:52:34Z | 11,641,102 | 8 | 2012-07-25T00:21:31Z | [
"php",
"javascript",
"python",
"regex",
"perl"
] | Is there any implementation of regular expressions, that supports variable-length lookbehind-assertion?
```
/(?<!foo.*)bar/
```
How can I write a r.e. that has the same meaning but uses no lookbehind-assertion?
Is there any chances that this type of assertion will be implemented someday?
**Update #1**
Things are m... | For Python there's a regex implementation which supports variable-length lookbehinds:
<http://pypi.python.org/pypi/regex>
It's designed to be backwards-compatible with the standard re module. |
Why does dis.dis(None) return output? | 11,641,211 | 6 | 2012-07-25T00:41:02Z | 11,641,228 | 19 | 2012-07-25T00:43:54Z | [
"python"
] | In particular, it outputs:
```
>>> dis.dis(None)
22 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (None)
6 COMPARE_OP 8 (is)
9 POP_JUMP_IF_FALSE 23
23 12 LOAD_GLOBAL 1 (distb)
15 CALL_FUNCTION ... | From the [documentation](http://docs.python.org/library/dis.html):
> dis.dis([bytesource])
>
> Disassemble the bytesource object. bytesource can denote either a module, a class, a method, a function, or a code object. For a module, it disassembles all functions. For a class, it disassembles all methods. For a single c... |
How to cPickle dump and load separate dictionaries to the same file? | 11,641,493 | 8 | 2012-07-25T01:33:39Z | 11,641,516 | 12 | 2012-07-25T01:37:27Z | [
"python",
"dictionary",
"pickle"
] | I have a process which runs and creates three dictionaries: 2 rather small, and 1 large.
I know I can store one dictionary like:
```
import cPickle as pickle
with open(filename, 'wb') as fp:
pickle.dump(self.fitResults, fp)
```
What I'd like to do is store all 3 dictionaries in the same file, with the ability to l... | Sure, you just dump each one separately and then load them separately:
```
with open(filename,'wb') as fp:
pickle.dump(dict1,fp)
pickle.dump(dict2,fp)
pickle.dump(dict3,fp)
with open(filename,'rb') as fp:
d1=pickle.load(fp)
d2=pickle.load(fp)
d3=pickle.load(fp)
```
make sure to dump the big o... |
How to pass bool argument to fabric command | 11,641,689 | 17 | 2012-07-25T02:03:16Z | 15,349,699 | 8 | 2013-03-11T22:11:00Z | [
"python",
"boolean",
"fabric"
] | Currently I'm using `fab -f check_remote.py func:"arg1","arg2"...` to run fab remote.
Now I need to send a bool arg, but True/False become a string arg, how to set it as bool type? | I would use a function:
```
def booleanize(value):
"""Return value as a boolean."""
true_values = ("yes", "true", "1")
false_values = ("no", "false", "0")
if isinstance(value, bool):
return value
if value.lower() in true_values:
return True
elif value.lower() in false_values... |
How to pass bool argument to fabric command | 11,641,689 | 17 | 2012-07-25T02:03:16Z | 19,536,667 | 30 | 2013-10-23T08:30:59Z | [
"python",
"boolean",
"fabric"
] | Currently I'm using `fab -f check_remote.py func:"arg1","arg2"...` to run fab remote.
Now I need to send a bool arg, but True/False become a string arg, how to set it as bool type? | I'm using this:
```
from distutils.util import strtobool
def func(arg1="default", arg2=False):
if arg2:
arg2 = bool(strtobool(arg2))
```
So far works for me.
it will parse values (ignoring case):
```
'y', 'yes', 't', 'true', 'on', '1'
'n', 'no', 'f', 'false', 'off', '0'
```
strtobool returns 0 or 1 tha... |
Can I use 32bit dll or exe in 64bit python? | 11,642,134 | 12 | 2012-07-25T03:07:23Z | 11,642,165 | 21 | 2012-07-25T03:13:05Z | [
"python",
"dll",
"32bit-64bit"
] | When I use CDLL to call 32bit dll in 32bit python, it works well.
But unfortunatelly in my 64bit win7 os only installs 64bit python, when calling it turns: it is not a effective win32 app!
Can I use 32bit dll or exe in 64bit python? Or I have to install 32bit python instead? | 64-bit EXEs cannot load 32-bit DLLs. (And vice versa: 32-bit EXEs cannot load 64-bit DLLs.) After all, they can't agree on the size of a pointer -- what would happen if the EXE allocated memory above the 4GB boundary and wanted to pass that pointer to the 32-bit DLL?
You'll have to either:
1. Make a 64-bit version of... |
Are there default icons in PyQt/PySide? | 11,643,221 | 18 | 2012-07-25T05:21:46Z | 12,288,753 | 27 | 2012-09-05T19:51:57Z | [
"python",
"user-interface",
"icons",
"pyqt",
"pyside"
] | I'm reading a tutorial on PySide and I was thinking , do I need to find my own icons for every thing or is there some way to use some built in icons . That way I wouldn't need to find an entire new set of icons if I want my little gui to run on another desktop environment . | What you need is Pyside QIcon.fromTheme function.
Basicaly it creates QIcon object with needed icon from current system theme.
Usage:
`undoicon = QIcon.fromTheme("edit-undo")`
"edit undo" - name of the icon "type"/"function" can be found [here](http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-lates... |
Python ImportError - undefined symbol - for custom C++ module | 11,643,666 | 10 | 2012-07-25T06:08:09Z | 11,663,373 | 12 | 2012-07-26T06:07:16Z | [
"c++",
"python",
"opencv",
"shared-libraries"
] | I've been developing a Python module in C++ using OpenCV 2.3 through 2.4.2, on Ubuntu 11.04. OpenCV was built from source. I'm not using the version of OpenCV from the Ubuntu repositories.
My Python module compiles with no issues and is loaded in Python properly. However, when I compile this module on Ubuntu 11.10 or ... | The solution is to put the generated module name before the other modules it depends on, on the g++ command-line.
```
g++ -fPIC -shared -o mymodule.so mymodule.cpp `pkg-config --cflags --libs python` `pkg-config --cflags --libs opencv` -I/usr/local/include/opencv2/legacy
```
The gcc man page says of the "-l" option,
... |
How do I get the URL of the active Google Chrome tab in Windows? | 11,645,123 | 6 | 2012-07-25T07:56:55Z | 11,645,124 | 10 | 2012-07-25T07:56:55Z | [
"python",
"winapi",
"google-chrome"
] | How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option. | First, you need to download and install [pywin32](http://sourceforge.net/projects/pywin32/files/). Import these modules in your script:
```
import win32gui
import win32con
```
If Google Chrome is the currently active window, first get the window handle by:
```
hwnd = win32gui.GetForegroundWindow()
```
(Otherwise, f... |
Simple HTML template in Python | 11,646,948 | 8 | 2012-07-25T09:42:35Z | 11,647,063 | 8 | 2012-07-25T09:49:54Z | [
"python",
"html",
"template-engine"
] | I'd like to fill a HTML template with data from Python. While I don't know any HTML, a colleague of mine would prepare the HTML template whereas I provide the data. However, he knows only little about Python.
Could you suggest a very basic template framework which handles this separation of HTML and Python nicely (i.e... | Well [django](https://www.djangoproject.com/) has very nice powerful templating engine, that's purpose is separating HTML from python logic (but that would require you to use django altogether, so it might be an overkill if you just want templating).
If your templates are *really* easy (no loops) you might use native ... |
non-blocking socket,error is always | 11,647,046 | 5 | 2012-07-25T09:48:45Z | 11,649,366 | 7 | 2012-07-25T12:10:01Z | [
"python",
"sockets"
] | ```
sock.setblocking(0)
try:
data = sock.recv(1024)
except socket.error, e:
if e.args[0] == errno.EWOULDBLOCK:
print 'EWOULDBLOCK'
else:
if not data: #recv over
sock.close()
print 'close================='
else:
print 'recv ---data---------'
poem += ... | The socket is non-blocking so `recv()` will raise an exception if there is no data to read. Note that errno.EWOULDBLOCK = errno.EAGAIN = 11. This is Python's (well the OS really) way of telling you to try the `recv()` again later.
I note that you close the socket each time you get this exception. That's not going to h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.