title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python PIL: how to make area transparent in PNG? | 4,379,978 | 8 | 2010-12-07T18:03:33Z | 4,380,602 | 16 | 2010-12-07T19:08:33Z | [
"python",
"image",
"png",
"transparency",
"python-imaging-library"
] | I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say
```
from PIL import Image
im = Image.open("sample.png")
transparent_area = (50,80,100,200)
...
```
I'd really appreciate some code as I haven't been able to find it, thanks a lot in advance!
Cheers,
Hoff | ```
import Image
import ImageDraw
im = Image.open("image.png")
transparent_area = (50,80,100,200)
mask=Image.new('L', im.size, color=255)
draw=ImageDraw.Draw(mask)
draw.rectangle(transparent_area, fill=0)
im.putalpha(mask)
im.save('/tmp/output.png')
```
I learned how to do this [here](http://stackoverflow.com/questi... |
Installing M2Crypto on CentOS | 4,380,191 | 11 | 2010-12-07T18:26:42Z | 4,380,239 | 9 | 2010-12-07T18:30:46Z | [
"python",
"install",
"m2crypto"
] | I am trying to install M2Crypto on CentOS by compiling from the source.
i am doing a python setup.py build
But I get the following error,
```
/usr/local/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'test_suite'
warnings.warn(msg)
running build
running build_py
running build_ext
buil... | The following should work:
```
env SWIG_FEATURES="-cpperraswarn -includeall -D__`uname -m`__ -I/usr/include/openssl" python setup.py build
```
Edit: and `openssl-devel` package is of course also required. |
Installing M2Crypto on CentOS | 4,380,191 | 11 | 2010-12-07T18:26:42Z | 7,571,520 | 7 | 2011-09-27T15:15:28Z | [
"python",
"install",
"m2crypto"
] | I am trying to install M2Crypto on CentOS by compiling from the source.
i am doing a python setup.py build
But I get the following error,
```
/usr/local/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'test_suite'
warnings.warn(msg)
running build
running build_py
running build_ext
buil... | I just had this problem. In M2Crypto's INSTALL file:
```
Note about Fedora Core -based Distributions
----------------------------------------------------
Fedora Core (and RedHat, CentOS etc.) have made changes to OpenSSL
configuration compared to many other Linux distributions. If you can not
build M2Crypto normally,... |
Django Model Field Default Based Off Another Field in Same Model | 4,380,879 | 41 | 2010-12-07T19:43:42Z | 4,380,936 | 9 | 2010-12-07T19:50:17Z | [
"python",
"django",
"django-models",
"django-1.2"
] | I have a model that I would like to contain a subjects name and their initials. (The data is somewhat anonymized and tracked by initials.)
Right now, I wrote
```
class Subject(models.Model):
name = models.CharField("Name", max_length=30)
def subject_initials(self):
return ''.join(map(lambda x: '' if ... | I don't know if there is a better way of doing this, but you can use a `pre_save` handler:
```
from django.db.models.signals import pre_save
def default_subject(sender, instance, using):
if not instance.subject_init:
instance.subject_init = instance.subject_initials()
pre_save.connect(default_subject, se... |
Django Model Field Default Based Off Another Field in Same Model | 4,380,879 | 41 | 2010-12-07T19:43:42Z | 4,381,252 | 39 | 2010-12-07T20:29:18Z | [
"python",
"django",
"django-models",
"django-1.2"
] | I have a model that I would like to contain a subjects name and their initials. (The data is somewhat anonymized and tracked by initials.)
Right now, I wrote
```
class Subject(models.Model):
name = models.CharField("Name", max_length=30)
def subject_initials(self):
return ''.join(map(lambda x: '' if ... | Models certainly do have a "self"! It's just that you're trying to define an attribute of a model class as being dependent upon a model instance; that's not possible, as the instance does not (and cannot) exist before your define the class and its attributes.
To get the effect you want, override the save() method of t... |
Installing mysql-python on Centos | 4,380,931 | 12 | 2010-12-07T19:49:59Z | 10,970,547 | 21 | 2012-06-10T17:02:26Z | [
"python",
"mysql"
] | I'm trying to get the MySQL-python lib installed on centos 5.5. I ran
```
sudo yum install MySQL-python
```
but then when I tried:
```
import MySQLdb
```
I get this error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "MySQLdb/__init__.py", line 22, in ?
raise ImportError("this i... | 1) Install package
```
# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution
Dependencies... |
Installing mysql-python on Centos | 4,380,931 | 12 | 2010-12-07T19:49:59Z | 30,637,456 | 8 | 2015-06-04T07:19:47Z | [
"python",
"mysql"
] | I'm trying to get the MySQL-python lib installed on centos 5.5. I ran
```
sudo yum install MySQL-python
```
but then when I tried:
```
import MySQLdb
```
I get this error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "MySQLdb/__init__.py", line 22, in ?
raise ImportError("this i... | I have **Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503**.
For me it worked with the following command:
```
# pip install mysql-python
```
**Note pre-requisites here:**
Install Python pip:
```
# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
# yum -y update
Reboot the machine (... |
Is there such a thing as working threading in python? | 4,381,176 | 3 | 2010-12-07T20:20:47Z | 4,381,264 | 9 | 2010-12-07T20:30:30Z | [
"python",
"multithreading",
"python-stackless"
] | I wrote a beautiful multithreaded script, and when I ran it, it performed worse with 25 threads than with just direct invocation of the thread handler.
Then I discovered the global interpreter lock. I want to ask, before I discard python for this script and rewrite the thing in something else, is there any way to do a... | The other approach is to abandon threads and instead use the [Multiprocessing](http://docs.python.org/library/multiprocessing.html) module (Python 2.6+), which gets around the GIL, and has an API that's at least similar to the one in the threading module. |
Python os module open file above current directory with relative path | 4,381,569 | 4 | 2010-12-07T21:06:29Z | 4,381,638 | 22 | 2010-12-07T21:12:21Z | [
"python",
"file-io",
"cgi",
"cgi-bin"
] | The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this.
```
/home/matt/project/dir1/cgi-bin/script.py
/home/matt/project/fileIwantToOp... | The path given to `open` should be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory.
A simple solution would be to make your path relative to the script. One possible solution.
```
import os.path
import... |
Defining a model class in Django shell fails | 4,382,032 | 26 | 2010-12-07T21:55:15Z | 4,382,190 | 44 | 2010-12-07T22:13:43Z | [
"python",
"django"
] | when I use the Django shell, it shows an error; this is the error:
```
>>> from django.db import models
>>> class Poll(models.Model):
... question = models.CharField(max_length=200)
... pub_date = models.DateTimeField('date published')
...
Traceback (most recent call last):
File "<console>", line 1, in <modu... | The model definition must come in an application - the error you're seeing there is that it tries to take the `__name__` `model_module` - which should be something like `project.appname.models` for `project\appname\models.py` - and get the app name, `appname`. In the interactive console, the module's `__name__` is `'__... |
Python augmented assignment issue | 4,382,246 | 13 | 2010-12-07T22:21:06Z | 4,382,593 | 14 | 2010-12-07T23:04:19Z | [
"python",
"arrays",
"numpy",
"numbers",
"complex-numbers"
] | i ran into something interesting about the python augmented assignment `+=`
it seems to be automatic data type conversion is not always done for `a += b` if a is a 'simpler' data type, while `a = a + b` seems to work always
cases where the conversion is done
```
a = 1
b = 1j
a = 1
b = 0.5
```
case where the conver... | For the `+` operator, Python defines three "special" methods that an object may implement:
* `__add__`: adds two items (`+` operator). When you do `a + b`, the `__add__` method of `a` is called with `b` as an argument.
* `__radd__`: reflected add; for `a + b`, the `__radd__` method of `b` is called with `a` as an inst... |
Comparing lists in Python | 4,382,301 | 3 | 2010-12-07T22:30:08Z | 4,382,323 | 8 | 2010-12-07T22:33:11Z | [
"python"
] | Say I have `list1 = [1,2,3,4]` and `list2 = [5,6,7,8]`. How would I compare the first element, `1`, in `list1` with the first element, `5`, in `list2`? And `2` with `6`, `3` with `7`, and so on.
I'm trying to use a for loop for this, but I'm not sure how to do it. I understand that doing `for x in list1` just checks a... | You can traverse both lists simultaneously using zip:
```
for (x, y) in zip(list1, list2): do_something
```
The 'zip' function gives you `[(1,5), (2,6), (3,7), (4,8)]`, so in loop iteration N you get the Nth element of each list. |
Abstract methods in Python | 4,382,945 | 108 | 2010-12-07T23:58:20Z | 4,382,961 | 30 | 2010-12-08T00:01:20Z | [
"python"
] | I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least.
I have a prototype which follow:
```
class Shape():
def __init__(self, shape_name):
self.shape = shape_name
cl... | See the [abc module](http://docs.python.org/library/abc.html). Basically, you define `__metaclass__ = abc.ABCMeta` on the class, then decorate each abstract method with `@abc.abstractmethod`. Classes derived from this class cannot then be instantiated unless all abstract methods have been overridden.
If your class is ... |
Abstract methods in Python | 4,382,945 | 108 | 2010-12-07T23:58:20Z | 4,382,964 | 139 | 2010-12-08T00:02:11Z | [
"python"
] | I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least.
I have a prototype which follow:
```
class Shape():
def __init__(self, shape_name):
self.shape = shape_name
cl... | Something along these lines, using ABC
```
import abc
class Shape(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def method_to_implement(self, input):
"""Method documentation"""
return
```
Also read this good tutorial: <http://www.doughellmann.com/PyMOTW/abc/>
You can also che... |
Abstract methods in Python | 4,382,945 | 108 | 2010-12-07T23:58:20Z | 4,383,103 | 172 | 2010-12-08T00:25:01Z | [
"python"
] | I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least.
I have a prototype which follow:
```
class Shape():
def __init__(self, shape_name):
self.shape = shape_name
cl... | Before abc was introduced you would see this frequently.
```
class Base(object):
def go(self):
raise NotImplementedError("Please Implement this method")
class Specialized(Base):
def go(self):
print "Consider me implemented"
``` |
Python regex separate space-delimited words into a list | 4,383,082 | 7 | 2010-12-08T00:21:22Z | 4,383,096 | 18 | 2010-12-08T00:23:11Z | [
"python",
"regex",
"string",
"list"
] | If I have a string = "hello world sample text"
I want to be able to convert it to a list = ["hello", "world", "sample", "text"]
How can I do that with regular expressions? (other methods not using re are acceptable) | ```
"hello world sample text".split()
```
will split on any whitespace. If you only want to split on spaces
```
"hello world sample text".split(" ")
```
regex version would be something like this
```
re.split(" +", "hello world sample text")
```
which works if you have multiple spaces between the words |
Importing files from different folder in Python | 4,383,571 | 288 | 2010-12-08T02:07:15Z | 4,383,597 | 433 | 2010-12-08T02:12:13Z | [
"python",
"importerror",
"python-import"
] | I have the following folder structure.
`application/app/folder/file.py`
and I want to import some functions from file.py in another Python file which resides in
`application/app2/some_folder/some_file.py`
I've tried
`from application.app.folder.file import func_name`
and some other various attempts but so far I c... | By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and `sys.path` which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).
However, y... |
Importing files from different folder in Python | 4,383,571 | 288 | 2010-12-08T02:07:15Z | 21,878,513 | 11 | 2014-02-19T11:00:06Z | [
"python",
"importerror",
"python-import"
] | I have the following folder structure.
`application/app/folder/file.py`
and I want to import some functions from file.py in another Python file which resides in
`application/app2/some_folder/some_file.py`
I've tried
`from application.app.folder.file import func_name`
and some other various attempts but so far I c... | Since your question looks \*nix specific, I think a clean way would be to use the environment variable
```
PYTHONPATH
```
as described in the documentation:
[Python2](http://docs.python.org/2/tutorial/modules.html#the-module-search-path "Python 2"), [Python3](https://docs.python.org/3/tutorial/modules.html#the-module... |
Importing files from different folder in Python | 4,383,571 | 288 | 2010-12-08T02:07:15Z | 21,995,949 | 144 | 2014-02-24T18:27:45Z | [
"python",
"importerror",
"python-import"
] | I have the following folder structure.
`application/app/folder/file.py`
and I want to import some functions from file.py in another Python file which resides in
`application/app2/some_folder/some_file.py`
I've tried
`from application.app.folder.file import func_name`
and some other various attempts but so far I c... | Nothing wrong with:
```
from application.app.folder.file import func_name
```
Just make sure **folder** also contains an **\_\_init\_\_.py**, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH. |
Importing files from different folder in Python | 4,383,571 | 288 | 2010-12-08T02:07:15Z | 27,097,894 | 9 | 2014-11-24T04:31:46Z | [
"python",
"importerror",
"python-import"
] | I have the following folder structure.
`application/app/folder/file.py`
and I want to import some functions from file.py in another Python file which resides in
`application/app2/some_folder/some_file.py`
I've tried
`from application.app.folder.file import func_name`
and some other various attempts but so far I c... | From what I know, add an `__init__.py` file directly in the folder of the functions you want to import will do the job. |
In Django models.py, what's the difference between default, null, and blank? | 4,384,098 | 26 | 2010-12-08T04:12:45Z | 4,384,131 | 32 | 2010-12-08T04:21:16Z | [
"python",
"database",
"django",
"string",
"integer"
] | null=True
blank=True
default = 0
What's the difference? When do you use what? | Direct from [Django model field reference](http://docs.djangoproject.com/en/dev/ref/models/fields/):
> **`Field.null`**
>
> If `True`, Django will store empty values as `NULL` in the database. Default is `False`.
>
> Note that empty string values will always get stored as empty strings, not as `NULL`. Only use `null=T... |
In Django models.py, what's the difference between default, null, and blank? | 4,384,098 | 26 | 2010-12-08T04:12:45Z | 4,384,133 | 8 | 2010-12-08T04:22:09Z | [
"python",
"database",
"django",
"string",
"integer"
] | null=True
blank=True
default = 0
What's the difference? When do you use what? | From [docs](http://docs.djangoproject.com/en/1.2/topics/db/models/):
> `null` If True, Django will store empty
> values as NULL in the database.
> Default is False.
>
> `blank` If True, the field is allowed to
> be blank. Default is False.
>
> `default` The default value for the
> field.
You can use "`default`" to se... |
Which Python async library would be best suited for my code? Asyncore? Twisted? | 4,384,360 | 17 | 2010-12-08T05:08:27Z | 4,385,667 | 47 | 2010-12-08T08:55:10Z | [
"python",
"asynchronous",
"twisted",
"asyncore"
] | I have a program I'm working on that will be reading from two 'network sources' simultaneously. I wanted to try out an asynchronous approach rather than use threading. This has lead me to wonder which library to use...
I've come up with some simple example code that kind of demonstrates what my program will be doing:
... | Twisted is better in pretty much every possible way. It's more portable, more featureful, simpler, more scalable, better maintained, better documented, and it can make a delicious omelette. Asyncore is, for all intents and purposes, obsolete.
It's hard to demonstrate all the ways in which Twisted is superior in a shor... |
What is the point of Python egg files? | 4,384,402 | 8 | 2010-12-08T05:16:23Z | 4,384,415 | 9 | 2010-12-08T05:19:48Z | [
"python",
"django",
"egg"
] | When I run `python setup.py install` django, it generates an egg file.
What is the usefulness of Python egg files? | [A small introduction to Python Eggs](http://mrtopf.de/blog/en/a-small-introduction-to-python-eggs/). |
README extension for Python projects | 4,384,796 | 31 | 2010-12-08T06:33:24Z | 4,384,920 | 7 | 2010-12-08T06:52:51Z | [
"python",
"github"
] | Python packaging tools expect that our readme file should be named README or README.txt. But if we follow this convention, GitHub displays it as plain text in the project page which is not pretty. (unlike the beautiful HTML version when named as README.rst)
Is there any technique to make both PyPI and GitHub happy abo... | You could use a [git filter driver](http://stackoverflow.com/questions/2316677/can-git-automatically-switch-between-spaces-and-tabs/2316728#2316728) which would, on checkout, take your `README.md` (needed by GitHub) and generate a proper `README` (needed by Python, although [Lennart Regebro](http://stackoverflow.com/us... |
README extension for Python projects | 4,384,796 | 31 | 2010-12-08T06:33:24Z | 4,384,952 | 10 | 2010-12-08T06:59:18Z | [
"python",
"github"
] | Python packaging tools expect that our readme file should be named README or README.txt. But if we follow this convention, GitHub displays it as plain text in the project page which is not pretty. (unlike the beautiful HTML version when named as README.rst)
Is there any technique to make both PyPI and GitHub happy abo... | A crude way I can think of is to make a symlink to `README` called `README.rst` and check them both in. |
README extension for Python projects | 4,384,796 | 31 | 2010-12-08T06:33:24Z | 4,386,698 | 25 | 2010-12-08T11:02:02Z | [
"python",
"github"
] | Python packaging tools expect that our readme file should be named README or README.txt. But if we follow this convention, GitHub displays it as plain text in the project page which is not pretty. (unlike the beautiful HTML version when named as README.rst)
Is there any technique to make both PyPI and GitHub happy abo... | PyPI has no requirement that the file is called README or README.txt, so just call it README.rst. In fact, PyPI will not as far as I'm aware look in your package at all (although I could be wrong there, I haven't studied the code or anything), the text that ends up ion the front is the `long_description` parameter.
Th... |
How to make an internal hyper link in sphinx documentation | 4,385,315 | 23 | 2010-12-08T08:02:17Z | 4,385,347 | 22 | 2010-12-08T08:10:30Z | [
"python",
"python-sphinx"
] | How to make an internal hyper link in sphinx documentation?
I am using:
```
:role:`target`
```
But it is not working. | Cross-referencing is done using a `ref`
```
:ref:`label-name`
```
You can provide your labels using:
```
.. _label-name:
```
See: <http://sphinx.pocoo.org/markup/inline.html#ref-role>
Roles are used to create custom interpreted text. See: <http://docutils.sourceforge.net/docs/ref/rst/directives.html#role> |
Tkinter: How to make a system tray application? | 4,385,656 | 6 | 2010-12-08T08:53:13Z | 4,385,739 | 9 | 2010-12-08T09:07:16Z | [
"python",
"user-interface",
"system",
"tkinter",
"tray"
] | i have a small application. I want my target users(windows,linux) to be able to start and exit the application from the system tray. I intend to use Tkinter because of its low footprint but, i dont know how to implement it.
Can tkinter do this or are there better alternatives. I need a GUI library that won't change my... | I don't know any direct examples but I found a TCL/Tk extension to use the systray over here <http://wiki.tcl.tk/4090> and a [page](http://wiki.python.org/moin/How%20Tkinter%20can%20exploit%20Tcl/Tk%20extensions) on the wiki giving information on how to use TCL/Tk extensions from Tkinter.
On a more general note, you m... |
reimporting a single function in python | 4,385,839 | 3 | 2010-12-08T09:20:17Z | 4,385,926 | 9 | 2010-12-08T09:29:44Z | [
"python",
"function",
"import"
] | Using python in an interactive mode one imports a module then if the module is changed (a bug fix or something) one can simply use the reload() command.
But what if I didn't import the entire module and used the 'from M import f,g' import statement. Is there any way to reimport only g?
(I tried removing the function ... | When you do a `from foo import bar`, you *are* importing the entire module. You are just making a copy of the symbol `bar` in the current namespace. You are *not* importing just the function.
The `reload` function is not totally reliable (e.g. it will not work for compiled C modules). I would recommend that you exit a... |
Too many open files in python | 4,386,482 | 18 | 2010-12-08T10:34:41Z | 4,386,502 | 9 | 2010-12-08T10:36:55Z | [
"python",
"file-descriptor"
] | I wrote kind of a test suite which is heavily file intensive. After some time (2h) I get an `IOError: [Errno 24] Too many open files: '/tmp/tmpxsqYPm'`. I double checked all file handles whether I close them again. But the error still exists.
I tried to figure out the number of allowed file descriptors using `resource... | Your test script overwrites `f` each iteration, which means that the file will get closed each time. Both logging to files and `subprocess` with pipes use up descriptors, which can lead to exhaustion. |
Too many open files in python | 4,386,482 | 18 | 2010-12-08T10:34:41Z | 4,493,805 | 8 | 2010-12-20T20:47:14Z | [
"python",
"file-descriptor"
] | I wrote kind of a test suite which is heavily file intensive. After some time (2h) I get an `IOError: [Errno 24] Too many open files: '/tmp/tmpxsqYPm'`. I double checked all file handles whether I close them again. But the error still exists.
I tried to figure out the number of allowed file descriptors using `resource... | resource.RLIMIT\_NOFILE is indeed 7, but that's an index into resource.getrlimit(), not the limit itself... resource.getrlimit(resource.RLIMIT\_NOFILE) is what you want your top range() to be |
Too many open files in python | 4,386,482 | 18 | 2010-12-08T10:34:41Z | 13,624,412 | 10 | 2012-11-29T11:08:22Z | [
"python",
"file-descriptor"
] | I wrote kind of a test suite which is heavily file intensive. After some time (2h) I get an `IOError: [Errno 24] Too many open files: '/tmp/tmpxsqYPm'`. I double checked all file handles whether I close them again. But the error still exists.
I tried to figure out the number of allowed file descriptors using `resource... | The corrected code is:
```
import resource
import fcntl
import os
def get_open_fds():
fds = []
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
for fd in range(0, soft):
try:
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
except IOError:
continue
fds.append(f... |
Python:Ascii character<->decimal representation conversion | 4,387,138 | 4 | 2010-12-08T11:57:33Z | 4,387,163 | 17 | 2010-12-08T12:00:23Z | [
"python",
"ascii"
] | Hi I need to be able to convert a ascii character into its decimal equivalent and vice-versa.
How can I do that? | ```
num=ord(char)
char=chr(num)
```
For example,
```
>>> ord('a')
97
>>> chr(98)
'b'
```
You can read more about the built-in functions in Python [here](http://docs.python.org/library/functions.html). |
simulator of realistic ECG signal from rr data for matlab or python | 4,387,878 | 3 | 2010-12-08T13:19:57Z | 4,450,827 | 9 | 2010-12-15T14:15:28Z | [
"python",
"matlab",
"numpy",
"signal-processing",
"scipy"
] | I have a series of rr data (distances between r-r peak in PQRST electrocardiogramm signal)
and I want to generate realistic ECG signal in matlab or python. I've found some materials for matlab (`ecg` built-in function in matlab) but I can't figure out how to generate it from rr data, and I've found nothing for python. ... | Does this suit your needs? If not, please let me know. Good luck.
```
import scipy
import scipy.signal as sig
rr = [1.0, 1.0, 0.5, 1.5, 1.0, 1.0] # rr time in seconds
fs = 8000.0 # sampling rate
pqrst = sig.wavelets.daub(10) # just to simulate a signal, whatever
ecg = scipy.concatenate([sig.resample(pqrst, int(r*fs)) ... |
How to seek and append to a binary file in python? | 4,388,201 | 6 | 2010-12-08T13:50:20Z | 4,388,244 | 13 | 2010-12-08T13:54:14Z | [
"python",
"file",
"binary",
"seek"
] | I am having problems appending data to a binary file. When i seek() to a location, then write() at that location and then read the whole file, i find that the data was not written at the location that i wanted. Instead, i find it right after every other data/text.
My code
```
file = open('myfile.dat', 'wb')
file.writ... | On some systems, `'ab'` forces all writes to happen at the end of the file. You probably want `'r+b'`. |
Python "safe" eval (string to bool/int/float/None/string) | 4,388,626 | 11 | 2010-12-08T14:34:51Z | 4,388,647 | 25 | 2010-12-08T14:36:20Z | [
"python",
"parsing",
"type-conversion"
] | I'm making a webapp that does some data processing, so I frequently find myself parsing strings (from an URL or a text file) into Python values.
I use a function that is "kind of" a safer version of eval (except that if it can't read the string, it stays a string):
```
def str_to_value(string):
for atom in (True,... | [`ast.literal_eval()`](http://docs.python.org/library/ast.html#ast.literal_eval)
```
>>> ast.literal_eval('{False: (1, 0x2), True: [3.14, 04, 0b101], None: ("6", u"7", r\'8\')}')
{False: (1, 2), True: [3.1400000000000001, 4, 5], None: ('6', u'7', '8')}
``` |
In-place type conversion of a NumPy array | 4,389,517 | 81 | 2010-12-08T16:01:46Z | 4,390,114 | 9 | 2010-12-08T16:59:50Z | [
"python",
"numpy"
] | Given a NumPy array of `int32`, how do I convert it to `float32` **in place**? So basically, I would like to do
```
a = a.astype(numpy.float32)
```
without copying the array. It is big.
The reason for doing this is that I have two algorithms for the computation of `a`. One of them returns an array of `int32`, the ot... | You can change the array type without converting like this:
```
a.dtype = numpy.float32
```
but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's `struct` module like this:
```
def toi(i):
return struct.... |
In-place type conversion of a NumPy array | 4,389,517 | 81 | 2010-12-08T16:01:46Z | 4,396,247 | 56 | 2010-12-09T08:31:03Z | [
"python",
"numpy"
] | Given a NumPy array of `int32`, how do I convert it to `float32` **in place**? So basically, I would like to do
```
a = a.astype(numpy.float32)
```
without copying the array. It is big.
The reason for doing this is that I have two algorithms for the computation of `a`. One of them returns an array of `int32`, the ot... | You can make a view with a different dtype (as long as the itemsize remains the same), and then copy in-place into the view:
```
import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x
print(y)
```
yields
```
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
```
To... |
In-place type conversion of a NumPy array | 4,389,517 | 81 | 2010-12-08T16:01:46Z | 10,622,758 | 97 | 2012-05-16T16:29:42Z | [
"python",
"numpy"
] | Given a NumPy array of `int32`, how do I convert it to `float32` **in place**? So basically, I would like to do
```
a = a.astype(numpy.float32)
```
without copying the array. It is big.
The reason for doing this is that I have two algorithms for the computation of `a`. One of them returns an array of `int32`, the ot... | ```
a = a.astype(numpy.float32, copy=False)
```
numpy astype has a copy flag. Why shouldn't we use it ? |
How to fetch a non-ascii url with Python urlopen? | 4,389,572 | 19 | 2010-12-08T16:06:33Z | 4,391,299 | 37 | 2010-12-08T19:13:27Z | [
"python",
"unicode",
"urllib2",
"non-ascii-characters",
"urlopen"
] | I need to fetch data from a URL with non-ascii characters but urllib2.urlopen refuses to open the resource and raises:
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0131' in position 26: ordinal not in range(128)
```
I know the URL is not standards compliant but I have no chance to change it.
What... | Strictly speaking URIs can't contain non-ASCII characters; what you have there is an [IRI](http://en.wikipedia.org/wiki/Internationalized_Resource_Identifier).
To convert an IRI to a plain ASCII URI:
* non-ASCII characters in the hostname part of the address have to be encoded using the [Punycode](http://en.wikipedia... |
Django: chaining 'startswith' and 'iexact' query filters? | 4,390,227 | 8 | 2010-12-08T17:10:20Z | 4,390,282 | 16 | 2010-12-08T17:15:50Z | [
"python",
"django",
"django-queryset"
] | I want to do do a case-insensitive `startswith` query in Django:
```
books = Book.objects.filter(title__iexact__startswith=query)
```
But I get the following error message:
```
FieldError at /names/
Join on field 'title' not permitted
```
How can I specify a case-insensitive `startswith` in Django? | [`istartswith`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#istartswith) |
Python: Getting filter to work with lambda taking multiple arguments | 4,391,043 | 11 | 2010-12-08T18:45:55Z | 4,391,063 | 8 | 2010-12-08T18:48:10Z | [
"python"
] | Using Python, am finding it difficult to get filter() to work with lambda for cases where more than 1 argument needs to be passed as is the case in the following snippet:
```
max_validation = lambda x,y,z: x < y < z
sequence1 = [1,4,8]
filter(max_validation, sequence1)
```
It raises the following error:
```
TypeErro... | The function passed to `filter()` only gets a single argument passed to it, which is the current element in the iterable being iterated.. If you need something fancier than that then `filter()` won't do. |
Python: Getting filter to work with lambda taking multiple arguments | 4,391,043 | 11 | 2010-12-08T18:45:55Z | 4,391,222 | 14 | 2010-12-08T19:04:09Z | [
"python"
] | Using Python, am finding it difficult to get filter() to work with lambda for cases where more than 1 argument needs to be passed as is the case in the following snippet:
```
max_validation = lambda x,y,z: x < y < z
sequence1 = [1,4,8]
filter(max_validation, sequence1)
```
It raises the following error:
```
TypeErro... | It's a little bit difficult to figure out exactly what you're trying to do. I'm going to interpret your question, then provide an answer. If this is not correct, please modify your question or comment on this answer.
# Question
I have sequences that are exactly three elements long. Here's one:
```
sequence1 = [1, 4,... |
Find the index of a dict within a list, by matching the dict's value | 4,391,697 | 50 | 2010-12-08T20:00:35Z | 4,391,722 | 60 | 2010-12-08T20:03:29Z | [
"python"
] | I have a list of dicts:
```
list = [{'id':'1234','name':'Jason'},
{'id':'2345','name':'Tom'},
{'id':'3456','name':'Art'}]
```
How can I efficiently find the index position [0],[1], or [2] by matching on name = 'Tom'?
If this were a one-dimensional list I could do list.index() but I'm not sure how to ... | ```
tom_index = next(index for (index, d) in enumerate(lst) if d["name"] == "Tom")
# 1
```
As others have pointed out, if you are going to fetch repeatedly from name, you better construct a dictionary with the names as keys so *get* operations are O(1). Just an idea:
```
def build_dict(seq, key):
return dict((d[k... |
Find the index of a dict within a list, by matching the dict's value | 4,391,697 | 50 | 2010-12-08T20:00:35Z | 4,391,978 | 18 | 2010-12-08T20:29:29Z | [
"python"
] | I have a list of dicts:
```
list = [{'id':'1234','name':'Jason'},
{'id':'2345','name':'Tom'},
{'id':'3456','name':'Art'}]
```
How can I efficiently find the index position [0],[1], or [2] by matching on name = 'Tom'?
If this were a one-dimensional list I could do list.index() but I'm not sure how to ... | A simple readable version is
```
def find(lst, key, value):
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return -1
``` |
Raise a ValueError | 4,393,268 | 30 | 2010-12-08T23:08:55Z | 4,393,280 | 71 | 2010-12-08T23:10:39Z | [
"python",
"string"
] | I have this code which find the largest index of a specific character in a string , but I want it to raise a ValueError, when that specific character dose not occur in a string
something like this
```
contains('bababa', 'k')
ValueError: could not find k in bababa
```
How can I do this?
**this is the code**
... | `raise ValueError('could not find %c in %s' % (ch,str))` |
Raise a ValueError | 4,393,268 | 30 | 2010-12-08T23:08:55Z | 4,393,430 | 8 | 2010-12-08T23:35:41Z | [
"python",
"string"
] | I have this code which find the largest index of a specific character in a string , but I want it to raise a ValueError, when that specific character dose not occur in a string
something like this
```
contains('bababa', 'k')
ValueError: could not find k in bababa
```
How can I do this?
**this is the code**
... | ```
>>> def contains(string, char):
... for i in xrange(len(string) - 1, -1, -1):
... if string[i] == char:
... return i
... raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
... |
Raise a ValueError | 4,393,268 | 30 | 2010-12-08T23:08:55Z | 4,393,676 | 8 | 2010-12-09T00:15:41Z | [
"python",
"string"
] | I have this code which find the largest index of a specific character in a string , but I want it to raise a ValueError, when that specific character dose not occur in a string
something like this
```
contains('bababa', 'k')
ValueError: could not find k in bababa
```
How can I do this?
**this is the code**
... | Here's a cleaned-up version of essentially your code and logic that works, BTW `find_last`, `find_last_index`, or something like that might be a better name for this function.
```
def contains(char_string, char):
largest_index = -1
for i, ch in enumerate(char_string):
if ch == char:
largest... |
Python function telling me I sent two arguments when I only sent one | 4,393,340 | 3 | 2010-12-08T23:19:57Z | 4,393,361 | 9 | 2010-12-08T23:22:27Z | [
"python",
"google-app-engine"
] | I'm using Google's [webapp](http://code.google.com/appengine/docs/python/tools/webapp/) framework.
What I'm trying to do below is simply send the results of [query.fetch](http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_fetch) to a function that will take the results and create a table with... | The first argument is set implicitly by python when the method is bound to an instance. In this case util. When defining a method in a class, the first argument is usually named `self` and is the bound object.
```
class Utilities():
def create_table(self, results):
pass # more to come
```
Should work fin... |
Picking a Random Word In Python? | 4,394,145 | 7 | 2010-12-09T01:50:44Z | 4,394,153 | 13 | 2010-12-09T01:52:14Z | [
"python",
"random"
] | How would I pick a random word from a long list of words (in one list not multiple) and then print it to the user? | Use the [`random.choice()`](http://docs.python.org/library/random.html#random.choice) function:
```
>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
``` |
Replacing a Django image doesn't delete original | 4,394,194 | 23 | 2010-12-09T02:00:38Z | 8,342,249 | 21 | 2011-12-01T13:37:57Z | [
"python",
"django",
"imagefield"
] | In Django, if you have a ImageFile in a model, deleting will remove the associated file from disk as well as removing the record from the database.
Shouldn't replacing an image also remove the unneeded file from disk? Instead, I see that it keeps the original and adds the replacement.
Now deleting the object won't de... | The best strategy I've found is to make a custom save method in the model:
```
class Photo(models.Model):
image = ImageField(...) # works with FileField also
def save(self, *args, **kwargs):
# delete old file when replacing by updating the file
try:
this = Photo.objects.get(id=sel... |
Replacing a Django image doesn't delete original | 4,394,194 | 23 | 2010-12-09T02:00:38Z | 11,326,011 | 8 | 2012-07-04T09:14:11Z | [
"python",
"django",
"imagefield"
] | In Django, if you have a ImageFile in a model, deleting will remove the associated file from disk as well as removing the record from the database.
Shouldn't replacing an image also remove the unneeded file from disk? Instead, I see that it keeps the original and adds the replacement.
Now deleting the object won't de... | The code in the following working example will, upon uploading an image in an ImageField, detect if a file with the same name exists, and in that case, delete that file before storing the new one.
It could easily be modified so that it deletes the old file regardless of the filename. But that's not what I wanted in my... |
Replacing a Django image doesn't delete original | 4,394,194 | 23 | 2010-12-09T02:00:38Z | 14,680,225 | 11 | 2013-02-04T04:08:47Z | [
"python",
"django",
"imagefield"
] | In Django, if you have a ImageFile in a model, deleting will remove the associated file from disk as well as removing the record from the database.
Shouldn't replacing an image also remove the unneeded file from disk? Instead, I see that it keeps the original and adds the replacement.
Now deleting the object won't de... | > Shouldn't replacing an image also remove the unneeded file from disk?
In the olden days, `FileField` was eager to clean up orphaned files. But that changed in [Django 1.2](https://docs.djangoproject.com/en/1.4/releases/1.2.5/#filefield-no-longer-deletes-files):
> In earlier Django versions, when a model instance co... |
Does python support fixed size LIFO? | 4,394,389 | 3 | 2010-12-09T02:47:49Z | 4,394,427 | 8 | 2010-12-09T02:57:19Z | [
"python"
] | I want a data structure, fixed size LIFO, last in first out. Is it already there?
Edit: Sorry, what I want is LIFO not FIFO.
I checked <http://docs.python.org/library/queue.html>, it already provides the LIFO, the only thing I want to achieve is automatically drop the oldest one.
Eg) LIFO size 5 with elements: 1 2 3... | Both [collections.deque](http://docs.python.org/library/collections.html#collections.deque) and [queue.Queue](http://docs.python.org/library/queue.html#Queue.Queue) support fifo and a max size. |
Python - solve polynomial for y | 4,394,504 | 4 | 2010-12-09T03:16:37Z | 4,394,535 | 9 | 2010-12-09T03:22:27Z | [
"python",
"lambda",
"equation"
] | I'm taking in a function (e.g. y = x\*\*2) and need to solve for x. I know I can painstakingly solve this manually, but I'm trying to find instead a method to use. I've browsed numpy, scipy and sympy, but can't seem to find what I'm looking for. Currently I'm making a lambda out of the function so it'd be nice if i'm a... | If you are looking for numerical solutions (i.e. just interested in the numbers, not the symbolic closed form solutions), then there are a few options for you in the [SciPy.optimize](http://www.scipy.org/doc/api_docs/SciPy.optimize.html) module. For something simple, the [`newton`](http://www.scipy.org/doc/api_docs/Sci... |
PyLint Best Practices? | 4,395,499 | 23 | 2010-12-09T06:29:25Z | 4,395,913 | 10 | 2010-12-09T07:32:26Z | [
"python",
"static-analysis",
"pylint"
] | pyLint looks like a good tool for running analysis of python code. However, our main objective is to catch any potential bugs and not coding convention. Enabling all pyLint check seems to generate lot of noise. Any suggestions on a set of pyLint features you use and is effective? | [Pyflakes](http://pypi.python.org/pypi/pyflakes) should serve your purpose well. |
PyLint Best Practices? | 4,395,499 | 23 | 2010-12-09T06:29:25Z | 4,396,711 | 20 | 2010-12-09T09:36:31Z | [
"python",
"static-analysis",
"pylint"
] | pyLint looks like a good tool for running analysis of python code. However, our main objective is to catch any potential bugs and not coding convention. Enabling all pyLint check seems to generate lot of noise. Any suggestions on a set of pyLint features you use and is effective? | You can block any warnings/errors you don't like, via:
pylint --disable=[error,error]
I've blocked these (description from <http://www.logilab.org/card/pylintfeatures>
W0511: Used when a warning note as FIXME or XXX is detected
W0142: Used \* or \* magic\* Used when a function or method is called using \*args or \*... |
PyLint Best Practices? | 4,395,499 | 23 | 2010-12-09T06:29:25Z | 4,977,086 | 7 | 2011-02-12T08:13:06Z | [
"python",
"static-analysis",
"pylint"
] | pyLint looks like a good tool for running analysis of python code. However, our main objective is to catch any potential bugs and not coding convention. Enabling all pyLint check seems to generate lot of noise. Any suggestions on a set of pyLint features you use and is effective? | -E will only flag what pylint think is an error (i.e. no warnings, no conventions...) |
PyLint Best Practices? | 4,395,499 | 23 | 2010-12-09T06:29:25Z | 19,118,976 | 8 | 2013-10-01T14:33:42Z | [
"python",
"static-analysis",
"pylint"
] | pyLint looks like a good tool for running analysis of python code. However, our main objective is to catch any potential bugs and not coding convention. Enabling all pyLint check seems to generate lot of noise. Any suggestions on a set of pyLint features you use and is effective? | To persistently disable warnings and conventions:
1. Create a `~/.pylintrc` file by running `pylint --generate-rcfile > ~/.pylintrc`
2. Edit `~/.pylintrc`
3. Uncomment `disable=` and change that line to `disable=W,C` |
Tracking global migration to Python 3.x | 4,395,683 | 6 | 2010-12-09T06:59:29Z | 4,397,760 | 7 | 2010-12-09T11:37:10Z | [
"python",
"migration",
"python-3.x"
] | Python 3.x is looking ever more tempting with cleaned up syntax (I like it, others may not) new features and what looks like a gradual progression towards more speed and better multithreading.
But Python 3.x is still held back by lack of 3rd party support. Important packages like Django, Twisted, etc. are not ported. ... | George Brandl has made a script that generates a graph with the amount of packages supporting Python 3:
[](http://dev.pocoo.org/~gbrandl/py3pkgs.png)
The Link on the CheeseShop front page shows the packages in question: <http://pypi.python.org/pypi?%3a... |
Where is the help.py for Android's monkeyrunner | 4,396,408 | 9 | 2010-12-09T08:58:12Z | 4,470,513 | 14 | 2010-12-17T12:37:01Z | [
"android",
"python",
"testing",
"monkeyrunner"
] | I just can't find the `help.py` file in order to create the API reference for the `monkeyrunner`. The command described at the [Android references](http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html#Help)
`monkeyrunner <format> help.py <outfile>` does not work when i call `monkeyrunner html... | I cannot find it either. But one can assume that it is simply calling MonkeyRunner.help() with the passed in arguments. If you just want to get something quick use this script I created also named **help.py**:
```
#!/usr/bin/env python
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrun... |
What's the difference between "bind to variables" and "bind to object" in Python | 4,396,679 | 3 | 2010-12-09T09:32:35Z | 4,397,009 | 8 | 2010-12-09T10:09:05Z | [
"python",
"binding",
"closures"
] | When I studied "naming and binding" in Python, I saw the following example:
```
>>> def testClosure(maxIndex):
def closureTest(maxIndex=maxIndex):
return maxIndex
maxIndex += 5
return closureTest()
>>> print(testClosure(10))
10
>>> def testClosure(maxIndex):
def closureTes... | Two key facts:
1. Python uses [the LEGB rule](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) to look up
the value of (bare) variables names.
LEGB stands for Local, Extended,
Global, Builtins. That means a
variable name "binds" to the local
value, and if there is non... |
How do I schedule a task with Celery that runs on 1st of every month? | 4,397,530 | 8 | 2010-12-09T11:07:55Z | 4,398,992 | 9 | 2010-12-09T14:00:06Z | [
"python",
"django",
"scheduled-tasks",
"scheduling",
"celery"
] | How do I schedule a task with [celery](/questions/tagged/celery "show questions tagged 'celery'") that runs on 1st of every month? | Since Celery 3.0 the crontab schedule now supports `day_of_month`
and `month_of_year` arguments: <http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#crontab-schedules> |
Java equivalent of python's getattr? | 4,398,432 | 8 | 2010-12-09T12:56:08Z | 4,398,453 | 10 | 2010-12-09T12:58:19Z | [
"java",
"python",
"reflection"
] | I'm converting some python code to java, and have a situation where I need to call methods of an object but don't know which methods until runtime. In python I resolve this by using getattr on my object and passing it a string that is the name of my method. How would you do something similar in Java? | [`Class.getField`](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getField(java.lang.String)) is your friend. It probably won't be very straightforward though since Python is dynamically typed and Java is statically typed (unless you know the types of your fields in advance.)
EDIT: How to translate the... |
Python Unit Testing: Automatically Running the Debugger when a test fails | 4,398,967 | 28 | 2010-12-09T13:58:23Z | 4,399,246 | 20 | 2010-12-09T14:24:54Z | [
"python",
"unit-testing",
"pdb",
"pyunit"
] | Is there a way to automatically start the debugger at the point at which a unittest fails?
Right now I am just using pdb.set\_trace() manually, but this is very tedious as I need to add it each time and take it out at the end.
For Example:
```
import unittest
class tests(unittest.TestCase):
def setUp(self):
... | ```
import unittest
import sys
import pdb
import functools
import traceback
def debug_on(*exceptions):
if not exceptions:
exceptions = (AssertionError, )
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
... |
Python Unit Testing: Automatically Running the Debugger when a test fails | 4,398,967 | 28 | 2010-12-09T13:58:23Z | 6,012,325 | 30 | 2011-05-16T00:54:29Z | [
"python",
"unit-testing",
"pdb",
"pyunit"
] | Is there a way to automatically start the debugger at the point at which a unittest fails?
Right now I am just using pdb.set\_trace() manually, but this is very tedious as I need to add it each time and take it out at the end.
For Example:
```
import unittest
class tests(unittest.TestCase):
def setUp(self):
... | I think what you are looking for is [nose](https://nose.readthedocs.org/en/latest/). It works like a test runner for [unittest](http://docs.python.org/library/unittest.html).
You can drop into the debugger on errors, with the following command:
```
nosetests --pdb
``` |
How to set the min and max height or width of a Frame? | 4,399,180 | 9 | 2010-12-09T14:18:28Z | 4,399,545 | 10 | 2010-12-09T14:55:15Z | [
"python",
"user-interface",
"tkinter",
"ttk"
] | The size of Tkinter windows can be controlled via the following methods:
```
.minsize()
.maxsize()
.resizable()
```
Are there equivalent ways to control the size of Tkinter or ttk Frames?
@Bryan: I changed your frame1.pack code to the following:
```
frame1.pack(fill='both', expand=True)
frame1.bind( '<Configure>', ... | There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink o... |
Python DNS server with custom backend | 4,399,512 | 8 | 2010-12-09T14:52:18Z | 4,401,671 | 12 | 2010-12-09T18:19:17Z | [
"python",
"dns"
] | Is there any DNS server written in python where I can easily use a custom backend?
Basically, I just want to answer look-ups for some domain names with my own IPs, but pass the rest of the look-ups on to a real DNS server. | I wrote such a thing recently, maybe you can use it as an example. It uses a DHT as the backend and looks up all .kad domains there. If you simply replace the `P2PMapping` with your own mapping (ie a dict like `{'google.com' : '127.0.0.1'}`) it should do what you want.
```
"""
Created on 16.08.2010
@author: Jochen Ri... |
Python os.getlogin problem | 4,399,617 | 15 | 2010-12-09T15:02:29Z | 4,399,639 | 28 | 2010-12-09T15:04:23Z | [
"python",
"gitpython"
] | If i create a file like:
```
import os
print os.getlogin()
```
and run it with cron, I get an exception
```
print os.getlogin()
OSError: [Errno 22] Invalid argument
```
If I run it manually in shell -- it works.
Problem is, GitPython 0.3.1 in commit() uses this function, and i need to use it.
Is there any workaro... | From the `os.getlogin()` [docs](http://docs.python.org/library/os.html#os.getlogin): "Returns the user logged in to the controlling terminal of the process." Your script does not have a controlling terminal when run from `cron`. The docs go on to suggest: "For most purposes, it is more useful to use the environment var... |
initial_data fixture management in django | 4,400,609 | 5 | 2010-12-09T16:30:00Z | 6,543,812 | 8 | 2011-07-01T05:10:44Z | [
"python",
"django",
"fixture"
] | The django projet I'm working on has a ton of initial\_data fixture data. It seems by default the only way to have data load automatically is to have a file in your app folder called `fixtures`, and the file needs to be named `initial_data.ext` (ext being xml or json or yaml or something).
This is really unflexable, I... | In my experience, hard-coded fixtures are a pain to write and a pain to maintain. Wherever a model change breaks a fixture, the Django initial load will return a very unfriendly error message and you will end-up adding a bunch a of print's in the Django core in order to find where the problem is coming from.
One of th... |
How can each element of a numpy array be operated upon according to its relative value? | 4,401,122 | 7 | 2010-12-09T17:14:12Z | 4,401,180 | 14 | 2010-12-09T17:20:38Z | [
"python",
"numpy"
] | Let say that we have an array
```
a = np.array([10,30,50, 20, 10, 90, 0, 25])
```
The pseudo code for what I want -
```
if a[x] > 80 then perform funcA on a[x]
if 40 < a[x] <= 80 then perform funcB on a[x]
if a[x] <= 40 then perform funcC on a[x]
```
What is the cleanest way to perform this using numpy functions? | Usually, you try to avoid any Python loops over NumPy arrays -- that's why you use NumPy in the first place. For the sake of example, I assume that `funcA()` adds 1 to all elements, `funcB()` adds 2 and `funcC()` adds 3 (please elaborate what they really do for a more tailor-made example). To achieve what you want, you... |
How can each element of a numpy array be operated upon according to its relative value? | 4,401,122 | 7 | 2010-12-09T17:14:12Z | 4,402,444 | 8 | 2010-12-09T19:49:09Z | [
"python",
"numpy"
] | Let say that we have an array
```
a = np.array([10,30,50, 20, 10, 90, 0, 25])
```
The pseudo code for what I want -
```
if a[x] > 80 then perform funcA on a[x]
if 40 < a[x] <= 80 then perform funcB on a[x]
if a[x] <= 40 then perform funcC on a[x]
```
What is the cleanest way to perform this using numpy functions? | Look at numpy.piecewise. I think you want:
```
np.piecewise( a, [a > 80, (40 < a) & (a <= 80), a <= 40], [funcA, funcB, funcC] )
``` |
custom JSON sort_keys order in Python | 4,402,491 | 15 | 2010-12-09T19:54:28Z | 4,402,799 | 11 | 2010-12-09T20:28:07Z | [
"python",
"json",
"sorting"
] | Is there any way in Python 2.6 to supply a custom key or cmp function to JSON's sort\_keys?
I've got a list of dicts coming from JSON like so:
```
[
{
"key": "numberpuzzles1",
"url": "number-puzzle-i.html",
"title": "Number Puzzle I",
"category": "nestedloops",
"points": "60",
"n": "087"
}... | An idea (tested with 2.7, sorry, I have no 2.6):
```
import json
import collections
json.encoder.c_make_encoder = None
d = collections.OrderedDict([("b", 2), ("a", 1)])
json.dumps(d)
# '{"b": 2, "a": 1}'
```
See: [OrderedDict](http://docs.python.org/dev/library/collections.html#collections.OrderedDict) + [issue6105](... |
Python's [<generator expression>] at least 3x faster than list(<generator expression>)? | 4,402,858 | 14 | 2010-12-09T20:35:11Z | 4,402,893 | 9 | 2010-12-09T20:40:06Z | [
"python",
"performance",
"profiling"
] | It appears that using [] around a generator expression (test1) behaves substantially better than putting it inside of list() (test2). The slowdown isn't there when I simply pass a list into list() for shallow copy (test3). Why is this?
Evidence:
```
from timeit import Timer
t1 = Timer("test1()", "from __main__ impor... | `list(e for e in x)` isn't a list comprehension, it's a `genexpr` object `(e for e in x)` being created and passed to the `list` factory function. Presumably the object creation and method calls create overhead. |
Python's [<generator expression>] at least 3x faster than list(<generator expression>)? | 4,402,858 | 14 | 2010-12-09T20:35:11Z | 4,402,909 | 32 | 2010-12-09T20:42:09Z | [
"python",
"performance",
"profiling"
] | It appears that using [] around a generator expression (test1) behaves substantially better than putting it inside of list() (test2). The slowdown isn't there when I simply pass a list into list() for shallow copy (test3). Why is this?
Evidence:
```
from timeit import Timer
t1 = Timer("test1()", "from __main__ impor... | Well, my first step was to set the two tests up independently to ensure that this is not a result of e.g. the order in which the functions are defined.
```
>python -mtimeit "x=[34534534, 23423523, 77645645, 345346]" "[e for e in x]"
1000000 loops, best of 3: 0.638 usec per loop
>python -mtimeit "x=[34534534, 23423523... |
How to Download Files using Python? | 4,403,289 | 4 | 2010-12-09T21:26:47Z | 4,403,361 | 15 | 2010-12-09T21:35:40Z | [
"python",
"linux",
"command-line",
"centos",
"wget"
] | HI, everyone. I am new to Python and am using Python 2.5 on CentOS.
I need to download files like `WGET` do.
I have done some search, and there are some solutions, an obvious way is this:
```
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = open('test.mp3','wb')
output.write(... | There's an easier way:
```
import urllib
urllib.urlretrieve("http://www.example.com/songs/mp3.mp3", "/home/download/mp3.mp3")
``` |
List files in a folder as a stream to begin process immediately | 4,403,598 | 7 | 2010-12-09T22:02:43Z | 4,403,746 | 11 | 2010-12-09T22:22:09Z | [
"python",
"filesystems",
"stream"
] | I get a folder with 1 million files in it.
I would like to begin process immediately, when listing files in this folder, in Python or other script langage.
The usual functions (os.listdir in python...) are blocking and my program has to wait the end of the list, which can take a long time.
What's the best way to lis... | If convenient, change your directory structure; but if not, you can [use ctypes to call `opendir` and `readdir`](http://mysqlcon.com/python/waling-directory-with-very-many-files-t6360-10.html#p23155).
Here is a copy of that code; all I did was indent it properly, add the `try/finally` block, and fix a bug. You might h... |
debugging python web service | 4,404,654 | 8 | 2010-12-10T00:50:04Z | 4,404,838 | 16 | 2010-12-10T01:25:34Z | [
"python",
"urllib2"
] | I am using the instructions found [here](http://www.diveintopython.net/http_web_services/user_agent.html), to try to inspect the HTTP commands being sent to my webserver.
However, I am not seeing the HTTP commands being printed on the console as suggested in the tutorial. Does anyone know how to display/debug the HTTP... | The tutorial information seems to be deprecated.
Correct way to debug with `urllib2` nowadays is:
```
import urllib2
request = urllib2.Request('http://diveintomark.org/xml/atom.xml')
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
feeddata = opener.open(request).read()
```
Debugging with `urllib... |
How do I turn MongoDB query into a JSON? | 4,404,742 | 24 | 2010-12-10T01:05:37Z | 4,405,290 | 22 | 2010-12-10T03:06:08Z | [
"python",
"database",
"django",
"json",
"mongodb"
] | ```
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
```
In my Django/Python code, I can't return a JSON from a mongo query because of "ObjectID". The error says that "ObjectID" is not serializa... | The **json** module won't work due to things like the ObjectID.
Luckily [PyMongo](http://api.mongodb.org/python/1.9%2B/index.html) provides **json\_util** which ...
> ... allow[s] for specialized encoding and
> decoding of BSON documents into Mongo
> Extended JSON's Strict mode. This lets
> you encode / decode BSON d... |
How do I turn MongoDB query into a JSON? | 4,404,742 | 24 | 2010-12-10T01:05:37Z | 4,407,284 | 7 | 2010-12-10T09:20:39Z | [
"python",
"database",
"django",
"json",
"mongodb"
] | ```
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
```
In my Django/Python code, I can't return a JSON from a mongo query because of "ObjectID". The error says that "ObjectID" is not serializa... | It's pretty easy to write a custom serializer which copes with the ObjectIds. Django already includes one which handles decimals and dates, so you can extend that:
```
from django.core.serializers.json import DjangoJSONEncoder
from bson import objectid
class MongoAwareEncoder(DjangoJSONEncoder):
"""JSON encoder c... |
How do I turn MongoDB query into a JSON? | 4,404,742 | 24 | 2010-12-10T01:05:37Z | 11,543,206 | 17 | 2012-07-18T14:02:46Z | [
"python",
"database",
"django",
"json",
"mongodb"
] | ```
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
```
In my Django/Python code, I can't return a JSON from a mongo query because of "ObjectID". The error says that "ObjectID" is not serializa... | Here is a simple sample, using pymongo 2.2.1
```
import os
import sys
import pymongo
from bson import BSON
from bson import json_util
if __name__ == '__main__':
try:
connection = pymongo.Connection('mongodb://localhost:27017')
database = connection['mongotest']
except:
print('Error: Unable to Connect'... |
My Python for loop is causing a MemoryError. How can I optimize this? | 4,405,083 | 3 | 2010-12-10T02:16:19Z | 4,405,094 | 17 | 2010-12-10T02:19:24Z | [
"python",
"optimization",
"memory",
"out-of-memory"
] | I'm trying to compile a list of all the MAC address Apple devices will have. `oui.txt` tells me Apple has been assigned 77 MAC ranges to use. These ranges come in the form of:
```
00:00:00
00:11:11
etc...
```
This leaves me the last three HEX digits to append. That's `16^6`. A total of 1291845632 Apple MAC addresses.... | `range(1, 1291845633)` creates a list of 1,291,845,632 elements (several GB) all at once. Use `xrange(1, 1291845633)` instead and it will generate elements as you need them instead of all at once.
Regardless, it looks like you want something more like this:
```
for mac in apple_mac_range:
for i in xrange(1677721... |
Twisted, gevent eventlet - When would I use them | 4,405,667 | 8 | 2010-12-10T04:29:56Z | 4,411,300 | 10 | 2010-12-10T16:55:44Z | [
"python",
"twisted",
"gevent",
"eventlet"
] | Under what circumstances would something like eventlet/gevent be better than twisted? Twisted seems like the most used, but eventlet/gevent must have some advantages...
I'm not looking for an answer to a specific scenario, just generalities. | It's an issue of aesthetic preference, I think.
First of all, eventlet can actually use Twisted for networking, so in a sense, it's not an either-or question, it's a this-is-built-on-top-of-that question.
Personally, I don't see the need for libraries like gevent or eventlet, especially since the advent of the `@inli... |
Shortest representation of this function in Python | 4,405,968 | 2 | 2010-12-10T05:30:09Z | 4,406,013 | 7 | 2010-12-10T05:37:41Z | [
"python",
"math"
] | 
Currently I have:
```
def func(points): #Input is a matrix with n lines and 2 columns.
centroid = numpy.mean(points, axis=0)
sum = 0
for point in points:
x = point[0] - centroid[0]
y = point[1] - centorid[1]
sum += x**2 + y**2
ret... | There is a builtin for summation of a sequence, called `sum` (oddly enough). We can create the data using a generator comprehension, and feed it directly to the `sum` function. Thus:
```
return math.sqrt(sum((p[0]-centroid[0])**2 + (p[1]-centroid[1])**2 for p in points))
``` |
light weight template engine for python | 4,406,102 | 3 | 2010-12-10T05:53:00Z | 4,406,158 | 9 | 2010-12-10T06:04:55Z | [
"python",
"templating"
] | Which is the simplest and light weight html templating engine in Python which I can use to generate customized email newsletters. | For a really minor templating task, Python itself isn't that bad. Example:
```
def dynamic_text(name, food):
return """
Dear %(name)s,
We're glad to hear that you like %(food)s and we'll be sending you some more soon.
""" % {'name':name, 'food':food}
```
In this sense, you can use string formatting in... |
light weight template engine for python | 4,406,102 | 3 | 2010-12-10T05:53:00Z | 4,406,166 | 11 | 2010-12-10T06:06:21Z | [
"python",
"templating"
] | Which is the simplest and light weight html templating engine in Python which I can use to generate customized email newsletters. | Anything wrong with [string.Template](http://docs.python.org/2/library/string.html#template-strings)? This is in the standard Python distribution and covered by [PEP 292](http://www.python.org/dev/peps/pep-0292/):
```
from string import Template
form=Template('''Dear $john,
I am sorry to imform you, $john, but you w... |
Twisted and Websockets: Beyond Echo | 4,406,256 | 9 | 2010-12-10T06:21:34Z | 4,406,318 | 9 | 2010-12-10T06:32:59Z | [
"python",
"twisted",
"comet",
"websocket",
"twisted.web"
] | In my ongoing curiosity about websockets, I'm noticing a trend:
The "hello world" of the websocket universe, at least at the moment, seems to be "echo" functionality. That is, the demonstrated application is typically, "I send something, I receive something."
While aptly demonstrating that the protocol is functional,... | This is an example of an updated EchoHandler that will instead of just being reactive, be proactive.
```
class ChattyHandler(WebSocketHandler):
def connectionMade(self):
self.transport.write('oh hai\n')
self.saysomething()
def saysomething(self):
self.transport.write('still there?\n')
... |
if else in a list comprehension | 4,406,389 | 176 | 2010-12-10T06:45:51Z | 4,406,398 | 56 | 2010-12-10T06:48:04Z | [
"python",
"list",
"list-comprehension",
"if-statement"
] | I have a list `l`:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
```
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
I tried
```
[x+1 for x in l if x >= 45 else x+5]
```
But it gives me a syntax error. How can I achieve an `if` – `else` like this in a list comprehension? | You must put the expression at the beginning of the list comprehension, an if statement at the end filters elements!
```
[x+1 if x >= 45 else x+5 for x in l]
``` |
if else in a list comprehension | 4,406,389 | 176 | 2010-12-10T06:45:51Z | 4,406,399 | 206 | 2010-12-10T06:48:13Z | [
"python",
"list",
"list-comprehension",
"if-statement"
] | I have a list `l`:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
```
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
I tried
```
[x+1 for x in l if x >= 45 else x+5]
```
But it gives me a syntax error. How can I achieve an `if` – `else` like this in a list comprehension? | ```
>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in l]
[27, 18, 46, 51, 99, 70, 48, 49, 6]
```
Do-something if `<condition>`, else do-something else. |
if else in a list comprehension | 4,406,389 | 176 | 2010-12-10T06:45:51Z | 4,406,400 | 57 | 2010-12-10T06:48:28Z | [
"python",
"list",
"list-comprehension",
"if-statement"
] | I have a list `l`:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
```
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
I tried
```
[x+1 for x in l if x >= 45 else x+5]
```
But it gives me a syntax error. How can I achieve an `if` – `else` like this in a list comprehension? | ```
[x+1 if x >= 45 else x+5 for x in l]
```
And for a reward, here is the comment, I wrote to remember this the first time I did this error:
> Python's conditional expression is `a if C else b` and can't be used as:
>
> ```
> [a for i in items if C else b]
> ```
>
> The right form is:
>
> ```
> [a if C else b for i ... |
if else in a list comprehension | 4,406,389 | 176 | 2010-12-10T06:45:51Z | 4,406,777 | 137 | 2010-12-10T08:00:55Z | [
"python",
"list",
"list-comprehension",
"if-statement"
] | I have a list `l`:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
```
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
I tried
```
[x+1 for x in l if x >= 45 else x+5]
```
But it gives me a syntax error. How can I achieve an `if` – `else` like this in a list comprehension? | The reason you're getting this error has to do with how the list comprehension is performed.
Keep in mind the following:
```
[ expression for item in list if conditional ]
```
Is equivalent to:
```
for item in list:
if conditional:
expression
```
Where the `expression` is in a slightly different format... |
if else in a list comprehension | 4,406,389 | 176 | 2010-12-10T06:45:51Z | 24,568,242 | 9 | 2014-07-04T06:50:06Z | [
"python",
"list",
"list-comprehension",
"if-statement"
] | I have a list `l`:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
```
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
I tried
```
[x+1 for x in l if x >= 45 else x+5]
```
But it gives me a syntax error. How can I achieve an `if` – `else` like this in a list comprehension? | You can also put the conditional expression in brackets inside the list comprehension:
```
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
print [[x+5,x+1][x >= 45] for x in l]
```
[false,true][condition] is the syntax |
Change the name of a key in dictionary | 4,406,501 | 117 | 2010-12-10T07:09:21Z | 4,406,521 | 244 | 2010-12-10T07:11:29Z | [
"python",
"dictionary",
"sequence"
] | I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this? | Easily done in 2 steps:
```
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
```
Or in 1 step:
```
dictionary[new_key] = dictionary.pop(old_key)
```
which will raise `KeyError` if `dictionary[old_key]` is undefined. Note that this *will* delete `dictionary[old_key]`.
```
>>> dictionary = { 1: 'one... |
Change the name of a key in dictionary | 4,406,501 | 117 | 2010-12-10T07:09:21Z | 4,406,558 | 15 | 2010-12-10T07:17:41Z | [
"python",
"dictionary",
"sequence"
] | I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this? | pop'n'fresh
```
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>
``` |
Change the name of a key in dictionary | 4,406,501 | 117 | 2010-12-10T07:09:21Z | 4,406,745 | 13 | 2010-12-10T07:55:42Z | [
"python",
"dictionary",
"sequence"
] | I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this? | if you want to change all the keys:
```
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
```
if you want to change single key:
You can go with any of the above suggestion. |
Change the name of a key in dictionary | 4,406,501 | 117 | 2010-12-10T07:09:21Z | 20,563,278 | 7 | 2013-12-13T09:41:44Z | [
"python",
"dictionary",
"sequence"
] | I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this? | In python 2.7 and higher, you can use dictionary comprehension:
This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'
`{'key1:' :1, 'key2:' : 2, 'key3:' : 3}`
to get rid of the trailing ':' in the keys:
`corrected_dict = { x.replace(':', ''): ori... |
how to use python iterators elegently | 4,407,157 | 3 | 2010-12-10T09:05:05Z | 4,407,394 | 7 | 2010-12-10T09:35:26Z | [
"python",
"loops",
"iterator"
] | i am trying to use iterators more for looping since i heard it is faster than index looping. one thing i am not sure is about how to treat the end of the sequence nicely. the way i can think of is to use 'try' and 'except StopIteration', which looks ugly to me.
to be more concrete, suppose we are asked to print the me... | I think handling `a` and `b` more symmetrically would make it easier to read. Also, using the built-in `next` function in Python 2.6 with a default value avoids the need to handle `StopIteration`:
```
def merge(a, b):
"""Merges two iterators a and b, returning a single iterator that yields
the elements of a an... |
Python: How to make an option to be required in optparse? | 4,407,539 | 21 | 2010-12-10T09:51:25Z | 4,407,608 | 51 | 2010-12-10T09:58:25Z | [
"python",
"command-line",
"command-line-arguments"
] | I've read this <http://docs.python.org/release/2.6.2/library/optparse.html>
But I'm not so clear how to make an option to be required in optparse?
I've tried to set "required=1" but I got an error:
> invalid keyword arguments: required
I want to make my script require `--file` option to be input by users. I know th... | You can implement a required option easily.
```
parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file',
dest='filename',
help='foo help')
(options, args) = parser.parse_args()
if not options.filename: # if filename is not give... |
Python: How to make an option to be required in optparse? | 4,407,539 | 21 | 2010-12-10T09:51:25Z | 8,522,959 | 7 | 2011-12-15T16:03:00Z | [
"python",
"command-line",
"command-line-arguments"
] | I've read this <http://docs.python.org/release/2.6.2/library/optparse.html>
But I'm not so clear how to make an option to be required in optparse?
I've tried to set "required=1" but I got an error:
> invalid keyword arguments: required
I want to make my script require `--file` option to be input by users. I know th... | On the help message of each required variable Im writting a '[REQUIRED]' string at the beggining, to tag it to be parsed later, then I can simply use this function to wrap it around:
```
def checkRequiredArguments(opts, parser):
missing_options = []
for option in parser.option_list:
if re.match(r'^\[RE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.