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 |
|---|---|---|---|---|---|---|---|---|---|
Is there an efficient way of concatenating scipy.sparse matrices? | 6,844,998 | 20 | 2011-07-27T13:20:09Z | 6,853,880 | 13 | 2011-07-28T03:46:45Z | [
"python",
"concatenation",
"scipy",
"sparse-matrix"
] | I'm working with some rather large sparse matrices (from 5000x5000 to 20000x20000) and need to find an efficient way to concatenate matrices in a flexible way in order to construct a stochastic matrix from separate parts.
Right now I'm using the following way to concatenate four matrices, but it's horribly inefficient... | Okay, I found the answer. Using scipy.sparse.coo\_matrix is much much faster than using lil\_matrix. I converted the matrices to coo (painless and fast) and then just concatenated the data, rows and columns after adding the right padding.
```
data = scipy.concatenate((m1S.data,bridgeS.data,bridgeTS.data,m2S.data))
row... |
Is there an efficient way of concatenating scipy.sparse matrices? | 6,844,998 | 20 | 2011-07-27T13:20:09Z | 10,557,162 | 33 | 2012-05-11T19:02:54Z | [
"python",
"concatenation",
"scipy",
"sparse-matrix"
] | I'm working with some rather large sparse matrices (from 5000x5000 to 20000x20000) and need to find an efficient way to concatenate matrices in a flexible way in order to construct a stochastic matrix from separate parts.
Right now I'm using the following way to concatenate four matrices, but it's horribly inefficient... | The sparse library now has [`hstack`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html#scipy.sparse.hstack) and [`vstack`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.vstack.html#scipy.sparse.vstack) for respectively concatenating matrices horizontally and vertically. |
MP3 audio file splitting with Python | 6,846,413 | 7 | 2011-07-27T14:51:04Z | 7,441,350 | 7 | 2011-09-16T07:17:34Z | [
"python",
"mp3",
"slice"
] | I have mp3 files and i want to slice these into samples, by giving a start and end time to a library function.
Does anyone know which python library suits me to do this?? | [Mp3splt](http://mp3splt.sourceforge.net/mp3splt_page/home.php), This works fabulously :)
Example:
```
import os
os.system("mp3splt inputfile.mp3")
``` |
Choose 1 element per index randomly from list A or B in Python | 6,846,468 | 2 | 2011-07-27T14:54:55Z | 6,846,551 | 10 | 2011-07-27T14:59:58Z | [
"python",
"list",
"random"
] | I have 2 lists in Python and I want to choose, for every index either an element from list A or list B.
I managed to do it easily but this solution has bad performance and it doesn't seem very elegant.
Can anybody sugest an alternative that doesn't rely in these **for** cycles with **if**'s inside?
I'll post the co... | ```
import random
from itertools import izip
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [0, 1, 2, 3, 4, 5]
[random.choice(pair) for pair in izip(l1, l2)]
# e.g. [0, 1, 'c', 3, 'e', 'f']
``` |
Checking if a datetime object in mongodb is in UTC format or not from python | 6,846,851 | 4 | 2011-07-27T15:19:58Z | 7,047,788 | 9 | 2011-08-13T00:48:39Z | [
"python",
"datetime",
"pymongo",
"pytz"
] | In `mongodb`, a field called `joining_date` appears as
```
"Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)"
```
This as you see is a UTC date .
But the same field when accessed from pymongo appears as
```
datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
```
From python i need to check that the date is in utc format or... | `datetime` objects returned by pymongo always represent a time in UTC, just as dates stored in MongoDB are always stored as (that is, assumed to be in) UTC.
pymongo can convert your `datetime`s automatically to be time zone aware if you set the `tz_info` flag to `True` when creating your `Connection`. You can then use... |
Search and remove element with elementTree in Python | 6,847,263 | 10 | 2011-07-27T15:45:06Z | 6,847,633 | 10 | 2011-07-27T16:07:51Z | [
"python",
"elementtree"
] | I have an XML document in which I want to search for some elements and if they match some criteria
I would like to delete them
However, I cannot seem to be able to access the parent of the element so that I can delete it
```
file = open('test.xml', "r")
elem = ElementTree.parse(file)
namespace = "{http://somens}"
p... | You can remove child elements with the according `remove` method. To remove an element you have to call its parents `remove` method. Unfortunately `Element` does not provide a reference to its parents, so it is up to you to keep track of parent/child relations (which speaks against your use of `elem.findall()`)
A prop... |
Push messages to clients in Python | 6,848,276 | 4 | 2011-07-27T16:59:10Z | 6,848,331 | 7 | 2011-07-27T17:03:05Z | [
"python",
"real-time"
] | How can I implement a system that can "push" messages to clients when necessary?
Basically, what I need is the ability to "push" text to Python clients from a Python server. The text will then be parsed to actions that will take care at the client side (I already know how to do this thing, once an 'action-text' is rece... | You can use redis publish subscribe model [more here](http://redis.io/topics/pubsub).
[Redis](http://redis.io/) is highly scalable and fast.
Example: (From <https://github.com/andymccurdy/redis-py/blob/master/tests/pubsub.py>)
```
import redis
import unittest
class PubSubTestCase(unittest.TestCase):
def setUp(s... |
process large text file in python | 6,848,857 | 4 | 2011-07-27T17:48:37Z | 6,850,260 | 9 | 2011-07-27T19:40:36Z | [
"python",
"text-files"
] | I have a very large file (3.8G) that is an extract of users from a system at my school. I need to reprocess that file so that it just contains their ID and email address, comma separated.
I have very little experience with this and would like to use it as a learning exercise for Python.
The file has entries that look... | That actually looks like an [LDIF](http://tools.ietf.org/html/rfc2849) file to me. The [python-ldap](http://www.python-ldap.org/doc/html/ldif.html) library has a pure-Python LDIF handling library that could help if your file possesses some of the nasty gotchas possible in LDIF, e.g. Base64-encoded values, entry folding... |
how do I specify extended ascii (i.e. range(256)) in the python magic encoding specifier line? | 6,850,486 | 9 | 2011-07-27T20:00:13Z | 6,852,271 | 12 | 2011-07-27T23:03:01Z | [
"python",
"templates",
"encoding",
"wsgi",
"mako"
] | I'm using mako templates to generate specialized config files. Some of these files contain extended ASCII chars (>127), but mako chokes saying that the chars are out of range when I use:
```
## -*- coding: ascii -*-
```
So I'm wondering if perhaps there's something like:
```
## -*- coding: eascii -*-
```
That I can... | **Short answer**
Use cp437 as the encoding for some retro DOS fun. All byte values greater than or equal to 32 decimal, except 127, are mapped to displayable characters in this encoding. Then use cp037 as the encoding for a truly trippy time. And then ask yourself how do you really know which of these, if either of th... |
Python and Smalltalk - Metaprogramming capabilities comparison | 6,852,189 | 10 | 2011-07-27T22:52:16Z | 6,853,978 | 12 | 2011-07-28T04:08:14Z | [
"python",
"oop",
"programming-languages",
"metaprogramming",
"smalltalk"
] | I have of late been learning Python, and am amazed by its superb runtime metaprogramming capabilities. Previously I came across the term 'runtime metaprogramming' was when I was reading about Smalltalk, which as far as I know boasts of best runtime metaprogramming capabilities. How well does Python stack up against Sma... | Python actually holds up fairly well here. Smalltalk usually doesn't make explicit distinction between program and metaprogramm, but Python is more explicit - eg, the special syntax for decorators or the `__foo__()` naming convention for metaprogramming hooks. This is a good thing.
On the other hand, it's a bit of an ... |
Python and Smalltalk - Metaprogramming capabilities comparison | 6,852,189 | 10 | 2011-07-27T22:52:16Z | 6,864,488 | 10 | 2011-07-28T19:22:52Z | [
"python",
"oop",
"programming-languages",
"metaprogramming",
"smalltalk"
] | I have of late been learning Python, and am amazed by its superb runtime metaprogramming capabilities. Previously I came across the term 'runtime metaprogramming' was when I was reading about Smalltalk, which as far as I know boasts of best runtime metaprogramming capabilities. How well does Python stack up against Sma... | Posted as an answer at questioner's request.
One of the big ideas of Smalltalk is orthogonality. Frankly Python suffers in this respect. Not everything works on everything. Examples:
* `inspect.getargspec()` does not work on built-in functions or the results of calls to `functools.partial` (in the C interpreter anywa... |
Python: Using addition to modify dictionary values | 6,852,819 | 3 | 2011-07-28T00:23:21Z | 6,852,831 | 12 | 2011-07-28T00:25:14Z | [
"python",
"dictionary",
"addition"
] | This is my first programming post as well as well my first program so please bear with me.
I have a dicionary that is initialized like so:
```
tab = ({'Mike': 0, 'Chad': 15, 'Taylor': 2})
```
I want to be able to add integers to each value in the dictionary.
For example, after adding 5, the dictionary should look ... | The easiest way?
```
for k in tab.keys():
tab[k] += 5
``` |
How do I make a PATCH request in Python? | 6,853,050 | 11 | 2011-07-28T01:02:07Z | 7,112,444 | 20 | 2011-08-18T18:41:40Z | [
"python",
"http",
"patch",
"httplib"
] | Is there a way to make a request using PATCH http method in Python?
I tried using httplib, but it doesn't accept PATCH as method param. | With [Requests](http://python-requests.org), making [PATCH requests](http://docs.python-requests.org/en/latest/api/#requests.patch) is very simple:
```
import requests
r = requests.patch('http://httpbin.org/patch')
``` |
How do I make a PATCH request in Python? | 6,853,050 | 11 | 2011-07-28T01:02:07Z | 9,023,005 | 8 | 2012-01-26T18:07:14Z | [
"python",
"http",
"patch",
"httplib"
] | Is there a way to make a request using PATCH http method in Python?
I tried using httplib, but it doesn't accept PATCH as method param. | Seems to work in 2.7.1 as well.
```
>>> import urllib2
>>> request = urllib2.Request('http://google.com')
>>> request.get_method = lambda: 'PATCH'
>>> resp = urllib2.urlopen(request)
Traceback (most recent call last):
...
urllib2.HTTPError: HTTP Error 405: Method Not Allowed
``` |
Postgres/psycopg2 - Inserting array of strings | 6,853,161 | 5 | 2011-07-28T01:22:31Z | 6,858,473 | 11 | 2011-07-28T11:51:47Z | [
"python",
"postgresql",
"psycopg2"
] | I'm using Postgres 9 and Python 2.7.2 along with psycopg2 and am trying to insert an array of string values with properly escaped quotation marks. Sample:
```
metadata = {"Name": "Guest", "Details": "['One', 'Two', 'Three']"}
cur.execute("insert into meta values ('%s');" % metadata)
```
which throws the exception:
... | You have to let psycopg do parameters binding for you: don't try to quote them yourself.
Psycopg automatically converts a python list of strings into a postgres array. Check <http://initd.org/psycopg/docs/usage.html> |
GeoDjango distance queries returning incorrect results | 6,853,800 | 6 | 2011-07-28T03:31:16Z | 6,869,548 | 7 | 2011-07-29T06:42:53Z | [
"python",
"django",
"postgresql",
"postgis",
"geodjango"
] | I just got GeoDjango up and running on my development machine. Problem is that I can't get a distance query to work correctly. No matter what SRID I use, the distance results are totally off. Here's an example.
```
>>> from django.contrib.gis.measure import D
>>> from app.models import Place
>>> from django.contrib.gi... | I hate to be answering my own question, but no one else stepped up to the plate and I figured out the solution.
I delved into PostGIS to isolate the issue to either the location database itself or to Django. So I converted the Django ORM query I had been using above into the ideal query that I would have expected the ... |
Is it necessary to include __init__ as the first function everytime in a class in Python? | 6,854,080 | 10 | 2011-07-28T04:27:01Z | 6,854,096 | 22 | 2011-07-28T04:29:48Z | [
"python"
] | I am new to Python and I want to know that whether it is necessary to include `__init__` as the first method while creating a class, as in the example below:
```
class ExampleClass:
def __init__(self, some_message):
self.message = some_message
print "New Class instance created, with message:"
... | No, it isn't necessary.
For example.
```
class A(object):
def f():
print 'foo'
```
And you can of course use it, in this manner:
```
a = A()
a.f()
```
In fact you can even define a class in this manner.
```
class A:
pass
```
However, defining `__init__` is a common practice because instances of a... |
Django Celery tutorial not returning results | 6,854,133 | 11 | 2011-07-28T04:35:49Z | 6,933,870 | 14 | 2011-08-03T22:04:32Z | [
"python",
"django",
"rabbitmq",
"celery"
] | **UDATE3:** found the issue. See the answer below.
**UPDATE2:** It seems I might have been dealing with an automatic naming and relative imports problem by running the djcelery tutorial through the manage.py shell, see below. It is still not working for me, but now I get new log error messages. See below.
**UPDATE:**... | I found the solution to my problem from another stackoverflow post: [Why does Celery work in Python shell, but not in my Django views? (import problem)](http://stackoverflow.com/questions/4643065/why-does-celery-work-in-python-shell-but-not-in-my-django-views-import-problem/6899753#6899753)
I had to add these lines to... |
Explain the "setup" and "teardown" methods used in test cases? | 6,854,658 | 33 | 2011-07-28T05:59:22Z | 6,854,681 | 17 | 2011-07-28T06:02:05Z | [
"python",
"unit-testing"
] | Can anyone explain me about the use of "setup" and "teardown" while writing test cases apart from this that setup is called immediately before calling the test method and teardown is called immediately after the test method has been called.. | You can use these to factor out code common to all tests in the test suite.
If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.
You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.
If you're doing... |
Explain the "setup" and "teardown" methods used in test cases? | 6,854,658 | 33 | 2011-07-28T05:59:22Z | 6,854,727 | 24 | 2011-07-28T06:08:43Z | [
"python",
"unit-testing"
] | Can anyone explain me about the use of "setup" and "teardown" while writing test cases apart from this that setup is called immediately before calling the test method and teardown is called immediately after the test method has been called.. | In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.
You can read more with examples [here](http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest).
> When a setUp() method is defined, the test runner will run that method
> prior to each test. Likewise, if a ... |
Convolution computations in Numpy/Scipy | 6,855,169 | 14 | 2011-07-28T07:00:54Z | 6,855,416 | 9 | 2011-07-28T07:27:04Z | [
"python",
"numpy",
"scipy",
"convolution"
] | Profiling some computational work I'm doing showed me that one bottleneck in my program was a function that basically did this (`np` is `numpy`, `sp` is `scipy`):
```
def mix1(signal1, signal2):
spec1 = np.fft.fft(signal1, axis=1)
spec2 = np.fft.fft(signal2, axis=1)
return np.fft.ifft(spec1*spec2, axis=1)
... | So I tested this out and can now confirm a few things:
1) numpy.convolve is not circular, which is what the fft code is giving you:
2) FFT does not internally pad to a power of 2. Compare the vastly different speeds of the following operations:
```
x1 = np.random.uniform(size=2**17-1)
x2 = np.random.uniform(size=2**... |
Can i use all standard Python libraries with IronPython or | 6,855,211 | 9 | 2011-07-28T07:05:28Z | 6,855,367 | 9 | 2011-07-28T07:22:29Z | [
"python",
"ironpython"
] | ... does it requires some sort of wrappers?
I was under expression that IronPython is a .NET implementation of the Python which somehow magically enables applications built with IronPython to use standard Python libraries (which I believe either a raw .py sources or .py source packaged into the eggs), but when I was r... | It depends:
* If a library module is implemented in pure python, it is likely to work.
* A library module that is implemented in C will not work. The [ironclad project](http://code.google.com/p/ironclad/) aims to allow IronPython to import and use compiled Python C extensions. |
splitting list in chunks of balanced weight | 6,855,394 | 6 | 2011-07-28T07:24:49Z | 6,855,546 | 8 | 2011-07-28T07:40:28Z | [
"python",
"algorithm",
"optimization",
"language-agnostic",
"combinatorics"
] | I need an algorithm to split a list of values into such chunks, that sum of values in every chunk is (**approximately**) equals (its some variation of [Knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem), I suppose)
So, for example [1, 2, 1, 4, 10, 3, 8] => [[8, 2], [10], [1, 3, 1, 4]]
Chunks of equal le... | **Greedy:**
1. Order the available items descending.
2. Create N empty groups
3. Start adding the items one at a time into the group that has the smallest sum in it.
*I think in most real life situations this should be enough.* |
What's the equivalent of .get in javascript? | 6,855,620 | 9 | 2011-07-28T07:47:59Z | 6,855,634 | 12 | 2011-07-28T07:49:02Z | [
"javascript",
"python"
] | ```
d = {'hello':'abc'}
d.get('hello','default_val');
```
Above is python. How to do this in javascript? I want to be able to set a default value if no key found. | You have (at least) four options:
1. In many cases, you can use [the curiously-powerful `||` operator](http://blog.niftysnippets.org/2008/02/javascripts-curiously-powerful-or.html):
```
x = obj.key || "default";
```
That means: Set `x` to `obj.key` unless `obj.key` is `undefined`, `0`, `false`, `""`, or ... |
How to have logarithmic bins in a Python histogram | 6,855,710 | 38 | 2011-07-28T07:55:35Z | 6,856,155 | 58 | 2011-07-28T08:37:05Z | [
"python",
"numpy",
"matplotlib",
"histogram"
] | As far as I know the option Log=True in the histogram function only refers to the y-axis.
```
P.hist(d,bins=50,log=True,alpha=0.5,color='b',histtype='step')
```
I need the bins to be equally spaced in log10. Is there something that can do this? | use logspace() to create a geometric sequence, and pass it to bins parameter. And set the scale of xaxis to log scale.
```
import pylab as pl
import numpy as np
data = np.random.normal(size=10000)
pl.hist(data, bins=np.logspace(0.1, 1.0, 50))
pl.gca().set_xscale("log")
pl.show()
```

```
I need the bins to be equally spaced in log10. Is there something that can do this? | The most direct way is to just compute the log10 of the limits, compute linearly spaced bins, and then convert back by raising to the power of 10, as below:
```
import pylab as pl
import numpy as np
data = np.random.normal(size=10000)
MIN, MAX = .01, 10.0
pl.figure()
pl.hist(data, bins = 10 ** np.linspace(np.log10(... |
Can I use an alias to execute a program from a python script | 6,856,119 | 7 | 2011-07-28T08:34:09Z | 6,857,271 | 12 | 2011-07-28T10:10:49Z | [
"python",
"bash",
"unix",
"alias",
"nuke"
] | I am almost brand new to python scripting, so please excuse any stupid questions, but any help anyone can give would be much appreciated.
I am trying to write a python script for other people to use, and in it I need to call a program that I won't always know the path to. To get around that, I ask the user to provide ... | The module you want is [subprocess](http://docs.python.org/library/subprocess.html).
A quick fix to your problem is to use the subprocess module, like so:
```
import subprocess
sp = subprocess.Popen(["/bin/bash", "-i", "-c", "nuke -x scriptpath"])
sp.communicate()
```
This is equivalent to calling:
```
nuke -x scri... |
Python: Call function if setter is called? | 6,856,177 | 3 | 2011-07-28T08:38:17Z | 6,856,228 | 7 | 2011-07-28T08:42:10Z | [
"python",
"object",
"encapsulation",
"setter"
] | I have a Python object which has certain attributes that are set after the constructor is called. For example,
```
def Student(object):
def __init__(name, address=None):
self.name = name
self.address = address
stud = Student("John")
stud.address = "123 Main St. New York, NY"
```
I would like to b... | What you probably need is a *property* concept.
```
class C(object):
def __init__(self, x):
self._x = x
def get_x(self):
return self._x
def set_x(self, x):
self._x = x
x = property(get_x, set_x)
obj = C(5)
obj.x = 6 # set
print obj.x # get
```
See this link for more details: <http://snippets... |
Python monotonically increasing memory usage (leak?) | 6,857,006 | 9 | 2011-07-28T09:47:17Z | 6,858,365 | 12 | 2011-07-28T11:43:04Z | [
"python",
"memory-leaks"
] | I'm using this simple code and observing monotonically increasing memory usage. I'm using this little module to dump stuff to disk. I observed it happens with unicode strings and not with integers, is there something I'm doing wrong?
When I do:
```
>>> from utils.diskfifo import DiskFifo
>>> df=DiskFifo()
>>> for i i... | The pickler module is storing all objects it has seen in its memo, so it doesn't have to pickle the same thing twice. You want to skip this (so references to your objects aren't stored in your pickler object) and clear the memo before dumping:
```
def append(self, x):
self.fd.seek(self.wpos)
self.pickler.clear... |
Python Pyramid Learning Resource | 6,858,987 | 8 | 2011-07-28T12:29:47Z | 6,864,933 | 8 | 2011-07-28T20:01:42Z | [
"python",
"pyramid"
] | I have trid learning the framework with the help of the book, [The Pyramid Web Application Development Framework](http://static.pylonsproject.org/pyramid-1.1.pdf). I have somewhat managed to understand up-to URL Dispatch. But I still find it difficult to grab some concepts.
Can you lead me to some easy-for-newbie tuto... | As far as I know, there are no other Pyramid books on the market. You might want to skim the "cookbook" at <http://docs.pylonsproject.org/projects/pyramid_cookbook/dev/> though. And as kracekumar said, joining the #pyramid IRC channel on freenode.net is a good idea. |
Python Pyramid Learning Resource | 6,858,987 | 8 | 2011-07-28T12:29:47Z | 6,866,564 | 13 | 2011-07-28T22:32:04Z | [
"python",
"pyramid"
] | I have trid learning the framework with the help of the book, [The Pyramid Web Application Development Framework](http://static.pylonsproject.org/pyramid-1.1.pdf). I have somewhat managed to understand up-to URL Dispatch. But I still find it difficult to grab some concepts.
Can you lead me to some easy-for-newbie tuto... | I've been doing web dev for > 15 years, and > 10 with Python, and I found some of the concepts in Pyramid hard to understand, too.
I'd suggest just pushing through; copy-n-paste if you have to, and keep on working. I'm noticing that concepts are 'gelling' for me after the fact, and what I used to find confusing I now ... |
difference between python file operation modules open and file. | 6,859,499 | 4 | 2011-07-28T13:11:15Z | 6,859,513 | 8 | 2011-07-28T13:12:14Z | [
"python"
] | I am working on file operation in python, i found two module,
What is difference between the two file operation module "open" and "file"
functionality wise i found both same.
thanks. | Python 2.x documentation [says it all](http://docs.python.org/library/functions.html#file):
> When opening a file, itâs preferable to use `open()` instead of invoking
> this constructor [`file()`] directly. `file` is more suited to type testing (for
> example, writing `isinstance(f, file)`).
In Python 3.x, `file` i... |
using mmap in python | 6,860,180 | 3 | 2011-07-28T13:59:31Z | 6,860,324 | 7 | 2011-07-28T14:09:20Z | [
"python",
"mmap"
] | can somebody please explain how does 0 influence mmap in python in this case:
```
mmap.mmap(0 , 256, "some tag")
```
I thought that I always need to transfer file descriptor rather than 0, so why zero? | From reading CPython 2.7 source code, it seems that on Windows, specifying `fileno = 0` has the same effect as specifying `fileno = -1`, where the latter means "map anonymous memory".
Only `-1` is accepted on Unix: on my 64-bit Ubuntu box with Python 2.6.5, `mmap.mmap(0, 256)` fails with `errno=19 (No such device)` an... |
Internationalisation Django (on OSX) | 6,860,188 | 23 | 2011-07-28T14:00:21Z | 6,861,500 | 9 | 2011-07-28T15:25:38Z | [
"python",
"django",
"unix",
"internationalization",
"gettext"
] | I'm trying to get gettext to work in Django on my OSX Leopard
```
django_manage.py makemessages -l nl
Importing Django settings module settings
processing language nl
Error: errors happened while running xgettext on __init__.py
/bin/sh: xgettext: command not found
```
In Terminal I get the same error, unless I put th... | I think you need to install gettext. Poedit includes only some of the programs provided by the gettext package.
Probably the easiest way to install (not only) gettext is via [homebrew](https://github.com/mxcl/homebrew). Once you have homebrew installed, run `brew install gettext`. After that, make sure that the progra... |
Internationalisation Django (on OSX) | 6,860,188 | 23 | 2011-07-28T14:00:21Z | 9,787,791 | 84 | 2012-03-20T13:31:57Z | [
"python",
"django",
"unix",
"internationalization",
"gettext"
] | I'm trying to get gettext to work in Django on my OSX Leopard
```
django_manage.py makemessages -l nl
Importing Django settings module settings
processing language nl
Error: errors happened while running xgettext on __init__.py
/bin/sh: xgettext: command not found
```
In Terminal I get the same error, unless I put th... | After installing, try linking gettext. This solved the problem for me.
```
brew install gettext
brew link gettext --force
``` |
function name as as input of another function? | 6,860,366 | 2 | 2011-07-28T14:12:00Z | 6,860,394 | 8 | 2011-07-28T14:13:39Z | [
"python"
] | I an image processing enginner, and am using Python as a prototyping language.
Most of the time, as I get thousands of images, named "imagen.jpg", n being the increment.
So the main structure of my program may be seen as :
```
def main_IP(imgRoot, stop_ncrement):
name = update_the_increment(imgRoot, stop_increment... | Functions can be passed around in python just like a string or any other object can.
```
def processImage(...):
pass
def main_IP(imgRoot, stop_ncrement, process_image):
name = update_the_increment(imgRoot, stop_increment)
img = load_the_image(name)
out_img = process_image(img)
displays_images(img,... |
Importing modules inside python class | 6,861,487 | 19 | 2011-07-28T15:24:48Z | 6,861,854 | 23 | 2011-07-28T15:48:38Z | [
"python",
"class",
"import",
"module"
] | I'm currently writing a class that needs `os`, `stat` and some others.
What's the best way to import these modules in my class?
I'm thinking about when others will use it, I want the 'dependency' modules to be already
imported when the class is instantiated.
Now I'm importing them in my methods, but maybe there's a ... | If your module will always import another module, always put it at the top as [PEP 8](http://www.python.org/dev/peps/pep-0008/) and the other answers indicate. Also, as @delnan mentions in a comment, `sys`, `os`, etc. are being used anyway, so it doesn't hurt to import them globally.
However, there is nothing wrong wi... |
Unable to import Python's email module at all | 6,861,818 | 24 | 2011-07-28T15:45:52Z | 6,862,236 | 74 | 2011-07-28T16:18:51Z | [
"python",
"email"
] | I can't seem to import the email module at all. Every time I do it I get an error. I've tried uninstalling Python and reinstalling, but the email module just refuses to work. I've even done "pip install email" and it's still broken. I'm on Windows 7 Home Premium x64, running an x86 version of Python.
Here's what happe... | It looks like you have a file named `email.py`. Don't use file names that have the same name as Python standard library modules. Generally, your working directory comes earlier on the Python search path for importing modules so files in your working directory will override modules with the same name in the standard lib... |
Unable to import Python's email module at all | 6,861,818 | 24 | 2011-07-28T15:45:52Z | 12,627,636 | 19 | 2012-09-27T18:13:23Z | [
"python",
"email"
] | I can't seem to import the email module at all. Every time I do it I get an error. I've tried uninstalling Python and reinstalling, but the email module just refuses to work. I've even done "pip install email" and it's still broken. I'm on Windows 7 Home Premium x64, running an x86 version of Python.
Here's what happe... | I just came across this error and wanted to share my solution. In my case, I had a file named `email.py` in directory. This created a name conflict between Python's `email.py` and my file. When smtplib tried to `import email.utils` it looked and my file and didn't find anything. After I renamed my copy of `email.py` in... |
Change a django form field to a hidden field | 6,862,250 | 67 | 2011-07-28T16:19:39Z | 6,862,413 | 89 | 2011-07-28T16:33:18Z | [
"python",
"html",
"django",
"django-forms"
] | I have a django form with a `RegexField` (which is very similar to a normal text input field). In my view, under certain conditions I want to hide this from the user, and trying to keep the form as similar as possible.
What's the best way to turn this field into a `HiddenInput` field? I know I can set attributes on th... | If you have a custom template and view you may exclude the field and use `{{ modelform.instance.field }}` to get the value.
also you may prefer to use in the view:
```
form.fields['field_name'].widget = forms.HiddenInput()
```
but I'm not sure it will protect save method on post.
Hope it helps. |
Change a django form field to a hidden field | 6,862,250 | 67 | 2011-07-28T16:19:39Z | 6,866,387 | 30 | 2011-07-28T22:10:21Z | [
"python",
"html",
"django",
"django-forms"
] | I have a django form with a `RegexField` (which is very similar to a normal text input field). In my view, under certain conditions I want to hide this from the user, and trying to keep the form as similar as possible.
What's the best way to turn this field into a `HiddenInput` field? I know I can set attributes on th... | Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you ca... |
Change a django form field to a hidden field | 6,862,250 | 67 | 2011-07-28T16:19:39Z | 7,490,785 | 99 | 2011-09-20T19:35:53Z | [
"python",
"html",
"django",
"django-forms"
] | I have a django form with a `RegexField` (which is very similar to a normal text input field). In my view, under certain conditions I want to hide this from the user, and trying to keep the form as similar as possible.
What's the best way to turn this field into a `HiddenInput` field? I know I can set attributes on th... | It also can be useful: `{{ form.field.as_hidden }}` |
Change a django form field to a hidden field | 6,862,250 | 67 | 2011-07-28T16:19:39Z | 32,075,230 | 16 | 2015-08-18T14:27:42Z | [
"python",
"html",
"django",
"django-forms"
] | I have a django form with a `RegexField` (which is very similar to a normal text input field). In my view, under certain conditions I want to hide this from the user, and trying to keep the form as similar as possible.
What's the best way to turn this field into a `HiddenInput` field? I know I can set attributes on th... | an option that worked for me, define the field in the original form as:
```
forms.CharField(widget = forms.HiddenInput(), required = False)
```
then when you override it in the new Class it will keep it's place. |
Including Duplicate Tables using Django's ORM Extra() | 6,865,356 | 5 | 2011-07-28T20:38:18Z | 6,866,577 | 8 | 2011-07-28T22:34:09Z | [
"python",
"sql",
"django",
"sparql",
"django-orm"
] | I'm trying to implement a simple triplestore using Django's ORM. I'd like to be able to search for arbitrarily complex triple patterns (e.g. as you would with SparQL).
To do this, I'm attempting to use the [.extra()](https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra) method. However, even though the do... | I think what you're missing is the select parameter (for the extra method)
This seems to work:
```
qs = Triple.objects.filter(subject="bob", predicate="knows").extra(select={'known': "t1.subject"}, tables=['"triple_triple" AS "t1"'], where=['triple_triple.object=t1.subject AND t1.predicate="has-a" AND t1.object="hous... |
Buildout vs virtualenv + pip for django? | 6,865,896 | 11 | 2011-07-28T21:25:58Z | 6,870,373 | 11 | 2011-07-29T08:13:51Z | [
"python",
"django",
"virtualenv",
"pip",
"buildout"
] | Pros and cons?
I'm personally using buildout for my django projects but thinking of switching to virtualenv + pip for its simplicity. | At the core, buildout and pip+virtualenv do the same. They both use python packages, install them, isolate them from the rest of your python environment, handle dependencies (through setup.py) and so on.
Buildout does more. Which, naturally, means a bit more configuration than with pip. You'll have to figure out wheth... |
YAML parsing and Python? | 6,866,600 | 53 | 2011-07-28T22:36:01Z | 6,866,697 | 101 | 2011-07-28T22:49:07Z | [
"python",
"parsing",
"yaml"
] | What is the best way to parse a YAML file into a Python object?
For example, this YAML:
```
Person:
name: XYZ
```
To this Python class:
```
class Person(yaml.YAMLObject):
yaml_tag = 'Person'
def __init__(self, name):
self.name = name
```
I am using PyYAML by the way. | If your YAML file looks like this:
```
# tree format
treeroot:
branch1:
name: Node 1
branch1-1:
name: Node 1-1
branch2:
name: Node 2
branch2-1:
name: Node 2-1
```
And you've installed `PyYAML` like this:
```
pip install PyYAML
```
And the Python code l... |
Using Django-Storages with amazon S3 and https | 6,866,893 | 8 | 2011-07-28T23:14:59Z | 6,867,227 | 16 | 2011-07-29T00:05:32Z | [
"python",
"django",
"django-storage"
] | We have an image uploader that uploads to AWS, using django-storages. Right now it sends images over http but we want it to use https.
Googling didn't help me find a way to configure django-storages to do it. Does anyone know the best way to accomplish this, or any documentation that would point me in the right direct... | Looking at the [source](https://bitbucket.org/david/django-storages/src/tip/storages/backends/s3.py) it appears you can enable HTTPS by setting `AWS_S3_SECURE_URLS = True`. |
How to convert escaped characters in Python? | 6,867,588 | 5 | 2011-07-29T01:08:01Z | 6,868,026 | 12 | 2011-07-29T02:23:57Z | [
"python",
"string-formatting"
] | I want to convert strings containing escaped characters to their normal form, the same way Python's lexical parser does:
```
>>> escaped_str = 'One \\\'example\\\''
>>> print(escaped_str)
One \'Example\'
>>> normal_str = normalize_str(escaped_str)
>>> print(normal_str)
One 'Example'
```
Of course the boring way will ... | ```
>>> escaped_str = 'One \\\'example\\\''
>>> print escaped_str.encode('string_escape')
One \\\'example\\\'
>>> print escaped_str.decode('string_escape')
One 'example'
```
Several similar codecs are [available](http://docs.python.org/library/codecs.html#standard-encodings), such as rot13 and hex.
The above is Pytho... |
Audio Recording in Python | 6,867,675 | 8 | 2011-07-29T01:22:34Z | 6,868,910 | 7 | 2011-07-29T05:15:05Z | [
"python",
"audio-recording",
"microphone",
"alsa",
"pyaudio"
] | I want to record short audio clips from a USB microphone in Python. I have tried pyaudio, which seemed to fail communicating with ALSA, and alsaaudio, the code example of which produces an unreadable files.
So my question: What is the easiest way to record clips from a USB mic in Python? | This script records to test.wav while printing the current amplitute:
```
import alsaaudio, wave, numpy
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1024)
w = wave.open('test.wav', 'w')
w.setnchannels(1)
w.setsampwidth(2... |
Python shlex.split(), ignore single quotes | 6,868,382 | 7 | 2011-07-29T03:37:32Z | 6,868,416 | 7 | 2011-07-29T03:45:02Z | [
"python",
"split",
"quotes",
"shlex"
] | How, in Python, can I use `shlex.split()` or similar to split strings, preserving only double quotes? For example, if the input is `"hello, world" is what 'i say'` then the output would be `["hello, world", "is", "what", "'i", "say'"]`. | You can use [`shlex.quotes`](http://docs.python.org/dev/library/shlex.html#shlex.shlex.quotes) to control which characters will be considered string quotes. You'll need to modify [`shlex.wordchars`](http://docs.python.org/dev/library/shlex.html#shlex.shlex.wordchars) as well, to keep the `'` with the `i` and the `say`.... |
Python shlex.split(), ignore single quotes | 6,868,382 | 7 | 2011-07-29T03:37:32Z | 6,868,440 | 15 | 2011-07-29T03:52:14Z | [
"python",
"split",
"quotes",
"shlex"
] | How, in Python, can I use `shlex.split()` or similar to split strings, preserving only double quotes? For example, if the input is `"hello, world" is what 'i say'` then the output would be `["hello, world", "is", "what", "'i", "say'"]`. | ```
import shlex
def newSplit(value):
lex = shlex.shlex(value)
lex.quotes = '"'
lex.whitespace_split = True
lex.commenters = ''
return list(lex)
print newSplit('''This string has "some double quotes" and 'some single quotes'.''')
``` |
Python: special characters giving me problems (from PDFminer) | 6,870,214 | 9 | 2011-07-29T08:00:20Z | 6,873,578 | 10 | 2011-07-29T13:06:53Z | [
"python"
] | I used pdf2text from PDFminer to reduce a PDF to text. Unfortunately it contains special characters. Let me show output from my console
```
>>>a=pdf_to_text("ap.pdf")
```
heres a sample of it, a little truncated
```
>>>a[5000:5500]
'f one architect. Decades ...... but to re\xef\xac\x82ect\none set of design ideas, t... | This problem often occurs when non-ASCII text is stored in `str` objects. What you are trying to do is to encode in `utf-8` a string already encoded in some encoding (because it contains characters with codes above `0x7f`).
To encode such a string in `utf-8` it has to be first decoded. Assuming that the original text ... |
how to access cell values faster with openpyxl? | 6,870,231 | 3 | 2011-07-29T08:02:12Z | 7,528,498 | 13 | 2011-09-23T11:50:15Z | [
"python",
"excel",
"xlsx",
"openpyxl"
] | ```
for rownum in range(0, len(self.sheet.rows) ):
for cell in self.sheet.rows[rownum]:
print cell.value
```
I want to access all cell values in a sheet row by row with openpyxl. Above code works but too slow. How can I access all cell values faster? | If you're only reading cells from top to bottom and from left to right (like most of us) you can use the "optimized reader" <http://openpyxl.readthedocs.org/en/latest/optimized.html>. It works quite fast (CPU bound) and has smaller memory footprint than regular reader.
Disclaimer: I'm the author of openpyxl. |
How to plot a data cube in python | 6,870,922 | 2 | 2011-07-29T09:06:36Z | 6,874,776 | 9 | 2011-07-29T14:36:12Z | [
"python",
"plot",
"cube"
] | I was wondering if there's a way to plot a data cube in Python. I mean I have three coordinate for every point
```
x=part.points[:,0]
y=part.points[:,1]
z=part.points[:,2]
```
And for every point I have a scalar field t(x,y,z)
I would like to plot a 3D data cube showing the position of the point and for every point ... | You can use [matplotlib](http://matplotlib.sourceforge.net/).
Here you have a working example (that moves!):
```
import random
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
mypoints = []
for _ in range(100):
mypoints.append([random.random(), #x
random.random(), #... |
Adding 5 days to a date in Python | 6,871,016 | 145 | 2011-07-29T09:17:19Z | 6,871,054 | 69 | 2011-07-29T09:20:23Z | [
"python",
"date",
"datetime"
] | I have a date `"10/10/11(m-d-y)"` and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.
I am using following code:
```
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
```
`print Date... | Import `timedelta` first.
```
from datetime import timedelta
```
And `Date.today()` will return today's datetime, may be you want
```
EndDate = Date + timedelta(days=10)
``` |
Adding 5 days to a date in Python | 6,871,016 | 145 | 2011-07-29T09:17:19Z | 6,871,056 | 12 | 2011-07-29T09:20:48Z | [
"python",
"date",
"datetime"
] | I have a date `"10/10/11(m-d-y)"` and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.
I am using following code:
```
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
```
`print Date... | I guess you are missing something like that:
```
from datetime import timedelta
``` |
Adding 5 days to a date in Python | 6,871,016 | 145 | 2011-07-29T09:17:19Z | 6,871,482 | 208 | 2011-07-29T10:03:46Z | [
"python",
"date",
"datetime"
] | I have a date `"10/10/11(m-d-y)"` and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.
I am using following code:
```
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
```
`print Date... | The previous answers are correct but it's generally a better practice to do:
```
import datetime
```
Then you'll have, using [`datetime.timedelta`](https://docs.python.org/2/library/datetime.html#datetime.timedelta):
```
date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")
end_date = date_1 + datetime.timede... |
Plot two histograms at the same time with matplotlib | 6,871,201 | 64 | 2011-07-29T09:37:08Z | 6,873,956 | 127 | 2011-07-29T13:33:44Z | [
"python",
"matplotlib",
"plot",
"histogram"
] | I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from
another file in the same histogram, so I do something like
```
n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
```
but the problem is that for each intervale, only the bar with the highest v... | Here you have a working example:
```
import random
import numpy
from matplotlib import pyplot
x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legen... |
Matplotlib contour isn't working | 6,871,369 | 2 | 2011-07-29T09:53:49Z | 6,873,633 | 7 | 2011-07-29T13:11:01Z | [
"python",
"matplotlib",
"sympy"
] | I'm trying to plot the batman equation. A solution in sympy or matplotlib will be great (sage isn't cool because I'm using windows). The problem is that if I comment out certain parts the part of the figure appears but with all the `F *=` parts, I get a blank plot.
```
import matplotlib.pyplot
from numpy import arange... | The parameter of sqrt is negative for many points, so the finally products are all NaN. You can plot every factor as following:
```
from __future__ import division # this is important, otherwise 1/2 will be 0
import matplotlib.pyplot
from numpy import arange
from numpy import meshgrid
from numpy import sqrt
from nump... |
Django: add a field to a modelform | 6,874,149 | 7 | 2011-07-29T13:47:39Z | 6,874,570 | 8 | 2011-07-29T14:20:19Z | [
"python",
"django",
"django-forms"
] | I want to add an extra field to a ModelForm. It seems easy, but I get the following error:
```
Django Version: 1.4 pre-alpha SVN-16573
Exception Type: TypeError
Exception Value:
argument of type 'NoneType' is not iterable
Exception Location: /usr/local/lib/django-trunk/django/forms/models.py in construct_instance,... | You should return cleaned data from `clean` method as documented [here](https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other)
That is:
```
def clean(self):
# perform checks
return self.cleaned_data
``` |
What is the difference between installing a package using pip vs. apt-get? | 6,874,527 | 14 | 2011-07-29T14:17:13Z | 6,874,826 | 14 | 2011-07-29T14:39:49Z | [
"python",
"linux",
"ubuntu",
"pip",
"apt-get"
] | I'm trying to deploy a Django site on an Ubuntu machine. I need to install Psycopg2 and PIL but it seems that I'm able to install them using either apt-get or using pip. Is there a difference in installing by the two methods? I know that using pip, I'm able to install it into a virtual environment but with apt-get it i... | You probably already know the benefits of apt-get. Automatic update notifications, other apt-installed packages that need those tools know they're installed, etc.
With pip, you know you're getting the latest version at the time you install it, you can install to a non-default version of Python, and you can install to ... |
Convert integer to hex-string with specific format | 6,874,906 | 8 | 2011-07-29T14:45:59Z | 6,874,949 | 13 | 2011-07-29T14:49:23Z | [
"python",
"string",
"int",
"hex"
] | I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes.
e.g.
281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05"
The format of the hex-string is important. The length of the int value is variable.
The format '0xffffbf949309L' don't work for me. (I get this with hex(int-va... | There might be a better solution, but you can do this:
```
x = 281473900746245
decoded_x = hex(x)[2:].decode('hex') # value: '\xff\xff\xbf\xde\x16\x05'
```
Breakdown:
```
hex(x) # value: '0xffffbfde1605'
hex(x)[2:] # value: 'ffffbfde1605'
hex(x)[2:].decode('hex') # value: '\xff\... |
With python socketserver how can I pass a variable to the constructor of the handler class | 6,875,599 | 8 | 2011-07-29T15:41:35Z | 6,875,827 | 17 | 2011-07-29T15:58:17Z | [
"python",
"python-2.7",
"socketserver"
] | I would like to pass my database connection to the EchoHandler class, however I can't figure out how to do that or access the EchoHandler class at all.
```
class EchoHandler(SocketServer.StreamRequestHandler):
def handle(self):
print self.client_address, 'connected'
if __name__ == '__main__':
conn = M... | Unfortunately, there really isn't an easy way to access the handlers directly from outside the server.
You have two options to get the information to the EchoHandler instances:
1. Store the connection as a property of the server (add `server.conn = conn` before calling `server_forever()`) and then access that propert... |
How does django handle multiple memcached servers? | 6,876,250 | 16 | 2011-07-29T16:36:20Z | 6,919,201 | 7 | 2011-08-02T21:58:15Z | [
"python",
"django",
"memcached",
"sharding"
] | In the django documentation it says this:
> ...
>
> One excellent feature of Memcached is its ability to share cache over
> multiple servers. This means you can run Memcached daemons on multiple
> machines, and the program will treat the group of machines as a single
> cache, without the need to duplicate cache values... | It's the actual memcached client who does the sharding. Django only passes the configuration from `settings.CACHES` to the client.
The order of the servers doesn't matter\*, but (at least for python-memcached) you can specify a 'weight' for each of the servers:
```
CACHES = {
'default': {
'BACKEND': 'djan... |
numpy arbitrary precision linear algebra | 6,876,377 | 11 | 2011-07-29T16:47:18Z | 6,879,889 | 14 | 2011-07-29T23:03:05Z | [
"python",
"math",
"numpy",
"linear-algebra",
"arbitrary-precision"
] | I have a numpy 2d array [medium/large sized - say 500x500]. I want to find the eigenvalues of the element-wise exponent of it. The problem is that some of the values are quite negative (-800,-1000, etc), and their exponents underflow (meaning they are so close to zero, so that numpy treats them as zero). Is there anywa... | SymPy can calculate arbitrary precision:
```
from sympy import exp, N, S
from sympy.matrices import Matrix
data = [[S("-800.21"),S("-600.00")],[S("-600.00"),S("-1000.48")]]
m = Matrix(data)
ex = m.applyfunc(exp).applyfunc(lambda x:N(x, 100))
vecs = ex.eigenvects()
print vecs[0][0] # eigen value
print vecs[1][0] # eig... |
numpy arbitrary precision linear algebra | 6,876,377 | 11 | 2011-07-29T16:47:18Z | 6,880,866 | 9 | 2011-07-30T03:18:35Z | [
"python",
"math",
"numpy",
"linear-algebra",
"arbitrary-precision"
] | I have a numpy 2d array [medium/large sized - say 500x500]. I want to find the eigenvalues of the element-wise exponent of it. The problem is that some of the values are quite negative (-800,-1000, etc), and their exponents underflow (meaning they are so close to zero, so that numpy treats them as zero). Is there anywa... | On 64-bit systems, there's a `numpy.float128` dtype. (I believe there's a `float96` dtype on 32-bit systems, as well) While `numpy.linalg.eig` doesn't support 128-bit floats, `scipy.linalg.eig` (sort of) does.
However, *none of this is going to matter*, in the long run. Any general solver for an eigenvalue problem is ... |
Manipulate WebP images in Python | 6,876,502 | 11 | 2011-07-29T16:58:40Z | 9,492,576 | 7 | 2012-02-29T02:01:43Z | [
"python",
"image-processing",
"image-manipulation",
"python-imaging-library",
"webp"
] | I'm looking for something like PIL (Python Imaging Library), which sadly doesn't support WebP images.
I'd like to be able to do resizes and crops. Or at least convert to JPEG and then I can work it with PIL. | Take a look at:
<http://code.google.com/p/python-webm/>
I was able to walk through the test file to see how they were doing it. |
Set a default value for a ttk Combobox | 6,876,518 | 6 | 2011-07-29T17:00:10Z | 6,876,926 | 16 | 2011-07-29T17:43:24Z | [
"python",
"python-3.x",
"combobox",
"tkinter",
"ttk"
] | I'm using Python 3.2.1 in Arch Linux x86\_64.
This one is really driving me crazy: I just want to have a default, preselected value for a `ttk.Combobox` as soon as I grid it. This is my code:
```
from tkinter import Tk, StringVar, ttk
root = Tk()
def combo(parent):
value = StringVar()
box = ttk.Combobox(pare... | The problem is that the instance of StringVar is getting garbage-collected. This is because it's a local variable due to how you wrote your code.
One solution is to use a class so that your StringVar persists:
```
from tkinter import Tk, StringVar, ttk
class Application:
def __init__(self, parent):
self... |
no UnicodeError when using print with a default encoding set to ASCII | 6,876,877 | 5 | 2011-07-29T17:38:14Z | 6,876,938 | 9 | 2011-07-29T17:44:13Z | [
"python",
"unicode"
] | After reading: [Dive into Python: Unicode Discussion](http://diveintopython.net/xml_processing/unicode.html)
I got curious to try printing my name in the `indic script`. I am using `v2.7.2` -
```
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> name = u'\u0935\u0948\u092D\u0935'
>>> print name
वà¥à¤à¤µ
```... | [print uses sys.stdout.encoding](http://wiki.python.org/moin/PrintFails), not `sys.getdefaultencoding()`:
> When Python finds its output attached to a terminal, it sets the
> sys.stdout.encoding attribute to the terminal's encoding. The print
> statement's handler will automatically encode unicode arguments into
> str... |
Automatically populating matrix elements in SymPy | 6,877,061 | 4 | 2011-07-29T17:56:51Z | 6,878,459 | 7 | 2011-07-29T20:06:31Z | [
"python",
"sympy"
] | Is there a way to implicitly define the elements of a symbolic matrix in SymPy following a rule such as: **symbol** followed by **subindices** in the matrix (or pairs of numbers)
For example, I would like to define a 3 x 2 matrix called `M`, and I would like SymPy to automatically create it and populate it as:
```
M ... | How about something like this:
```
import sympy
M = sympy.Matrix(3, 2, lambda i,j:sympy.var('M_%d%d' % (i+1,j+1)))
```
Edit: I suppose I should add a small explanation. The first two arguments to **sympy.Matrix()** are defining the matrix as 3x2 (as you specified). The third argument is a **lambda** function, which ... |
Automatically populating matrix elements in SymPy | 6,877,061 | 4 | 2011-07-29T17:56:51Z | 20,624,781 | 7 | 2013-12-17T02:23:13Z | [
"python",
"sympy"
] | Is there a way to implicitly define the elements of a symbolic matrix in SymPy following a rule such as: **symbol** followed by **subindices** in the matrix (or pairs of numbers)
For example, I would like to define a 3 x 2 matrix called `M`, and I would like SymPy to automatically create it and populate it as:
```
M ... | Consider using the `MatrixSymbol` rather than `Matrix` object. `MatrixSymbol` represents matrices without the need for explicit elements.
```
In [1]: M = MatrixSymbol('M', 3, 2)
In [2]: M # Just an expression
Out[2]: M
In [3]: Matrix(M) # Turn it into an explicit matrix if you desire
Out[3]:
â¡Mââ Mâââ... |
How to pack a UUID into a struct in Python? | 6,877,096 | 2 | 2011-07-29T18:00:03Z | 6,877,225 | 8 | 2011-07-29T18:10:19Z | [
"python",
"struct",
"uuid",
"pack"
] | I have a UUID that I was thinking of packing into a struct using UUID.int, which turns it into a 128-bit integer. But none of the struct format characters are large enough to store it, how to go about doing this?
Sample code:
```
s = struct.Struct('L')
unique_id = uuid.uuid4()
tuple = (unique_id.int)
packed = s.p... | It is a 128-bit integer, what would you expect it to be turned into? You can split it into several components â e.g. two 64-bit integers:
```
max_int64 = 0xFFFFFFFFFFFFFFFF
packed = struct.pack('>QQ', (u.int >> 64) & max_int64, u.int & max_int64)
# unpack
a, b = struct.unpack('>QQ', packed)
unpacked = (a << 6... |
Find the number of occurrences of a subsequence in a string | 6,877,249 | 46 | 2011-07-29T18:12:05Z | 6,877,313 | 85 | 2011-07-29T18:17:17Z | [
"python",
"algorithm",
"dynamic-programming"
] | For example, let the string be the first 10 digits of pi, `3141592653`, and the subsequence be `123`. Note that the sequence occurs twice:
```
3141592653
1 2 3
1 2 3
```
This was an interview question that I couldn't answer and I can't think of an efficient algorithm and it's bugging me. I feel like it shou... | This is a classical [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) problem (and not typically solved using regular expressions).
> ***My naive implementation (count the 3's for each 2 after each 1) has been running for an hour and it's not done.***
That would be an exhaustive search approach ... |
Find the number of occurrences of a subsequence in a string | 6,877,249 | 46 | 2011-07-29T18:12:05Z | 6,991,014 | 11 | 2011-08-09T03:14:14Z | [
"python",
"algorithm",
"dynamic-programming"
] | For example, let the string be the first 10 digits of pi, `3141592653`, and the subsequence be `123`. Note that the sequence occurs twice:
```
3141592653
1 2 3
1 2 3
```
This was an interview question that I couldn't answer and I can't think of an efficient algorithm and it's bugging me. I feel like it shou... | Great answer, [aioobe](http://stackoverflow.com/users/276052/aioobe)! to complement your answer, some possible implementations in Python:
```
# straightforward, naïve solution; too slow!
def num_subsequences(seq, sub):
if not sub:
return 1
elif not seq:
return 0
result = num_subsequences(... |
Scoring a string based on how English-like it is | 6,878,303 | 11 | 2011-07-29T19:51:25Z | 6,878,408 | 7 | 2011-07-29T20:01:26Z | [
"python",
"c",
"cryptography",
"cryptanalysis"
] | I'm not sure how exactly to word this question, so here's an example:
string1 = "THEQUICKBROWNFOX"
string2 = "KLJHQKJBKJBHJBJLSDFD"
I want a function that would score string1 higher than string2 and a million other gibberish strings. Note the lack of spaces, so this is a character-by-character function, not word-by-w... | I would start with a simple probability model for how likely each letter is, given the previous (possibly-null, at start-of-word) letter. You could build this based on a dictionary file. You could then expand this to use 2 or 3 previous letters as context to condition the probabilities if the initial model is not good ... |
Putting a `Cookie` in a `CookieJar` | 6,878,418 | 29 | 2011-07-29T20:02:17Z | 6,930,182 | 36 | 2011-08-03T16:56:15Z | [
"python",
"cookies",
"http-request",
"python-requests"
] | I'm using the new Python Requests library to make http requests. I obtain a cookie from the server as text. How do I turn that into a `CookieJar` with the cookie in it? | I'm confused by this question. The requests library will put the cookies in the jar for you.
```
import requests
import cookielib
URL = '...whatever...'
jar = cookielib.CookieJar()
r = requests.get(URL, cookies=jar)
r = requests.get(URL, cookies=jar)
```
The first request to the URL will fill the jar. The second re... |
Putting a `Cookie` in a `CookieJar` | 6,878,418 | 29 | 2011-07-29T20:02:17Z | 20,155,713 | 11 | 2013-11-22T22:30:19Z | [
"python",
"cookies",
"http-request",
"python-requests"
] | I'm using the new Python Requests library to make http requests. I obtain a cookie from the server as text. How do I turn that into a `CookieJar` with the cookie in it? | A requests `Session` will also receive and send cookies.
```
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
```
(Code above stolen from <http://www.python-requests.org/en/lat... |
Opening a file for append | 6,878,628 | 6 | 2011-07-29T20:25:25Z | 6,878,867 | 13 | 2011-07-29T20:48:19Z | [
"python"
] | I just had a passing thought and figured what better place to ask then right here. Out of curiosity, does anyone know if opening a file for append, like this:
```
file_name = "abc"
file_handle = open(file_name,"a")
```
Is essentially the same as opening a file for writing and seeking to the end:
```
file_name = "abc... | After playing a bit in my terminal, I can say what the differences are on ubuntu linux 11.04 using python 2.7.1.
Opening with 'w' truncates (i.e. erases the contents of) the file as soon as it's opened. In other words, just opening the file with `open('file.txt', 'w')` and exiting leaves behind an empty file.
Opening... |
Print file age in seconds using Python | 6,879,364 | 15 | 2011-07-29T21:45:47Z | 6,879,454 | 17 | 2011-07-29T21:58:08Z | [
"python",
"file"
] | I need my script to download new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds. | This shows how to find a file's (or directory's) last modification time:
Here are the number of seconds since the Epoch, using [os.stat](http://docs.python.org/library/os.html#os.stat)
```
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52
```
Or, equivalently, using [os.path.getmtime](h... |
Print file age in seconds using Python | 6,879,364 | 15 | 2011-07-29T21:45:47Z | 6,879,539 | 8 | 2011-07-29T22:09:48Z | [
"python",
"file"
] | I need my script to download new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds. | Another approach (I know I wasn't the first answer but here goes anyway):
```
import time, os, stat
def file_age_in_seconds(pathname):
return time.time() - os.stat(pathname)[stat.ST_MTIME]
``` |
Why is the Python CSV reader ignoring double-quoted fields? | 6,879,596 | 6 | 2011-07-29T22:17:56Z | 6,879,712 | 18 | 2011-07-29T22:35:32Z | [
"python",
"csv"
] | I think this is probably something simple, but after an hour of searching, I've had no luck figuring out what I'm doing wrong.
I'm using the following code to read a CSV file - I have no problem reading the file, but when a line contains a field that is double-quoted because it contains the delimiter, the CSV reader i... | If you look at the dialect that you're using, you'll notice that the excel dialect is
configured as follows:
```
class excel(Dialect):
"""Describe the usual properties of Excel-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = True
skipinitialspace = False
lineterminator = '... |
Is a hmac-sha1 hash always 20 bytes long? Python code | 6,880,514 | 5 | 2011-07-30T01:31:37Z | 6,880,524 | 10 | 2011-07-30T01:35:13Z | [
"python",
"hmacsha1"
] | Is the digest always 20 bytes long? len(hashed.digest()) seems to always be 20.
```
hashed = hmac.new(key, signature_base_string, sha)
print hashed.digest()
print len(hashed.digest())
i = 0
for c in hashed.digest():
i = i + 1
print ord(c)
print base64.b64encode(hashed.digest())
``` | All hashing functions have fixed length outputs. [SHA1](http://en.wikipedia.org/wiki/SHA-1) is 160 bits, or 20 bytes. |
Is there a point to dependency injection container in Python? | 6,880,884 | 15 | 2011-07-30T03:24:57Z | 6,881,159 | 7 | 2011-07-30T04:52:36Z | [
"python",
"dependency-injection"
] | Been messing about with python, as usual it throws my rigid static typed Object Oriented world in to a bit of a mess. Python supports duck typing, has no usable concept of interface based programming (as in C# interfaces) and allows Global variables. With all these goodies is there really any point to a dependency inje... | ## The conclusion
(The following is the most relevant part of the original post. I admit, I waxed a little poetical, and so I though I should simply include the most important sentences in their own section. That said, I feel that the poetic waxing is important enough that I have not deleted it.)
Dependency injection... |
Is there a point to dependency injection container in Python? | 6,880,884 | 15 | 2011-07-30T03:24:57Z | 6,881,741 | 13 | 2011-07-30T07:18:40Z | [
"python",
"dependency-injection"
] | Been messing about with python, as usual it throws my rigid static typed Object Oriented world in to a bit of a mess. Python supports duck typing, has no usable concept of interface based programming (as in C# interfaces) and allows Global variables. With all these goodies is there really any point to a dependency inje... | > has no usable concept of interface based programming (as in C# interfaces)
Just because the compiler can't check that you're using the interface correctly doesn't mean there's "no usable concept of interfaces". You document an interface, and write unit tests.
As for globals, it's not like `public static` methods an... |
Is there a way to autogenerate valid arithmetic expressions? | 6,881,170 | 6 | 2011-07-30T04:55:57Z | 6,881,218 | 14 | 2011-07-30T05:06:35Z | [
"python",
"parsing"
] | I'm currently trying to create a Python script that will autogenerate space-delimited arithmetic expressions which are valid. However, I get sample output that looks like this: `( 32 - 42 / 95 + 24 ( ) ( 53 ) + ) 21`
While the empty parentheses are perfectly OK by me, I can't use this autogenerated expression in calcu... | Yes, you can generate random arithmetic expressions in a Pythonic way. You need to change your approach, though. Don't try to generate a string and count parens. Instead generate a random *expression tree*, then output that.
By an expression tree, I mean an instance of a class called, say, `Expression` with subclasses... |
Pygame Error: Video System not Initialized | 6,881,482 | 10 | 2011-07-30T06:12:50Z | 6,885,984 | 11 | 2011-07-30T21:10:54Z | [
"python",
"pygame"
] | I have used Pygame with python 2.7 before but recently I 'upgraded' to python 3.2. I downloaded and installed the newest version of Pygame which is said to work with this version of python. I have, however, had this rather frustrating error on what should be a simple block of code. The code is:
```
import pygame, rand... | ```
if event.type == pygame.quit():
```
In the line above, you're calling pygame.quit which is a function, while what you really want is the constant pygame.QUIT.
By calling pygame.quit(), pygame is no longer initialized, which is why you get that error.
Thus, changing the line to:
```
if event.type == pygame.QUIT: #... |
Python: Use an import done inside of a class in a function | 6,883,319 | 3 | 2011-07-30T13:14:51Z | 6,883,558 | 8 | 2011-07-30T13:55:40Z | [
"python",
"python-import"
] | Can anyone explain how to make the following example work? Since several functions inside of the class will use the same function from platform I thought it would be better to import it right inside of the class, but I don't see how I can use it inside of the function (since I constantly get errors about it).
```
#!/u... | Well, it is not that simple.
Actually, import statement in many aspects looks like direct definition of something in place of it. If you write
```
class test:
from platform import system
```
it looks exactly like
```
class test:
def system():
# ....
```
and then you have following problems:
1. you ... |
how to delete dir created by python tempfile.mkdtemp | 6,884,991 | 12 | 2011-07-30T18:02:21Z | 6,886,556 | 21 | 2011-07-30T23:23:08Z | [
"python",
"linux"
] | I have a python program creates tmp directories under /temp by using tempfile.mkdtemp.
Unfortunately, the python program did not delete the directory after using it. So now the disk space is low.
Questions:
1. How do I delete the temp directories left under /temp manually? I
tried to delete them manually but got... | Read the [documentation](http://docs.python.org/library/tempfile.html#tempfile.mkdtemp), it's simple. ;) From the docs: the directory is readable, writable, and searchable only by the creating user ID.
To delete temp directory try something like this:
```
import errno
import shutil
import tempfile
try:
tmp_dir =... |
how to delete dir created by python tempfile.mkdtemp | 6,884,991 | 12 | 2011-07-30T18:02:21Z | 22,726,782 | 24 | 2014-03-29T03:54:58Z | [
"python",
"linux"
] | I have a python program creates tmp directories under /temp by using tempfile.mkdtemp.
Unfortunately, the python program did not delete the directory after using it. So now the disk space is low.
Questions:
1. How do I delete the temp directories left under /temp manually? I
tried to delete them manually but got... | To manage resources (like files) in Python, best practice is to use the `with` keyword, which automatically releases the resources (i.e., cleans up, like closing files); this is available from Python 2.5.
From Python 3.2, you can use `tempfile.TemporaryDirectory()` instead of `tempfile.mkdtmp()` â this is usable in ... |
PyMySQL can't connect to MySQL on localhost | 6,885,164 | 17 | 2011-07-30T18:31:09Z | 14,351,678 | 23 | 2013-01-16T05:01:28Z | [
"python",
"mysql",
"mysql-error-2003"
] | I'm trying to connect to MySQL on localhost using PyMySQL:
```
import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')
```
but (both on Python 2.7 and Python 3.2) I get the error:
> socket.error: [Errno 111] Connection refused
>
> pymysql.err.OperationalError: (2003, "Can't conn... | Two guesses:
1. Run `mysqladmin variables | grep socket` to get where the socket is located, and try setting up a connection like so:
```
pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
```
2. Run `mysqladmin variables | grep port` and verify that the port is 3306. If not... |
How I can I lazily read multiple JSON objects from a file/stream in Python? | 6,886,283 | 49 | 2011-07-30T22:12:57Z | 6,886,417 | 26 | 2011-07-30T22:43:28Z | [
"python",
"json",
"serialization"
] | I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately `json.load()` just `.read()`s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.
Is there any way to do this? Using the standard library would be i... | JSON generally isn't very good for this sort of incremental use; there's no standard way to serialise multiple objects so that they can easily be loaded one at a time, without parsing the whole lot.
The object per line solution that you're using is seen elsewhere too. Scrapy calls it 'JSON lines':
* <http://doc.scrap... |
How I can I lazily read multiple JSON objects from a file/stream in Python? | 6,886,283 | 49 | 2011-07-30T22:12:57Z | 6,886,743 | 17 | 2011-07-31T00:18:07Z | [
"python",
"json",
"serialization"
] | I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately `json.load()` just `.read()`s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.
Is there any way to do this? Using the standard library would be i... | Sure you can do this. You just have to take to `raw_decode` directly. This implementation loads the whole file into memory and operates on that string (much as `json.load` does); if you have large files you can modify it to only read from the file as necessary without much difficulty.
```
import json
from json.decoder... |
How I can I lazily read multiple JSON objects from a file/stream in Python? | 6,886,283 | 49 | 2011-07-30T22:12:57Z | 7,795,029 | 17 | 2011-10-17T14:11:12Z | [
"python",
"json",
"serialization"
] | I'd like to read multiple JSON objects from a file/stream in Python, one at a time. Unfortunately `json.load()` just `.read()`s until end-of-file; there doesn't seem to be any way to use it to read a single object or to lazily iterate over the objects.
Is there any way to do this? Using the standard library would be i... | This is a pretty nasty problem actually because you have to stream in lines, but pattern match across multiple lines against braces, but also pattern match json. It's a sort of json-preparse followed by a json parse. Json is, in comparison to other formats, easy to parse so it's not always necessary to go for a parsing... |
Get all object attributes in Python? | 6,886,493 | 111 | 2011-07-30T23:03:44Z | 6,886,507 | 150 | 2011-07-30T23:08:01Z | [
"python",
"introspection",
"python-2.6"
] | Is there a way to get **all** attributes/methods/fields/etc. of an object in Python?
`vars()` is *close* to what I want, but it doesn't work unless an object has a `__dict__`, which isn't always true (e.g. it's not true for a `list`, a `dict`, etc.). | Use the built-in function [`dir()`](http://docs.python.org/library/functions.html#dir). |
Get all object attributes in Python? | 6,886,493 | 111 | 2011-07-30T23:03:44Z | 6,886,536 | 31 | 2011-07-30T23:16:04Z | [
"python",
"introspection",
"python-2.6"
] | Is there a way to get **all** attributes/methods/fields/etc. of an object in Python?
`vars()` is *close* to what I want, but it doesn't work unless an object has a `__dict__`, which isn't always true (e.g. it's not true for a `list`, a `dict`, etc.). | What you probably want is [`dir()`](http://docs.python.org/library/functions.html#dir).
The catch is that classes are able to override the special `__dir__` method, which causes `dir()` to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some o... |
How to install PyCairo 1.10 on Mac OSX with default python | 6,886,578 | 16 | 2011-07-30T23:29:18Z | 7,215,895 | 13 | 2011-08-27T16:43:22Z | [
"python",
"pycairo"
] | Has anyone installed pycairo 1.10 on the mac using the new waf build? Its failing on can't find python headers. | I think waf is seriously broken for Mac OS X :(
Here's how it worked for me. After `python waf configure` failed to find Python.h, I looked through the **config.log** file located in **build\_directory** and found out that the true cause of failure was incompatible architecture. The waf script tries to build a simple ... |
How to install PyCairo 1.10 on Mac OSX with default python | 6,886,578 | 16 | 2011-07-30T23:29:18Z | 9,764,104 | 12 | 2012-03-19T01:58:36Z | [
"python",
"pycairo"
] | Has anyone installed pycairo 1.10 on the mac using the new waf build? Its failing on can't find python headers. | For anyone coming back to this, I was able to get py2cairo installed on OSX Lion with a slightly different approach, based on llimllib's link. Hope this helps:
```
python waf clean
export PYTHONPATH=/Library/Frameworks/Python.framework/Versions/2.7/
export LD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/... |
How to search values in a dictionary in python | 6,886,757 | 2 | 2011-07-31T00:23:28Z | 6,886,799 | 8 | 2011-07-31T00:35:10Z | [
"python",
"list",
"csv"
] | I have a big csv files with the following format:
CSV FILE 1
```
id, person, city
1, John, NY
2, Lucy, Miami
3, Smith, Los Angeles
4, Mike, Chicago
5, David, Los Angeles
6, Daniel, NY
```
On another CSV file I have each city with a numerical code:
CSV FILE 2
```
city , code
NY , 1... | You have some extra whitespace there, and unlike some storage formats, CSV does care about it. If that is actually in your source data, you may have to strip it out before it will be processed as you expect (otherwise various fields will have leading and trailing whitespace).
Assuming that the whitespace is gone, howe... |
Django design pattern for web analytics screens that take a really long time to calculate | 6,887,100 | 8 | 2011-07-31T02:05:50Z | 6,889,383 | 14 | 2011-07-31T12:11:29Z | [
"python",
"django",
"batch-file"
] | I have an "analytics dashboard" screen that is visible to my django web applications users that takes a really long time to calculate. It's one of these screens that goes through every single transaction in the database for a user and gives them metrics on it.
I would love for this to be a realtime operation, but calc... | What you're looking for is a combination of offline processing and caching. By offline, I mean that the computation logic happens outside the request-response cycle. By caching, I mean that the result of your expensive calculation is sufficiently valid for X time, during which you do not need to recalculate it for disp... |
Specific doubts on kgp.py program in dive into python book | 6,889,235 | 3 | 2011-07-31T11:38:45Z | 6,889,293 | 7 | 2011-07-31T11:50:34Z | [
"python",
"xml"
] | [Dive into Python: XML Processing](http://linux.die.net/diveintopython/html/xml_processing/parsing_xml.html#kgp.divein) -
Here I am referring to a portion of `kgp.py` program -
```
def getDefaultSource(self):
xrefs = {}
for xref in self.grammar.getElementsByTagName("xref"):
xrefs[xref.attributes["id"].value] ... | [*Dive Into Python*](http://diveintopython.net/index.html) is seven years old now (published 2004), and doesn't always contain the most modern code. So you need to go easy on it: [*Dive Into Python 3*](http://diveintopython3.net/xml.html) might be a better bet.
Your suggestion for doubt 1 changes the meaning of the co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.