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 |
|---|---|---|---|---|---|---|---|---|---|
Python "in" keyword efficiency | 12,905,513 | 31 | 2012-10-15T23:37:46Z | 12,905,527 | 42 | 2012-10-15T23:39:33Z | [
"python"
] | In Python, what is the efficiency of the `in` keyword, such as in:
```
a = [1, 2, 3]
if 4 in a:
...
``` | The complexity for lists is:
```
O(n)
```
For sets it is:
```
O(1)
```
<http://wiki.python.org/moin/TimeComplexity> |
Python "in" keyword efficiency | 12,905,513 | 31 | 2012-10-15T23:37:46Z | 12,905,554 | 31 | 2012-10-15T23:42:08Z | [
"python"
] | In Python, what is the efficiency of the `in` keyword, such as in:
```
a = [1, 2, 3]
if 4 in a:
...
``` | It depends on the right hand [operand](http://docs.python.org/reference/expressions.html#in):
> The operators `in` and `not in` test for collection membership. [...] The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and conta... |
Python dict how to create key or append an element to key? | 12,905,999 | 40 | 2012-10-16T00:42:07Z | 12,906,014 | 65 | 2012-10-16T00:43:35Z | [
"python",
"python-2.7",
"dictionary"
] | I'm new to Python. Not only am I learning its functions, types and such, but also I am trying to learn the Pythonic ways to do things and hence my question:
I have an empty dictionary. Name: `dict_x`
It is to have keys of which values are lists.
From a separate iteration, I obtain a key (ex: `key_123`), and an item (... | Use [`dict.setdefault()`](http://docs.python.org/library/stdtypes.html#dict.setdefault):
```
dic.setdefault(key,[]).append(value)
```
**help(dict.setdefault)**:
```
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
``` |
Python dict how to create key or append an element to key? | 12,905,999 | 40 | 2012-10-16T00:42:07Z | 12,906,281 | 16 | 2012-10-16T01:19:57Z | [
"python",
"python-2.7",
"dictionary"
] | I'm new to Python. Not only am I learning its functions, types and such, but also I am trying to learn the Pythonic ways to do things and hence my question:
I have an empty dictionary. Name: `dict_x`
It is to have keys of which values are lists.
From a separate iteration, I obtain a key (ex: `key_123`), and an item (... | Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most *"pythonic"*, and commented the pros and cons that might not be obvious at first glance:
**Using `collections.defaultdict`:**
```
import collections
dict_x = collections.defau... |
ImportError: No module named psycopg2 | 12,906,351 | 17 | 2012-10-16T01:30:55Z | 12,928,164 | 10 | 2012-10-17T06:09:54Z | [
"python",
"centos",
"openerp",
"centos5"
] | when installing process of openerp 6, i want to generate a config file with this command,
cd /home/openerp/openerp-server/bin/
`./openerp-server.py -s --stop-after-init -c /home/openerp/openerp-server.cfg`
but it was always showed a message
`ImportError: No module named psycopg2`
when i check for psycopg2 package,... | Please try to run the command `import psycopg2` on the python console. If you get the error then check the `sys.path` where the python look for the install module. If the parent directory of the `python-psycopg2-2.4.5-1.rhel5.x86_64` is there in the `sys.path` or not. If its not in the `sys.path` then run `export PYTHO... |
ImportError: No module named psycopg2 | 12,906,351 | 17 | 2012-10-16T01:30:55Z | 23,104,715 | 31 | 2014-04-16T09:04:21Z | [
"python",
"centos",
"openerp",
"centos5"
] | when installing process of openerp 6, i want to generate a config file with this command,
cd /home/openerp/openerp-server/bin/
`./openerp-server.py -s --stop-after-init -c /home/openerp/openerp-server.cfg`
but it was always showed a message
`ImportError: No module named psycopg2`
when i check for psycopg2 package,... | Step 1: Install the dependencies
```
sudo apt-get install build-dep python-psycopg2
```
Step 2: Then run this command in your virtualenv
```
pip install psycopg2
```
ref: [Fernando Munoz](http://stackoverflow.com/users/1975004/fernando-munoz) |
type object 'datetime.datetime' has no attribute 'datetime' | 12,906,402 | 25 | 2012-10-16T01:39:33Z | 12,906,456 | 59 | 2012-10-16T01:50:18Z | [
"python",
"django"
] | I'm following a django tutorial, and I have gotten the following error:
> type object 'datetime.datetime' has no attribute 'datetime'
On the following line:
```
date = datetime.datetime(int(year), int(month), 1)
```
Does anybody know the reason for the error?
I imported datetime with `from datetime import datetime... | Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that `datetime` is both a top-level module as well as being a type within that module. This is confusing.
Your error is probably based on the confusing naming of the module, and what either you or a mod... |
type object 'datetime.datetime' has no attribute 'datetime' | 12,906,402 | 25 | 2012-10-16T01:39:33Z | 19,699,270 | 18 | 2013-10-31T05:48:22Z | [
"python",
"django"
] | I'm following a django tutorial, and I have gotten the following error:
> type object 'datetime.datetime' has no attribute 'datetime'
On the following line:
```
date = datetime.datetime(int(year), int(month), 1)
```
Does anybody know the reason for the error?
I imported datetime with `from datetime import datetime... | For python 3.3
```
from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)
``` |
Django how to check if the object has property in view | 12,906,933 | 8 | 2012-10-16T03:01:48Z | 12,907,341 | 16 | 2012-10-16T03:57:05Z | [
"python",
"django"
] | I am trying to get the documents property in a general function, but a few models may not have the documents attribute. Is there any way to first check if a model has the documents property, and then conditionally run code?
```
if self.model has property documents:
context['documents'] = self.get_object().do... | You can use `hasattr()` to check to see if model has the documents property.
```
if hasattr(self.model, 'documents'):
doStuff(self.model.documents)
```
However, [this answer](http://stackoverflow.com/a/610923/1269296) points out that some people feel the "easier to ask for forgiveness than permission" approach is... |
Empty model in z3 | 12,908,067 | 4 | 2012-10-16T05:27:05Z | 12,917,342 | 7 | 2012-10-16T14:45:05Z | [
"python",
"z3"
] | **z3py snippet:**
```
x = Int('x')
s = Solver()
s.add(x <= x)
print s.check()
print s.model()
print s.model().sexpr()
```
<http://rise4fun.com/Z3Py/mfPU>
**Output:**
```
sat
[]
```
Any value of `x` would do but `z3` returns empty model.
Does a missing free variable `x` in the model indicates that any integer valu... | Yes, in Z3, if a constant (such as `x`) does not appear in the model, then it is a "don't care". That is, any value of `x` will satisfy the formula. When evaluating the value of a constant, we can enable "model completion". That is, Z3 will use an arbitrary interpretation for "don't care" symbols. Here is an example <h... |
overriding __cmp__ python function | 12,908,933 | 3 | 2012-10-16T06:45:31Z | 12,909,103 | 7 | 2012-10-16T06:58:21Z | [
"python"
] | Hi I am overriding `__cmp__` . If the second object passed is `None`, or if it is not an instance of `someClass`, then it returns `-1`.
I don't understand what exactly is happening here.
```
class someClass():
def __cmp__(self, obj):
if obj == None:
return -1
if not isinstance(obj, som... | The convention for `__cmp__` is:
```
a < b : return -1
a = b : return 0
a > b : return 1
```
This of course makes only sense if both `a` and `b` are of compatible types, say numbers. If you have a 'corner case', where `a` or `b` is either None or incompatible (`not instanceof`), you should report an error, as this is... |
Analog of Python's range in Scheme | 12,909,856 | 6 | 2012-10-16T07:47:54Z | 12,910,265 | 7 | 2012-10-16T08:16:03Z | [
"python",
"scheme"
] | How to create a list of consecutive numbers in Scheme?
In Python to create a list of integers from 1 to 10 would be `range(1,11)`. Is there an equivalent for Scheme?
`mzscheme --version` gives `Welcome to Racket v5.2.1.`
**Edit:** Per <http://stackoverflow.com/a/7144310/596361> to implement range functionality, this... | Look for **iota** (as defined in SRFI-1).
Example: (iota 10 1) gives 10 consecutive integers starting from 1 (instead of the default of 0).
**iota** doesn't take the same arguments as range but it duplicates all the functionality - ascending ranges, descending ranges, starting from 0 if only one bound is given, abili... |
Errors installing Matplotlib - clang | 12,910,126 | 4 | 2012-10-16T08:06:32Z | 12,944,601 | 8 | 2012-10-17T22:50:22Z | [
"python",
"xcode",
"osx",
"matplotlib",
"clang"
] | I've tried to install Matplot lib but I'm still struggling to get past errors.
I've installed numpy and psipy but have the following error when I use easy\_install (there is a similar error with pip).
And yes, I've installed the command line tools in Xcode in a bid to solve the 'gcc-4.2 not found' problem.
```
pymod... | I recently had this issue as well, but I was using pip. If you have [homebrew](http://mxcl.github.com/homebrew/) installed you can solve it by running the following commands:
```
brew install freetype
brew install libpng
brew link freetype
pip install git+https://github.com/matplotlib/matplotlib.git#egg=matplotlib-dev... |
Pandas DataFrame slicing by day/hour/minute | 12,910,187 | 6 | 2012-10-16T08:11:17Z | 12,910,278 | 11 | 2012-10-16T08:16:51Z | [
"python",
"pandas",
"slice"
] | I have pandas Dataframe with datetime index like 'YYYY-MM-DD HH:MM:SS'.
```
Index Parameter
2007-05-02 14:14:08 134.8
2007-05-02 14:14:32 134.8
2007-05-02 14:14:41 134.8
2007-05-02 14:14:53 134.8
2007-05-02 14:15:01 134.8
2007-05-02 14:15:09 134.8
......
2007-05-30 23:08:02 ... | use `df.ix[x:y]` where `x` and `y` are datetime objects.
Example:
```
In [117]: frame.index.summary()
Out[117]: 'DatetimeIndex: 6312960 entries, 2000-04-05 00:01:00 to 2012-04-06 00:00:00\nFreq: T'
In [118]: x=datetime(2001, 4, 5, 0, 1)
In [119]: y=datetime(2001, 4, 5, 0, 5)
In [120]: print frame.ix[x:y]
... |
How do I use a X509 certificate with PyCrypto? | 12,911,373 | 14 | 2012-10-16T09:18:48Z | 12,921,889 | 28 | 2012-10-16T19:14:27Z | [
"python",
"openssl",
"rsa",
"pycrypto"
] | I want to encrypt some data in python with PyCrypto.
However I get an error when using `key = RSA.importKey(pubkey)`:
```
RSA key format is not supported
```
The key was generated with:
```
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.pem
```
The code is:
```
def encrypt(data... | PyCrypto does not support X.509 certificates. You must first extract the public key with the command:
```
openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem
```
Then, you can use `RSA.importKey` on `publickey.pem`.
---
If you don't want or cannot use openssl, you can take the PEM X.509 certifica... |
error: command 'gcc' failed with exit status when installing psycopg2 | 12,911,717 | 13 | 2012-10-16T09:40:09Z | 12,912,105 | 24 | 2012-10-16T10:00:19Z | [
"python",
"gcc",
"centos",
"openerp",
"centos5"
] | i need to install `psycopg2` for `openerp` installation process, but i always found that error. i've already used `pip` and `easy_install`, my `gcc` is the latest version. Really need your help to solve my problem...
this is my complete error with easy\_install..
```
[root@server01 ~]# easy_install psycopg2
Searc... | You'll need to install the development package for PostgreSQL, which for instance under Ubuntu is a `sudo apt-get install libpq-dev`... and for CentOS it's `yum install postgresql-devel` |
error: command 'gcc' failed with exit status when installing psycopg2 | 12,911,717 | 13 | 2012-10-16T09:40:09Z | 13,175,790 | 14 | 2012-11-01T11:10:28Z | [
"python",
"gcc",
"centos",
"openerp",
"centos5"
] | i need to install `psycopg2` for `openerp` installation process, but i always found that error. i've already used `pip` and `easy_install`, my `gcc` is the latest version. Really need your help to solve my problem...
this is my complete error with easy\_install..
```
[root@server01 ~]# easy_install psycopg2
Searc... | May Your system is missing the Python headers. To fix this, run:
```
sudo apt-get install python-dev
```
or
```
sudo apt-get install python3-dev
``` |
error: command 'gcc' failed with exit status when installing psycopg2 | 12,911,717 | 13 | 2012-10-16T09:40:09Z | 14,225,130 | 21 | 2013-01-08T22:27:41Z | [
"python",
"gcc",
"centos",
"openerp",
"centos5"
] | i need to install `psycopg2` for `openerp` installation process, but i always found that error. i've already used `pip` and `easy_install`, my `gcc` is the latest version. Really need your help to solve my problem...
this is my complete error with easy\_install..
```
[root@server01 ~]# easy_install psycopg2
Searc... | For the case of CentOS, I had this very same problem, that I solved installing these packages:
```
sudo yum install postgresql-libs
sudo yum install postgresql-devel
sudo yum install python-devel
```
only then, I was able to perform successfully:
```
sudo easy_install psycopg2
``` |
How to pull all the unique combinations from a list of lists | 12,913,293 | 2 | 2012-10-16T11:04:27Z | 12,913,336 | 11 | 2012-10-16T11:06:54Z | [
"python",
"list",
"loops"
] | I want to iterate over a list of lists, and pull all the combinations from the lists.
I can do it in the following way:
```
list = [['1','2','3'],['a','b','c'],['x','y','z']]
for itemi in list[0]:
print itemi
for itemj in list[1]:
print itemi+itemj
for itemk in list[2]:
print itemi... | Use [`itertools.product()`](http://docs.python.org/library/itertools.html?highlight=itertools#itertools.product):
```
>>> l = [['1','2','3'],['a','b','c'],['x','y','z']]
>>> import itertools
>>> list(itertools.product(*l))
[('1', 'a', 'x'), ('1', 'a', 'y'), ('1', 'a', 'z'), ('1', 'b', 'x'),
('1', 'b', 'y'), ('1', 'b... |
Python object deletion | 12,913,362 | 4 | 2012-10-16T11:08:36Z | 12,913,571 | 7 | 2012-10-16T11:20:54Z | [
"python",
"python-2.7"
] | ```
a = [1,2,3,4,5]
b = a[1]
print id(a[1],b) # out put shows same id.hence both represent same object.
del a[1] # deleting a[1],both a[1],b have same id,hence both are aliases
print a # output: [1,3,4,5]
print b # output: 2
```
Both b,a[1] have same id but deleting one isn't effectin... | `del` doesn't delete objects, it deletes **references**.
There is an object which is the integer value `2`. That one single object was referred to by two places; `a[1]` and `b`.
You deleted `a[1]`, so that reference was gone. But that has no effect on the **object** `2`, only on the reference that was in `a[1]`. So t... |
Same output in different workers in multiprocessing | 12,915,177 | 5 | 2012-10-16T12:53:21Z | 12,915,206 | 8 | 2012-10-16T12:55:07Z | [
"python",
"parallel-processing",
"multiprocessing"
] | I have very simple cases where the work to be done can be broken up and distributed between workers. I tired a very simple multiprocessing example from [here](http://broadcast.oreilly.com/2009/04/pymotw-multiprocessing-part-2.html):
```
import multiprocessing
import numpy as np
import time
def do_calculation(data):
... | I think you'll need to re-seed the random number generator using [numpy.random.seed](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html) in your `do_calculation` function.
My guess is that the random number generator (RNG) gets seeded when you import the module. Then, when you use multiprocessi... |
How to use the 'hex' encoding in Python 3.2 or higher? | 12,917,278 | 14 | 2012-10-16T14:40:54Z | 12,917,604 | 17 | 2012-10-16T14:58:36Z | [
"python",
"encoding",
"python-3.x",
"hex"
] | In Python 2, to get a string representation of the hexadecimal digits in a string, you could do
```
>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'
```
In Python 3, that doesn't work anymore (tested on Python 3.2 and 3.3):
```
>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
File "<stdin>", ... | You need to go via the [`codecs`](https://docs.python.org/3/library/codecs.html) module and the [`hex_codec`](https://docs.python.org/3/library/codecs.html#binary-transforms) codec (or its `hex` alias if available\*):
```
codecs.encode(b'\x12', 'hex_codec')
```
\* From the documentation: *"Changed in version 3.4: Res... |
How to use the 'hex' encoding in Python 3.2 or higher? | 12,917,278 | 14 | 2012-10-16T14:40:54Z | 12,919,120 | 12 | 2012-10-16T16:19:05Z | [
"python",
"encoding",
"python-3.x",
"hex"
] | In Python 2, to get a string representation of the hexadecimal digits in a string, you could do
```
>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'
```
In Python 3, that doesn't work anymore (tested on Python 3.2 and 3.3):
```
>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
File "<stdin>", ... | Yet another way using [`binascii.hexlify()`](http://docs.python.org/3/library/binascii.html#binascii.hexlify):
```
>>> import binascii
>>> binascii.hexlify(b'\x12\x34\x56\x78')
b'12345678'
``` |
Reading multiple numbers from a text file | 12,917,588 | 9 | 2012-10-16T14:57:34Z | 12,917,624 | 8 | 2012-10-16T14:59:35Z | [
"python",
"text",
"python-3.x",
"numbers"
] | I am new to programming in python and need help doing this.
I have a text file with several numbers like this:
```
12 35 21
123 12 15
12 18 89
```
I need to be able to read the individual numbers of each line to be able to use them in mathematical formulas. | In python, you read a line from a file as a string. You can then work with the string to get the data you need:
```
with open("datafile") as f:
for line in f: #Line is a string
#split the string on whitespace, return a list of numbers
# (as strings)
numbers_str = line.split()
#con... |
How to share secondary y-axis between subplots in matplotlib | 12,919,230 | 10 | 2012-10-16T16:25:45Z | 12,924,646 | 18 | 2012-10-16T22:49:52Z | [
"python",
"matplotlib"
] | If you have multiple subplots containing a secondary y-axis (created using *twinx*), how can you share these secondary y-axis between the subplots? I want them to scale equally in an automatic way (so not setting the y-limits afterwards by hand).
For the primary y-axis, this is possible by using the keyword *sharey* in... | You can use `Axes.get_shared_y_axes()` like so:
```
from numpy.random import rand
import matplotlib
matplotlib.use('gtkagg')
import matplotlib.pyplot as plt
# create all axes we need
ax0 = plt.subplot(211)
ax1 = ax0.twinx()
ax2 = plt.subplot(212)
ax3 = ax2.twinx()
# share the secondary axes
ax1.get_shared_y_axes().j... |
How to define free-variable in python? | 12,919,278 | 13 | 2012-10-16T16:28:24Z | 12,919,351 | 20 | 2012-10-16T16:33:11Z | [
"python"
] | The **local/global/free variable** definitions from [python doc](http://docs.python.org/py3k/reference/executionmodel.html):
> If a name is bound in a block, it is a **local variable** of that block, unless declared as nonlocal. If a name is bound at the module level, it is a **global variable**. (The variables of the... | ## Definition of a free variable: Used, but **neither global nor bound**.
For example:
1. `x` is not free in Code 1, because it's a **global** variable.
2. `x` is not free in `bar()` in Code 2, because it's a **bound** variable.
3. `x` is free in `foo()`.
Python makes this distinction because of closures. A free var... |
Nohup is not writing log to output file | 12,919,980 | 52 | 2012-10-16T17:09:04Z | 12,920,094 | 39 | 2012-10-16T17:17:11Z | [
"python",
"nohup"
] | I am using the following command to run a python script in the background:
```
nohup ./cmd.py > cmd.log &
```
But it appears that nohup is not writing anything to the log file. cmd.log is created but is always empty. In the python script, I am using `sys.stdout.write` instead of `print` to print to standard output. A... | It looks like you need to flush stdout periodically (e.g. `sys.stdout.flush()`). In my testing Python doesn't automatically do this even with `print` until the program exits. |
Nohup is not writing log to output file | 12,919,980 | 52 | 2012-10-16T17:09:04Z | 12,920,116 | 119 | 2012-10-16T17:19:17Z | [
"python",
"nohup"
] | I am using the following command to run a python script in the background:
```
nohup ./cmd.py > cmd.log &
```
But it appears that nohup is not writing anything to the log file. cmd.log is created but is always empty. In the python script, I am using `sys.stdout.write` instead of `print` to print to standard output. A... | You can run Python with the `-u` flag to avoid output buffering:
```
nohup python -u ./cmd.py > cmd.log &
``` |
Python `for` syntax: block code vs single line generator expressions | 12,920,214 | 12 | 2012-10-16T17:25:29Z | 12,920,247 | 11 | 2012-10-16T17:27:41Z | [
"python",
"for-loop"
] | I'm familiar with the `for` loop in a block-code context. eg:
```
for c in "word":
print c
```
I just came across some examples that use `for` differently. Rather than beginning with the `for` statement, they tag it at the end of an expression (and don't involve an indented code-block). eg:
```
sum(x*x for x in ... | What you are pointing to is `Generator` in Python. Take a look at: -
* <http://wiki.python.org/moin/Generators>
* <http://www.python.org/dev/peps/pep-0255/>
* <http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features>
See the documentation: - [`Generator Expression`](http://docs.python.org/tutorial/cla... |
Mark ticks in latex in matplotlib | 12,920,800 | 7 | 2012-10-16T18:07:03Z | 12,921,209 | 12 | 2012-10-16T18:33:36Z | [
"python",
"latex",
"matplotlib"
] | In a plot in matplotlib I specially want to mark points on the x-axis as pi/2, pi, 3pi/2 and so on in latex. How can I do it? | The `plt.xticks` command can be used to place LaTeX tick marks. See this [doc page](http://matplotlib.sourceforge.net/users/usetex.html) for more details.
```
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
cos = np.cos
pi = np.pi
# This is not necessary if `text.usetex : True` is already... |
What happens when you call `append` on a list? | 12,921,222 | 2 | 2012-10-16T18:34:34Z | 12,921,266 | 7 | 2012-10-16T18:36:35Z | [
"python",
"class",
"append",
"implementation"
] | Firstly, I don't know what the most appropriate title for this question would be. Contender: "how to implement `list.append` in custom class".
I have a `class` called `Individual`. Here's the relevant part of the class:
```
from itertools import count
class Individual:
ID = count()
def __init__(self, chromoso... | [`.append()`](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) is simply a method that takes one argument, and you can easily define one yourself:
```
def append(self, newitem):
self.chromosomes.append(newitem)
```
No magic methods required. |
Changing a list with a twist: whats going on behind the scenes | 12,922,706 | 2 | 2012-10-16T20:15:30Z | 12,922,730 | 10 | 2012-10-16T20:17:51Z | [
"python",
"list"
] | In python you can change a list like this:
```
In [303]: x = [1,2,3,4,5,6]
In [304]: x[x <= 3]+=3
In [305]: x
Out[306]: [4, 2, 3, 4, 5, 6]
```
I have known about this for some time now, but I don't think I fully understand whats going on behind the scenes. I would appriciate, if someone would find the time to expla... | `x <= 3` is a boolean expression. Since in Python, the `boolean` type is a subclass of `int`, the `False` outcome is interpreted as `0`, so the end effect is:
```
x[0] += 3
```
Or, demonstrated in a different way:
```
>>> False == 0
True
>>> True == 1
True
>>> isinstance(False, int)
True
```
The `dis.dis()` method ... |
"variable, variable =" syntax in python? | 12,923,059 | 2 | 2012-10-16T20:40:42Z | 12,923,087 | 10 | 2012-10-16T20:42:42Z | [
"python"
] | I'm just getting started in python, and either haven't read about this, or missed it, and I don't know what to search for to find my answer.
Playing around with the IMAP module I came across this line of code.
```
result, data = mail.search(None, "ALL")
```
What is happening with the two variables here? Is this a sy... | This is a form of sequence unpacking. If the RHS is an iterable of length 2 (since you have 2 objects on the LHS), you can use it. e.g.:
```
a,b = (1, 2) #The RHS here is a tuple, but it could be a list, generator, etc.
print a #1
print b #2
```
Python3 extends this in an interesting way to allow the RHS to have mor... |
How to setup a group in supervisord? | 12,923,320 | 16 | 2012-10-16T20:59:42Z | 12,935,120 | 20 | 2012-10-17T13:12:10Z | [
"python",
"configuration",
"supervisord"
] | So I'm setting up supervisord and trying to control several processes and that all works fine, now I want to setup a group so I can start/stop different sets of processes rather than all or nothing. Here's a snippet of my config file.
```
[group:tapjoy]
programs=tapjoy-game1,tapjoy-game2
[program:tapjoy-game1]
comman... | You need to use a `*` wildcard to select all programs in a group:
```
supervisorctl restart tapjoy:*
```
Note: it may that your shell requires you to escape the `*`, usually with `\*` |
Nearest Neighbor Search: Python | 12,923,586 | 14 | 2012-10-16T21:20:09Z | 13,079,101 | 17 | 2012-10-26T00:07:55Z | [
"python",
"numpy",
"nearest-neighbor",
"kdtree",
"closest-points"
] | I have a 2 dimensional array:
```
MyArray = array([6588252.24, 1933573.3, 212.79, 0, 0],
[6588253.79, 1933602.89, 212.66, 0, 0],
etc...)
```
The first two elements `MyArray[0]` and `MyArray[1]` are the *X* and *Y* coordinates of the points.
For every element in the array, I would lik... | Thanks to John Vinyard for suggesting scipy. After some good research and testing, here is the solution to this question:
Prerequisites:
Install Numpy and SciPy
1. Import the SciPy and Numpy Modules
2. Make a copy of the 5 dimensional array including *just* the X and Y values.
3. Create an instance of a `cKDTree` as ... |
Python and default dict, how to pprint | 12,925,052 | 16 | 2012-10-16T23:36:47Z | 12,925,062 | 22 | 2012-10-16T23:38:38Z | [
"python"
] | I am using default dict. I need to `pprint`.
However, when I `pprint` ...this is how it looks.
```
defaultdict(<functools.partial object at 0x1f68418>, {u'300:250': defaultdict(<functools.partial object at 0x1f683c0>, {0: defaultdict(<type 'list'>, {u'agid1430864021': {u'status': u'0', u'exclude_regi..........
```
H... | I've used `pprint(dict(defaultdict))` before as a work-around. |
Python and default dict, how to pprint | 12,925,052 | 16 | 2012-10-16T23:36:47Z | 18,376,589 | 17 | 2013-08-22T09:29:59Z | [
"python"
] | I am using default dict. I need to `pprint`.
However, when I `pprint` ...this is how it looks.
```
defaultdict(<functools.partial object at 0x1f68418>, {u'300:250': defaultdict(<functools.partial object at 0x1f683c0>, {0: defaultdict(<type 'list'>, {u'agid1430864021': {u'status': u'0', u'exclude_regi..........
```
H... | The best solution I've found is a bit of a hack, but an elegant one (if a hack can ever be):
```
class PrettyDefaultDict(collections.defaultdict):
__repr__ = dict.__repr__
```
And then use the `PrettyDefaultDict` class instead of `collections.defaultdict`. It works because of the way the pprint module works (at l... |
Using adaptive step sizes with scipy.integrate.ode | 12,926,393 | 14 | 2012-10-17T02:52:46Z | 12,935,589 | 7 | 2012-10-17T13:36:31Z | [
"python",
"scipy",
"ode"
] | The (brief) documentation for `scipy.integrate.ode` says that two methods (`dopri5` and `dop853`) have stepsize control and dense output. Looking at the examples and the code itself, I can only see a very simple way to get output from an integrator. Namely, it looks like you just step the integrator forward by some fix... | The `integrate` method accepts a boolean argument `step` that tells the method to return a single internal step. However, it appears that the 'dopri5' and 'dop853' solvers do not support it.
The following code shows how you can get the internal steps taken by the solver when the 'vode' solver is used:
```
import nump... |
Using adaptive step sizes with scipy.integrate.ode | 12,926,393 | 14 | 2012-10-17T02:52:46Z | 14,468,861 | 11 | 2013-01-22T22:01:50Z | [
"python",
"scipy",
"ode"
] | The (brief) documentation for `scipy.integrate.ode` says that two methods (`dopri5` and `dop853`) have stepsize control and dense output. Looking at the examples and the code itself, I can only see a very simple way to get output from an integrator. Namely, it looks like you just step the integrator forward by some fix... | I've been looking at this to try to get the same result. It turns out you can use a hack to get the step-by-step results by setting nsteps=1 in the ode instantiation. It will generate a UserWarning at every step (this can be caught and suppressed).
```
import numpy as np
from scipy.integrate import ode
import matplotl... |
Speeding up pairing of strings into objects in Python | 12,926,575 | 33 | 2012-10-17T03:15:42Z | 12,927,096 | 20 | 2012-10-17T04:26:16Z | [
"python",
"performance",
"algorithm",
"optimization",
"cython"
] | I'm trying to find an efficient way to pair together rows of data containing integer points, and storing them as Python objects. The data is made up of `X` and `Y` coordinate points, represented as a comma separated strings. The points have to be paired, as in `(x_1, y_1), (x_2, y_2), ...` etc. and then stored as a lis... | When dealing with the creating of *large* numbers of objects, often the single biggest performance enhancement you can use is to turn the garbage collector off. Every "generation" of objects, the garbage collector traverses all the live objects in memory, looking for objects that are a part of cycles but are not pointe... |
Speeding up pairing of strings into objects in Python | 12,926,575 | 33 | 2012-10-17T03:15:42Z | 12,994,214 | 7 | 2012-10-21T01:41:26Z | [
"python",
"performance",
"algorithm",
"optimization",
"cython"
] | I'm trying to find an efficient way to pair together rows of data containing integer points, and storing them as Python objects. The data is made up of `X` and `Y` coordinate points, represented as a comma separated strings. The points have to be paired, as in `(x_1, y_1), (x_2, y_2), ...` etc. and then stored as a lis... | I got a 50% improvement by using arrays, and a holder object that lazily constructs Point objects when accessed. I also "slotted" the Point object for better storage efficiency. However, a tuple would probably be better.
Changing the data structure may also help, if that's possible. But this will never be instantaneou... |
Speeding up pairing of strings into objects in Python | 12,926,575 | 33 | 2012-10-17T03:15:42Z | 13,001,574 | 9 | 2012-10-21T19:51:43Z | [
"python",
"performance",
"algorithm",
"optimization",
"cython"
] | I'm trying to find an efficient way to pair together rows of data containing integer points, and storing them as Python objects. The data is made up of `X` and `Y` coordinate points, represented as a comma separated strings. The points have to be paired, as in `(x_1, y_1), (x_2, y_2), ...` etc. and then stored as a lis... | I would
* use `numpy` arrays for this problem (`Cython` would be an option, if this is still not fast enough).
* store the points as a vector not as single `Point` instances.
* rely on existing parsers
* (if possible) parse the data once and than store it in a binary format like hdf5 for further calculations, which wi... |
Speeding up pairing of strings into objects in Python | 12,926,575 | 33 | 2012-10-17T03:15:42Z | 13,008,770 | 15 | 2012-10-22T09:48:21Z | [
"python",
"performance",
"algorithm",
"optimization",
"cython"
] | I'm trying to find an efficient way to pair together rows of data containing integer points, and storing them as Python objects. The data is made up of `X` and `Y` coordinate points, represented as a comma separated strings. The points have to be paired, as in `(x_1, y_1), (x_2, y_2), ...` etc. and then stored as a lis... | Simply running with pypy makes a big difference
```
$ python pairing_strings.py
total time: 2.09194397926
$ pypy pairing_strings.py
total time: 0.764246940613
```
disable gc didn't help for pypy
```
$ pypy pairing_strings.py
total time: 0.763386964798
```
namedtuple for Point makes it worse
```
$ pypy pairin... |
Speeding up pairing of strings into objects in Python | 12,926,575 | 33 | 2012-10-17T03:15:42Z | 13,040,475 | 8 | 2012-10-23T22:45:00Z | [
"python",
"performance",
"algorithm",
"optimization",
"cython"
] | I'm trying to find an efficient way to pair together rows of data containing integer points, and storing them as Python objects. The data is made up of `X` and `Y` coordinate points, represented as a comma separated strings. The points have to be paired, as in `(x_1, y_1), (x_2, y_2), ...` etc. and then stored as a lis... | Faster method, using Numpy (speedup of about **7x**):
```
import numpy as np
txt = ','.join(','.join(row) for row in data)
arr = np.fromstring(txt, dtype=int, sep=',')
return arr.reshape(100000, 2, 10).transpose((0,2,1))
```
Performance comparison:
```
def load_1(data):
all_point_sets = []
gc.disable()
f... |
How to make a sunburst plot in R or Python? | 12,926,779 | 18 | 2012-10-17T03:41:44Z | 12,927,886 | 9 | 2012-10-17T05:49:19Z | [
"python",
"ggplot2",
"data-visualization",
"sunburst-diagram"
] | So far I have been unable to find an R library that can create a sunburst plot like those by [John Stasko](http://www.cc.gatech.edu/gvu/ii/sunburst/). Anyone knows how to accomplish that in R or Python?
 | You can create something along the lines of a sunburst plot using `geom_tile` from the `ggplot2` package. Let's first create some random data:
```
require(ggplot2); theme_set(theme_bw())
require(plyr)
dat = data.frame(expand.grid(x = 1:10, y = 1:10),
z = sample(LETTERS[1:3], size = 100, replace = TRUE... |
How to make a sunburst plot in R or Python? | 12,926,779 | 18 | 2012-10-17T03:41:44Z | 32,888,561 | 9 | 2015-10-01T13:14:47Z | [
"python",
"ggplot2",
"data-visualization",
"sunburst-diagram"
] | So far I have been unable to find an R library that can create a sunburst plot like those by [John Stasko](http://www.cc.gatech.edu/gvu/ii/sunburst/). Anyone knows how to accomplish that in R or Python?
 | You can even build an interactive version quite easily with R now:
```
# devtools::install_github("timelyportfolio/sunburstR")
library(sunburstR)
# read in sample visit-sequences.csv data provided in source
# https://gist.github.com/kerryrodden/7090426#file-visit-sequences-csv
sequences <- read.csv(
system.file("ex... |
numpy unique without sort | 12,926,898 | 9 | 2012-10-17T03:58:57Z | 12,926,989 | 17 | 2012-10-17T04:11:20Z | [
"python",
"numpy"
] | How can I use numpy unique without sorting the result but just in the order they appear in the sequence? Something like this?
`a = [4,2,1,3,1,2,3,4]`
`np.unique(a) = [4,2,1,3]`
rather than
`np.unique(a) = [1,2,3,4]`
Use naive solution should be fine to write a simple function. But as I need to do this multiple tim... | You can do this with the `return_index` parameter:
```
>>> import numpy as np
>>> a = [4,2,1,3,1,2,3,4]
>>> np.unique(a)
array([1, 2, 3, 4])
>>> indexes = np.unique(a, return_index=True)[1]
>>> [a[index] for index in sorted(indexes)]
[4, 2, 1, 3]
``` |
parsing excel style formula | 12,929,086 | 6 | 2012-10-17T07:18:32Z | 12,929,794 | 7 | 2012-10-17T08:06:48Z | [
"python"
] | I am working on building formula reference map from spreadsheet xml using python. formula is like
```
=IF(AND(LEN(R[-2]C[-1])>0,R[-1]C),WriteCurve(OFFSET(R16C6, 0,0,R9C7,R10C7),R15C6,R10C3, R8C3),"NONE")
```
I am only interested in getting nth argument of writecurve function. here i comes up very C style program basi... | The best Excel formula parser I'm aware of is [E. W. Bachtal's algorithm](http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html). There's a Python port by Robin Macharg; the most recent version I know about is part of the [pycel project](https://github.com/dgorissen/pycel), but it can be used standalone - [tokeni... |
WSGIPythonPath is not working | 12,931,013 | 5 | 2012-10-17T09:19:23Z | 12,931,688 | 11 | 2012-10-17T09:56:13Z | [
"python",
"apache2",
"mod-wsgi",
"pythonpath"
] | I am deploying my web.py application on Apache2 with mod\_wsgi.
Here is my virt\_host file,
```
WSGIPythonPath /home/ubuntu/plotwatt/libplotwatt:/home/ubuntu/plotwatt/pwstage/src
<VirtualHost *:20108>
ServerAdmin gslabrails.dev.plotwatt.com
DocumentRoot /var/www
WSGIScriptAlias / /var/www/currentcost/server.py
WSGI... | According to [the docs](https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonPath), you cannot use `WSGIPythonPath` when using daemon mode. Use the 'python-path' option to the [WSGIDaemonProcess directive](https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess) instead. |
How to check with Python and sqlite3 if one sqlite database file exists? | 12,932,607 | 6 | 2012-10-17T10:46:41Z | 12,932,782 | 10 | 2012-10-17T10:55:30Z | [
"python",
"sqlite3"
] | I am trying to create a function in Python 2.7.3 to open a sqlite database.
This is my code at the moment:
```
import sqlite3 as lite
import sys
db = r'someDb.sqlite'
def opendb(db):
try:
conn = lite.connect(db)
except sqlite3.Error:
print "Error open db.\n"
return False
cur = c... | You'll have to explicitly test for the existence using [`os.path.isfile`](http://docs.python.org/library/os.path.html#os.path.isfile):
```
if os.path.isfile(db):
```
There is no way to force the `sqlite3.connect` function to not create the file for you. |
How to check with Python and sqlite3 if one sqlite database file exists? | 12,932,607 | 6 | 2012-10-17T10:46:41Z | 15,355,790 | 13 | 2013-03-12T07:45:32Z | [
"python",
"sqlite3"
] | I am trying to create a function in Python 2.7.3 to open a sqlite database.
This is my code at the moment:
```
import sqlite3 as lite
import sys
db = r'someDb.sqlite'
def opendb(db):
try:
conn = lite.connect(db)
except sqlite3.Error:
print "Error open db.\n"
return False
cur = c... | `os.path.isfile()` is just telling you if a file exists, not if it exists AND is a SQLite3 database! Knowing <http://www.sqlite.org/fileformat.html>, you could do this :
```
def isSQLite3(filename):
from os.path import isfile, getsize
if not isfile(filename):
return False
if getsize(filename) < 10... |
Reading csv header white space and case insensitive | 12,933,895 | 2 | 2012-10-17T12:03:17Z | 12,934,129 | 7 | 2012-10-17T12:16:15Z | [
"python",
"csv",
"python-3.x"
] | Is there a possibility to read the header of a CSV file white space and case insensitive? As for now I use `csv.dictreader` like this:
```
import csv
csvDict = csv.DictReader(open('csv-file.csv', 'rU'))
# determine column_A name
if 'column_A' in csvDict.fieldnames:
column_A = 'column_A'
elif ' column_A' in csvDic... | You can redefine `reader.fieldnames`:
```
import csv
import io
content = '''column_A " column_B"
1 2'''
reader = csv.DictReader(io.BytesIO(content), delimiter = ' ')
reader.fieldnames = [field.strip().lower() for field in reader.fieldnames]
for line in reader:
print(line)
```
yields
```
{'column_b': '2', 'colum... |
Printing a list of objects of user defined class | 12,933,964 | 20 | 2012-10-17T12:07:10Z | 12,934,023 | 23 | 2012-10-17T12:10:17Z | [
"python"
] | So I have a class, called `Vertex`.
```
class Vertex:
'''
This class is the vertex class. It represents a vertex.
'''
def __init__(self, label):
self.label = label
self.neighbours = []
def __str__(self):
return("Vertex "+str(self.label)+":"+str(self.neighbours))
```
I wan... | If you just want to print the label for each object, you could use a loop or a list comprehension:
```
print [vertex.label for vertex in x]
```
But to answer your original question, you need to define the `__repr__` method to get the list output right. It could be something as simple as this:
```
def __repr__(self):... |
Is there a short contains function for lists? | 12,934,190 | 163 | 2012-10-17T12:19:53Z | 12,934,223 | 281 | 2012-10-17T12:21:03Z | [
"python",
"list",
"search",
"collections",
"contains"
] | I see people are using `any` to gather another list to see if an item exists in a list, but is there a quick way to just do?:
```
if list.contains(myItem):
# do something
``` | You can use this syntax:
```
if myItem in list:
# do something
```
Also, inverse operator:
```
if myItem not in list:
# do something
```
It's work fine for lists, tuples, sets and dicts (check keys).
**Note** that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts. |
Is there a short contains function for lists? | 12,934,190 | 163 | 2012-10-17T12:19:53Z | 12,934,468 | 25 | 2012-10-17T12:36:43Z | [
"python",
"list",
"search",
"collections",
"contains"
] | I see people are using `any` to gather another list to see if an item exists in a list, but is there a quick way to just do?:
```
if list.contains(myItem):
# do something
``` | In addition to what other have said, you may also be interested to know that what `in` does is to call the `list.__contains__` method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
```
>>> class ContainsEverything:
def __init__(self):
... |
Access URI Parameters via webapp2 | 12,934,427 | 5 | 2012-10-17T12:33:04Z | 12,937,647 | 10 | 2012-10-17T15:18:00Z | [
"python",
"google-app-engine",
"webapp2"
] | I want to access the URI parameters of the given request:
```
http://localhost:8080/account/user?un=erik&pw=gaius
```
I can't make the following code work though,
**main.py**
```
app = webapp2.WSGIApplication([('/', MainPage),
('/account/user', account.User)],
... | ```
class User(webapp2.RequestHandler):
def get(self):
un = self.request.get('un')
pw = self.request.get('pw')
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Yey!' + un + ' ' + pw)
``` |
Selecting fields from JSON output | 12,934,699 | 7 | 2012-10-17T12:49:38Z | 12,934,757 | 13 | 2012-10-17T12:52:29Z | [
"python"
] | Using Python, how can i extract the field `id` to a variable? Basicaly, i to transform this:
```
{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}
```
to something like
```... | Assume you stored that dictionary in a variable called values. To get `id` in to a variable, do:
```
idValue = values['criteria'][0]['id']
```
If that json is in a file, do the following to load it:
```
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
```
If that ... |
How to detect lowercase letters in Python? | 12,934,997 | 8 | 2012-10-17T13:04:46Z | 12,935,035 | 16 | 2012-10-17T13:07:12Z | [
"python",
"string",
"lowercase",
"letters"
] | I need to know if there is a function that detects the lowercase letters in a string. Say I started writing this program:
```
s = input('Type a word')
```
Would there be a function that lets me detect a lowercase letter within the string s? Possibly ending up with assigning those letters to a different variable, or j... | To check if a character is lower case, use the `islower` method of `str`. This simple imperative program prints all the lowercase letters in your string:
```
for c in s:
if c.islower():
print c
```
Note that in Python 3 you should use `print(c)` instead of `print c`.
---
> Possibly ending up with assig... |
How to plot line (polygonal chain) with numpy/scipy/matplotlib with minimal smoothing | 12,935,098 | 8 | 2012-10-17T13:11:00Z | 12,936,696 | 7 | 2012-10-17T14:32:32Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"spline"
] | I am trying to plot a line in matplotlib.. I am searching for the right type of interpolation.. I want something like this

where every line is smoothed. I tried several combination of scipy and matplotlib, such as
```
x_new = np.arange(x, x... | For that type of graph, you want *monotonic* interpolation. The [`PchipInterpolator`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.PchipInterpolator.html) class (which you can refer to by its shorter alias `pchip`) in scipy.interpolate can be used:
```
import numpy as np
from scipy.interpolate... |
combinations between two lists? | 12,935,194 | 18 | 2012-10-17T13:16:31Z | 12,935,562 | 14 | 2012-10-17T13:35:11Z | [
"python",
"algorithm"
] | Itâs been a while and Iâm having trouble wrapping my head around a algorithm Iâm try to make. Basically, I have two lists and want to get all the combinations of the two lists.
I might not be explaining it correct so hereâs a example.
```
name = 'a', 'b'
number = 1, 2
```
the output in this case would be:
`... | Suppose `len(list1) >= len(list2)`. Then what you appear to want is to take all permutations of length `len(list2)` from `list1` and match them with items from list2. In python:
```
>>> import itertools
>>> list1=['a','b','c']
>>> list2=[1,2]
>>> [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
[[('a',... |
combinations between two lists? | 12,935,194 | 18 | 2012-10-17T13:16:31Z | 34,032,549 | 74 | 2015-12-01T23:57:18Z | [
"python",
"algorithm"
] | Itâs been a while and Iâm having trouble wrapping my head around a algorithm Iâm try to make. Basically, I have two lists and want to get all the combinations of the two lists.
I might not be explaining it correct so hereâs a example.
```
name = 'a', 'b'
number = 1, 2
```
the output in this case would be:
`... | The simplest way is to use `itertools.product`:
```
a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]
``` |
python - call instance method using __func__ | 12,935,241 | 10 | 2012-10-17T13:18:58Z | 12,935,356 | 18 | 2012-10-17T13:24:03Z | [
"python"
] | I am new to python, and I don't quite understand the `__func__` in python 2.7.
I know when I define a class like this:
```
class Foo:
def f(self, arg):
print arg
```
I can use either `Foo().f('a')` or `Foo.f(Foo(), 'a')` to call this method. However, I can't call this method by `Foo.f(Foo, 'a')`. But I a... | When you access `Foo.f` or `Foo().f` a *method* is returned; it's unbound in the first case and bound in the second. A python method is essentially a wrapper around a function that also holds a reference to the class it is a method of. When bound, it also holds a reference to the instance.
When you *call* an method, i... |
Converting string to base36 inconsistencies between languages. | 12,935,891 | 6 | 2012-10-17T13:50:05Z | 12,935,993 | 10 | 2012-10-17T13:55:45Z | [
"javascript",
"python",
"base36"
] | I have noticed some inconsistencies between Python and JavaScript when converting a string to base36.
**Python Method:**
```
>>> print int('abcdefghijr', 36)
```
Result: 37713647386641447
**Javascript Method:**
```
<script>
document.write(parseInt("abcdefghijr", 36));
</script>
```
Result: 37713647386641450
... | That number takes 56 bits to represent. JavaScript's numbers are actually [double-precision binary floating point numbers](http://en.wikipedia.org/wiki/Double_precision), or `double` for short. These are 64 bit in total, and can represent a far wider *range* of values than a 64 bit integers, but due to how they achieve... |
'{' is not recognized as an internal or external command, operable program or batch file | 12,937,063 | 3 | 2012-10-17T14:49:06Z | 12,937,142 | 8 | 2012-10-17T14:52:38Z | [
"python"
] | Running on Windows, the following Python program produces the above output (the content of the output variable)
```
import commands
cmd = "dir"
(output) = commands.getoutput(cmd)
print output
```
Very interesting and frustrating. Can someone point me to the explanation please? | See the [documentation](http://docs.python.org/library/commands.html#commands.getstatusoutput):
> cmd is actually run as { cmd ; } 2>&1
Which is where the `{` are coming from. You should use `subprocess` instead.
```
import subprocess
p = subprocess.Popen(['dir'],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell... |
Can I run py2app on Windows? | 12,937,916 | 8 | 2012-10-17T15:33:15Z | 14,162,623 | 8 | 2013-01-04T18:17:38Z | [
"python",
"windows",
"py2app"
] | I recently discovered that an outdated version of Python was causing my Wx app to run into errors.
I can't install Python 2.7.3 on my Mac, and when I tried it in a virtual machine, py2app was still "compiling" the app after running overnight (my Windows/Linux box has an â1GHz processor).
Is there a version of py2ap... | According to the [project page](http://pypi.python.org/pypi/py2app/) and the [readme](http://svn.pythonmac.org/py2app/py2app/trunk/README.txt), py2app is directed at creating Mac apps out of python code. Obviously you won't be able to run the final product on a windows machine. But if the question is can you build the ... |
Python: instance has no attribute | 12,938,917 | 10 | 2012-10-17T16:26:52Z | 12,938,989 | 17 | 2012-10-17T16:31:22Z | [
"python",
"class",
"attributeerror"
] | I have a problem with list within a class in python. Here's my code :
```
class Residues:
def setdata(self, name):
self.name = name
self.atoms = list()
a = atom
C = Residues()
C.atoms.append(a)
```
Something like this. I get an error saying:
```
AttributeError: Residues instance has no attribute... | Your class doesn't have a `__init__()`, so by the time it's instantiated, the attribute `atoms` is not present. You'd have to do `C.setdata('something')` so `C.atoms` becomes available.
```
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
... |
How to list all installed packages and their versions in Python? | 12,939,975 | 62 | 2012-10-17T17:29:49Z | 12,939,998 | 22 | 2012-10-17T17:31:21Z | [
"python"
] | Is there a way in Python to list all installed packages and their versions?
I know I can go inside `python/Lib/site-packages` and see what files and directories exist, but I find this very awkward. What I'm looking for something that is similar to `npm list` [[1]](https://npmjs.org/doc/list.html). | `help('modules')` should do it for you.
in IPython :
```
In [1]: import #import press-TAB
Display all 631 possibilities? (y or n)
ANSI audiodev markupbase
AptUrl audioop markupsafe
ArgImagePlugin avahi marshal... |
How to list all installed packages and their versions in Python? | 12,939,975 | 62 | 2012-10-17T17:29:49Z | 12,940,002 | 99 | 2012-10-17T17:31:30Z | [
"python"
] | Is there a way in Python to list all installed packages and their versions?
I know I can go inside `python/Lib/site-packages` and see what files and directories exist, but I find this very awkward. What I'm looking for something that is similar to `npm list` [[1]](https://npmjs.org/doc/list.html). | If you have pip install and you want to see what packages have been installed with your installer tools you can simply call this:
```
pip freeze
```
It will also include version numbers for the installed packages.
**Update**
pip has been updated to also produce the same output as `pip freeze` by calling:
```
pip l... |
How to list all installed packages and their versions in Python? | 12,939,975 | 62 | 2012-10-17T17:29:49Z | 13,785,041 | 8 | 2012-12-09T05:50:48Z | [
"python"
] | Is there a way in Python to list all installed packages and their versions?
I know I can go inside `python/Lib/site-packages` and see what files and directories exist, but I find this very awkward. What I'm looking for something that is similar to `npm list` [[1]](https://npmjs.org/doc/list.html). | You can try : **Yolk**
For install yolk, try:
```
easy_install yolk
```
> Yolk is a Python tool for obtaining information about installed Python
> packages and querying packages avilable on PyPI (Python Package
> Index).
>
> You can see which packages are active, non-active or in development
> mode and show you whic... |
How to list all installed packages and their versions in Python? | 12,939,975 | 62 | 2012-10-17T17:29:49Z | 33,457,406 | 8 | 2015-10-31T22:42:20Z | [
"python"
] | Is there a way in Python to list all installed packages and their versions?
I know I can go inside `python/Lib/site-packages` and see what files and directories exist, but I find this very awkward. What I'm looking for something that is similar to `npm list` [[1]](https://npmjs.org/doc/list.html). | If you want to get information about your installed python distributions and don't want to use your cmd console or terminal for it, but rather through python code, you can use the following code (tested with python 3.4):
```
import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_onl... |
How to count rows with SELECT COUNT(*) with SQLAlchemy? | 12,941,416 | 12 | 2012-10-17T18:59:48Z | 12,942,318 | 9 | 2012-10-17T19:56:13Z | [
"python",
"sql",
"sqlalchemy"
] | I'd like to know if it's possible to generate a `SELECT COUNT(*) FROM TABLE` statement in SQLAlchemy without explicitly asking for it with `execute()`.
If I use:
`session.query(table).count()`
then it generates something like:
```
SELECT count(*) AS count_1 FROM
(SELECT table.col1 as col1, table.col2 as col2, ..... | Query for just a single known column:
```
session.query(MyTable.col1).count()
``` |
How to count rows with SELECT COUNT(*) with SQLAlchemy? | 12,941,416 | 12 | 2012-10-17T18:59:48Z | 12,942,437 | 23 | 2012-10-17T20:03:28Z | [
"python",
"sql",
"sqlalchemy"
] | I'd like to know if it's possible to generate a `SELECT COUNT(*) FROM TABLE` statement in SQLAlchemy without explicitly asking for it with `execute()`.
If I use:
`session.query(table).count()`
then it generates something like:
```
SELECT count(*) AS count_1 FROM
(SELECT table.col1 as col1, table.col2 as col2, ..... | I managed to render the following SELECT with SQLAlchemy on both layers.
```
SELECT count(*) AS count_1
FROM "table"
```
## Usage from the SQL Expression layer
```
from sqlalchemy import select, func, Integer, Table, Column, MetaData
metadata = MetaData()
table = Table("table", metadata,
Column('prim... |
Python Variable Scope and Classes | 12,941,748 | 2 | 2012-10-17T19:18:51Z | 12,941,775 | 7 | 2012-10-17T19:20:17Z | [
"python",
"python-2.7"
] | In Python, if I define a variable:
```
my_var = (1,2,3)
```
and try to access it in `__init__` function of a class:
```
class MyClass:
def __init__(self):
print my_var
```
I can access it and print `my_var` without stating (global my\_var).
If I put `my_var` right after `class MyClass` however, I get s... | When you put it right after `class MyClass`, it becomes a class attribute and you can get access to it via `MyClass.my_var` or as `self.my_var` from within the class (provided you don't create an *instance* variable with the same name).
Here's a little demo:
```
my_var = 'global'
class MyClass(object):
my_var = 'c... |
Python Variable Scope and Classes | 12,941,748 | 2 | 2012-10-17T19:18:51Z | 12,942,115 | 9 | 2012-10-17T19:42:13Z | [
"python",
"python-2.7"
] | In Python, if I define a variable:
```
my_var = (1,2,3)
```
and try to access it in `__init__` function of a class:
```
class MyClass:
def __init__(self):
print my_var
```
I can access it and print `my_var` without stating (global my\_var).
If I put `my_var` right after `class MyClass` however, I get s... | Complementing @mgilson's answer:
Note that Python Class variables are shared among the class instances. And the behaviour might be VERY unexpected and seem weird. In practice it works like this:
```
class MyClass(object):
my_var = 10
def __init__(self):
print(self.my_var)
m1 = MyClass()
print(m1.my_... |
How to perform non-linear optimization with scipy/numpy or sympy? | 12,942,153 | 4 | 2012-10-17T19:44:13Z | 12,943,214 | 7 | 2012-10-17T20:55:29Z | [
"python",
"numpy",
"scipy",
"sympy"
] | I am trying to find the optimal solution to the follow system of equations in Python:
```
(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0
```
Given the values a point(x,y) and a radius (r):
```
x1, y1, r1 = (0, 0, 0.88)
x2, y2, r2 = (2, 0, 1)
x3, y3, r3 = (0, 2, 0.75)
```... | If I understand your question correctly, I *think* this is what you're after:
```
from scipy.optimize import minimize
import numpy as np
def f(coord,x,y,r):
return np.sum( ((coord[0] - x)**2) + ((coord[1] - y)**2) - (r**2) )
x = np.array([0, 2, 0])
y = np.array([0, 0, 2])
r = np.array([.88, 1, .75])
# ini... |
Python string comparison with different case and float | 12,942,690 | 4 | 2012-10-17T20:18:38Z | 12,942,704 | 8 | 2012-10-17T20:19:39Z | [
"python"
] | why python is giving output like this:
```
>>> 'apple' > 'T'
True
>>> 'apple' > 't'
False
```
It should be True for both cases.right?
Edit:
I got the Idea of ASCII Table.Thanks!!
Now what about this.Is 11.1 is being treated as '11.1'?
```
>>> 'apple' > 11.1
True
``` | Because `a` comes after `T` in the ASCII character set, but before `t`.
The decimal ASCII encoding of these letters:
* `T` is 84.
* `a` is 97.
* `t` is 116. |
OpenCV Python single (rather than multiple) blob tracking? | 12,943,410 | 12 | 2012-10-17T21:09:09Z | 12,946,024 | 8 | 2012-10-18T02:01:42Z | [
"python",
"opencv",
"blob",
"color-tracking"
] | I've been trying to get single color blob tracking thru OpenCV on Python.
The below code is working, but it finds the centroid of all the tracked pixels, not just the centroid of the biggest blob. This is because I'm taking the moments of all the pixels, but I'm not sure how else to color track.
I'm kind of stuck on wh... | You need to do it like this :
1) Get the thresholded image using inRange function, and you can apply some erosion and dilation to remove small noisy particles. It will help to improve the processing speed.
2) find Contours using 'findContours' function
3) find areas of contours using 'contourArea' function and selec... |
Is it possible to show the exact position in Sublime Text 2? | 12,943,594 | 19 | 2012-10-17T21:21:34Z | 13,002,055 | 42 | 2012-10-21T20:47:41Z | [
"python",
"sublimetext2",
"markdown"
] | I've been learning Markdown, and using the Python Markdown package, which often returns the following when I try to convert text that has been pasted in from the web:
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in
position 1611: ordinal not in range(128)
```
At the bottom of my editor I cu... | You could make a simple python script to do this.
1.
Save this code to your User folder as `characterCounter.py` (`Preferences > Browse Packages > User`):
```
import sublime, sublime_plugin
class PositionListener(sublime_plugin.EventListener):
def on_selection_modified(self,view):
text = "Position: "
sels ... |
How to Python prettyprint a JSON file | 12,943,819 | 199 | 2012-10-17T21:38:43Z | 12,944,035 | 336 | 2012-10-17T21:54:12Z | [
"python",
"json",
"pretty-print"
] | I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work. | The `json` module already implements some basic pretty printing with the `indent` parameter:
```
>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
"foo",
{
"bar": [
"baz",... |
How to Python prettyprint a JSON file | 12,943,819 | 199 | 2012-10-17T21:38:43Z | 32,228,333 | 58 | 2015-08-26T13:42:04Z | [
"python",
"json",
"pretty-print"
] | I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work. | You can do this on the command line:
```
cat some.json | python -m json.tool
```
(as already mentioned in the commentaries to the question).
Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it... |
How to Python prettyprint a JSON file | 12,943,819 | 199 | 2012-10-17T21:38:43Z | 32,246,976 | 11 | 2015-08-27T10:30:08Z | [
"python",
"json",
"pretty-print"
] | I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work. | # Pygmentize + Python json.tool = Pretty Print with Syntax Highlighting
Pygmentize is a killer tool. [See this.](http://stackoverflow.com/a/27501509/2670370)
I combine python json.tool with pygmentize
```
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
```
See the link above for pygmentize installation ... |
Using unicodedata.normalize in Python 2.7 | 12,944,678 | 7 | 2012-10-17T22:57:50Z | 12,947,127 | 18 | 2012-10-18T04:28:15Z | [
"python",
"python-2.7",
"unicode",
"normalization",
"unicode-normalization"
] | Once again, I am very confused with a unicode question. I can't figure out how to successfully use [unicodedata.normalize](http://docs.python.org/library/unicodedata.html) to convert non-ASCII characters as expected. For instance, I want to convert the string
```
u"CÅur"
```
To
```
u"Coeur"
```
I am pretty sure th... | You could try [`Unidecode`](http://pypi.python.org/pypi/Unidecode):
```
# -*- coding: utf-8 -*-
from unidecode import unidecode # $ pip install unidecode
print(unidecode(u"CÅur"))
# -> Coeur
``` |
How can I infinitely loop an iterator in Python, via a generator or other? | 12,944,882 | 5 | 2012-10-17T23:20:40Z | 12,944,904 | 22 | 2012-10-17T23:23:51Z | [
"python",
"loops",
"generator"
] | It's my understanding that using a Generator is the best way to achieve something like this, but I'm open to suggestions.
Specifically, one use case is this: I'd like to print some items alongside another list, of an arbitrary length, truncating the initial iterator as necessary.
Here is working python code that demo... | You can use [`itertools.cycle`](http://docs.python.org/library/itertools.html#itertools.cycle) (source included on linked page).
```
import itertools
a = [1, 2, 3]
for element in itertools.cycle(a):
print element
# -> 1 2 3 1 2 3 1 2 3 1 2 3 ...
``` |
Substrings of a string | 12,945,029 | 4 | 2012-10-17T23:35:41Z | 12,945,063 | 9 | 2012-10-17T23:39:28Z | [
"python",
"string",
"substrings"
] | How many substrings can you make out of a string like âabcdâ?
For example, suppose I have a string containing the following:
```
'abcd'
```
How can I get it to look like this:
```
['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
``` | Try this:
```
def consecutive_groups(iterable):
s = tuple(iterable)
for size in range(1, len(s)+1):
for index in range(len(s)+1-size):
yield iterable[index:index+size]
>>> print list(consecutive_groups('abcd'))
['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
```
And the numbe... |
Get January 1st of next year | 12,945,089 | 2 | 2012-10-17T23:41:54Z | 12,945,130 | 14 | 2012-10-17T23:46:19Z | [
"python",
"django"
] | This really shouldn't be this hard but for some reason I can't seem to get it.
I am trying to run a filter on my query that compares the date range between today, and the first day of next year.
Getting today is no problem, but I can't seem to get the first day of next year. I want to be able to provide myself with J... | Does this work?
```
>>> today = datetime.datetime.now()
>>> next_year = datetime.datetime(year=today.year+1, month=1, day=1)
>>> next_year
datetime.datetime(2013, 1, 1, 0, 0)
``` |
Is this the way to validate Django model fields? | 12,945,339 | 11 | 2012-10-18T00:13:00Z | 12,945,692 | 18 | 2012-10-18T01:07:18Z | [
"python",
"django",
"django-models"
] | As I understand it, when one creates a Django application, data is validated by the form before it's inserted into a model instance which is then written to the database. But if I want to create an additional layer of protection at the data model layer, is what I've done below the current "best practice?" I'm trying to... | Firstly, you shouldn't override `full_clean` as you have done. From the [django docs on full\_clean](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean):
> **`Model.full_clean(exclude=None)`**
> This method calls `Model.clean_fields()`, `Model.clean()`, and `Model.validate_... |
pyodbc.connect timeout argument is ignored for calls to SQL Server | 12,945,353 | 7 | 2012-10-18T00:14:35Z | 12,954,722 | 9 | 2012-10-18T12:30:41Z | [
"python",
"sql-server-2005",
"pyodbc"
] | I am using pyodbc on Linux with FreeTDS to connect to SQL Server 2005. I have noticed that the timeout argument to my connection is not being honoured by my queries.
When I run the following I would expect to see timeout errors after both cursor.execute calls.
```
import pyodbc
import time
connString = 'SERVER=dbser... | Add [`Connection.timeout`](http://code.google.com/p/pyodbc/wiki/Connection#timeout) variable assignment to your code. Defaults to `0` (timeout disabled), expected in seconds.
```
import pyodbc
import time
connString = 'SERVER=dbserver;PORT=1433;DATABASE=db;UID=dbuser;PWD=dbpwd;' + \
'DRIVER=FreeTDS'
cnxn... |
why is my timedelta math off? | 12,945,752 | 2 | 2012-10-18T01:17:12Z | 12,945,783 | 9 | 2012-10-18T01:22:03Z | [
"python",
"datetime"
] | I couldn't find anything online and probably has some stupid simple answer, but being new to python I don't understand:
```
import pytz
from datetime import datetime, timedelta
now_utc = pytz.utc.localize(datetime.utcnow())
past = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=120))
delta = (now_utc-past).se... | ```
>>> print now_utc - past
0:01:59.999976
```
So there is 119 seconds and 999976 microseconds. Because you did two separate `datetime.utcnow()` calls with a little (24 microseconds) interval. |
Pandas timeseries plot setting x-axis major and minor ticks and labels | 12,945,971 | 59 | 2012-10-18T01:51:08Z | 13,674,286 | 46 | 2012-12-02T21:53:14Z | [
"python",
"matplotlib",
"pandas"
] | I want to be able to set the major and minor xticks and their labels for a time series graph plotted from a Pandas time series object.
The Pandas 0.9 "what's new" page says:
> "you can either use to\_pydatetime or register a converter for the
> Timestamp type"
but I can't work out how to do that so that I can use th... | Both `pandas` and `matplotlib.dates` use `matplotlib.units` for locating the ticks.
But while `matplotlib.dates` has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the [code](https://github.com/pydata/pandas/blob/master/pandas/tseries/convert... |
Two's Complement Binary in Python? | 12,946,116 | 16 | 2012-10-18T02:14:59Z | 12,946,226 | 35 | 2012-10-18T02:31:11Z | [
"python",
"binary",
"bit-manipulation"
] | Integers in Python are stored in two's complement, correct?
Although:
```
>>> x = 5
>>> bin(x)
0b101
```
And:
```
>>> x = -5
>>> bin(x)
-0b101
```
That's pretty lame. How do I get python to give me the numbers in REAL binary bits, and without the 0b infront of it? So:
```
>>> x = 5
>>> bin(x)
0101
>>> y = -5
>>> ... | It works best if you provide a mask. That way you specify how far to sign extend.
```
>>> bin(-27 & 0b1111111111111111)
'0b1111111111100101'
```
Or perhaps more generally:
```
def bindigits(n, bits):
s = bin(n & int("1"*bits, 2))[2:]
return ("{0:0>%s}" % (bits)).format(s)
>>> print bindigits(-31337, 24)
111... |
Two's Complement Binary in Python? | 12,946,116 | 16 | 2012-10-18T02:14:59Z | 12,947,353 | 10 | 2012-10-18T04:53:39Z | [
"python",
"binary",
"bit-manipulation"
] | Integers in Python are stored in two's complement, correct?
Although:
```
>>> x = 5
>>> bin(x)
0b101
```
And:
```
>>> x = -5
>>> bin(x)
-0b101
```
That's pretty lame. How do I get python to give me the numbers in REAL binary bits, and without the 0b infront of it? So:
```
>>> x = 5
>>> bin(x)
0101
>>> y = -5
>>> ... | To properly interpret a binary sequence as two's complement, there needs to a length associated with the sequence. When you are working low-level types that correspond directly to CPU registers, there is an implicit length. Since Python integers can have an arbitrary length, there really isn't an internal two's complem... |
How do I do use non-integer string labels with SVM from scikit-learn? Python | 12,946,373 | 6 | 2012-10-18T02:53:31Z | 12,950,584 | 10 | 2012-10-18T08:46:52Z | [
"python",
"nlp",
"svm",
"scikit-learn",
"pos-tagging"
] | Scikit-learn has fairly user-friendly python modules for machine learning.
I am trying to train an SVM tagger for Natural Language Processing (NLP) where my labels and input data are words and annotation. E.g. Part-Of-Speech tagging, rather than using double/integer data as input tuples `[[1,2], [2,0]]`, my tuples wil... | Most machine learning algorithm process input samples that are vector of floats such that **a small (often euclidean) distance** between a pair of samples **means** that the 2 samples are **similar** in a way that is relevant for the problem at hand.
It is the responsibility of the machine learning practitioner to fin... |
matplotlib subplots with same 'settings' | 12,946,521 | 3 | 2012-10-18T03:13:36Z | 12,953,787 | 9 | 2012-10-18T11:41:03Z | [
"python",
"matplotlib"
] | I'm plotting the same data in two different formats: log scale and linear scale.
Basically I want to have exactly the same plot, but with different scales, one on the top of the other.
What I have right now is this:
```
# These are the plot 'settings'
plt.xlabel('Size')
plt.ylabel('Time(s)');
plt.title('Matrix multi... | The `plt.*` settings usually apply to matplotlib's *current* plot; with `plt.subplot`, you're starting a new plot, hence the settings no longer apply to it. You can share labels, ticks, etc., by going through the [`Axes`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes) objects associated with the plots ([... |
TypeError: __init__() takes at least 2 arguments (1 given) error | 12,947,599 | 4 | 2012-10-18T05:18:37Z | 12,947,652 | 7 | 2012-10-18T05:23:10Z | [
"python",
"python-3.x"
] | I am developing a simple text based Dungeon game using Python3. First the user is prompted to select the hero from screen.py file.
```
from game import *
class GameScreen:
'''Display the current state of a game in a text-based format.
This class is fully implemented and needs no
additional work from stud... | **The Problem**
In `GameScreen.initialize_game()`, you set `hero=Rogue()`, but the `Rogue` constructor takes `rogue` as an argument. (Said another way, the `__init__` of `Rogue` requires that `rogue` be passed in.) You likely have this same issue when you set `hero=Mage` and `hero=Barbarian`.
**The Solution**
Luckil... |
The definitive method to use NumPy and SciPy from IronPython | 12,948,061 | 6 | 2012-10-18T06:02:53Z | 16,007,320 | 9 | 2013-04-15T03:36:49Z | [
"python",
".net",
"numpy",
"ironpython",
"python.net"
] | There is a way to use NumPy/SciPy in IronPython, using [IronClad](http://code.google.com/p/ironclad/) to execute/communicate with the CPython binaries of the same. A newer project, [Python Tools for VS](http://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net) allows for a faster integration with .NE... | Scipy for .NET looks like a dream come true to me. MSVS roundhouse kicks every other python IDE in the face, and seemless interop with all other .NET languages would be awesome (looking at you in particular, F#... you could really be the functional gateway drug... but I can't leave my scientific python toolstack behind... |
matplotlib wont draw python3 | 12,948,446 | 22 | 2012-10-18T06:30:50Z | 15,920,545 | 15 | 2013-04-10T08:20:36Z | [
"python",
"python-3.x",
"matplotlib",
"install",
"backend"
] | I installed matplotlib successfully inside a virtualenv. Now I'm trying to get it to draw. I know how to change the backend, but I'm having a whole lot of trouble figuring out what to change it to.
Has anyone managed to get it totally working with python3? If yes, how?
I have tried a bunch of things. I have cycled th... | I ran into exact same issue, but after much efforts I managed to make TkAgg working (which was giving the import error for \_tkagg). Little late, but someone might find it useful.
FWIW I resolved the issue as follows (to use TkAgg):
* Installed **`tk-dev`** from package manager
* *Reinstalled* `python3-tk` from packa... |
python: What happens when class attribute, instance attribute, and method all have the same name? | 12,949,064 | 19 | 2012-10-18T07:14:13Z | 12,949,375 | 14 | 2012-10-18T07:31:32Z | [
"python",
"methods",
"instance-variables",
"class-attributes"
] | How does python differentiate a class attribute, instance attribute, and method when the names are the same?
```
class Exam(object):
test = "class var"
def __init__(self, n):
self.test = n
def test(self):
print "method : ",self.test
test_o = Exam("Fine")
print dir(test_o)
print Exam.t... | Class attributes are accessible through the class:
```
YourClass.clsattribute
```
or through the instance (if the instance has not overwritten the class attribute):
```
instance.clsattribute
```
Methods, as stated [by ecatmur in his answer](http://stackoverflow.com/a/12949167/510937), are descriptors and are set as... |
How can I serve temporary files from Python Pyramid | 12,949,077 | 7 | 2012-10-18T07:14:44Z | 12,950,646 | 8 | 2012-10-18T08:50:17Z | [
"python",
"pyramid"
] | Currently, I'm just serving files like this:
```
# view callable
def export(request):
response = Response(content_type='application/csv')
# use datetime in filename to avoid collisions
f = open('/temp/XML_Export_%s.xml' % datetime.now(), 'r')
# this is where I usually put stuff in the file
resp... | **Update:**
Please see Michael Merickel's answer for a better solution and explanation.
If you want to have the file deleted once `response` is returned, you can try the following:
```
import os
from datetime import datetime
from tempfile import NamedTemporaryFile
# view callable
def export(request):
response =... |
How can I serve temporary files from Python Pyramid | 12,949,077 | 7 | 2012-10-18T07:14:44Z | 12,958,754 | 8 | 2012-10-18T15:56:42Z | [
"python",
"pyramid"
] | Currently, I'm just serving files like this:
```
# view callable
def export(request):
response = Response(content_type='application/csv')
# use datetime in filename to avoid collisions
f = open('/temp/XML_Export_%s.xml' % datetime.now(), 'r')
# this is where I usually put stuff in the file
resp... | You do not want to set a file pointer as the `app_iter`. This will cause the WSGI server to read the file line by line (same as `for line in file`), which is typically not the most efficient way to control a file upload (imagine one character per line). Pyramid's supported way of serving files is via `pyramid.response.... |
Add a column with a groupby on a hierarchical dataframe | 12,950,024 | 9 | 2012-10-18T08:14:42Z | 12,989,920 | 7 | 2012-10-20T15:31:46Z | [
"python",
"group-by",
"pandas"
] | I have a dataframe structured like this:
```
First A B
Second bar baz foo bar baz foo
Third cat dog cat dog cat dog cat dog cat dog cat dog
0 3 8 7 7 4 7 5 3 2 2 6 2
1 ... | There definitely is a weakness in the API here but I'm not sure off the top of my head to make it easier to do what you're doing. Here's one simple way around this, at least for your example:
```
In [20]: df
Out[20]:
First A B
Second foo bar baz ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.