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 |
|---|---|---|---|---|---|---|---|---|---|
Using MySQL with Django - Access denied for user '@'localhost | 11,170,133 | 20 | 2012-06-23T14:09:28Z | 11,170,252 | 26 | 2012-06-23T14:25:14Z | [
"python",
"mysql",
"django"
] | So I'm learning Django (1, 3, 1, 'final', 0) through this resource: <http://www.djangobook.com/en/2.0/chapter05/>
I installed 'mysql-server' and 'python-mysqldb' via Synaptic. I changed the relevant setting in settings.py.
The book mentioned above tells us to run from the manage.py shell:
```
>>> from django.db impo... | Your user does not have an access to database. Use the commands below to set up your database.
```
DROP DATABASE IF EXISTS `mydb`;
CREATE DATABASE `mydb`
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
USE 'mysql';
GRANT ALL PRIVILEGES ON mydb.* TO 'mydb_user'@'localhost' IDENTIFIED BY 'your_passw... |
pandas row specific apply | 11,170,653 | 9 | 2012-06-23T15:22:48Z | 11,170,956 | 7 | 2012-06-23T16:00:18Z | [
"python",
"pandas"
] | Similar to [this R question](http://stackoverflow.com/questions/2545879/row-column-counter-in-apply-functions), I'd like to apply a function to each item in a Series (or each row in a DataFrame) using Pandas, but want to use as an argument to this function the index or id of that row. As a trivial example, suppose one ... | If you use the apply method with a function what happens is that every item in the Series will be mapped with such a function. E.g.
```
>>> s.apply(enumerate)
a <enumerate object at 0x13cf910>
b <enumerate object at 0x13cf870>
c <enumerate object at 0x13cf820>
d <enumerate object at 0x13cf7d0>
e <enumer... |
how tell python script to use particular version | 11,170,827 | 16 | 2012-06-23T15:46:23Z | 11,171,390 | 15 | 2012-06-23T17:05:23Z | [
"python",
"version",
"virtualenv"
] | How do I, in the main.py module (presumably), tell python which interpreter to use? What I mean is: if I want a particular script to use version 3 of python to interpret the entire program, how do I do that?
Bonus: how would this affect a virtualenv? Am I right in thinking that if I create a virtualenv for my program ... | You can she-bang line the top line of the script but that'll only work when executing as ./my\_program.py.
If you execute as `python my_program.py`, then the whatever Python version that `which python` returns will be used.
In re: to virtualenv use: `virtualenv -p /usr/bin/python3.2` or whatever to set it up to use t... |
How to make a copy of a python module in runtime? | 11,170,949 | 22 | 2012-06-23T15:59:06Z | 11,199,969 | 9 | 2012-06-26T02:19:23Z | [
"python",
"python-c-extension"
] | I need to make a copy of a socket module to be able to use it and to have one more socket module monkey-patched and use it differently.
Is it possible?
I mean to really copy a module, namely to get the same result in **runtime** as I've copied socketmodule.c changed initsocket() function to initmy\_socket() and insta... | This is pretty disgusting, but this might suffice:
```
import sys
# if socket was already imported, get rid of it and save a copy
save = sys.modules.pop('socket', None)
# import socket again (it's not in sys.modules, so it will be reimported)
import socket as mysock
if save is None:
# if we didn't have a saved ... |
How to make a copy of a python module in runtime? | 11,170,949 | 22 | 2012-06-23T15:59:06Z | 11,285,504 | 14 | 2012-07-01T20:45:47Z | [
"python",
"python-c-extension"
] | I need to make a copy of a socket module to be able to use it and to have one more socket module monkey-patched and use it differently.
Is it possible?
I mean to really copy a module, namely to get the same result in **runtime** as I've copied socketmodule.c changed initsocket() function to initmy\_socket() and insta... | You can always do tricks like importing a module then deleting it from sys.modules or trying to copy a module. However, Python already provides what you want in its Standard Library.
```
import imp # Standard module to do such things you want to.
# We can import any module including standard ones:
os1=imp.load_module... |
Python Regular Expression example | 11,171,045 | 22 | 2012-06-23T16:13:02Z | 11,171,056 | 14 | 2012-06-23T16:15:11Z | [
"python",
"regex"
] | I want to write a simple Regular Expression in Python that extracts a number from HTML. The html sample is as follows
```
Your number is <b>123</b>
```
Now how can I extract 123, i.e. contents of first bold text after string "Your number is".
Can any Python guru help me in this.
Thanks, | Given `s = "Your number is <b>123</b>"` then:
```
import re
m = re.search(r"\d+", s)
```
will work and give you
```
m.group()
'123'
```
The regular expression looks for 1 or more consecutive digits in your string.
Note that in this specific case we *knew* that there would be a numeric sequence, otherwise you w... |
Python Regular Expression example | 11,171,045 | 22 | 2012-06-23T16:13:02Z | 11,171,076 | 39 | 2012-06-23T16:18:38Z | [
"python",
"regex"
] | I want to write a simple Regular Expression in Python that extracts a number from HTML. The html sample is as follows
```
Your number is <b>123</b>
```
Now how can I extract 123, i.e. contents of first bold text after string "Your number is".
Can any Python guru help me in this.
Thanks, | ```
import re
m = re.search("Your number is <b>(\d+)</b>",
"xxx Your number is <b>123</b> fdjsk")
if m:
print m.groups()[0]
``` |
Why does "i, j = 1" result in "int .. is not iterable"? | 11,172,357 | 3 | 2012-06-23T19:29:31Z | 11,172,364 | 10 | 2012-06-23T19:31:12Z | [
"python"
] | I am trying to implement a partition function for quicksort in Python.
```
def partition(ls):
if len(ls) == 0:
return
pivot = ls[0]
i, j = 1
while j < len(ls):
if ls[j] <= pivot:
i += 1
temp = ls[i]
ls[i] = ls[j]
ls[j] = temp
j += 1
ls[0] = ls[i]
ls[i] = pivot
```
Howev... | When you list multiple targets separated by commas on the left of an assignment, it tries to iterate over the right hand side and assign pieces to the pieces on the left. So if you do `x, y = (1, 2)` then x will be 1 and y will be 2.
If you want to make i and j both be 1, do `i = j = 1`.
(Note that this binds both va... |
configuring nginx and uwsgi for python flask application | 11,172,448 | 4 | 2012-06-23T19:42:24Z | 11,172,494 | 8 | 2012-06-23T19:49:13Z | [
"python",
"uwsgi"
] | am trying to configure uwsgi and in the process it says on a tutorial that I must run
uwsgi -s /tmp/uwsgi.sock -w myapp:app
the problem is -w is an invalid option. Can anyone help me point out why or what should I do?
Thanks | maybe you are using debian-supplied packages. They are fully modular so you need to install/load the required plugins:
<http://projects.unbit.it/uwsgi/wiki/Quickstart> |
Why can't I use the scipy.io? | 11,172,623 | 5 | 2012-06-23T20:10:33Z | 11,172,686 | 10 | 2012-06-23T20:20:28Z | [
"python",
"import",
"scipy"
] | I've been trying to get started with scipy, but the package is giving me some problems. The tutorial leans heavily on scipy.io, but when I import scypi and try to use scipy.io, I get errors:
```
In [1]: import scipy
In [2]: help(scipy.io)
---------------------------------------------------------------------------
Att... | Two things here. First, you cannot in general access a module in a package by doing `import package` and then trying to access `package.module`. You often have to do what you did, `import package.module`, or (if you don't want to type `package.module` all the time, you can do `from package import module`. So you can al... |
Determining the byte size of a scipy.sparse matrix? | 11,173,019 | 11 | 2012-06-23T21:10:05Z | 11,173,074 | 15 | 2012-06-23T21:18:10Z | [
"python",
"scipy",
"sparse-matrix"
] | Is it possible to determine the byte size of a scipy.sparse matrix? In NumPy you can determine the size of an array by doing the following:
```
import numpy as np
print(np.zeros((100, 100, 100).nbytes)
8000000
``` | A sparse matrix is constructed from regular numpy arrays, so you can get the byte count for any of these just as you would a regular array.
If you just want the number of bytes of the array elements:
```
>>> from scipy.sparse import csr_matrix
>>> a = csr_matrix(np.arange(12).reshape((4,3)))
>>> a.data.nbytes
88
```
... |
Connecting an overloaded PyQT signal using new-style syntax | 11,173,028 | 3 | 2012-06-23T21:12:07Z | 11,178,796 | 11 | 2012-06-24T15:46:20Z | [
"pyqt4",
"python",
"signals-slots"
] | I am designing a custom widget which is basically a **QGroupBox** holding a configurable number of **QCheckBox** buttons, where each one of them should control a particular bit in a bitmask represented by a [**QBitArray**](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qbitarray.html). In order to do that, ... | While browsing for related questions I found [this answer](http://stackoverflow.com/a/9269089/1007502) to be exactly what I needed. The correct new-style signal syntax for connecting only **QButtonGroup's** *buttonClicked(int)* signal to **QBitArray's** *toggleBit(int)*, ignoring the other overloaded signatures, involv... |
Assign contents of Python dict to multiple variables at once? | 11,173,607 | 5 | 2012-06-23T22:48:08Z | 11,173,619 | 7 | 2012-06-23T22:50:23Z | [
"python",
"dictionary"
] | I would like to do something like this
```
def f():
return { 'a' : 1, 'b' : 2, 'c' : 3 }
{ a, b } = f() # or { 'a', 'b' } = f() ?
```
I.e. so that a gets assigned 1, b gets 2, and c is undefined
This is similar to this
```
def f()
return( 1,2 )
a,b = f()
``` | It wouldn't make any sense for unpacking to depend on the variable names. The closest you can get is:
```
a, b = [f()[k] for k in ('a', 'b')]
```
This, of course, evaluates `f()` twice.
---
You could write a function:
```
def unpack(d, *keys)
return tuple(d[k] for k in keys)
```
Then do:
```
a, b = unpack(f(... |
Can one partially apply the second argument of a function that takes no keyword arguments? | 11,173,660 | 13 | 2012-06-23T22:58:26Z | 11,173,826 | 17 | 2012-06-23T23:29:29Z | [
"python",
"arguments",
"partial-application"
] | Take for example the python built in `pow()` function.
```
xs = [1,2,3,4,5,6,7,8]
from functools import partial
list(map(partial(pow,2),xs))
>>> [2, 4, 8, 16, 32, 128, 256]
```
but how would I raise the xs to the power of 2?
to get `[1, 4, 9, 16, 25, 49, 64]`
```
list(map(partial(pow,y=2),xs))
TypeError: pow() ... | # No
According to [the documentation](http://docs.python.org/library/functools.html#functools.partial.args), [`partial`](http://docs.python.org/library/functools.html#functools.partial) *cannot* do this (emphasis my own):
> **partial.args**
>
> > The *leftmost* positional arguments that will be prepended to the posit... |
Can one partially apply the second argument of a function that takes no keyword arguments? | 11,173,660 | 13 | 2012-06-23T22:58:26Z | 11,173,903 | 7 | 2012-06-23T23:43:03Z | [
"python",
"arguments",
"partial-application"
] | Take for example the python built in `pow()` function.
```
xs = [1,2,3,4,5,6,7,8]
from functools import partial
list(map(partial(pow,2),xs))
>>> [2, 4, 8, 16, 32, 128, 256]
```
but how would I raise the xs to the power of 2?
to get `[1, 4, 9, 16, 25, 49, 64]`
```
list(map(partial(pow,y=2),xs))
TypeError: pow() ... | I think I'd just use this simple one-liner:
```
import itertools
print list(itertools.imap(pow, [1, 2, 3], itertools.repeat(2)))
```
**Update:**
I also came up with a funnier than useful solution. It's a beautiful syntactic sugar, profiting from the fact that the `...` literal means `Ellipsis` in Python3. It's a mod... |
AttributeError("'str' object has no attribute 'read'") | 11,174,024 | 35 | 2012-06-24T00:12:14Z | 11,174,103 | 65 | 2012-06-24T00:33:50Z | [
"python",
"python-2.7",
"urllib2",
"attributeerror",
"canonical-quickly"
] | In Python I'm getting an error:
```
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
```
Given python code:
```
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
r... | The problem is that for `json.load` you should pass a file like object with a `read` function defined. So either you use [`json.load(reponse)`](http://docs.python.org/library/json.html#json.load) or [`json.loads(response.read())`](http://docs.python.org/library/json.html#json.loads). |
AttributeError("'str' object has no attribute 'read'") | 11,174,024 | 35 | 2012-06-24T00:12:14Z | 11,174,518 | 9 | 2012-06-24T02:19:32Z | [
"python",
"python-2.7",
"urllib2",
"attributeerror",
"canonical-quickly"
] | In Python I'm getting an error:
```
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
```
Given python code:
```
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
r... | ```
AttributeError("'str' object has no attribute 'read'",)
```
This means exactly what it says: something tried to find a `.read` attribute on the object that you gave it, and you gave it an object of type `str` (i.e., you gave it a string).
The error occurred here:
```
json.load (jsonofabitch)['data']['children']
... |
Python's multiprocessing and memory | 11,174,172 | 17 | 2012-06-24T00:47:56Z | 11,223,899 | 9 | 2012-06-27T10:14:58Z | [
"python",
"multiprocessing"
] | I am using `multiprocessing.imap_unordered` to perform a computation on a list of values:
```
def process_parallel(fnc, some_list):
pool = multiprocessing.Pool()
for result in pool.imap_unordered(fnc, some_list):
for x in result:
yield x
pool.terminate()
```
Each call to `fnc` returns ... | As you can see by looking into the corresponding source file (`python2.7/multiprocessing/pool.py`), the IMapUnorderedIterator uses a `collections.deque` instance for storing the results. If a new item comes in, it is added and removed in the iteration.
As you suggested, if another huge object comes in while the main t... |
Why do Python's @staticmethods interact so poorly with decorated classes? | 11,174,362 | 4 | 2012-06-24T01:31:51Z | 11,174,452 | 7 | 2012-06-24T01:58:16Z | [
"python",
"python-2.7",
"decorator",
"memoization"
] | Recently, the StackOverflow community helped me develop a fairly concise `@memoize` decorator that is able to decorate not only functions but also methods and classes in a general way, ie, without having any foreknowledge of what type of thing it will be decorating.
One of the problems that I ran into is that if you d... | Several thoughts for you:
* The operation of a *staticmethod* is completely orthogonal to the operator of class decorators. Making a function into a staticmethod only affect what happens during attribute lookup. A class decorator is a compile-time transformation on a class.
* There isn't a "bug" in *functools.wraps*. ... |
how to json serialize objects in python | 11,174,614 | 2 | 2012-06-24T02:48:00Z | 11,174,634 | 9 | 2012-06-24T02:54:37Z | [
"python",
"json"
] | Does python support random json serialization? I get this error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "commands.py", line 36, in toJson
return json.dumps(self)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 231, ... | json within python by default can only handle certain objects like dictionaries, list and basic types such as ints, strings and so on for more complex types you need to define your own serialization scheme
```
>>> help(json)
Extending JSONEncoder::
>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
... |
How to subclass an OrderedDict? | 11,174,702 | 15 | 2012-06-24T03:16:56Z | 11,174,708 | 26 | 2012-06-24T03:19:33Z | [
"python",
"inheritance",
"subclass",
"ordereddictionary"
] | Subclassing a Python `dict` works as expected:
```
>>> class DictSub(dict):
... def __init__(self):
... self[1] = 10
...
>>> DictSub()
{1: 10}
```
However, doing the same thing with a `collections.OrderedDict` does not work:
```
>>> import collections
>>> class OrdDictSub(collections.OrderedDict... | You need to invoke `OrderedDict.__init__` from your `__init__`:
```
class OrdDictSub(collections.OrderedDict):
def __init__(self):
super(OrdDictSub, self).__init__()
```
You haven't given `OrderedDict` a chance to initialize itself. Technically, you want to do this for your `dict` subclass as well, since ... |
Avoiding nested for loops | 11,174,745 | 8 | 2012-06-24T03:30:11Z | 11,174,751 | 10 | 2012-06-24T03:31:51Z | [
"python",
"for-loop"
] | I am trying to do some parameter testing on another code using python. I need to test 6 independent parameters, but I need all of the possible combinations of them.
Each parameter has a minimum, a maximum, and a step value that needs to be passed to it. The first easy solution that popped into my head was a nested for... | You can probably use `itertools.product`: <http://docs.python.org/library/itertools.html#itertools.product> .
Something like
```
for var1, var2 in itertools.product(xrange(min1, max1, step1), xrange(min2, max2, step2)):
# stuff
```
. . . only with all six vars in there. |
Avoiding nested for loops | 11,174,745 | 8 | 2012-06-24T03:30:11Z | 11,174,757 | 20 | 2012-06-24T03:33:19Z | [
"python",
"for-loop"
] | I am trying to do some parameter testing on another code using python. I need to test 6 independent parameters, but I need all of the possible combinations of them.
Each parameter has a minimum, a maximum, and a step value that needs to be passed to it. The first easy solution that popped into my head was a nested for... | Here's how to use `product`:
```
x1 = xrange(min1,max1,step1)
x2 = xrange(min2,max2,step2)
x3 = xrange(min3,max3,step3)
...
for v1, v2, v3, v4, v5, v6 in itertools.product(x1, x2, x3, x4, x5, x6):
icky_thing(....)
```
or a bit more compactly:
```
ranges = [
xrange(min1,max1,step1),
xrange(min2,max2,step... |
Convert unicode string to byte string | 11,174,790 | 8 | 2012-06-24T03:42:37Z | 11,174,804 | 19 | 2012-06-24T03:46:26Z | [
"python",
"unicode"
] | I get a string from a function that is represented like `u'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'`, but to process it I need it to be bytestring (like `'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'`).
How do I convert it without changes?
My best guess so far is to take `s.encode('unicode_escape')`, which will return ... | ISO 8859-1 (aka Latin-1) maps the first 256 Unicode codepoints to their byte values.
```
>>> u'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1')
'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'
``` |
Can you help me with this python exercise? | 11,175,022 | 3 | 2012-06-24T04:48:37Z | 11,175,081 | 8 | 2012-06-24T05:00:54Z | [
"python"
] | I want to write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
Here is my code so far:
```
def count(list1):
x = 0
total... | You might be over-thinking the process a bit. The logic doesn't need to really be split up into case tests like that. The part you have right so far is the total counter, but you should only need to loop over each value in the list. Not do a conditional while, with if..else
Normally I wouldn't just give an answer, but... |
Code for Greatest Common Divisor in Python | 11,175,131 | 48 | 2012-06-24T05:13:02Z | 11,175,154 | 165 | 2012-06-24T05:19:03Z | [
"python"
] | The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is Euclidâs algorithm, which is based on the observation that if `r` is the remainder when `a` is divided by `b`, then `gcd(a, b) = gcd(b, r)`. As a base case, we can... | It's [in the standard library](https://docs.python.org/dev/library/fractions.html#fractions.gcd).
```
>>> from fractions import gcd
>>> gcd(20,8)
4
```
Source from the inspect module:
```
>>> print inspect.getsource(gcd)
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the re... |
Code for Greatest Common Divisor in Python | 11,175,131 | 48 | 2012-06-24T05:13:02Z | 18,944,210 | 21 | 2013-09-22T13:13:27Z | [
"python"
] | The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is Euclidâs algorithm, which is based on the observation that if `r` is the remainder when `a` is divided by `b`, then `gcd(a, b) = gcd(b, r)`. As a base case, we can... | The algorithms with m-n can runs awfully long.
This one performs much better:
```
def gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return x
``` |
Code for Greatest Common Divisor in Python | 11,175,131 | 48 | 2012-06-24T05:13:02Z | 28,633,554 | 8 | 2015-02-20T16:21:16Z | [
"python"
] | The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is Euclidâs algorithm, which is based on the observation that if `r` is the remainder when `a` is divided by `b`, then `gcd(a, b) = gcd(b, r)`. As a base case, we can... | This version of code utilizes Euclid's Algorithm for finding GCD.
```
def gcdIter(a, b):
if b == 0:
return a
else:
return gcdIter(b, a % b)
``` |
Sort a list efficiently which contains only 0 and 1 without using any builtin python sort function? | 11,175,645 | 2 | 2012-06-24T07:14:34Z | 11,175,700 | 8 | 2012-06-24T07:21:47Z | [
"python"
] | What is the most efficient way to sort a list, `[0,0,1,0,1,1,0]` whose elements are only `0` & `1`, without using any builtin `sort()` or `sorted()` or `count()` function. O(n) or less than that | ```
>>> lst = [0,0,1,0,1,1,0]
>>> l, s = len(lst), sum(lst)
>>> result = [0] * (l - s) + [1] * s
>>> result
[0, 0, 0, 0, 1, 1, 1]
``` |
pass a string variable into a gql query | 11,176,084 | 5 | 2012-06-24T08:36:21Z | 11,176,117 | 7 | 2012-06-24T08:43:15Z | [
"python",
"google-app-engine",
"gae-datastore",
"gql"
] | How in the world do I pass a string variable into GQL with python?? I can do it fine in SQL but it just isn't working. here is what I have:
```
personalposts = db.GqlQuery("select * from PersonalPost where user_id = %s order by created desc limit 30" % user_id)
```
This has been killing me but should be really simple... | This should work:
```
personalposts = db.GqlQuery("select * from PersonalPost where user_id =:1 order by created desc limit 30",user_id)
```
`GqlQuery` syntax examples:
```
q = GqlQuery("SELECT * FROM Song WHERE composer = 'Lennon, John'")
q = GqlQuery("SELECT __key__ FROM Song WHERE composer = :1", "Lennon, John")... |
Does Pyramid have a Signal/Slot system | 11,176,192 | 7 | 2012-06-24T09:01:55Z | 11,176,337 | 9 | 2012-06-24T09:27:26Z | [
"python",
"signals",
"pylons",
"pyramid"
] | Django happens to have a [Signals](https://docs.djangoproject.com/en/1.4/topics/signals/) system built in and it would be quite useful for a project I'm working on.
I've been reading though the Pyramid docs and it does appear to have an [Events](http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/events.... | The events system used by Pyramid fulfils the exact same use-cases as the Signals system. Your application can define arbitrary events and attach subscribers to them.
To create a new event, define an interface for it:
```
from zope.interface import (
Attribute,
Interface,
)
class IMyOwnEvent(Interface):
... |
Python file operations | 11,176,724 | 11 | 2012-06-24T10:34:27Z | 11,176,772 | 9 | 2012-06-24T10:42:13Z | [
"python",
"file-io"
] | I got an err "IOError: [Errno 0] Error" with this python program:
```
from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
print file.read() # 1
file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()
```... | Python uses stdio's fopen function and passes the mode as argument. I am assuming you use windows, since @Lev says the code works fine on Linux.
The following is from the [fopen](http://msdn.microsoft.com/en-us/library/yeby3zcb%28v=vs.80%29.aspx) documentation of windows, this may be a clue to solving your problem:
>... |
Change locale for django-admin-tools | 11,177,330 | 6 | 2012-06-24T12:10:43Z | 11,177,826 | 7 | 2012-06-24T13:24:13Z | [
"python",
"django",
"internationalization",
"django-admin",
"django-admin-tools"
] | In my `settings.py` file I have:
```
LANGUAGE_CODE = 'ru-RU'
```
also, I have installed and working django-admin-tools. But admin language still english. What I'm doing wrong?
PS.
```
$ cat settings.py | grep USE | grep -v USER
USE_I18N = True
USE_L10N = True
USE_TZ = True
``` | You need to set the language specifically for the admin app. Since django does not provide a language drop down as part of the default login, you have a few options:
1. Login to your normal (non admin view), with superuser/staff credentials and the correct language, then shift over to the admin URL.
2. Update the admi... |
Print list without brackets in a single row | 11,178,061 | 34 | 2012-06-24T13:59:28Z | 11,178,075 | 46 | 2012-06-24T14:01:07Z | [
"python",
"list"
] | I have a list in Python
e.g.
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
```
I want to print the array in a single line without the normal " []
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
```
Will give the output as;
```
["Sam", "Peter", "James", "Julian", "Ann"]
```
That is no... | ```
print ', '.join(names)
```
This, like it sounds, just takes all the elements of the list and joins them with `', '`. |
Print list without brackets in a single row | 11,178,061 | 34 | 2012-06-24T13:59:28Z | 11,178,085 | 7 | 2012-06-24T14:02:40Z | [
"python",
"list"
] | I have a list in Python
e.g.
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
```
I want to print the array in a single line without the normal " []
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
```
Will give the output as;
```
["Sam", "Peter", "James", "Julian", "Ann"]
```
That is no... | This is what you need
```
", ".join(names)
``` |
Print list without brackets in a single row | 11,178,061 | 34 | 2012-06-24T13:59:28Z | 14,679,742 | 14 | 2013-02-04T02:45:41Z | [
"python",
"list"
] | I have a list in Python
e.g.
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
```
I want to print the array in a single line without the normal " []
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
```
Will give the output as;
```
["Sam", "Peter", "James", "Julian", "Ann"]
```
That is no... | General solution, works on arrays of non-strings:
```
>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'
``` |
Print list without brackets in a single row | 11,178,061 | 34 | 2012-06-24T13:59:28Z | 35,119,046 | 7 | 2016-01-31T20:24:27Z | [
"python",
"list"
] | I have a list in Python
e.g.
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
```
I want to print the array in a single line without the normal " []
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
```
Will give the output as;
```
["Sam", "Peter", "James", "Julian", "Ann"]
```
That is no... | Here is a simple one.
```
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names)
```
the star unpacks the list and return every element in the list. |
Counting number of calls to random in Python? | 11,178,136 | 3 | 2012-06-24T14:09:43Z | 11,178,201 | 7 | 2012-06-24T14:18:51Z | [
"python",
"random",
"python-3.x"
] | I have a Python application in which I would like to monitor the number of calls to functions in the standard random module, at runtime; is there any nice way to do this, or do I have to "manually" do it? | It seems to me that Python profiler should be able to do it "nicely". Look at [a post about Python profiling on SO](http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script).
At runtime, it seems that the [decorators](http://stackoverflow.com/questions/1301735/counting-python-method-calls-within-a... |
Numpy array broadcasting rules | 11,178,179 | 9 | 2012-06-24T14:16:10Z | 11,178,246 | 7 | 2012-06-24T14:25:05Z | [
"python",
"numpy",
"numpy-broadcasting"
] | I'm having some trouble understanding the rules for array broadcasting in Numpy.
Obviously, if you perform element-wise multiplication on two arrays of the same dimensions and shape, everything is fine. Also, if you multiply a multi-dimensional array by a scalar it works. This I understand.
But if you have two N-dime... | Well, the meaning of trailing axes is explained on the linked documentation page.
If you have two arrays with different dimensions number, say one `1x2x3` and other `2x3`, then you compare only the trailing common dimensions, in this case `2x3`. But if both your arrays are two-dimensional, then their corresponding size... |
How can I pass data from Flask to JavaScript in a template? | 11,178,426 | 50 | 2012-06-24T14:50:39Z | 11,178,486 | 63 | 2012-06-24T14:59:00Z | [
"javascript",
"python",
"flask",
"jinja2"
] | My app makes a call to an API that returns a dictionary. I want to pass information from this dict to JavaScript in the view. I am using the Google Maps API in the JS, specifically, so I'd like to pass it a list of tuples with the long/lat information. I know that `render_template` will pass these variables to the view... | You can use `{{ variable }}` anywhere in your template, not just in the HTML part. So this should work:
```
<html>
<head>
<script>
var someJavaScriptVar = '{{ geocode[1] }}';
</script>
<body>
<p>Hello World</p>
<button onclick="alert('Geocode: {{ geocode[0] }} ' + someJavaScriptVar)" />
</body>
</html>
```
Think of i... |
How can I pass data from Flask to JavaScript in a template? | 11,178,426 | 50 | 2012-06-24T14:50:39Z | 23,071,187 | 42 | 2014-04-14T21:58:01Z | [
"javascript",
"python",
"flask",
"jinja2"
] | My app makes a call to an API that returns a dictionary. I want to pass information from this dict to JavaScript in the view. I am using the Google Maps API in the JS, specifically, so I'd like to pass it a list of tuples with the long/lat information. I know that `render_template` will pass these variables to the view... | The ideal way to go about getting pretty much any Python object into a JavaScript object is to use JSON. JSON is great as a format for transfer between systems, but sometimes we forget that it stands for JavaScript Object Notation. This means that injecting JSON into the template is the same as injecting JavaScript cod... |
Overcome appengine 500 byte string limit in python? consider text | 11,178,869 | 2 | 2012-06-24T15:55:33Z | 11,179,190 | 7 | 2012-06-24T16:34:38Z | [
"python",
"string",
"google-app-engine",
"text",
"limit"
] | I get this:
```
BadValueError: Property is 804 bytes long; it must be 500 or less. Consider Text instead, which can store strings of any length.
```
I read this: <http://blog.zmxv.com/2012/02/appengine-go-sdks-500-byte-string.html> and this: [App Engine BadValueError On Bulk Data Upload - TextProperty being constru... | so consider the `TextProperty`.
switch from.
```
yourproperty = db.StringProperty()
```
to
```
yourproperty = db.TextProperty()
```
and you will be fine. keep in mind that `TextProperty` is **not indexed**. |
Python inheritance: TypeError: object.__init__() takes no parameters | 11,179,008 | 39 | 2012-06-24T16:13:54Z | 11,179,026 | 54 | 2012-06-24T16:15:40Z | [
"python",
"inheritance"
] | I get this error:
```
TypeError: object.__init__() takes no parameters
```
when running my code, I don't really see what I'm doing wrong here though:
```
class IRCReplyModule(object):
activated=True
moduleHandlerResultList=None
moduleHandlerCommandlist=None
modulename=""
def __init__(self,modul... | You are calling the wrong class name in your super() call:
```
class SimpleHelloWorld(IRCReplyModule):
def __init__(self):
#super(IRCReplyModule,self).__init__('hello world')
super(SimpleHelloWorld,self).__init__('hello world')
```
Essentially what you are resolving to is the `__init__` ... |
Pass additional parameters to post_save signal | 11,179,380 | 12 | 2012-06-24T16:56:42Z | 11,388,127 | 11 | 2012-07-09T01:23:17Z | [
"python",
"django"
] | hey i have a user registration form in my django application which collects additional data while a user is trying to register such as address, city, country, phone number etc.
This data is saved in the Account model class through `post_save` signal. The user creation process goes something like this :
```
# Function... | What I do is to set some '\_attrs' to the instance and then use them in the signal handler.
I imagine your case could be:
```
# Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
if created:
attrs_needed = ['_language', '_field', '_otherfield']
if... |
API reference to WebKit WebView implementation in GTK (Python) | 11,179,859 | 4 | 2012-06-24T17:57:45Z | 11,180,274 | 8 | 2012-06-24T18:50:16Z | [
"python",
"documentation",
"webkit",
"gtk",
"pygobject"
] | I'm working on a Python Gtk3 app on Ubuntu, which primarily uses `WebView` from WebKit. I couldn't find all the methods available to WebView object in python, currently I only know its `open()` method, so, where can I get detailed reference to all its methods, including some documentation on handling cookies and user p... | Because of GOBject Introspection, you should have access to every public class/method/function available in the WebKit. Hence, the original API documentation should help.
To know every method available, you can even use the classic help from Python. For instance:
```
$ python
>>> from gi.repository import WebKit
>>> ... |
Auto Generating Migrations using alembic | 11,180,013 | 4 | 2012-06-24T18:16:40Z | 11,193,390 | 20 | 2012-06-25T16:33:57Z | [
"python",
"sqlalchemy",
"database-migration",
"alembic"
] | In the tutorial:
<http://alembic.readthedocs.org/en/latest/tutorial.html>
I tested Auto Generating Migrations function by below command:
```
alembic revision --autogenerate -m "Added account table"
```
and got error:
```
Traceback (most recent call last):
File "/usr/local/bin/alembic", line 9, in <module>
load_entry... | "Is the myapp.mymodel already there, or I need to create that using python. How to do that?" -- if you're asking that, it sounds as if you do not yet have anything that you need to migrate.
The idea of a migration, Ã la Alembic, goes like this:
1. First you have your data model defined in your python code, usually
... |
Aggregating multiple test cases from multiple modules to run in PyDev TestRunner | 11,180,433 | 6 | 2012-06-24T19:12:46Z | 11,187,907 | 9 | 2012-06-25T10:50:46Z | [
"python",
"unit-testing",
"pydev"
] | What's the best way to aggregate test cases from multiple modules such that a single test run will execute them all and present the results in the PyDev UnitTest window? | There are many choices in PyDev depending on what you want:
1. Right-click a folder and choose 'run as > Python unit-test' (will run all modules below the dir as unit-tests).
2. Right-click multiple python modules and choose 'run as > Python unit-test' (will load the tests for all those modules and run them).
3. Creat... |
Python: What's the difference between __builtin__ and __builtins__? | 11,181,519 | 49 | 2012-06-24T21:56:06Z | 11,181,607 | 45 | 2012-06-24T22:10:21Z | [
"python",
"python-3.x",
"python-2.7",
"language-design",
"python-module"
] | I was coding today and noticed something. If I open a new interpreter session (IDLE) and check what's defined with the `dir` function I get this:
```
$ python
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', ... | Straight from the python documentation:
<http://docs.python.org/reference/executionmodel.html>
> By default, when in the `__main__` module, `__builtins__` is the
> built-in module `__builtin__` (note: no 's'); when in any other
> module, `__builtins__` is an alias for the dictionary of the
> `__builtin__` module itsel... |
Python: What's the difference between __builtin__ and __builtins__? | 11,181,519 | 49 | 2012-06-24T21:56:06Z | 11,181,616 | 16 | 2012-06-24T22:11:48Z | [
"python",
"python-3.x",
"python-2.7",
"language-design",
"python-module"
] | I was coding today and noticed something. If I open a new interpreter session (IDLE) and check what's defined with the `dir` function I get this:
```
$ python
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', ... | You should use `__builtin__` in your programs (in the rare cases that you need it), because `__builtins__` is an implementation detail of CPython. It may either be identical to `__builtin__`, or to `__builtin__.__dict__`, depending on the context. As [the documentation](http://docs.python.org/library/__builtin__.html) ... |
How can I build my C extensions with MinGW-w64 in Python? | 11,182,765 | 22 | 2012-06-25T02:12:27Z | 15,796,486 | 9 | 2013-04-03T19:38:20Z | [
"python",
"c",
"compilation",
"64bit"
] | So I have a few Python C extensions I have previously built for and used in 32 bit Python running in Win7. I have now however switched to 64 bit Python, and I am having issues building the C extension with MinGW-w64.
I made the changes to distutils as per [this post](http://bugs.python.org/issue11723), but I am gettin... | This worked for me with Python 3.3 :
1. create static python lib from dll
python dll is usually in C:/Windows/System32; in msys shell:
```
gendef.exe python33.dll
dlltool.exe --dllname python33.dll --def python33.def --output-lib libpython33.a
mv libpython33.a C:/Python33/libs
```
2. use swig to ... |
how to implement nested item in scrapy? | 11,184,557 | 15 | 2012-06-25T06:46:39Z | 13,944,690 | 9 | 2012-12-19T02:27:44Z | [
"python",
"json",
"scrapy"
] | I am scraping some data with complex hierarchical info and need to export the result to json.
I defined the items as
```
class FamilyItem():
name = Field()
sons = Field()
class SonsItem():
name = Field()
grandsons = Field()
class GrandsonsItem():
name = Field()
age = Field()
weight = Fie... | When saving the nested items, make sure to wrap them in a call to dict(), e.g.:
```
gs1 = GrandsonsItem()
gs1['name'] = 'GS1'
gs1['age'] = 18
gs1['weight'] = 50
gs2 = GrandsonsItem()
gs2['name'] = 'GS2'
gs2['age'] = 19
gs2['weight'] = 51
s1 = SonsItem()
s1['name'] = 'S1'
s1['grandsons'] = [dict(gs1), dict(gs2)]
jen... |
Running OpenCV from a Python virtualenv | 11,184,847 | 13 | 2012-06-25T07:08:48Z | 13,315,497 | 11 | 2012-11-09T20:29:13Z | [
"python",
"opencv",
"virtualenv"
] | I'm trying to install OpenCV within a virtualenv on my Ubuntu Server 12.04. I found [a thread discussing this](http://stackoverflow.com/questions/9592389/is-it-possible-to-run-opencv-python-binding-from-a-virtualenv) but managed to extract no information from it.
I tried using `pip install pyopencv` but it failed.
``... | Fired up a virtualenv and followed this guide: <http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/> , up until manipulating and copying the cv shared objects. Instead, I copied cv.so (from my OpenCV-2.2.0/lib directory) to my virtualenv site-packages (eg. env/lib/python2.7/site-packages/). Once ... |
Running OpenCV from a Python virtualenv | 11,184,847 | 13 | 2012-06-25T07:08:48Z | 24,112,175 | 7 | 2014-06-09T00:14:00Z | [
"python",
"opencv",
"virtualenv"
] | I'm trying to install OpenCV within a virtualenv on my Ubuntu Server 12.04. I found [a thread discussing this](http://stackoverflow.com/questions/9592389/is-it-possible-to-run-opencv-python-binding-from-a-virtualenv) but managed to extract no information from it.
I tried using `pip install pyopencv` but it failed.
``... | Here is the cleanest way, using pyenv and the virtualenv plug-in.
Install Python with shared library support (so we get a libpython2.7.dylib on Mac OS X or libpython2.7.so on Linux).
```
env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install -v 2.7.6
```
Create the virtualenv, based on the version of python we ju... |
Variable scope and Try Catch in python | 11,185,873 | 12 | 2012-06-25T08:33:55Z | 11,185,984 | 15 | 2012-06-25T08:40:50Z | [
"python",
"variables",
"try-catch",
"scope",
"python-imaging-library"
] | ```
import Image
import os
for dirname,dirs,files in os.walk("."):
for filename in files:
try:
im = Image.open(os.path.join(dirname,filename));
except IOError:
print "error opening file :: " + os.path.join(dirname,filename)
print im.size
```
Here i'm trying to print... | What's wrong with the "else" clause ?
```
for filename in files:
try:
im = Image.open(os.path.join(dirname,filename))
except IOError, e:
print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)
else:
print im.size
```
Now since you're in a loop, you can also use ... |
remove zero lines 2-D numpy array | 11,188,364 | 7 | 2012-06-25T11:20:03Z | 11,188,955 | 14 | 2012-06-25T11:59:49Z | [
"python",
"multidimensional-array",
"numpy"
] | I run a `qr factorization` in `numpy` which returns a list of `ndarrays`, namely `Q`and `R`:
```
>>> [q,r] = np.linalg.qr(np.array([1,0,0,0,1,1,1,1,1]).reshape(3,3))
```
`R` is a two-dimensional array, having pivoted zero-lines at the bottom (even proved for all examples in my test set):
```
>>> print r
[[ 1.4142135... | Use `np.all` with an `axis` argument:
```
>>> r[np.all(r == 0, axis=1)]
array([[ 0., 0., 0.]])
>>> r[~np.all(r == 0, axis=1)]
array([[-1.41421356, -0.70710678, -0.70710678],
[ 0. , -1.22474487, -1.22474487]])
``` |
How to split the string into segments in python | 11,188,619 | 3 | 2012-06-25T11:36:22Z | 11,188,706 | 7 | 2012-06-25T11:41:39Z | [
"python",
"string"
] | I have a string built from a few segments, which are not separated, but not overlap. This looks like that:
```
<python><regex><split>
```
I would like to split in into:
```
<python>, <regex>, <split>
```
I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I could... | Try [re.findall](http://docs.python.org/library/re.html#re.findall):
```
import re
your_string = '<python><regex><split>'
parts = re.findall(r'<.+?>', your_string)
print parts # ['<python>', '<regex>', '<split>']
``` |
How can I edit/rename keys during json.load in python? | 11,188,889 | 7 | 2012-06-25T11:55:57Z | 11,189,108 | 12 | 2012-06-25T12:09:41Z | [
"python",
"json",
"mongodb"
] | I have a json file ( ~3Gb ) that I need to load into mongodb. Quite a few of the json keys contain a . (dot), which causes the load into mongodb to fail. I want to the load the json file, and edit the key names in the process, say replace the dot with an empty space. Using the following python code
```
import json
de... | You almost had it:
```
import json
def remove_dot_key(obj):
for key in obj.keys():
new_key = key.replace(".","")
if new_key != key:
obj[new_key] = obj[key]
del obj[key]
return obj
new_json = json.loads(data, object_hook=remove_dot_key)
```
You were returning a diction... |
Is there any nicer way to write successive "or" statements in Python? | 11,189,793 | 22 | 2012-06-25T12:55:38Z | 11,189,839 | 30 | 2012-06-25T12:58:16Z | [
"python",
"conditional"
] | Simple question to which I can't find any "nice" answer by myself:
Let's say I have the following condition:
```
if 'foo' in mystring or 'bar' in mystring or 'hello' in mystring:
# Do something
pass
```
Where the number of `or` statement can be quite longer depending on the situation.
Is there a "nicer" (mo... | A way could be
```
if any(s in mystring for s in ('foo', 'bar', 'hello')):
pass
```
The thing you iterate over is a tuple, which is built upon compilation of the function, so it shouldn't be inferior to your original version.
If you fear that the tuple will become too long, you could do
```
def mystringlist():
... |
Is there any nicer way to write successive "or" statements in Python? | 11,189,793 | 22 | 2012-06-25T12:55:38Z | 11,189,864 | 7 | 2012-06-25T13:00:22Z | [
"python",
"conditional"
] | Simple question to which I can't find any "nice" answer by myself:
Let's say I have the following condition:
```
if 'foo' in mystring or 'bar' in mystring or 'hello' in mystring:
# Do something
pass
```
Where the number of `or` statement can be quite longer depending on the situation.
Is there a "nicer" (mo... | This sounds like a job for a regex.
```
import re
if re.search("(foo|bar|hello)", mystring):
# Do something
pass
```
It should be faster, too. Especially if you compile the regex ahead of time.
If you're generating the regular expression automatically, you could use `re.escape()` to make sure no special cha... |
django - getlist() | 11,190,070 | 24 | 2012-06-25T13:12:34Z | 11,190,754 | 52 | 2012-06-25T14:00:08Z | [
"python",
"django"
] | I just posted this question [jQuery - passing arrays in post request](http://stackoverflow.com/questions/11189079/jquery-passing-arrays-in-post-request/), where I don't to send arrays in post request, but there is no problem in jQuery code.
The problem is with receiving the POST request in django. I did like this.
``... | jQuery POST's arrays with the `[]` suffix because PHP and some web frameworks understand that convention, and re-build the array on the server-side for you automatically. Django doesn't work that way, but you should be able to access the data via:
```
ukeys = request.POST.getlist('ukeys[]')
``` |
Python matplotlib superimpose scatter plots | 11,190,735 | 9 | 2012-06-25T13:59:25Z | 11,190,864 | 12 | 2012-06-25T14:05:57Z | [
"python",
"plot",
"matplotlib",
"scatter-plot"
] | I am using Python matplotlib. i want to superimpose scatter plots. I know how to superimpose continuous line plots with commands:
```
>>> plt.plot(seriesX)
>>> plt.plot(Xresampl)
>>> plt.show()
```
But it does not seem to work the same way with scatter. Or maybe using plot() with a further argument specifying line st... | You simply call the `scatter` function twice, `matplotlib` will superimpose the two plots for you. You might want to specify a color, as the default for all scatter plots is blue. This is perhaps why you were only seeing one plot.
```
import numpy as np
import pylab as plt
X = np.linspace(0,5,100)
Y1 = X + 2*np.rando... |
Regular Expressions in Python unexpectedly slow | 11,190,835 | 25 | 2012-06-25T14:04:14Z | 11,192,394 | 16 | 2012-06-25T15:31:54Z | [
"python",
"regex",
"python-3.x"
] | Consider this Python code:
```
import timeit
import re
def one():
any(s in mystring for s in ('foo', 'bar', 'hello'))
r = re.compile('(foo|bar|hello)')
def two():
r.search(mystring)
mystring="hello"*1000
print([timeit.timeit(k, number=10000) for k in (one, two)])
mystring="goodbye"*1000
print([time... | ## Note to future readers
I think the correct answer is actually that Python's string handling algorithms are *really* optimized for this case, and the `re` module is actually a bit slower. What I've written below is true, but is probably not relevant to the simple regexps I have in the question.
## Original Answer
... |
python how to check list does't contain any value | 11,191,264 | 5 | 2012-06-25T14:28:46Z | 11,191,310 | 11 | 2012-06-25T14:31:22Z | [
"python-3.x",
"python-2.7",
"python"
] | consider this simple function
```
def foo(l=[]):
if not l: print "List is empty"
else : print "List is not empty"
```
Now let's call foo
```
x=[]
foo(x)
#List is empty
foo('')
#List is empty
```
But if x=[''] the list is not considered as empty!!!
```
x=['']
foo(x)
#List is not empty
```
Questions -
1.... | Using the built-in `any()`
```
def foo(l=[]):
if any(l):
print 'List is not empty'
else:
print 'List is empty'
foo([''])
# List is empty
``` |
Error message "no handlers could be found for logger ZODB.FileStorage" on copied ZODB database | 11,191,398 | 12 | 2012-06-25T14:36:16Z | 11,195,734 | 26 | 2012-06-25T19:09:48Z | [
"python",
"logging"
] | I created a database using `ZODB`, then I copied-pasted it to another PC. I wonder why every time I log in this database (the copied one) I get this error:
```
no handlers could be found for logger (ZODB.FileStorage)
```
Note: the program doesn't break, it just print out the statement in red as if it's an error.
Wha... | **Short Answer**
You don't *need* to configure it for your application. Its useful to do so.
**Long Answer**
The [logging](http://docs.python.org/library/logging.html) module is a python module that allows any python code to log information in a way that is output-agnostic to the actual application using it. Librari... |
Why do python .pyc files contain the absolute path of their source code? | 11,191,680 | 12 | 2012-06-25T14:52:36Z | 11,218,099 | 8 | 2012-06-27T01:15:30Z | [
"python"
] | Why do python `.pyc` files contain the absolute path of their source code, instead of a relative path or something else?
A typical `__init__.pyc` from Python 2.7 on Ubuntu:
`\ufffd\ufffd\ufffdOc@sddlTdS(i\ufffd\ufffd\ufffd\ufffd(t*N(tdbapi2(((s&/usr/lib/python2.7/sqlite3/__init__.py<module>s` | To give the information in tracebacks. See for instance <http://docs.python.org/library/compileall#cmdoption-compileall-d> |
Convert a datetime.date object into a datetime.datetime object with zeros for any missing time attributes | 11,192,814 | 3 | 2012-06-25T15:55:15Z | 11,192,834 | 10 | 2012-06-25T15:56:51Z | [
"python",
"date",
"datetime",
"python-datetime"
] | Is there a built-in function that converts a datetime.date object into a datetime.datetime object with 0's for the missing stuff? For example, suppose
```
tdate = datetime.date(2012,1,31)
```
I want to write something like either of these
```
tdatetime = datetime.date.datetime()
tdatetime = datetime.datetime(tdate)
... | Use [`.combine(date, time)`](http://docs.python.org/library/datetime.html#datetime.datetime.combine) with an empty [`time` instance](http://docs.python.org/library/datetime.html#time-objects):
```
>>> import datetime
>>> tdate = datetime.date(2012,1,31)
>>> datetime.datetime.combine(tdate, datetime.time())
datetime.da... |
'int' object has no attribute '__getitem__' | 11,194,110 | 21 | 2012-06-25T17:18:51Z | 11,194,185 | 30 | 2012-06-25T17:24:37Z | [
"python",
"runtime-error"
] | ```
import math
import os
class collection:
col = [[0 for col in range(5)] for row in range(6)]
dist = [[0 for col in range(6)] for row in range(6)]
filename = ""
result = ""
def __init__(self,arg1):
self.filename = arg1
def coll(self):
for i in range(6):
try:
... | The error:
```
'int' object has no attribute '__getitem__'
```
means that you're attempting to apply the index operator `[]` on an int, not a list. So is `col` not a list, even when it should be? Let's start from that.
Look here:
```
col = [[0 for col in range(5)] for row in range(6)]
```
Use a different variable ... |
Convert a directory structure in the filesystem to JSON with Node.js | 11,194,287 | 29 | 2012-06-25T17:31:15Z | 11,194,896 | 42 | 2012-06-25T18:14:00Z | [
"javascript",
"python",
"django",
"node.js",
"filesystems"
] | I have a file structure like this:
```
root
|_ fruits
|___ apple
|______images
|________ apple001.jpg
|________ apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg
```
I would like to, using Javascript and Node.js, listen to this root directory and all sub directories and create a... | Here's a sketch. Error handling is left as an exercise for the reader.
```
var fs = require('fs'),
path = require('path')
function dirTree(filename) {
var stats = fs.lstatSync(filename),
info = {
path: filename,
name: path.basename(filename)
};
if (stats.isDirector... |
Convert a directory structure in the filesystem to JSON with Node.js | 11,194,287 | 29 | 2012-06-25T17:31:15Z | 31,831,122 | 8 | 2015-08-05T11:23:18Z | [
"javascript",
"python",
"django",
"node.js",
"filesystems"
] | I have a file structure like this:
```
root
|_ fruits
|___ apple
|______images
|________ apple001.jpg
|________ apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg
```
I would like to, using Javascript and Node.js, listen to this root directory and all sub directories and create a... | The accepted answer works, but it is *synchronous* and will deeply hurt your performance, especially for large directory trees.
I highly encourage you to use the following **asynchronous** solution, it is both faster and non-blocking.
Based on the parallel solution [here](http://stackoverflow.com/a/5827895/3017785)... |
Deleting information from an HDF5 file | 11,194,927 | 13 | 2012-06-25T18:15:36Z | 11,214,815 | 12 | 2012-06-26T19:41:59Z | [
"python",
"hdf5"
] | I realize that a SO user has formerly asked this [question](http://stackoverflow.com/questions/1124994/removing-data-from-a-hdf5-file?rq=1) but it was asked in 2009 and I was hoping that more knowledge of HDF5 was available or newer versions had fixed this particular issue. To restate the question here concerning my ow... | Removing entire nodes (groups or datasets) from a hdf5 file should be no problem.
However if you want to reclaim the space you have to run the `h5repack` tool.
From the [hdf5 docs](http://www.hdfgroup.org/HDF5/doc/UG/UG_frame10Datasets.html):
> 5.5.2. Deleting a Dataset from a File and Reclaiming Space
>
> HDF5 doe... |
Break or exit out of "with" statement? | 11,195,140 | 11 | 2012-06-25T18:30:17Z | 11,195,196 | 13 | 2012-06-25T18:33:55Z | [
"python",
"with-statement"
] | I'd just like to exit out of a `with` statement under certain conditions:
```
with open(path) as f:
print 'before condition'
if <condition>: break #syntax error!
print 'after condition'
```
Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition: `if not <cond... | The best way would be to encapsulate it in a function and use `return`:
```
def do_it():
with open(path) as f:
print 'before condition'
if <condition>:
return
print 'after condition'
``` |
Break or exit out of "with" statement? | 11,195,140 | 11 | 2012-06-25T18:30:17Z | 23,665,658 | 17 | 2014-05-14T21:43:07Z | [
"python",
"with-statement"
] | I'd just like to exit out of a `with` statement under certain conditions:
```
with open(path) as f:
print 'before condition'
if <condition>: break #syntax error!
print 'after condition'
```
Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition: `if not <cond... | `with` giving you trouble? Throw more `with`-able objects at the problem!
```
class fragile(object):
class Break(Exception):
"""Break out of the with statement"""
def __init__(self, value):
self.value = value
def __enter__(self):
return self.value.__enter__()
def __exit__(self,... |
Processing single file from multiple processes in python | 11,196,367 | 34 | 2012-06-25T19:54:19Z | 11,196,615 | 46 | 2012-06-25T20:11:29Z | [
"python",
"multithreading",
"multiprocessing"
] | I have a single big text file in which I want to process each line ( do some operations ) and store them in a database. Since a single simple program is taking too long, I want it to be done via multiple processes or threads.
Each thread/process should read the DIFFERENT data(different lines) from that single file and ... | What you are looking for is a Producer/Consumer pattern
**Basic threading example**
Here is a basic example using the [threading module](http://docs.python.org/library/threading.html) (instead of multiprocessing)
```
import threading
import Queue
import sys
def do_work(in_queue, out_queue):
while True:
... |
How do I yield results from a nested Python generator function? | 11,197,186 | 7 | 2012-06-25T20:52:26Z | 11,197,219 | 9 | 2012-06-25T20:54:24Z | [
"python",
"function",
"nested",
"generator",
"yield"
] | I have a function which yields results as it downloads them. For the purposes of this question, lets say I yield a sting once every second but I want a convenience function to wrap my generator:
```
import time
def GeneratorFunction(max_val):
for i in range(0,5):
time.sleep(1)
yield "String %d"%i
... | Can't believe I missed this; The answer is to simply return the generator function with suitable arguments applied:
```
import time
def GeneratorFunction(max_val):
for i in range(0,5):
time.sleep(1)
yield "String %d"%i
def SmallGenerator():
return GeneratorFunction(3) # <-- note the use of re... |
How do I yield results from a nested Python generator function? | 11,197,186 | 7 | 2012-06-25T20:52:26Z | 11,197,245 | 18 | 2012-06-25T20:56:16Z | [
"python",
"function",
"nested",
"generator",
"yield"
] | I have a function which yields results as it downloads them. For the purposes of this question, lets say I yield a sting once every second but I want a convenience function to wrap my generator:
```
import time
def GeneratorFunction(max_val):
for i in range(0,5):
time.sleep(1)
yield "String %d"%i
... | SmallGenerator need to be something around:
```
def SmallGenerator():
for item in GeneratorFunction(3):
yield item
```
In your implementation SmallGenerator yields an actual generator, not the items generated by it. |
Writing to a file in a for loop | 11,198,718 | 10 | 2012-06-25T23:13:25Z | 11,198,743 | 14 | 2012-06-25T23:16:08Z | [
"python",
"python-2.7"
] | ```
text_file = open("new.txt", "r")
lines = text_file.readlines()
for line in lines:
var1, var2 = line.split(",");
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
text_file.close()
```
I have 10 lines of text in new.txt like Adam:8154
George:5234 and so on. Now i... | That is because you are opening , writing and closing the file 10 times inside your for loop
```
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
```
You should open and close your file outside for loop.
```
myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
my... |
Writing to a file in a for loop | 11,198,718 | 10 | 2012-06-25T23:13:25Z | 11,198,757 | 7 | 2012-06-25T23:18:10Z | [
"python",
"python-2.7"
] | ```
text_file = open("new.txt", "r")
lines = text_file.readlines()
for line in lines:
var1, var2 = line.split(",");
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
text_file.close()
```
I have 10 lines of text in new.txt like Adam:8154
George:5234 and so on. Now i... | The main problem was that you were opening/closing files repeatedly inside your loop.
Try this approach:
```
with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:
for line in text_file:
var1, var2 = line.split(",");
myfile.write(var1+'\n')
```
We open both files at once and because... |
Error message for virtualenvwrapper on OS X Lion | 11,199,360 | 9 | 2012-06-26T00:41:31Z | 11,199,458 | 14 | 2012-06-26T00:54:52Z | [
"python",
"osx-lion",
"virtualenv",
"homebrew"
] | I've used homebrew to install python on a new Mac Lion installation, and have been trying to install virtualenv and virtualenvwrapper with pip, but when I start a new terminal session, I get this traceback:
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named virtu... | Since you have your own version of python, have you tried overriding VIRTUALENVWRAPPER\_PYTHON? (It looks like you want `export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python`) [The virtualenvwrapper docs](http://www.doughellmann.com/docs/virtualenvwrapper/install.html#python-interpreter-virtualenv-and-path) suggest se... |
Send dict as response in Python Bottle with custom status code | 11,200,018 | 3 | 2012-06-26T02:27:37Z | 11,200,057 | 9 | 2012-06-26T02:36:22Z | [
"python",
"json",
"http",
"bottle"
] | ```
import bottle
from bottle import route, run
@route('/', method='GET')
def homepage():
return {'foo' : 'bar'}
if __name__=='__main__':
bottle.debug(True)
run(host='0.0.0.0', port= 8080, reloader = True)
```
This config will return a json object representing the dict from homepage with HTTP status code... | You can set the `response.status` attribute:
```
from bottle import response
@route('/', method='GET')
def homepage():
response.status = 202
return {'foo' : 'bar'}
``` |
How can my chameleon template accept message flashes from the pyramid framework? | 11,200,430 | 7 | 2012-06-26T03:32:13Z | 11,207,378 | 10 | 2012-06-26T12:30:44Z | [
"python",
"pyramid",
"chameleon",
"template-tal"
] | I'm learning pyramid and it seems they are trying to get people to use chameleon instead of mako so I thought I'd give chameleon a chance. I like it so far and I can do basic things in the template such as if and for loops but I'm not sure how to get message flashes to appear.
In the pyramid tutorial they do this in a... | The (untested) equivalent in chameleon is:
```
<div id="flash" tal:condition="request.session.peek_flash()">
<span tal:omit-tag=""
tal:repeat="message request.session.pop_flash()">
${message}<br>
</span>
</div>
```
The [`tal:omit-tag` attribute](http://chameleon.repoze.org/docs/latest/reference.htm... |
How to read /dev/random in python | 11,200,636 | 4 | 2012-06-26T04:06:01Z | 11,200,868 | 12 | 2012-06-26T04:41:48Z | [
"python",
"unix"
] | I read in a book that `/dev/random` is like an infinite file, but when I set up the following codes to see what the content look like, it prints nothing.
```
with open("/dev/random") as f:
for i in xrange(10):
print f.readline()
```
BTW, when I tried this with `/dev/urandom`, it worked. | FWIW, the preferred way of accessing this stream (or something like it) in a semi-portable way is *[os.urandom()](http://docs.python.org/library/os.html#os.urandom)* |
scrapy authentication login with cookies | 11,200,926 | 6 | 2012-06-26T04:51:23Z | 11,201,465 | 10 | 2012-06-26T05:55:20Z | [
"python",
"authentication",
"selenium",
"login",
"scrapy"
] | i am new to scrapy and decided to try it out because of good online reviews. I am trying to login to a website with scrapy. I have successfully logged in with a combination of selenium and mechanize by collecting the needed cookies with selenium and adding them to mechanize. Now I am trying to do something similar with... | Your question is more of debug issue, so my answer will have just some notes on your question, not the exact answer.
```
def parse(self, response,my_cookies=get_cookies):
return Request(url="http://my_domain.com/",
cookies=my_cookies,
callback=self.login)
```
`my_cookies=get_cookies` - you are ass... |
Why does the 'int' object is not callable error occur when using the sum() function? | 11,201,801 | 2 | 2012-06-26T06:28:29Z | 11,201,835 | 13 | 2012-06-26T06:31:09Z | [
"python",
"sum",
"python-2.7",
"callable"
] | I'm trying to figure out why I'm getting an error when using the sum function on a range.
Here is the code:
```
data1 = range(0, 1000, 3)
data2 = range(0, 1000, 5)
data3 = list(set(data1 + data2)) # makes new list without duplicates
total = sum(data3) # calculate sum of data3 list's elements
print total
```
And here... | This means that somewhere else in your code, you have something like:
```
sum = 0
```
Which shadows the builtin sum (which *is* callable) with an int (which isn't). |
Why does the 'int' object is not callable error occur when using the sum() function? | 11,201,801 | 2 | 2012-06-26T06:28:29Z | 11,201,943 | 8 | 2012-06-26T06:41:29Z | [
"python",
"sum",
"python-2.7",
"callable"
] | I'm trying to figure out why I'm getting an error when using the sum function on a range.
Here is the code:
```
data1 = range(0, 1000, 3)
data2 = range(0, 1000, 5)
data3 = list(set(data1 + data2)) # makes new list without duplicates
total = sum(data3) # calculate sum of data3 list's elements
print total
```
And here... | You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
```
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" fo... |
Generate presentation with Python | 11,202,648 | 3 | 2012-06-26T07:33:39Z | 17,069,465 | 8 | 2013-06-12T15:30:02Z | [
"python",
"powerpoint",
"openxml",
"openoffice-impress"
] | I'm working with data processing and want to generate PowerPoint or OpenOffice Impress presentation with some data analysis directly from Python. Is there any libraries for Python to do that? I'm using Unix enviroment. | Looks like this is starting to come along well: <https://github.com/scanny/python-pptx/> |
How to perform partial inheritance | 11,204,053 | 2 | 2012-06-26T09:09:37Z | 11,204,743 | 9 | 2012-06-26T09:50:59Z | [
"python",
"inheritance"
] | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible... | The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplemented... |
How to properly use python's isinstance() to check if a variable is a number? | 11,204,789 | 24 | 2012-06-26T09:53:33Z | 11,204,859 | 10 | 2012-06-26T09:57:21Z | [
"python",
"python-2.5",
"pep8"
] | I found some old Python code that was doing something like:
```
if type(var) is type(1):
...
```
As expected, `pep8` complains about this recommending usage of `isinstance()`.
Now, the problem is that the `numbers` module was added in Python 2.6 and I need to write code that works with Python 2.5+
So `if isinsta... | Python 2 supports four types for numbers `int`,`float`, `long` and `complex`and `python 3.x` supports 3:`int`, `float` and `complex`
```
>>> num = 10
>>> if isinstance(num, (int, float, long, complex)): #use tuple if checking against multiple types
print('yes it is a number')
yes it is a number
>>> isinstance(n... |
How to properly use python's isinstance() to check if a variable is a number? | 11,204,789 | 24 | 2012-06-26T09:53:33Z | 11,204,870 | 61 | 2012-06-26T09:57:53Z | [
"python",
"python-2.5",
"pep8"
] | I found some old Python code that was doing something like:
```
if type(var) is type(1):
...
```
As expected, `pep8` complains about this recommending usage of `isinstance()`.
Now, the problem is that the `numbers` module was added in Python 2.6 and I need to write code that works with Python 2.5+
So `if isinsta... | You can use the [`types` module](http://docs.python.org/library/types.html):
```
>>> import types
>>> var = 1
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
>>> isinstance(var, NumberTypes)
True
```
Note the use of a tuple to test against multiple types.
Under the hood, `IntTyp... |
Detect period of unknown source | 11,205,037 | 5 | 2012-06-26T10:09:35Z | 11,210,226 | 8 | 2012-06-26T15:01:08Z | [
"python",
"algorithm",
"math",
"floyd-cycle-finding"
] | How to detect repeating digits in an infinite sequence? I tried **Floyd & Brent** detection algorithm but come to nothing...
I have a generator that yields numbers ranging from 0 to 9 (inclusive) and I have to recognize a period in it.
Example test case:
```
import itertools
# of course this is a fake one just to of... | # Empirical methods
Here's a fun take on the problem. The more general form of your question is this:
> Given a repeating sequence of unknown length, determine the period of
> the signal.
The process to determine the repeating frequencies is known as the [Fourier Transform](http://en.wikipedia.org/wiki/Fourier_trans... |
How to convert UTF8 string into HTML string in python 2.5 for correct accent displaying? | 11,205,105 | 3 | 2012-06-26T10:13:23Z | 11,205,316 | 7 | 2012-06-26T10:25:57Z | [
"python",
"html",
"utf-8"
] | My string UFT8, coming from a database (CSV file encoded in UTF8) is displayed like this on a browser with my main.py code: `value ="roulement \u00e0 billes"`
=> how to convert any of such string into HTML entities, such as value="roulement à billes" in order to display correctly as `roulement à billes` with a ... | First you should make sure `value` is of type unicode and not a string
```
value.encode('ascii', 'xmlcharrefreplace')
```
Should get you the HTML enitites
[Python Unicode Documentation](http://docs.python.org/howto/unicode.html)
```
>>> value = u"roulement \u00e0 billes"
>>> print value
roulement à billes
>>> prin... |
has_header from csv.Sniffer gives different results for files with same layout | 11,205,128 | 7 | 2012-06-26T10:14:53Z | 11,243,883 | 13 | 2012-06-28T11:43:41Z | [
"python",
"csv"
] | I have the following snippet of code:
```
import csv
def has_header(first_lines):
sniffer = csv.Sniffer()
return sniffer.has_header(first_lines)
```
Where `first_lines` are the first 2048 bytes of the file. The function works well most of the time and returns `True` for a file that begins like this:
```
SPE... | when i try this (with `data1` being your first and `data2` your second sample:
```
for data in (data1, data2):
s=csv.Sniffer()
d = s.sniff(data)
print(repr(d.delimiter))
```
I get:
```
' '
'7'
```
That means the problem is actually the detection of the delimiter. As you can see [in docstring of \_guess\... |
Why don't list operations return the resulting list? | 11,205,254 | 3 | 2012-06-26T10:21:52Z | 11,205,638 | 8 | 2012-06-26T10:44:30Z | [
"python"
] | I'm interested in the thought process that led to this. To me, a relative newbie, it seems hampering, since it prevents "chaining" of list processing (e.g. `mylist.reverse().append('a string')[:someLimit]`). I imagine it might be that "The Powers That Be" decided that list comprehension is a better paradigm (a valid op... | The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned... GvR's (our Python BDFL) states the design choice here: <http://mail.python.org/pi... |
Python: BeautifulSoup - get an attribute value based on the name attribute | 11,205,386 | 25 | 2012-06-26T10:29:43Z | 11,205,758 | 53 | 2012-06-26T10:51:26Z | [
"python",
"beautifulsoup"
] | I want to print an attribute value based on its name, take for example
```
<META NAME="City" content="Austin">
```
I want to do something like this
```
soup = BeautifulSoup(f) //f is some HTML containing the above meta tag
for meta_tag in soup('meta'):
if meta_tag['name'] == 'City':
print meta_tag['cont... | It's pretty simple, use the following -
```
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']
u'Austin'
```
Leave a comment if anything is not clear. |
Python: Map list of two-entry-dicts to dict with first entry as key and second as value | 11,206,434 | 2 | 2012-06-26T11:33:24Z | 11,206,464 | 7 | 2012-06-26T11:35:19Z | [
"python"
] | I have something like this:
```
[{'date': 1, 'value':5}, {'date':2,'value':3}, ...]
```
and want to map the values this two keys to this:
```
{1:5, 2:3, ...}
```
How can I do this in a nice way? | ```
>>> lis = [{'date': 1, 'value':5}, {'date':2,'value':3}]
>>> {x['date']:x['value'] for x in lis}
{1: 5, 2: 3}
``` |
How to Print next year from current year in Python | 11,206,489 | 30 | 2012-06-26T11:37:08Z | 11,206,511 | 91 | 2012-06-26T11:38:40Z | [
"python",
"datetime"
] | How can I print the next year if the current year is given in python using the simplest code, possibly in one line using datetime module. | Both date and datetime objects have a `year` attribute, which is a number. Just add 1:
```
>>> from datetime import date
>>> print date.today().year + 1
2013
```
If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:
```
>>> year = 2012
>>> print year + 1
2013
``... |
How to write Python sort key functions for descending values | 11,206,884 | 22 | 2012-06-26T12:00:52Z | 11,207,326 | 16 | 2012-06-26T12:26:52Z | [
"python",
"sorting"
] | The move in recent versions of Python to passing a *key* function to `sort()` from the previous *cmp* function is making it trickier for me to perform complex sorts on certain objects.
For example, I want to sort a set of objects from newest to oldest, with a set of string tie-breaker fields. So I want the dates in re... | The most generic way to do this is simply to sort separately by each key in turn. Python's sorting is always stable so it is safe to do this:
```
sort(data, key=tiebreakerkey)
sort(data, key=datekey, reverse=True)
```
will (assuming the relevant definitions for the key functions) give you the data sorted by descendin... |
How to write Python sort key functions for descending values | 11,206,884 | 22 | 2012-06-26T12:00:52Z | 11,207,560 | 10 | 2012-06-26T12:41:09Z | [
"python",
"sorting"
] | The move in recent versions of Python to passing a *key* function to `sort()` from the previous *cmp* function is making it trickier for me to perform complex sorts on certain objects.
For example, I want to sort a set of objects from newest to oldest, with a set of string tie-breaker fields. So I want the dates in re... | I think the docs are incomplete. I interpret the word "primarily" to mean that there are still reasons to use cmp\_to\_key, and this is one of them. `cmp` was removed because it was an "attractive nuisance:" people would gravitate to it, even though `key` was a better choice.
But your case is clearly better as a `cmp`... |
How to write Python sort key functions for descending values | 11,206,884 | 22 | 2012-06-26T12:00:52Z | 11,207,585 | 7 | 2012-06-26T12:42:36Z | [
"python",
"sorting"
] | The move in recent versions of Python to passing a *key* function to `sort()` from the previous *cmp* function is making it trickier for me to perform complex sorts on certain objects.
For example, I want to sort a set of objects from newest to oldest, with a set of string tie-breaker fields. So I want the dates in re... | The slow-but-elegant way to do this is to create a value wrapper that has reversed ordering:
```
from functools import total_ordering
@total_ordering
class ReversedOrder:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return other.value == self.value
def __lt__(self,... |
Is it possible to read FTP files without writing them using Python? | 11,208,957 | 14 | 2012-06-26T13:56:30Z | 11,209,373 | 22 | 2012-06-26T14:17:35Z | [
"python",
"ftp",
"ftplib"
] | I am trying to read files using Python's ftplib without writing them. Something roughly equivalent to:
```
def get_page(url):
try:
return urllib.urlopen(url).read()
except:
return ""
```
but using FTP.
I tried:
```
def get_page(path):
try:
ftp = FTP('ftp.site.com', 'anonymous', '... | Well, you have the answer right in front of you: The retrbinary method accepts as second parameter a reference to a function that is called whenever file content is retrieved from the ftp connection.
Here is a simple example:
```
#!/usr/bin/env python
from ftplib import FTP
def writeFunc(s):
print "Read: " + s
ft... |
Waterfall plot python? | 11,209,646 | 11 | 2012-06-26T14:29:14Z | 11,221,289 | 16 | 2012-06-27T07:26:22Z | [
"python",
"matlab",
"numpy",
"matplotlib",
"scipy"
] | Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything. | You can do a waterfall in matplotlib using the [PolyCollection](http://matplotlib.sourceforge.net/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](http://matplotlib.sourceforge.net/examples/mplot3d/polys3d_demo.html) to have more details on how ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.