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 supports a limited form of multiple inheritance. In what way limited? | 10,674,428 | 20 | 2012-05-20T14:50:02Z | 10,675,121 | 12 | 2012-05-20T16:21:13Z | [
"python",
"inheritance",
"multiple-inheritance",
"concept"
] | In the python tutorial it's said that "[Python supports a limited form of multiple inheritance](http://docs.python.org/release/2.6/tutorial/classes.html#multiple-inheritance)".
What are the limitations? | I'm not sure to what limitations the author of the python tutorial was referring, but I would guess it has in part to do with the way that method / attribute lookup is implemented in python (the "method resolution order" or MRO). Python uses the [C3 superclass linearization](http://en.wikipedia.org/wiki/C3_linearizatio... |
Norm of a arrays of vectors in python | 10,674,464 | 4 | 2012-05-20T14:53:34Z | 10,674,608 | 7 | 2012-05-20T15:09:54Z | [
"python",
"arrays",
"numpy",
"norm"
] | I have this array
```
A = array([[-0.49740509, -0.48618909, -0.49145315],
[-0.48959259, -0.48618909, -0.49145315],
[-0.49740509, -0.47837659, -0.49145315],
...,
[ 0.03079315, -0.01194593, -0.06872366],
[ 0.03054901, -0.01170179, -0.06872366],
[ 0.03079315, -0.01170179, -0.06872366]])
```
which i... | Doing it manually might be fastest (although there's always some neat trick someone posts I didn't think of):
```
In [75]: from numpy import random, array
In [76]: from numpy.linalg import norm
In [77]:
In [77]: A = random.rand(1000,3)
In [78]: timeit normedA_0 = array([norm(v) for v in A])
100 loops, best of 3: ... |
Count verbs, nouns, and other parts of speech with python's NLTK | 10,674,832 | 11 | 2012-05-20T15:41:14Z | 10,674,885 | 15 | 2012-05-20T15:49:40Z | [
"python",
"nlp",
"tagging",
"nltk",
"part-of-speech"
] | I have multiple texts and I would like to create profiles of them based on their usage of various parts of speech, like nouns and verbs. Basially, I need to count how many times each part of speech is used.
I have tagged the text but am not sure how to go further:
```
tokens = nltk.word_tokenize(text.lower())
text = ... | The `pos_tag` method gives you back a list of (token, tag) pairs:
```
tagged = [('the', 'DT'), ('dog', 'NN'), ('sees', 'VB'), ('the', 'DT'), ('cat', 'NN')]
```
If you are using Python 2.7 or later, then you can do it simply with:
```
>>> from collections import Counter
>>> counts = Counter(tag for word,tag in tagged... |
How to import a module in Python with importlib.import_module | 10,675,054 | 16 | 2012-05-20T16:12:51Z | 10,675,081 | 27 | 2012-05-20T16:17:07Z | [
"python",
"import",
"module",
"python-importlib"
] | I'm trying to use `importlib.import_module` in python 2.7.2 and run into the strange error.
Consider the following dir structure:
```
a
|
+ - __init__.py
- b
|
+ - __init__.py
- c.py
```
`a/b/__init__.py` has the following code:
```
import importlib
mod = importl... | For relative imports you have to a) use relative name b) provide anchor explicitly:
```
importlib.import_module('.c', 'a.b')
```
Of course, you could also just do absolute import instead:
```
importlib.import_module('a.b.c')
``` |
Error converting miles to kilometers | 10,675,442 | 2 | 2012-05-20T17:07:21Z | 10,675,456 | 10 | 2012-05-20T17:09:19Z | [
"python"
] | I'm trying to learn python and am attempting to create a simple formula that converts miles to kilometers and returns some text with the conversion.
Here's what I have:
```
def mile(x):
z = x * 1.609344
print "%.2f" % z
x = float(raw_input("How many miles are you traveling? "))
z = mile(x)
print "That's ... | Your function needs to return the result.
```
def mile(x):
z = x * 1.609344
return z
``` |
Converting GAE model into JSON | 10,675,849 | 3 | 2012-05-20T18:06:19Z | 10,675,886 | 7 | 2012-05-20T18:11:26Z | [
"python",
"google-app-engine"
] | I'm using the [code found here](http://stackoverflow.com/a/2305601/458960) to convert a GAE model into JSON:
```
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
```
It works just fine, but if a property does not have a value, it puts a default string of "None", and this... | ```
def to_dict(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
```
You don't need to create a list first (the surrounding `[]`), you can just use a [generator expression](http://docs.python.org/reference/expressions.html#generator-expre... |
bash: syntax error near unexpected token `(' - Python | 10,676,050 | 10 | 2012-05-20T18:32:38Z | 10,676,069 | 25 | 2012-05-20T18:34:48Z | [
"python",
"syntax"
] | ```
# from lxml import etree;
import module2dbk;
print module2dbk.xsl_transform(etree.parse('test-ccap/col10614/index.cnxml'), []);
Error: bash: syntax error near unexpected token `('
``` | add `#!/usr/bin/env python` at the top of your script, or call your script using `python myscript.py` |
bash: syntax error near unexpected token `(' - Python | 10,676,050 | 10 | 2012-05-20T18:32:38Z | 10,676,072 | 8 | 2012-05-20T18:35:06Z | [
"python",
"syntax"
] | ```
# from lxml import etree;
import module2dbk;
print module2dbk.xsl_transform(etree.parse('test-ccap/col10614/index.cnxml'), []);
Error: bash: syntax error near unexpected token `('
``` | Are you typing this at the unix command prompt? You should be doing this inside the python environment, ie. type `python` at the prompt and work from there.
Also, no `;` needed at the end of the line in Python |
difference between perl's hash and python's dictionary | 10,676,441 | 8 | 2012-05-20T19:20:48Z | 10,676,514 | 16 | 2012-05-20T19:30:48Z | [
"python",
"perl"
] | I am new to perl, at most places where hash is used a reference to python's dictionaries is given. A difference which I have noticed is that the hashes don't preserve the order of elements. I would like to know if there are some more concrete and fundamental differences between the two. | The most fundamental difference is that perl hashes don't throw errors if you access elements that aren't there.
```
$ python -c 'd = {}; print d["a"]'
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'a'
$ perl -e '$d = {}; print $d->{a}'
$
```
Perl hashes auto create elements too... |
difference between perl's hash and python's dictionary | 10,676,441 | 8 | 2012-05-20T19:20:48Z | 10,678,553 | 8 | 2012-05-21T01:12:36Z | [
"python",
"perl"
] | I am new to perl, at most places where hash is used a reference to python's dictionaries is given. A difference which I have noticed is that the hashes don't preserve the order of elements. I would like to know if there are some more concrete and fundamental differences between the two. | Another major difference is that in Python you can have (user-defined) objects as your dictionary keys. Dictionaries will use the objects' `__hash__` and `__eq__` methods to manage this.
In Perl, you can't use objects as hash keys by default. Keys are stored as strings and objects will be interpolated to strings if yo... |
Why does using None fix Python's mutable default argument issue? | 10,676,729 | 17 | 2012-05-20T19:59:31Z | 10,676,761 | 13 | 2012-05-20T20:03:19Z | [
"python",
"function",
"arguments",
"mutable"
] | I'm at the point in learning Python where I'm dealing with [the Mutable Default Argument problem](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument).
```
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def good_append(new_item, a_li... | The problem only exists if the default *value* is mutable, which `None` is not. What gets stored along with the function object is the default value. When the function is called, the function's context is initialized with the default value.
```
a_list = []
```
just assigns a new object to the name `a_list` in the con... |
Why does using None fix Python's mutable default argument issue? | 10,676,729 | 17 | 2012-05-20T19:59:31Z | 10,677,032 | 11 | 2012-05-20T20:42:12Z | [
"python",
"function",
"arguments",
"mutable"
] | I'm at the point in learning Python where I'm dealing with [the Mutable Default Argument problem](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument).
```
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def good_append(new_item, a_li... | The default value of `a_list` (or any other default value, for that matter) is stored in the function's interiors once it has been initialized and thus can be modified in any way:
```
>>> def f(x=[]): return x
...
>>> f.func_defaults
([],)
>>> f.func_defaults[0] is f()
```
So the value in `func_defaults` is the same ... |
Why does using None fix Python's mutable default argument issue? | 10,676,729 | 17 | 2012-05-20T19:59:31Z | 10,677,167 | 18 | 2012-05-20T20:59:44Z | [
"python",
"function",
"arguments",
"mutable"
] | I'm at the point in learning Python where I'm dealing with [the Mutable Default Argument problem](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument).
```
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def good_append(new_item, a_li... | > It looks like a\_list would still be initialized only once
"initialization" is not something that happens to variables in Python, because variables in Python are just names. "initialization" only happens to objects, and it's done via the class' `__init__` method.
When you write `a = 0`, that is an assignment. That ... |
Error saying that name 'math' is not defined when trying to use asin() | 10,676,896 | 3 | 2012-05-20T20:22:38Z | 10,676,903 | 7 | 2012-05-20T20:24:23Z | [
"python"
] | I have made a Trignometric calculator (Kind of - it only uses the sine ratio as of now) but I can't get it to work right. I get an error that says math is not defined when it's supposed to get the length of the line. Here is my code:
```
trig = raw_input ('What are you looking for? A) I have the opposite, and I wa... | You need to `import math` before you can use it -- otherwise Python doesn't know what you're talking about.
Once you do that, you'll get another error: your inputs are strings, and you need to convert them to numbers (with `float()`) before you can pass them as arguments to math functions. As [nye17 pointed out](http:... |
Convert float to comma-separated string | 10,677,350 | 8 | 2012-05-20T21:26:15Z | 10,677,386 | 12 | 2012-05-20T21:30:36Z | [
"python"
] | How would I convert a float into its 'accounting form' --
```
100028282.23 --> 100,028,282.23
100028282 --> 100,028,282.00
```
Is there a python method that does this? | You can use the [`locale.format()`](http://docs.python.org/library/locale.html#locale.format) function to do this:
```
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.utf8')
'en_US.utf8'
>>> locale.format("%.2f", 100028282.23, grouping=True)
'100,028,282.23'
```
Note that you have to give the precision: ... |
Convert float to comma-separated string | 10,677,350 | 8 | 2012-05-20T21:26:15Z | 10,677,401 | 12 | 2012-05-20T21:32:22Z | [
"python"
] | How would I convert a float into its 'accounting form' --
```
100028282.23 --> 100,028,282.23
100028282 --> 100,028,282.00
```
Is there a python method that does this? | As an alternative to [beerbajay](http://stackoverflow.com/a/10677386/577088)'s excellent answer, simple string formatting works in 2.7+, without requiring an import:
```
>>> '{0:,.2f}'.format(24322.34)
'24,322.34'
``` |
SQLAlchemy ORM: modify the columns returned from a query | 10,677,514 | 8 | 2012-05-20T21:49:05Z | 10,686,462 | 15 | 2012-05-21T13:44:43Z | [
"python",
"orm",
"sqlalchemy"
] | If I've got an SQLAlchemy ORM query:
```
admin_users = Session.query(User).filter_by(is_admin=True)
```
Is it possible to modify the columns returned by that query?
For example, so that I could select only the `User.id` column, and use that in a sub query:
```
admin_email_addresses = Session.query(EmailAddress)\
... | I feel your pain on the `values()` thing. In 0.6.5 I added `with_entities()` which is just like `values()` except doesn't iterate:
```
q = q.with_entities(User.id)
``` |
Elementwise multiplication of arrays of different shapes in python | 10,677,542 | 8 | 2012-05-20T21:53:55Z | 10,677,778 | 7 | 2012-05-20T22:32:40Z | [
"python",
"arrays",
"numpy",
"multiplication"
] | Say I have two arrays `a` and `b`,
```
a.shape = (5,2,3)
b.shape = (2,3)
```
then `c = a * b` will give me an array `c` of shape `(5,2,3)` with `c[i,j,k] = a[i,j,k]*b[j,k]`.
Now the situation is,
```
a.shape = (5,2,3)
b.shape = (2,3,8)
```
and I want `c` to have a shape `(5,2,3,8)` with `c[i,j,k,l] = a[i,j... | I think the following should work:
```
import numpy as np
a = np.random.normal(size=(5,2,3))
b = np.random.normal(size=(2,3,8))
c = np.einsum('ijk,jkl->ijkl',a,b)
```
and:
```
In [5]: c.shape
Out[5]: (5, 2, 3, 8)
In [6]: a[0,0,1]*b[0,1,2]
Out[6]: -0.041308376453821738
In [7]: c[0,0,1,2]
Out[7]: -0.0413083764538217... |
Elementwise multiplication of arrays of different shapes in python | 10,677,542 | 8 | 2012-05-20T21:53:55Z | 10,677,805 | 10 | 2012-05-20T22:37:00Z | [
"python",
"arrays",
"numpy",
"multiplication"
] | Say I have two arrays `a` and `b`,
```
a.shape = (5,2,3)
b.shape = (2,3)
```
then `c = a * b` will give me an array `c` of shape `(5,2,3)` with `c[i,j,k] = a[i,j,k]*b[j,k]`.
Now the situation is,
```
a.shape = (5,2,3)
b.shape = (2,3,8)
```
and I want `c` to have a shape `(5,2,3,8)` with `c[i,j,k,l] = a[i,j... | This should work:
```
a[..., numpy.newaxis] * b[numpy.newaxis, ...]
```
Usage:
```
In : a = numpy.random.randn(5,2,3)
In : b = numpy.random.randn(2,3,8)
In : c = a[..., numpy.newaxis]*b[numpy.newaxis, ...]
In : c.shape
Out: (5, 2, 3, 8)
```
Ref: [Array Broadcasting in numpy](http://docs.scipy.org/doc/numpy-1.10.... |
Can the Django ORM store an unsigned 64-bit integer (aka ulong64 or uint64) in a reliably backend-agnostic manner? | 10,678,102 | 19 | 2012-05-20T23:34:54Z | 10,678,167 | 14 | 2012-05-20T23:47:19Z | [
"python",
"django",
"orm",
"django-models",
"unsigned-long-long-int"
] | All the docs I've seen imply that you *might* be able to do that, but there isn't anything official w/r/t ulong64/uint64 fields. There are a few off-the-shelf options that look quite promising in this arena:
* `BigIntegerField` ... almost, but signed;
* `PositiveIntegerField` ... suspiciously 32-bit-looking; and
* `De... | Although I did not test it, but you may wish to just subclass `BigIntegerField`. The original `BigIntegerField` looks like that ([source here](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1012)):
```
class BigIntegerField(IntegerField):
empty_strings_allowed = False
descrip... |
How can I selectively escape percent (%) in Python strings? | 10,678,229 | 165 | 2012-05-21T00:01:44Z | 10,678,240 | 296 | 2012-05-21T00:03:43Z | [
"python",
"escaping",
"python-2.7"
] | I have the following code
```
test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test
print(selectiveEscape)
```
I would like to get the output:
```
Print percent % in sentence and not have it break.
```
What actually happens:
```
selectiveEscape = "Use percent % in sentence ... | ```
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
``` |
How can I selectively escape percent (%) in Python strings? | 10,678,229 | 165 | 2012-05-21T00:01:44Z | 10,678,288 | 35 | 2012-05-21T00:12:34Z | [
"python",
"escaping",
"python-2.7"
] | I have the following code
```
test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test
print(selectiveEscape)
```
I would like to get the output:
```
Print percent % in sentence and not have it break.
```
What actually happens:
```
selectiveEscape = "Use percent % in sentence ... | Alternatively, as of Python 2.6, you can use new string formatting (described in [PEP 3101](http://www.python.org/dev/peps/pep-3101/)):
```
'Print percent % in sentence and not {0}'.format(test)
```
which is especially handy as your strings get more complicated. |
How can I selectively escape percent (%) in Python strings? | 10,678,229 | 165 | 2012-05-21T00:01:44Z | 10,681,279 | 17 | 2012-05-21T07:46:33Z | [
"python",
"escaping",
"python-2.7"
] | I have the following code
```
test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test
print(selectiveEscape)
```
I would like to get the output:
```
Print percent % in sentence and not have it break.
```
What actually happens:
```
selectiveEscape = "Use percent % in sentence ... | try using `%%` to print % sign . |
Flipping the boolean values in a list Python | 10,678,441 | 12 | 2012-05-21T00:42:44Z | 10,678,448 | 22 | 2012-05-21T00:43:52Z | [
"python"
] | I have a boolean list in Python
```
mylist = [True , True, False,...]
```
which I want to change to the logical opposite `[False, False, True , ...]`
Is there an inbuilt way to do this in Python (something like a call `not(mylist)` ) without a hand-written loop to reverse the elements? | It's easy with list comprehension:
```
mylist = [True , True, False]
[not i for i in mylist]
```
yields
```
[False, False, True]
``` |
QSettings setpath ini format still using registry on windows | 10,678,651 | 2 | 2012-05-21T01:34:54Z | 10,684,606 | 8 | 2012-05-21T11:43:24Z | [
"python",
"qt",
"pyqt",
"qsettings"
] | I'm trying to set the path to store some custom settings for my app using QSettings::setPath and defaulFormat but both seem to be ignored when I try and use the settings file.
```
>>> QSettings.setDefaultFormat(QSettings.IniFormat)
>>> QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, "C:\\")
>>> settings3 =... | The QSettings documentation misleadingly suggests that the code
```
QSettings settings("Moose Soft", "Facturo-Pro");
```
is equivalent to
```
QCoreApplication::setOrganizationName("Moose Soft");
QCoreApplication::setApplicationName("Facturo-Pro");
QSettings settings;
```
but this is not true. Try this
```
from PyS... |
Evaluate sympy expression from an array of values | 10,678,843 | 24 | 2012-05-21T02:17:47Z | 10,683,911 | 31 | 2012-05-21T10:55:21Z | [
"python",
"scipy",
"sympy"
] | I'm experimenting with sympy and I've hit upon an issue I can't work out.
Using scipy I can write an expression and evaluate it for an array of x values as follows:
```
import scipy
xvals = scipy.arange(-100,100,0.1)
f = lambda x: x**2
f(xvals)
```
Using sympy I can write the same expression as follows:
```
import ... | First of all, at the moment SymPy does not guarantee support for numpy arrays which is what you want in this case. Check this bug report <http://code.google.com/p/sympy/issues/detail?id=537>
Second, If you want to evaluate something numerically for *many* values SymPy is not the best choice (it is a symbolic library a... |
Numpy Array summing with weights | 10,679,523 | 5 | 2012-05-21T04:32:38Z | 10,679,848 | 8 | 2012-05-21T05:23:22Z | [
"python",
"arrays",
"numpy"
] | I have a two dimensional numpy array.
Each row is three elements long and is an integer 0-3. This represents a 6 bit integer, with each cell representing two bits, in order.
I'm trying to transform them into the full integer.
E.g.
```
for i in range(len(myarray)):
myarray[i] = myarray[i][0] * 16 + myarray[i][1] *... | The dot product inclination is correct, and that includes the sum you need. So, to get the sum of the products of the elements of a target array and a set of weights:
```
>>> a = np.array([[0,1,2],[2,2,3]])
>>> a
array([[0, 1, 2],
[2, 2, 3]])
>>> weights = np.array([16,4,2])
>>> np.dot(a,weights)
array([ 8, 46]... |
Is it possible to draw a plot vertically with python matplotlib? | 10,679,612 | 7 | 2012-05-21T04:48:23Z | 10,680,090 | 8 | 2012-05-21T05:53:57Z | [
"python",
"matplotlib"
] | I need to draw a plot looks like this:

Is it possible? How can I do this? | I don't know what is your data for ... but here is a 'vertical' plot of *hypothetical* oxygen levels in near sea surface...
Note that nothing special is required. Simply order your `x` and `y` values such that a line drawn from the first coordinate to the second and so on gives the vertical line you desire.
(The one ... |
How do I fix table x has no column named y? | 10,680,192 | 2 | 2012-05-21T06:04:09Z | 10,680,262 | 8 | 2012-05-21T06:12:21Z | [
"python",
"django",
"model"
] | I edited a model in django and as a result I get the error: "table reserve\_time has no column named reservation" for the below models:
```
from django.db import models
import datetime
class Club(models.Model):
establishment = models.CharField(max_length=200)
address = models.CharField(max_length=200)
def... | The problem here is that django will not do anything to fix your tables when you make field changes. All `syncdb` will do is create tables that do not already exist. If you decide to change your schema and add fields, you either need to create them manually in your database, or drop the table and let `syncdb` recreate ... |
Define a class with optional argument in Python | 10,681,038 | 7 | 2012-05-21T07:27:26Z | 11,426,729 | 8 | 2012-07-11T06:24:54Z | [
"python",
"class",
"arguments",
"default"
] | ```
class class1():
def setdata(self,value1, value2):
self.data = value1+value2
def display(self):
print(self.data)
```
For the above code, when I use it. It will require exactly two arguments.
```
>>>a = class1()
>>>a.setdata('123','456')
```
But what if I want to set a `default value` for `value2`, for... | Try this please:
```
def setdata(self, value1, value2 = '000'):
Your code here
``` |
How can I get value of the nested dictionary using ImmutableMultiDict on Flask? | 10,682,068 | 11 | 2012-05-21T08:48:08Z | 10,683,124 | 16 | 2012-05-21T09:58:22Z | [
"python",
"flask",
"werkzeug"
] | ```
address_dict = {'address': {'US': 'San Francisco', 'US': 'New York', 'UK': 'London'}}
```
When above parameters was sent via requests, how can I get values in address key using request.form on Flask?
```
import requests
url = 'http://example.com'
params = {"address": {"US": "San Francisco", "UK": "London", "CH":... | for example like this:
```
from werkzeug.datastructures import ImmutableMultiDict
imd = ImmutableMultiDict([('address', u'US'), ('address', 'US'), ('address', 'UK')])
print imd.getlist('address')
```
prints:
```
[u'US', 'US', 'UK']
```
---
edit:
Your POST-request is sent [`application/x-www-form-urlencoded`](http... |
comment out nested triple quotes | 10,682,565 | 4 | 2012-05-21T09:21:50Z | 10,682,599 | 10 | 2012-05-21T09:24:12Z | [
"python",
"comments"
] | In python to comment-out multiple lines we use triple quotes
```
def x():
"""This code will
add 1 and 1 """
a=1+1
```
but what if I have to comment out a block of code which already contains lot of other comment out blocks (triple quote comments). For example if I want to comment out this function fully.... | > In python to comment-out multiple lines we use triple commas
Thatâs just *one way* of doing it, and youâre technically using a string literal, not a comment. And, although it has become fairly established, this way of writing comments has the drawback you observed: you cannot comment out nested blocks.1
Python ... |
Piping popen stderr and stdout | 10,683,184 | 7 | 2012-05-21T10:02:22Z | 10,683,323 | 36 | 2012-05-21T10:12:01Z | [
"python"
] | I want to call scripts from a directory (they are executable shell scripts) via python.
so far so good:
```
for script in sorted(os.listdir(initdir), reverse=reverse):
if script.endswith('.*~') or script == 'README':
continue
if os.access(script, os.X_OK):
try:
... | Confer <http://docs.python.org/library/subprocess.html>.
> communicate() returns a tuple (stdoutdata, stderrdata).
After the subprocess has finished, you can get the return code from the Popen instance:
> Popen.returncode: The child return code, set by poll() and wait() (and indirectly by communicate()).
Likewise, ... |
(Python C API) PyRun_StringFlags missing builtin functions? | 10,683,713 | 7 | 2012-05-21T10:38:58Z | 10,684,099 | 7 | 2012-05-21T11:10:45Z | [
"python",
"python-c-api",
"python-embedding"
] | I am trying to embed some python in my pet project. I have reduced my problem to the following code:
```
#include <Python.h>
#include "iostream"
int main(int argc, char *argv[])
{
Py_Initialize();
PyObject *globals = Py_BuildValue("{}");
PyObject *locals = Py_BuildValue("{}");
PyObject *string_resul... | One way:
```
g = PyDict_New();
if (!g)
return NULL;
PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());
```
And then pass `g` as `globals`. |
Python checking if a fork() process is finished | 10,684,180 | 7 | 2012-05-21T11:16:45Z | 10,684,233 | 10 | 2012-05-21T11:20:09Z | [
"python",
"fork"
] | Just wondering if some one could help me out. The problem I'm having is that I os.fork() to get several bits of information and send them to a file, but checking to see if the fork process is not working.
```
import sys
import time
import os
import re
ADDRESS = argv[1]
sendBytes = argv[2]
proID2 = os.fork()
if pr... | To wait for the child process to terminate, use one of the `os.waitXXX()` functions, such as [`os.waitpid()`](http://docs.python.org/library/os.html#os.waitpid). This method is reliable; as a bonus, it will give you the status information. |
Reduce resolution of array through summation | 10,685,654 | 4 | 2012-05-21T12:55:25Z | 10,685,869 | 15 | 2012-05-21T13:08:50Z | [
"python",
"numpy"
] | If I have an array like this:
```
a = np.array([[ 1, 2, 3, 4],
[ 5 ,6, 7, 8],
[ 9,10,11,12],
[13,14,15,16]])
```
I want to 'change the resolution', and end up with a smaller array, (say 2 rows by 2 cols, or 2 rows by 4 cols, etc.). I want this resolution change to happen thro... | With your example:
```
a.reshape(2,2,2,2).sum(axis=1).sum(axis=2)
```
returns:
```
array([[14, 22],
[46, 54]])
```
Now let's create a general functionâ¦
```
def shrink(data, rows, cols):
return data.reshape(rows, data.shape[0]/rows, cols, data.shape[1]/cols).sum(axis=1).sum(axis=2)
```
works for your ... |
Why does the login method of Flask use 'GET'? | 10,686,444 | 6 | 2012-05-21T13:43:46Z | 10,686,550 | 8 | 2012-05-21T13:50:12Z | [
"python",
"login",
"flask"
] | I'm trying to learn more about Flask for a project, and I'm wondering if someone can explain to me why the sample code lists the methods 'GET' and 'POST', when it only ever tries to process a login if the request was 'POST'?
```
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request... | GET and POST methods are both handled by your function.
* When GET is used, the login form (`login.html`) is returned for the user to log in. This is the last line of the function.
* When POST is used, the form is validated using provided login/password. After that the user is either redirected to an other page (url f... |
Reading data from text file with missing values | 10,686,657 | 4 | 2012-05-21T13:57:16Z | 10,686,777 | 7 | 2012-05-21T14:04:41Z | [
"python",
"numpy",
"python-2.7"
] | I want to read data from a file that has many missing values, as in this example:
```
1,2,3,4,5
6,,,7,8
,,9,10,11
```
I am using the numpy.loadtxt function:
```
data = numpy.loadtxt('test.data', delimiter=',')
```
The problem is that the missing values break loadtxt (I get a *"ValueError: could not convert string t... | I'd probably use [genfromtxt](http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html#importing-data-with-genfromtxt):
```
>>> from numpy import genfromtxt
>>> genfromtxt("missing1.dat", delimiter=",")
array([[ 1., 2., 3., 4., 5.],
[ 6., nan, nan, 7., 8.],
[ nan, nan, 9., 10., ... |
Python dictionary with objects into dictionary with strings | 10,687,229 | 3 | 2012-05-21T14:30:47Z | 10,687,246 | 10 | 2012-05-21T14:31:48Z | [
"python",
"dictionary"
] | I've got dictionary with objects values and string keys:
```
dict{
'key1': object_1
'key2': object_2
}
```
And I'd like to convert it into:
```
dict{
'key1': str(object_1)
'key2': str(object_2)
}
```
Where str(object\_1) is a string representation of object\_1. What is the simplest and the most pythonic way of perf... | ```
dict((k, str(v)) for k, v in d.iteritems())
```
or in Python2.7+:
```
{k: str(v) for k, v in d.items()}
```
For more complicated dicts (with tuples of objects as values):
```
dict((k, tuple(str(x) for x in v)) for k, v in d.iteritems())
{k: tuple(str(x) for x in v) for k, v in d.items()}
``` |
Generate a list of datetimes between an interval | 10,688,006 | 25 | 2012-05-21T15:18:04Z | 10,688,060 | 44 | 2012-05-21T15:22:49Z | [
"python",
"list",
"datetime",
"date",
"period"
] | Given two datetimes (`start_date` and `end_date`), I'd like to generate a list of other datetimes between these two dates, the new datetimes being separated by a variable interval. e.g. every 4 days between 2011-10-10 and 2011-12-12 or every 8 hours between now and tomorrow 19p.m.
Maybe something roughly equivalent to... | Use [`datetime.timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects):
```
from datetime import date, datetime, timedelta
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
>>> for result in perdelta(date(2011, 10, 10), date(2011, 12,... |
Generate a list of datetimes between an interval | 10,688,006 | 25 | 2012-05-21T15:18:04Z | 10,688,309 | 9 | 2012-05-21T15:40:18Z | [
"python",
"list",
"datetime",
"date",
"period"
] | Given two datetimes (`start_date` and `end_date`), I'd like to generate a list of other datetimes between these two dates, the new datetimes being separated by a variable interval. e.g. every 4 days between 2011-10-10 and 2011-12-12 or every 8 hours between now and tomorrow 19p.m.
Maybe something roughly equivalent to... | Try this:
```
from datetime import datetime
from dateutil.relativedelta import relativedelta
def date_range(start_date, end_date, increment, period):
result = []
nxt = start_date
delta = relativedelta(**{period:increment})
while nxt <= end_date:
result.append(nxt)
nxt += delta
retu... |
Python remove negative number entries/rows from csv | 10,688,389 | 2 | 2012-05-21T15:45:41Z | 10,688,497 | 8 | 2012-05-21T15:53:42Z | [
"python",
"linux",
"csv",
"awk",
"matplotlib"
] | I have a ever growing csv file that looks like:
```
143100, 2012-05-21 09:52:54.165852
125820, 2012-05-21 09:53:54.666780
109260, 2012-05-21 09:54:55.144712
116340, 2012-05-21 09:55:55.642197
125640, 2012-05-21 09:56:56.094999
122820, 2012-05-21 09:57:56.546567
124770, 2012-05-21 09:58:57.046050
103830, 2012-05-21 09:... | The Python idiom would be to use a generator expression to filter the lines:
```
sys.stdout.writelines(line for line in sys.stdin if not line.startswith('-'))
```
Or in a processing context:
```
filtered = (line for line in sys.stdin if not line.startswith('-'))
for line in filtered:
# ...
``` |
Trying to install Scrapy - error: Could not find 'openssl.exe' | 10,688,843 | 5 | 2012-05-21T16:19:32Z | 10,778,839 | 9 | 2012-05-28T02:45:27Z | [
"python",
"pip",
"scrapy",
"pyopenssl"
] | Any thoughts on how to fix this problem? I am using pip to install Scrapy on a Win XP Pro SP 3 machine. I have Python 2.7 installed on the machine. There seems to be a problem with pyOpenSSL. I am getting a "Could not find 'openssl.exe'" error.
Here is my log file. I had to hack it up a little because of the URLs in i... | you can just goto <http://pypi.python.org/pypi/pyOpenSSL/0.13> and download the windows installer, after that, continue your scrapy install. |
What is the simplest way to add a hyperlink to a canvas element in ReportLab? | 10,688,923 | 3 | 2012-05-21T16:25:19Z | 10,689,067 | 7 | 2012-05-21T16:35:58Z | [
"python",
"canvas",
"hyperlink",
"reportlab"
] | I am using ReportLab to make a pdf using Python. I want to add a shape to the canvas, and have that shape act as a hyperlink. What is the simplest way to make the rectangle in the following example link to google.com?
```
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
c = canvas.Canvas("hell... | Call `linkURL` on the Canvas:
```
c.linkURL('http://google.com', (inch, inch, 1*inch, 1*inch), relative=1)
```
The rectangle is the clickable area, so you'd have to match that to the drawn rectangle.
See more examples in this blog post: <http://www.hoboes.com/Mimsy/hacks/adding-links-to-pdf/> |
Output all variables into Mako template | 10,689,162 | 3 | 2012-05-21T16:42:24Z | 12,007,275 | 7 | 2012-08-17T13:58:42Z | [
"python",
"templates",
"mako"
] | I don't have an easy access to the code, I'm working only with a Mako template, and I would like to know all the values that were made available to the template, which I can use.
Is there a way to add something in the template, so that the output result would contain all the variables (recursively)? | You're looking for [the context object](http://docs.makotemplates.org/en/latest/runtime.html#mako.runtime.Context). After a minute or two of play:
```
${context.keys()} # list of direct variable names
${context.__dict__} # probably more along what you're looking for.
```
The entire section on the [Mako Runtime en... |
Determining if a GIF is transparent in Python | 10,689,512 | 11 | 2012-05-21T17:09:52Z | 10,689,590 | 14 | 2012-05-21T17:16:21Z | [
"python",
"image",
"python-imaging-library",
"gif"
] | How would I go about checking if a GIF is transparent (even partially)?
I accomplished this with PNGs by opening the image up with PIL and checking the image's mode. But GIFs have the same mode regardless.
As for false positives I don't mind if a completely opaque GIF gets flagged as transparent (assuming this is a r... | ```
img = Image.open(filename)
if img.mode == "RGBA" or "transparency" in img.info:
# image uses transparency
```
See [here](http://www.pythonware.com/library/pil/handbook/format-gif.htm) for how transparency works with GIF (and 8-bit, palettized, PNGs).
Note that your false positive case *is* possible: a GIF cou... |
How I can read a bit in Python? | 10,689,748 | 8 | 2012-05-21T17:28:08Z | 10,689,798 | 19 | 2012-05-21T17:31:11Z | [
"python",
"io",
"binary"
] | I know how to read bytes (x.read(number\_of\_bytes)), but how can I read bits in Python?
I have to read only 5 bits (not 8 bits[1 byte]) from a binary file
Any Idea or approach? | Python can only read a byte at a time. You'd need to read in a full byte, then just extract the value you want from that byte, e.g.
```
b = x.read(1)
firstfivebits = b >> 3
```
Or if you wanted the 5 least significant bits, rather than the 5 most significant bits:
```
b = x.read(1)
lastfivebits = b & 0b11111
```
So... |
Check if values in a set are in a numpy array in python | 10,690,233 | 4 | 2012-05-21T18:01:11Z | 10,690,790 | 10 | 2012-05-21T18:43:39Z | [
"python",
"numpy"
] | I want to check if a NumPyArray has values in it that are in a set, and if so set that area in an array = 1. If not set a keepRaster = 2.
```
numpyArray = #some imported array
repeatSet= ([3, 5, 6, 8])
confusedRaster = numpyArray[numpy.where(numpyArray in repeatSet)]= 1
```
Yields:
```
<type 'exceptions.TypeError'>... | In versions 1.4 and higher, numpy provides the [`in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html) function.
```
>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> np.in1d(test, states)
array([ True, False, True, False, True], dtype=bool)
```
You can use that as a mask for assign... |
Django-admin.py runserver not working | 10,690,284 | 4 | 2012-05-21T18:06:09Z | 10,690,383 | 7 | 2012-05-21T18:13:08Z | [
"python",
"django",
"django-admin"
] | I am new to python and django and I recently faced some problems.
Django-admin.py runserver does not work (ubuntu 12.04).
Terminal error code:
```
linas@ubuntu:~$ django-admin.py runserver
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py", line 5, in <module>
management.execute_from_c... | Use `manage.py` from your project directory
```
cd project
./manage.py runserver
``` |
How to programmatically determine if ndb property is multivalue | 10,690,418 | 3 | 2012-05-21T18:15:02Z | 10,704,614 | 8 | 2012-05-22T14:58:09Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I am translating an app from Datastore to ndb and have encountered a problem in the xml import routine. The problem is that I am not able to programmatically determine whether a property of a ndb.model class is a multivalue property or not.
I suspect that this is due to lack of basic Python skills since the code I hav... | Actually, the underscore-prefixed options *are* the official API. It's a bug that they aren't documented, I will fix that. I explained a little more here: <http://code.google.com/p/appengine-ndb-experiment/issues/detail?id=187>
In particular, to get the properties of a model, you should use House.\_properties, not the... |
Django 1.4 - bulk_create with a list | 10,691,359 | 5 | 2012-05-21T19:27:54Z | 10,691,433 | 16 | 2012-05-21T19:33:19Z | [
"python",
"django"
] | I have a list, which I would like to bulk\_create entries for in the database.
How can I do this without looping through the list, which I presume, would take away the point of bulk\_create.
For example:
Instead of...
```
for x in list:
bulk_create...
```
How could I...
```
bulk_create for the entire list at ... | `bulk_create` takes a list of objects as a single arg, in a single call. What you are doing in your example would be the same as looping and doing `create()`
Referencing: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create>
```
aList = [
Entry(headline="Django ... |
Python map() dictionary values | 10,692,482 | 5 | 2012-05-21T20:54:36Z | 10,692,596 | 12 | 2012-05-21T21:03:43Z | [
"python",
"dictionary",
"map",
"lambda"
] | I'm trying to use map() on the dict\_values object returned by the values() function on a dictionary. However, I can't seem to be able to map() over a dict\_values:
```
map(print, h.values())
Out[31]: <builtins.map at 0x1ce1290>
```
I'm sure there's an easy way to do this. What I'm actually trying to do is create a s... | In Python 3, `map` returns an iterator, not a list. You still have to iterate over it, either by calling `list` on it explicitly, or by putting it in a `for` loop. But you shouldn't use `map` this way anyway. `map` is really for collecting return values into an iterable or sequence. Since neither `print` nor `set.updat... |
How to query dbpedia resource ontology 'wikiPageExternalLink' | 10,693,216 | 6 | 2012-05-21T21:56:45Z | 10,694,219 | 7 | 2012-05-22T00:10:25Z | [
"python",
"sparql",
"dbpedia"
] | Using sparql\sparqlwrapper in python, how will I be able to query for the values of a certain dbpedia resource? For example, how will I be able to get the dbpedia-owl:wikiPageExternalLink values of <http://dbpedia.org/page/Asturias>?
Here's a simple example on how will I be able to query for the rdfs:label of Asturias.... | Not sure where you're stuckâthis is really easy:
```
SELECT ?label
WHERE { <http://dbpedia.org/resource/Asturias>
dbpedia-owl:wikiPageExternalLink ?label }
```
Usually you need to declare the namespace prefixes like `rdfs:` or `dbpedia-owl:` if you want to use them in the query, but on the DBpedia endpo... |
generating a file with django to download with javascript/jQuery | 10,693,314 | 5 | 2012-05-21T22:07:22Z | 10,694,862 | 7 | 2012-05-22T01:56:24Z | [
"jquery",
"python",
"django",
"download"
] | Using Django, I want to make some data available for download.
My jQuery call looks like this so far:
```
$.getJSON("/get_data",
{ users: users, study: "{{study.id}}" } ,
function(json){
alert('some data!');
}
);
```
This calls one of my Django views, which in tur... | The classic solution for this is to use an hidden `iframe`.
In your `urls.py`
```
url(r'^test/getFile', 'getFile')
```
In your `views.py`
```
def getFile(request):
fileContent = "Your name is %s" % request.GET['name']
res = HttpResponse(fileContent)
res['Content-Disposition'] = 'attachment; filename=you... |
Can django-tastypie display a different set of fields in the list and detail views of a single resource? | 10,693,379 | 9 | 2012-05-21T22:14:23Z | 10,702,494 | 13 | 2012-05-22T12:57:12Z | [
"python",
"django",
"tastypie"
] | I would like for a particular `django-tastypie` model resource to have only a subset of fields when listing objects, and all fields when showing a detail. Is this possible? | You would have to specify all fields in the actual ModelResource then override the `get_list` method to filter out only the fields you want to show. See the internal implementation of `get_list` on `Resource` to see how to override it.
However, note this will only apply on GET requests, you should still be able to POS... |
Can django-tastypie display a different set of fields in the list and detail views of a single resource? | 10,693,379 | 9 | 2012-05-21T22:14:23Z | 16,034,908 | 18 | 2013-04-16T10:38:14Z | [
"python",
"django",
"tastypie"
] | I would like for a particular `django-tastypie` model resource to have only a subset of fields when listing objects, and all fields when showing a detail. Is this possible? | You can also now use the [`use_in`](http://django-tastypie.readthedocs.org/en/latest/fields.html#use-in) attribute on a field to specify the relevant resource to show the field in. This can either be `list` or `detail`, or a callback. |
Implementing the AirDrop protocol | 10,693,411 | 11 | 2012-05-21T22:17:58Z | 11,794,768 | 34 | 2012-08-03T11:23:58Z | [
"python",
"c",
"wifi",
"bonjour",
"adhoc"
] | I am interested in implementing AirDrop as a client on a device such as an iPad or Windows computer. Can anyone point me in the right direction for implementing the AirDrop protocol in either Python or C. Any help on this would be greatly appreciated. Thanks in advance. | For the benefit of you or anyone who will try to reverse-engineer and implement Airdrop, here is what I found and what you will have to do to get started:
There are two steps involved and they can be done in independently or in parallel.
1. Reverse-engineer the way the physical WLAN ad-hoc network is created and name... |
How to pass a boolean from javascript to python? | 10,693,630 | 7 | 2012-05-21T22:46:05Z | 10,693,668 | 19 | 2012-05-21T22:50:54Z | [
"javascript",
"python"
] | The following seems to pass a string instead of a boolean value. How would I pass a boolean?
```
$.post('/ajax/warning_message/', {'active': false}, function() {
return
});
```
```
def warning_message(request):
active = request.POST.get('active')
print active
return HttpResponse()
``` | In your Python code do this:
```
active = True if request.POST.get('active') == 'true' else False
```
Or even simpler:
```
active = request.POST.get('active') == 'true'
```
Be aware that the `get()` function will always return a string, so you need to convert it according to the actual type that you need. |
Calculate distance between cities & find surrounding cities based on GeoPT, in Python on Google App Engine | 10,693,699 | 5 | 2012-05-21T22:55:21Z | 10,710,021 | 7 | 2012-05-22T20:53:30Z | [
"python",
"google-app-engine",
"geolocation",
"distance"
] | I have a cities model defined which saves the `geoname_id` and `location` (as GeoPt) of a city. There are two things that I want to achieve.
1. I want to get all cities within `500km` radius from a given city.
2. I want to calculate distance in `km` between two given cities.
What would be the best way to achieve this... | This works perfect but is a lil slow :
Function to Calculate Distance. The Arguments passed to this function are tuples of latitude and longitude of a location or a Geopt():
```
def HaversineDistance(location1, location2):
"""Method to calculate Distance between two sets of Lat/Lon."""
lat1, lon1 = location1
la... |
Creating a secondary site-packages directory (and loading packages from .pth files therein) | 10,693,706 | 14 | 2012-05-21T22:56:32Z | 10,693,758 | 14 | 2012-05-21T23:06:08Z | [
"python",
"pythonpath"
] | I would like to install some packages into a third-party `site-packages` directory (beyond the standard system locations). Is there any way to set this up such that .pth files therein are respected?
---
Background: I'm using OS X, virtualenv, and homebrew. There are a few packages (notably wxPython in my case) that d... | Take a look at the [site](http://docs.python.org/library/site.html) module. It provides the function [`addsitedir`](http://docs.python.org/library/site.html#site.addsitedir) which should do what you want.
The easiest way to use this would be to create a file named `sitecustomize.py` or `usercustomize.py` and place it ... |
How to test template context variables with Flask | 10,693,808 | 10 | 2012-05-21T23:12:31Z | 10,694,980 | 19 | 2012-05-22T02:18:22Z | [
"python",
"flask"
] | Django's test client returns a test Response object which includes the template context variables that were used to render the template. <https://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Response.context>
How can I get access to template context variables while testing in Flask?
Example view:
... | Thanks to [@andrewwatts](https://twitter.com/#!/andrewwatts) I used (a version of) [Flask-Testing](http://pypi.python.org/pypi/Flask-Testing)
```
from flask.ext.testing import TestCase
class MyViewTestCase(TestCase):
def create_app(self):
# This method is required by flask.ext.testing.TestCase. It is cal... |
How Does Calling Work In Python? | 10,694,608 | 5 | 2012-05-22T01:11:37Z | 10,694,746 | 8 | 2012-05-22T01:35:17Z | [
"python",
"programming-languages"
] | For a project I'm working on, I'm implementing a linked-list data-structure, which is based on the idea of a pair, which I define as:
```
class Pair:
def __init__(self, name, prefs, score):
self.name = name
self.score = score
self.preferences = prefs
self.next_pair = 0
self.... | Python does not copy anything when passing variables to a function. It is neither call-by-value nor call-by-reference, but of those two it is more similar to call-by-reference. You could think of it as "call-by-value, but the value is a reference".
If you pass a **mutable** object to a function, then modifying that ob... |
How Does Calling Work In Python? | 10,694,608 | 5 | 2012-05-22T01:11:37Z | 10,694,799 | 8 | 2012-05-22T01:45:18Z | [
"python",
"programming-languages"
] | For a project I'm working on, I'm implementing a linked-list data-structure, which is based on the idea of a pair, which I define as:
```
class Pair:
def __init__(self, name, prefs, score):
self.name = name
self.score = score
self.preferences = prefs
self.next_pair = 0
self.... | In Python, everything is an object. Simple assignment *stores a reference* to the assigned object in the assigned-to name. As a result, it is more straightforward to think of Python variables as names that are assigned to objects, rather than objects that are stored in named locations.
For example:
```
baz = 2
```
.... |
How to implement user_loader callback in Flask-Login | 10,695,093 | 20 | 2012-05-22T02:40:23Z | 10,696,264 | 12 | 2012-05-22T05:38:03Z | [
"python",
"authentication",
"login",
"flask",
"python-2.x"
] | I'm attempting to use Flask and the [Flask-Login](http://packages.python.org/Flask-Login) extension to implement user authentication in a Flask app. The goal is to pull user account information from a database and then log in a user, but I'm getting stuck, and I've narrowed it down to a particular part of Flask-Login b... | You will need to load the user object from the DB upon every request. The strongest reason for that requirement is that Flask-Login will check the authentication token every time to ensure its continuing validity. The calculation of this token may require parameters stored on the user object.
For example, suppose a us... |
Sort a list of tuples by 2nd item (integer value) | 10,695,139 | 141 | 2012-05-22T02:48:02Z | 10,695,158 | 90 | 2012-05-22T02:51:24Z | [
"python",
"list",
"tuples"
] | I have a list of tuples that looks something like this:
```
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? | ```
>>> from operator import itemgetter
>>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
>>> sorted(data,key=itemgetter(1))
[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]
```
IMO using `itemgetter` is more readable in this case than the solution by @cheeken. It is
also faster since almost all... |
Sort a list of tuples by 2nd item (integer value) | 10,695,139 | 141 | 2012-05-22T02:48:02Z | 10,695,161 | 197 | 2012-05-22T02:51:36Z | [
"python",
"list",
"tuples"
] | I have a list of tuples that looks something like this:
```
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? | Try using the `key` keyword with `sorted()`.
```
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
```
`key` should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access `[1]`.
F... |
Sort a list of tuples by 2nd item (integer value) | 10,695,139 | 141 | 2012-05-22T02:48:02Z | 10,695,175 | 9 | 2012-05-22T02:54:10Z | [
"python",
"list",
"tuples"
] | I have a list of tuples that looks something like this:
```
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? | From python wiki:
```
>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
``` |
Sort a list of tuples by 2nd item (integer value) | 10,695,139 | 141 | 2012-05-22T02:48:02Z | 20,108,780 | 21 | 2013-11-20T22:49:59Z | [
"python",
"list",
"tuples"
] | I have a list of tuples that looks something like this:
```
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? | As a python neophyte, I just wanted to mention that if the data did actually look like this:
```
data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
then `sorted()` would automatically sort by the second element in the tuple, as the first elements are all identical. |
Sort a list of tuples by 2nd item (integer value) | 10,695,139 | 141 | 2012-05-22T02:48:02Z | 29,332,637 | 15 | 2015-03-29T17:50:13Z | [
"python",
"list",
"tuples"
] | I have a list of tuples that looks something like this:
```
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
```
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? | Adding to Cheeken's answer,
This is how you sort a list of tuples by the 2nd item in **descending order**.
```
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
``` |
What is the result of a yield expression in Python? | 10,695,456 | 28 | 2012-05-22T03:44:50Z | 10,695,490 | 37 | 2012-05-22T03:49:42Z | [
"python",
"generator",
"yield"
] | I know that yield turns a function into a generator, but what is the return value of the yield expression itself? For example:
```
def whizbang():
for i in range(10):
x = yield i
```
What is the value of variable `x` as this function executes?
I've read the Python documentation: <http://docs.python.org... | You can also `send` values to generators. If no value is sent then `x` is `None`, otherwise `x` takes on the sent value. Here is some info: <http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features>
```
>>> def whizbang():
for i in range(10):
x = yield i
print 'got sent:'... |
django admin custom commands - passing a list of strings into args | 10,697,133 | 3 | 2012-05-22T06:51:28Z | 10,697,418 | 7 | 2012-05-22T07:14:31Z | [
"python",
"django"
] | I have a list of strings which I would like to pass into args in my django custom command.
```
list = ['abc', 'def', 'ghi', etc...]
```
How can I do this from within a python function:
```
management.call_command('commandname', args, options)
```
I've tired passing on my list of args both:
[1] directly:
```
m... | The call\_command method is using [Arbitrary Arguments List](http://docs.python.org/dev/tutorial/controlflow.html#arbitrary-argument-lists) for command arguments.
So, you need to use:
```
list = ['abc', 'def', 'ghi']
management.call_command('commandname', *list)
```
Which is the same than:
```
management.call_comma... |
Python regular expression split() string | 10,697,757 | 4 | 2012-05-22T07:38:33Z | 10,697,801 | 10 | 2012-05-22T07:41:32Z | [
"python",
"regex",
"string",
"split"
] | I'm quite new to regular expression in python. I have the following string and want to split them into five categories. I just use the split() but it will just split according to white spaces.
```
s = "1 0 A10B 1/00 Description: This is description with spaces"
sp = s.split()
>>> sp
["1", "0", "A10B", "1/00", "Descrip... | You may simply specify a number of splits:
```
s.split(' ', 4)
``` |
linear programming in python? | 10,697,995 | 12 | 2012-05-22T07:56:30Z | 10,699,501 | 17 | 2012-05-22T09:42:35Z | [
"python",
"linear",
"linear-programming"
] | I need to make a linear programming model. Here are the inequalities I'm using (for example):
```
6x + 4y <= 24
x + 2y <= 6
-x + y <= 1
y <= 2
```
I need to find the area described by these inequalities, and shade it in a graph, as well as keep track of the vertices of the bounding lines of this area, and draw the bo... | I'd recommend the package [cvxopt](http://abel.ee.ucla.edu/cvxopt/index.html) for solving convex optimization problems in Python. A short example with Python code for a linear program is in cvxopt's documentation [here](http://abel.ee.ucla.edu/cvxopt/examples/tutorial/lp.html). |
linear programming in python? | 10,697,995 | 12 | 2012-05-22T07:56:30Z | 10,705,799 | 19 | 2012-05-22T16:06:12Z | [
"python",
"linear",
"linear-programming"
] | I need to make a linear programming model. Here are the inequalities I'm using (for example):
```
6x + 4y <= 24
x + 2y <= 6
-x + y <= 1
y <= 2
```
I need to find the area described by these inequalities, and shade it in a graph, as well as keep track of the vertices of the bounding lines of this area, and draw the bo... | **UPDATE:** The answer has become somewhat outdated in the past 4 years,
here is an update. You have many options:
* If you do not *have to* do it Python then it is a lot more easier to
do this in a **modeling langage**, see [Any good tools to solve
integer programs on linux?](http://stackoverflow.com/a/10668020/3... |
Argparse: Check if any arguments have been passed | 10,698,468 | 17 | 2012-05-22T08:33:35Z | 10,699,341 | 11 | 2012-05-22T09:30:56Z | [
"python",
"command-line-arguments",
"argparse"
] | My script should start a demo mode, when the no parameters are given. I tried this:
```
args = parser.parse_args()
if len(args) == 0:
run_demo()
else:
# evaluate args
```
Which gives a `*** TypeError: object of type 'Namespace' has no len()` as `args` is no list.
How would I achieve what I want? | argparse lets you set (inside a Namespace object) all the variables mentioned in the arguments you added to the parser, based on your specification and the command line being parsed. If you set a default, then those variables will have that default value if they weren't seen on the command line, they won't be absent fr... |
Argparse: Check if any arguments have been passed | 10,698,468 | 17 | 2012-05-22T08:33:35Z | 10,699,527 | 30 | 2012-05-22T09:44:37Z | [
"python",
"command-line-arguments",
"argparse"
] | My script should start a demo mode, when the no parameters are given. I tried this:
```
args = parser.parse_args()
if len(args) == 0:
run_demo()
else:
# evaluate args
```
Which gives a `*** TypeError: object of type 'Namespace' has no len()` as `args` is no list.
How would I achieve what I want? | If your goal is to detect when **no argument** has been given to the command, then doing this via `argparse` is the wrong approach (as Ben has nicely pointed out).
Think simple! :-) I believe that argparse does not depopulate `sys.argv`. So, `if not len(sys.argv) > 1`, then no argument has been provided by the user. |
Reading raw messages from Amazon SQS using boto | 10,698,786 | 8 | 2012-05-22T08:56:27Z | 10,699,240 | 7 | 2012-05-22T09:24:17Z | [
"python",
"amazon-web-services",
"boto",
"amazon-sqs"
] | By default, boto encodes messages with Base64 before the messages are sent to SQS. Example code:
```
conn = boto.connect_sqs('access_key_id', 'secret_key')
q = conn.get_queue('myqueue')
m = Message()
m.set_body('hello!')
q.write(m)
```
By replacing Message() with RawMessage(), I can send raw messages to the queue wi... | Actually `Message` class inherits from `RawMessage`, so it has all of it's methods.
One of these methods is:
**[`get_body_encoded()`](http://boto.s3.amazonaws.com/ref/sqs.html#boto.sqs.message.RawMessage.get_body_encoded)**
> *This method is really a semi-private method used by the Queue.write
> method when writing t... |
Reading raw messages from Amazon SQS using boto | 10,698,786 | 8 | 2012-05-22T08:56:27Z | 17,497,541 | 12 | 2013-07-05T22:19:32Z | [
"python",
"amazon-web-services",
"boto",
"amazon-sqs"
] | By default, boto encodes messages with Base64 before the messages are sent to SQS. Example code:
```
conn = boto.connect_sqs('access_key_id', 'secret_key')
q = conn.get_queue('myqueue')
m = Message()
m.set_body('hello!')
q.write(m)
```
By replacing Message() with RawMessage(), I can send raw messages to the queue wi... | In case you are interested to just read the messages off SQS queue and the producer was someone else, you may start seeing garbage character when call get\_messages().
See <https://github.com/boto/boto/issues/831>
Solution in this case again, is to
```
from boto.sqs.message import RawMessage
q.set_message_class(RawMe... |
built-in range or numpy.arange: which is more efficient? | 10,698,858 | 17 | 2012-05-22T09:02:05Z | 10,709,601 | 22 | 2012-05-22T20:23:16Z | [
"python",
"numpy",
"python-3.x",
"range"
] | When iterating over a large array with a range expression, should I use Python's built-in range function, or numpy's `arange` to get the best performance?
My reasoning so far:
`arange` probably resorts to a native implementation and might be faster therefore. On the other hand, `arange` returns a full array, which oc... | For large arrays numpy should be the faster solution.
In numpy you should use combinations of vectorized calculations, [ufuncs](http://docs.scipy.org/doc/numpy/reference/ufuncs.html) and [indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) to solve your problems as it runs at `C` speed.
Looping o... |
List comprehension suggestion | 10,700,393 | 2 | 2012-05-22T10:39:35Z | 10,700,482 | 7 | 2012-05-22T10:46:10Z | [
"python",
"list-comprehension"
] | ```
>>> odd,even=[ ],[ ]
>>> [even.append(x) if x%2==0 else odd.append(x) for x in range(51)]
[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, Non... | Best to just loop once. It's 6 lines, but they are *fast* lines
```
odd, even=[ ], [ ]
for x in range(51):
if x%2:
odd.append(x)
else:
even.append(x)
``` |
django-gunicorn-nginx: 502 bad gateway | 10,700,638 | 5 | 2012-05-22T10:56:44Z | 10,704,879 | 8 | 2012-05-22T15:14:15Z | [
"python",
"django",
"nginx",
"gunicorn"
] | I'm trying to ship my web application to the server and this is my first time configuring the server. I'm using **django-gunicorn-nginx** setup by following this tutorial <http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/> First everything was perfect and I got the **django welcome page**. Then I loaded the a... | First. Don't use `if` in an nginx conf. It's bad. Like really, really horrible. Use the following instead:
```
location / {
try_files $uri @proxy;
}
location @proxy {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http:... |
Example of how to use PyLZMA | 10,701,528 | 7 | 2012-05-22T11:53:47Z | 12,292,596 | 10 | 2012-09-06T03:32:16Z | [
"python",
"archive",
"extraction",
"7zip"
] | I want to use [PyLZMA](http://www.joachim-bauch.de/projects/pylzma/) to extract a file from an archive (e.g. test.7z) and extract it to the same directory.
I'm a newbie to Python and have no idea how to start. I've done some googling and found [some examples](http://nullege.com/codes/search/pylzma.decompress) and [doc... | Here is a Python class to handle the basic functionality. I have used it for my own work:
```
import py7zlib
class SevenZFile(object):
@classmethod
def is_7zfile(cls, filepath):
'''
Class method: determine if file path points to a valid 7z archive.
'''
is7z = False
fp = ... |
Python - Algorithm find time slots | 10,702,224 | 8 | 2012-05-22T12:40:08Z | 10,702,653 | 9 | 2012-05-22T13:07:38Z | [
"python",
"algorithm",
"datetime"
] | Let's say today I work from 09:00 to 18:00, I have 3 appointments:
* 10:00 - 10:30
* 12:00 - 13:00
* 15:30 - 17:10
I need to find a list of available time slots of 1 hour in the day.
Here is the list that I should get
* 09:00 - 10:00
* 10:30 - 11:30
* 13:00 - 14:00
* 14:00 - 15:00
I have already implemented that ... | ```
#time_slots.py
from datetime import datetime, timedelta
appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),
(datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),
(datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]
hours = (datetime(2012, 5, 22,... |
Choosing an appropriate way to use Neo4j in Python | 10,702,623 | 8 | 2012-05-22T13:05:05Z | 10,725,096 | 7 | 2012-05-23T17:38:41Z | [
"python",
"neo4j",
"gremlin",
"bulbs",
"tinkerpop"
] | I am currently using embedded python binding for neo4j. I do not have any issues currently since my graph is very small (sparse and upto 100 nodes). The algorithm I am developing involves quite a lot of traversals on the graph, more specifically DFS on the graph in general as well as on different subgraphs.
In the futu... | Django is an MVC web framework so you may be interested in that if yours is to be a web application.
From the point of view of py2neo (of which I am the author), I am trying to focus hard on performance by using the batch execution mechanism automatically where appropriate as well as providing strong Cypher support. I... |
How can I express this Python for loop in Haskell? | 10,703,800 | 3 | 2012-05-22T14:11:19Z | 10,703,920 | 9 | 2012-05-22T14:17:07Z | [
"python",
"haskell",
"io",
"iteration",
"wget"
] | Sometimes when I want to use `wget`, I just end up printing a bunch of lines with Python like so:
```
>>> for i in range(25):
... print "http://www.theoi.com/Text/HomerOdyssey", i, ".html"
...
http://www.theoi.com/Text/HomerOdyssey 0 .html
http://www.theoi.com/Text/HomerOdyssey 1 .html
http://www.theoi.com/Text/Hom... | ```
mapM_ (\i -> putStrLn (concat ["http://www.theoi.com/Text/HomerOdyssey", show i, ".html"])) [0..24]
```
As a bonus, this doesn't print any spaces.
Now some theory:
* `putStrLn` is a function that takes a *single* argument. Python, Perl, etc will slurp up all the arguments you give to `print` and turn it into a s... |
How can I express this Python for loop in Haskell? | 10,703,800 | 3 | 2012-05-22T14:11:19Z | 10,703,929 | 13 | 2012-05-22T14:17:46Z | [
"python",
"haskell",
"io",
"iteration",
"wget"
] | Sometimes when I want to use `wget`, I just end up printing a bunch of lines with Python like so:
```
>>> for i in range(25):
... print "http://www.theoi.com/Text/HomerOdyssey", i, ".html"
...
http://www.theoi.com/Text/HomerOdyssey 0 .html
http://www.theoi.com/Text/HomerOdyssey 1 .html
http://www.theoi.com/Text/Hom... | ```
for i in range(25):
... print "http://www.theoi.com/Text/HomerOdyssey", i, ".html"
```
becomes:
> import Control.Monad
so that we can:
```
forM_ [1..25] $ \i ->
putStrLn $ "http://www.theoi.com/Text/HomerOdyssey" ++ show i ++ ".html"
``` |
relative import does not work in Python | 10,705,598 | 2 | 2012-05-22T15:54:00Z | 10,705,695 | 8 | 2012-05-22T15:59:25Z | [
"python",
"python-3.x"
] | I have a project structure like this...
```
app/
main.py
app/
__init__.py
boot.py
server.py
controllers/
__init__.py
home.py
```
The imports are...
```
# main.py
from app import server
# server.py
from . import boot
# boot.py
from . import controllers... | You are importing `boot` which is importing `controllers`, which is then asked to import `home`, and `home` then tries to import `boot`, but it wasn't done importing yet. Don't do this, you are creating a circular dependency here.
Also see [Circular import dependency in Python](http://stackoverflow.com/questions/15563... |
Python equivalent of java ObjectOutputStream and ObjectInputStream? | 10,706,592 | 2 | 2012-05-22T16:59:22Z | 10,706,664 | 8 | 2012-05-22T17:03:34Z | [
"java",
"python",
"equivalent"
] | In java I can transfer objects between server and client by using [Object Output Stream](http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html) and [Object Input Stream](http://docs.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html). Is there anything equivalent in python?
**Related:**
* ... | The pickle module in Python provides object serialization and deserialization functionality. <http://docs.python.org/library/pickle.html>
It's not particularly secure, so you should always validate the incoming data, but it should support your needs. |
scatterplot with xerr and yerr with matplotlib | 10,707,147 | 5 | 2012-05-22T17:39:44Z | 10,707,967 | 8 | 2012-05-22T18:34:09Z | [
"python",
"plot",
"matplotlib"
] | i am looking to visualize the positions of two arrays with each other. My Table looks like this
```
Number Description value_1 value_2 err_1 err_2
1 descript_1 124.46 124.46 22.55 54.2
2 Descript_2 8.20 50.2 0.37 0.1
3 ... | It sounds like you want something like this?
```
import matplotlib.pyplot as plt
x = [124.46, 8.20, 52.55, 4.33]
y = [124.46, 50.2, 78.3, 778.8]
xerr = [54.2, 0.1, 2.41, 1.78]
yerr = [22.55, 0.37, 3.77, 0.14]
descrip = ['Atom 1', 'Atom 2', 'Atom 3', 'Atom 4']
plt.errorbar(x, y, xerr, yerr, capsize=0, ls='none', co... |
What is the difference between __set__ and __setattr__ in Python and when should which be used? | 10,707,206 | 10 | 2012-05-22T17:44:19Z | 10,707,293 | 13 | 2012-05-22T17:49:35Z | [
"python",
"attributes",
"getter-setter"
] | As the title says.
Coming from Java im used to:
```
private int A;
public void setA(int A) {
this.A = A;
}
public int getA() {
return this.A
}
```
How do I do that (if I need to) in Python.
And if one of `__setattr__` or `__set__` is used for this, what is the other one used for?
Edit:
I feel I need to cl... | In python, something like this *should* be implemented using a `property` (and then only when they do something useful).
```
class Foo(object):
def __init__(self):
self._x = None
@property
def x(self):
return self._x
@x.setter
def x(self,y):
self._x = y
```
In this exampl... |
What is the difference between __set__ and __setattr__ in Python and when should which be used? | 10,707,206 | 10 | 2012-05-22T17:44:19Z | 10,707,336 | 8 | 2012-05-22T17:52:06Z | [
"python",
"attributes",
"getter-setter"
] | As the title says.
Coming from Java im used to:
```
private int A;
public void setA(int A) {
this.A = A;
}
public int getA() {
return this.A
}
```
How do I do that (if I need to) in Python.
And if one of `__setattr__` or `__set__` is used for this, what is the other one used for?
Edit:
I feel I need to cl... | If the getter/setter are really as trivial as that, then you shouldn't even bother with them: just use an instance variable. If you do need a getter/setter that does something interesting, then you should switch to a property, as mgilson described. Note that you can change from an instance variable to a property withou... |
Python's append() only allows unique items in a list? | 10,708,430 | 3 | 2012-05-22T19:06:09Z | 10,708,460 | 7 | 2012-05-22T19:07:57Z | [
"python",
"data-structures",
"append"
] | The python documentation implies that duplicate items can exist within a list, and this is supported by the assignmnet: list = ["word1", "word1"]. However, Python's append() doesn't seem to add an item if it's already in the list. Am I missing something here or is this a deliberate attempt at a set() like behaviour?
`... | There *is* no second word2.
```
>>> d = {}
>>> d["word1"] = 1
>>> d["word2"] = 2
>>> d
{'word1': 1, 'word2': 2}
>>> d["word2"] = 3
>>> d
{'word1': 1, 'word2': 3}
```
Dictionaries map a specific key to a specific value. If you want a single key to correspond to multiple values, typically a list is used, and a defaultd... |
How can I install pycrypto on a 64-bit Windows 7 machine? | 10,708,538 | 3 | 2012-05-22T19:12:39Z | 13,824,816 | 9 | 2012-12-11T16:55:25Z | [
"python",
"windows",
"pip",
"pycrypto"
] | I tried installing PyCrypto using `pip`, but it complained about needing vcvarsall.bat. I installed Visual Studio 2008, but now I get `ValueError: [u'path']` when I try to install it from `pip`.
I tried downloading a pre-built binary from [Voidspace](http://www.voidspace.org.uk/python/modules.shtml#pycrypto), but they... | [Voidspace](http://www.voidspace.org.uk/python/modules.shtml#pycrypto) now has prebuilt 64bit binaries:
eg. [The 64bit binary for python 2.7](http://www.voidspace.org.uk/downloads/pycrypto26/pycrypto-2.6.win-amd64-py2.7.exe) |
Python: Decimal part of a large float | 10,708,840 | 3 | 2012-05-22T19:32:23Z | 10,708,924 | 8 | 2012-05-22T19:38:09Z | [
"python"
] | I'm trying to get the decimal part of `(pow(10, i) - 1)/23` for `0 < i < 50`. I have tried
```
(pow(10, i) - 1)/23 % 1
```
in Python 3 but I get `0.0` for all values of `i` greater than 17.
How can I extract the decimal part of a large integer in Python? | To preserve precision, I'd probably use the [fractions](http://docs.python.org/library/fractions.html) module:
```
>>> from fractions import Fraction
>>> Fraction(10)
Fraction(10, 1)
>>> Fraction(10)**50
Fraction(100000000000000000000000000000000000000000000000000, 1)
>>> Fraction(10)**50-1
Fraction(999999999999999999... |
Surf missing in opencv 2.4 for python | 10,709,610 | 8 | 2012-05-22T20:23:42Z | 10,710,438 | 8 | 2012-05-22T21:26:43Z | [
"python",
"opencv",
"surf"
] | I'm trying to instantiate a SURF object in python using OpenCV as described [here](http://docs.opencv.org/modules/nonfree/doc/feature_detection.html#surf) but this happens:
```
>>> import cv2
>>> cv2.__version__
'2.4.0'
>>> cv2.SURF()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeEr... | It is a regression which should be fixed in the next library update.
But SURF is not really absent. You still can access it via the generic wrappers:
```
surf_detector = cv2.FeatureDetector_create("SURF")
surf_descriptor = cv2.DescriptorExtractor_create("SURF")
```
---
**Update:** `cv2.SURF()` is restored in OpenCV... |
comparing numpy arrays containing NaN | 10,710,328 | 15 | 2012-05-22T21:18:46Z | 10,710,390 | 8 | 2012-05-22T21:23:25Z | [
"python",
"numpy"
] | For my unittest, I want to check if two arrays are identical. Reduced example:
```
a=np.array([1, 2, np.NaN])
b=np.array([1, 2, np.NaN])
if np.all(a==b):
print 'arrays are equal'
```
This does not work because nan != nan.
What is the best way to proceed?
Thanks in advance. | You could use numpy masked arrays, mask the `NaN` values and then use `numpy.ma.all` or `numpy.ma.allclose`:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.all.html>
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.allclose.html>
For example:
```
a=np.array([1, 2, np.NaN])
b=np.array([1,... |
comparing numpy arrays containing NaN | 10,710,328 | 15 | 2012-05-22T21:18:46Z | 10,710,413 | 14 | 2012-05-22T21:24:50Z | [
"python",
"numpy"
] | For my unittest, I want to check if two arrays are identical. Reduced example:
```
a=np.array([1, 2, np.NaN])
b=np.array([1, 2, np.NaN])
if np.all(a==b):
print 'arrays are equal'
```
This does not work because nan != nan.
What is the best way to proceed?
Thanks in advance. | I'm not certain this is the *best* way to proceed, but it is *a* way:
```
>>> ((a == b) | (numpy.isnan(a) & numpy.isnan(b))).all()
True
``` |
comparing numpy arrays containing NaN | 10,710,328 | 15 | 2012-05-22T21:18:46Z | 10,710,613 | 12 | 2012-05-22T21:42:36Z | [
"python",
"numpy"
] | For my unittest, I want to check if two arrays are identical. Reduced example:
```
a=np.array([1, 2, np.NaN])
b=np.array([1, 2, np.NaN])
if np.all(a==b):
print 'arrays are equal'
```
This does not work because nan != nan.
What is the best way to proceed?
Thanks in advance. | Alternatively you can use [`numpy.testing.assert_equal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_equal.html#numpy.testing.assert_equal) or [`numpy.testing.assert_array_equal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_array_equal.html) with a `try/except`:... |
Trouble with UTF-8 CSV input in Python | 10,710,446 | 15 | 2012-05-22T21:27:12Z | 10,710,872 | 9 | 2012-05-22T22:07:39Z | [
"python",
"encoding",
"utf-8"
] | This seems like it should be an easy fix, but so far a solution has eluded me. I have a single column csv file with non-ascii chars saved in utf-8 that I want to read in and store in a list. I'm attempting to follow the principle of the ["Unicode Sandwich"](http://nedbatchelder.com/text/unipain.html) and decode upon re... | At it fails from the first char to read, you may have a BOM. Use `codecs.open('utf8file.csv', 'rU', encoding='utf-8-sig')` if your file is UTF8 and has a BOM at the beginning. |
Trouble with UTF-8 CSV input in Python | 10,710,446 | 15 | 2012-05-22T21:27:12Z | 10,711,237 | 10 | 2012-05-22T22:52:54Z | [
"python",
"encoding",
"utf-8"
] | This seems like it should be an easy fix, but so far a solution has eluded me. I have a single column csv file with non-ascii chars saved in utf-8 that I want to read in and store in a list. I'm attempting to follow the principle of the ["Unicode Sandwich"](http://nedbatchelder.com/text/unipain.html) and decode upon re... | Your first snippet won't work. You are feeding unicode data to the csv reader, which (as documented) can't handle it.
Your 2nd and 3rd snippets are confused. Something like the following is all that you need:
```
f = open('your_utf8_encoded_file.csv', 'rb')
reader = csv.reader(f)
for utf8_row in reader:
unicode_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.