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 |
|---|---|---|---|---|---|---|---|---|---|
Pyramid: how to set cookie without renderer? | 8,746,087 | 8 | 2012-01-05T16:35:14Z | 8,748,975 | 12 | 2012-01-05T20:04:03Z | [
"python",
"pyramid"
] | In configuration file:
```
config.add_route('lang', '/lang-{code}')
```
In views:
```
@view_config(route_name='lang')
def lang(request):
code = request.matchdict['code']
response = Response()
response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
return HTTPFound(location=request... | [This answer](http://stackoverflow.com/a/8746156/) is excellent. Another option is usage of the `HTTPFound` instance as a `Response`:
```
@view_config(route_name='lang')
def lang(request):
code = request.matchdict['code']
response = HTTPFound(location=request.environ['HTTP_REFERER'])
response.set_cookie('l... |
Python's pretty printing of matrix | 8,747,500 | 2 | 2012-01-05T18:10:17Z | 8,747,570 | 9 | 2012-01-05T18:15:15Z | [
"python",
"regex",
"string",
"list"
] | I have to print several rows of data and do it good. I can do it with C++ changing parameters of std::cout, but I can't understand how I can do it with Python. For example, I have this:
```
row1 = [1, 'arc1.tgz', 'First', '15.02.1992']
row2 = [16, 'arc2modified.tgz', 'Second', 'today']
row3 = ['112', 'arc89.tgz', 'Cor... | ```
my_matrix = [row1, row2, row3]
print "\n".join(["\t".join(map(str, r)) for r in my_matrix])
```
ETA: My original answer missed that you wanted each column to be of a fixed width, using padded spaces (rather than tabs). It also looks like you want exactly two spaces between the longest datum and the next column. In... |
Assignment with "or" in python | 8,747,740 | 6 | 2012-01-05T18:27:51Z | 8,747,786 | 7 | 2012-01-05T18:31:28Z | [
"python",
"coding-style",
"variable-assignment"
] | Is it considered bad style to assign values to variables like this?
```
x = "foobar" or None
y = some_variable or None
```
In the above example, x gets the value 'foobar'. | No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours. |
scipy, lognormal distribution - parameters | 8,747,761 | 17 | 2012-01-05T18:29:08Z | 8,748,722 | 17 | 2012-01-05T19:45:09Z | [
"python",
"statistics",
"scipy"
] | I want to fit lognormal distribution to my data, using python `scipy.stats.lognormal.fit`. According to the [manual](http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.lognorm.html), `fit` returns *shape, loc, scale* parameters. But, lognormal distribution normally needs only [two parameters](http://... | The distributions in scipy are coded in a generic way wrt two parameter location and scale so that location is the parameter (`loc`) which shifts the distribution to the left or right, while `scale` is the parameter which compresses or stretches the distribution.
For the two parameter lognormal distribution, the "mean... |
Is there a builtin identity function in python? | 8,748,036 | 56 | 2012-01-05T18:49:27Z | 8,748,063 | 19 | 2012-01-05T18:51:43Z | [
"python",
"python-3.x"
] | I'd like to point to a function that does nothing:
```
def identity(*args)
return args
```
my use case is something like this
```
try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity
```
Of course, I could use the `identity` defined above, but a built-in would certainly run faster (... | No, there isn't a built-in `identity` function, but writing one that behaves appropriately for both single and multiple inputs is not difficult:
```
def identity(*args):
if len(args) == 1:
return args[0]
return args
```
And in use:
```
>>> identity(4)
4 # passed in a single object, got that ... |
Is there a builtin identity function in python? | 8,748,036 | 56 | 2012-01-05T18:49:27Z | 8,748,111 | 8 | 2012-01-05T18:55:51Z | [
"python",
"python-3.x"
] | I'd like to point to a function that does nothing:
```
def identity(*args)
return args
```
my use case is something like this
```
try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity
```
Of course, I could use the `identity` defined above, but a built-in would certainly run faster (... | yours will work fine. When the number of parameters is fix you can use an anonymous function like this:
```
lambda x: x
``` |
Is there a builtin identity function in python? | 8,748,036 | 56 | 2012-01-05T18:49:27Z | 8,748,146 | 39 | 2012-01-05T18:58:27Z | [
"python",
"python-3.x"
] | I'd like to point to a function that does nothing:
```
def identity(*args)
return args
```
my use case is something like this
```
try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity
```
Of course, I could use the `identity` defined above, but a built-in would certainly run faster (... | Doing some more research, there is none, a feature was asked in [issue 1673203](http://bugs.python.org/issue1673203) And from [Raymond Hettinger said there won't be](http://mail.python.org/pipermail/python-ideas/2009-March/003647.html):
> Better to let people write their own trivial pass-throughs
> and think about the... |
Removing Duplicates From Dictionary | 8,749,158 | 13 | 2012-01-05T20:17:22Z | 8,749,473 | 21 | 2012-01-05T20:40:28Z | [
"python",
"dictionary",
"duplicates"
] | I have the following Python 2.7 dictionary data structure (I do not control source data - comes from another system as is):
```
{112762853378:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4'],
'alias': ['www.example.com']
},
112762853385:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4'],
'alias... | You could go though each of the items (the key value pair) in the dictionary and add them into a result dictionary if the value was not already in the result dictionary.
```
input_raw = {112762853378:
{'dst': ['10.121.4.136'],
'src': ['1.2.3.4'],
'alias': ['www.example.com']
},
112762853385:
{'ds... |
creating a defaultlist in python | 8,749,542 | 9 | 2012-01-05T20:45:29Z | 8,749,640 | 17 | 2012-01-05T20:53:39Z | [
"python",
"list",
"subclassing"
] | I'm trying to create a list equivalent for the very useful [`collections.defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict). The following design works nicely:
```
class defaultlist(list):
def __init__(self, fx):
self._fx = fx
def __setitem__(self, index, value):
... | On the example you give, you first try to retrieve a non-existing value on the list, as you do `dl[2]['a']`, Python first retrieve the third (index 2) element on the list, then proceed to get the element named 'a' on that object - therefore you have to implement your automatic extending behavior to the `__getitem__` me... |
Point and figure chart with matplotlib | 8,750,648 | 4 | 2012-01-05T22:16:35Z | 8,761,382 | 7 | 2012-01-06T16:54:10Z | [
"python",
"matplotlib"
] | I'm trying to make a [point and figure chart](http://en.wikipedia.org/wiki/File%3aPoint%26Figure.GIF). I can get it to work printing out on the terminal but I want to graph it with matplotlib. What would be the best way of doing something like this? I was thinking scatter, but when I do this the columns are spread out ... | You can adjust the size of the symbols used in a scatter plot by choosing the `s` [parameter](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.scatter). You also will likely need to adjust the size of your figure (with [figsize](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.fi... |
python http web server | 8,752,155 | 2 | 2012-01-06T01:04:07Z | 8,752,187 | 7 | 2012-01-06T01:08:51Z | [
"python",
"http",
"httpserver",
"basehttprequesthandler"
] | I have created a simple http server for my family on the local network, when i add a html file and png picture and tried to view the HTML file, my image cannot load.
It says:
"The image âhttp://***.***.***.***:255/header.pngâ cannot be displayed because it contains errors."
Here is a bit of my code
```
... | The default mode of [`open`](http://docs.python.org/library/functions.html#open) is `'r'`, which stands for reading text data and does automatic EOL conversion on Windows. Replace `f = open(curdir + sep + self.path); self.wfile.write(f.read())` with
```
fn = os.path.normpath(os.path.join(curdir, self.path))
if not fn.... |
How to change the behavior of a python dictionary's __setattr__? | 8,752,451 | 3 | 2012-01-06T01:46:19Z | 8,752,472 | 11 | 2012-01-06T01:50:39Z | [
"python",
"types",
"dictionary",
"customization",
"internals"
] | In Python, everything has a class. Therefore `dict` also has a class.
So, in theory, I should be able to change the implementation of the keyvalue assignment behavior.
**Example:**
```
d = dict()
d['first'] = 3 # Internally d['first'] is stored as 6 [i.e. value*2 if value is INT]
print d['first'] # should print... | It is `__setitem__` that have to be overriden in this case -
and it is as simples as:
```
class MyDict(dict):
def __setitem__(self, key, value):
dict.__setitem__(self, key, 2 * value)
```
Example:
```
>>> m = MyDict()
>>> m[0] = 5
>>> m
{0: 10}
```
`__setattr__` controls how object attributes themselv... |
How to change the behavior of a python dictionary's __setattr__? | 8,752,451 | 3 | 2012-01-06T01:46:19Z | 8,752,824 | 7 | 2012-01-06T02:55:26Z | [
"python",
"types",
"dictionary",
"customization",
"internals"
] | In Python, everything has a class. Therefore `dict` also has a class.
So, in theory, I should be able to change the implementation of the keyvalue assignment behavior.
**Example:**
```
d = dict()
d['first'] = 3 # Internally d['first'] is stored as 6 [i.e. value*2 if value is INT]
print d['first'] # should print... | Be careful when subclassing `dict`. If you just override `__setitem__`, then other `dict` methods, such as `update`, will not call your `__setitem__`.
```
class MyDict(dict):
def __setitem__(self, key, value):
dict.__setitem__(self, key, 2 * value)
d = MyDict()
d['first'] = 3
print(d['first'])
# 6
d.upd... |
Is it possible to add a header to the email django sends to admins when a 500 is generated? | 8,752,765 | 5 | 2012-01-06T02:42:12Z | 8,752,832 | 8 | 2012-01-06T02:57:25Z | [
"python",
"django",
"email"
] | I'm using a third party to send email, and they allow me to categorize my email by adding headers to the emails i send through them.
Is it possible to either add a header to the exception email before it gets sent? Or at least, I'll managing sending the email by catching the exception in the middleware, but how do I g... | 1. **Subclass AdminEmailHandler** (defined in [django.utils.log](https://code.djangoproject.com/browser/django/trunk/django/utils/log.py)).
2. Configure [logging](https://docs.djangoproject.com/en/dev/topics/logging/) accordingly.
Here is how `AdminEmailHandler` works:
```
class AdminEmailHandler(logging.Handler):
... |
How to make celery retry using the same worker? | 8,753,216 | 6 | 2012-01-06T04:04:19Z | 8,762,481 | 11 | 2012-01-06T18:15:47Z | [
"python",
"django",
"rabbitmq",
"celery"
] | I'm just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broken into several steps, each of which takes considerable time to complete. Therefore, if some step fails, I'd like celer... | You could have every celeryd instance consume from a queue named after the hostname of the worker:
```
celeryd -l info -n worker1.example.com -Q celery,worker1.example.com
```
sets the hostname to `worker1.example.com` and will consume from a queue named the same, as well as the default queue (named `celery`).
Then... |
Python multiprocessing for parallel processes | 8,753,306 | 6 | 2012-01-06T04:17:23Z | 8,753,815 | 13 | 2012-01-06T05:35:04Z | [
"python",
"multiprocessing"
] | I'm sorry if this is too simple for some people, but I still don't get the trick with python's multiprocessing. I've read
<http://docs.python.org/dev/library/multiprocessing>
<http://pymotw.com/2/multiprocessing/basics.html>
and many other tutorials and examples that google gives me... many of them from here too.
... | You are correct, they are executing sequentially in your example.
`p.join()` causes the current thread to block until it is finished executing. You'll either want to join your processes individually outside of your for loop (e.g., by storing them in a list and then iterating over it) or use something like `numpy.Pool`... |
Remove String From List | 8,753,517 | 3 | 2012-01-06T04:51:46Z | 8,753,548 | 13 | 2012-01-06T04:54:54Z | [
"python",
"list"
] | I have a list of strings containing IP addresses and DNS names with which I would like to remove the values beginning with "10." only. The sample data is as follows:
`['www.example.com','1.2.3.4','4.3.2.1','example.net','10.1.1.10','10.1.1.11',...]`
I thought this would be simple and started with the following:
```
... | The easy way would be to use list comprehensions:
```
filtered = [ v for v in address if not v.startswith('10.') ]
``` |
How to get a list of all the fonts currently available for Matplotlib? | 8,753,835 | 16 | 2012-01-06T05:38:14Z | 8,755,818 | 23 | 2012-01-06T09:33:52Z | [
"python",
"matplotlib"
] | e.g. when I want to set `font` in
```
matplotlib.rc('font', **font)
```
Thanks. | ```
import matplotlib.font_manager
matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
```
Check [this](http://matplotlib.sourceforge.net/api/font_manager_api.html) for other options. |
python compiler | 8,753,906 | 13 | 2012-01-06T05:46:55Z | 8,754,506 | 15 | 2012-01-06T07:03:56Z | [
"python"
] | I have a few queries regarding python
1. Why is there no python compiler to create native code? I have found py2exe etc but they just pack a python interpreter along with them and hence, it is again the interpreter executing the code.
2. Is it not possible to create a python compiler like a LISP compiler and hence the... | [Nuitka â Python Compiler](http://www.nuitka.net/blog/nuitka-a-python-compiler/)
> **What it is**
>
> I thought there ought to be possible to use a compiler for Python, a better compiler than what CPython already has with its bytecode. This is what Nuitka is supposed to be.
>
> It is my attempt to translate pure Pyt... |
python compiler | 8,753,906 | 13 | 2012-01-06T05:46:55Z | 8,757,210 | 9 | 2012-01-06T11:34:30Z | [
"python"
] | I have a few queries regarding python
1. Why is there no python compiler to create native code? I have found py2exe etc but they just pack a python interpreter along with them and hence, it is again the interpreter executing the code.
2. Is it not possible to create a python compiler like a LISP compiler and hence the... | Question 1:
* [Nuitka](http://www.nuitka.net/blog/2011/12/nuitka-release-0-3-16/) (Direct Python code to C++)
* [ShedSkin](http://code.google.com/p/shedskin/) (Compiles implicitly statically typed Python to C++, stand-alone programs or
extension modules)
* [Cython](http://cython.org/) (From a superset of Python to C... |
It is possible to install Fabric(Python) in Virtualenv? Getting an error | 8,755,809 | 7 | 2012-01-06T09:32:38Z | 8,756,712 | 15 | 2012-01-06T10:52:26Z | [
"python",
"virtualenv",
"fabric"
] | I'm trying to install Fabric in Virtualenv but I'm getting an error. I'm usinh Python 2.7.2+
```
src/MD2.c:31:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command /home/andre/python_virtualenv/bin... | If you use Debian-flavored Linux, you need to install python2.x-dev package
sudo apt-get install python2.7-dev
This is because some python libs are just binding to C libs which need to be compiled before used, requiring headers to do so.
Fabric use Paramiko to connect via SSH, which includes such bindings.
Headers ... |
Python - Where should a library store temporary files? | 8,757,313 | 2 | 2012-01-06T11:43:48Z | 8,757,323 | 7 | 2012-01-06T11:44:49Z | [
"python",
"package",
"temporary-files",
"temporary-directory"
] | I'm writing a Python library which needs to cache remote data on the local machine.
I would like to prevent the library from polluting the OS and placing temp files where they don't belong. To use OS default temp folders seems a bit long winded as I would like to use one OS-Independent way of doing this.
Would storin... | Consider using `tempfile`, see <http://docs.python.org/library/tempfile.html> |
python3 multiprocessing example crashed my pc :( | 8,759,234 | 4 | 2012-01-06T14:20:57Z | 8,759,324 | 9 | 2012-01-06T14:27:42Z | [
"python",
"python-3.x",
"multiprocessing"
] | I am new to multiprocessing
I have run example code for two 'highly recommended' multiprocessing examples given in response to other stackoverflow multiprocessing questions. Here is an example of one (which i dare not run again!)
**test2.py** (running from pydev)
```
import multiprocessing
class MyFancyClass(object... | From [the docs](http://docs.python.org/py3k/library/multiprocessing.html#windows):
> Make sure that the main module can be safely imported by a new Python
> interpreter without causing unintended side effects (such a starting a
> new process).
Thus, on Windows, you must wrap your code inside a
```
if __name__=='__ma... |
Equivalent of __func__ (from C) in Python | 8,759,359 | 4 | 2012-01-06T14:30:43Z | 8,759,414 | 7 | 2012-01-06T14:34:34Z | [
"python",
"python-2.x"
] | I want to create some kind of debugging output for python and want to pass the functionname to another function for output.
The only reasonable way I found to do so was:
```
def foobar():
print 'hello world'
print foobar.__name__
```
is there something that does the same thing for the current function to improv... | One thing you could try is to create a decorator that does this:
```
def traceme(func):
def newfunc(*args, **kwargs):
ret = func(*args, **kwargs)
print func.__name__
return ret
return newfunc
@traceme
def foobar():
print 'hello world'
``` |
Equivalent of __func__ (from C) in Python | 8,759,359 | 4 | 2012-01-06T14:30:43Z | 8,759,448 | 7 | 2012-01-06T14:37:06Z | [
"python",
"python-2.x"
] | I want to create some kind of debugging output for python and want to pass the functionname to another function for output.
The only reasonable way I found to do so was:
```
def foobar():
print 'hello world'
print foobar.__name__
```
is there something that does the same thing for the current function to improv... | [sys.\_getframe](http://code.activestate.com/recipes/66062-determining-current-function-name/) can do that:
```
import sys
def foobar():
print sys._getframe().f_code.co_name
``` |
Re-raise Python exception and preserve stack trace | 8,760,267 | 36 | 2012-01-06T15:34:30Z | 8,760,670 | 36 | 2012-01-06T16:03:08Z | [
"python",
"exception",
"stack-trace"
] | I'm trying to catch an exception in a thread and re-raise it in the main thread:
```
import threading
import sys
class FailingThread(threading.Thread):
def run(self):
try:
raise ValueError('x')
except ValueError:
self.exc_info = sys.exc_info()
failingThread = FailingThread... | You need to use all three arguments to raise:
```
raise failingThread.exc_info[0], failingThread.exc_info[1], failingThread.exc_info[2]
```
passing the traceback object in as the third argument preserves the stack.
From `help('raise')`:
> If a third object is present and not `None`, it must be a traceback
> object ... |
How can I get a textarea from model+ModelForm? | 8,761,106 | 3 | 2012-01-06T16:32:59Z | 8,761,154 | 13 | 2012-01-06T16:35:52Z | [
"python",
"django",
"forms",
"model"
] | models.py=>
```
from django.db import models
from django.forms import ModelForm
from datetime import date
import datetime
from django import forms
from django.forms import Textarea
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created = models.DateField(au... | I think this [section](https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#s-overriding-the-default-field-types-or-widgets) in the documentation should be useful to solve the problem.
```
from django.forms import ModelForm, Textarea
class PostModelForm(ModelForm):
class Meta:
model = Post
... |
Django - Modifying the look of simple search results | 8,761,166 | 3 | 2012-01-06T16:36:30Z | 8,761,286 | 7 | 2012-01-06T16:46:00Z | [
"python",
"django",
"search"
] | I'm making my first steps with django, at the moment im trying to apply simple search solution for my website using: <http://julienphalip.com/post/2825034077/adding-search-to-a-django-site-in-a-snap>
This is how code looks like:
search.py
```
import re
from django.db.models import Q
def normalize_query(query_strin... | This is where your problem is
```
{% for i in found_entries %}
<li><a href="{{ i.get_absolute_url }}">{{i}}</a></li>
{% endfor %}
```
When you simply show `{{i}}`, then the model's `__unicode__` method is used.
If you want to show more, you can use `{{i.category}}`... |
Peter Piper piped a Python program - and lost all his unicode characters | 8,761,310 | 16 | 2012-01-06T16:48:15Z | 8,761,688 | 8 | 2012-01-06T17:15:31Z | [
"python",
"utf-8",
"character-encoding",
"iso-8859-1",
"piping"
] | I have a Python script that loads a web page using `urllib2.urlopen`, does some various magic, and spits out the results using `print`. We then run the program on Windows like so:
```
python program.py > output.htm
```
**Here's the problem:**
The `urlopen` reads data from an IIS web server which outputs UTF8. It spi... | From your comments and question update it seems that the data is correctly encoded in UTF-8. This means you just need to tell your browser it's UTF-8, either by using a BOM, or better, by adding encoding information to your HTML document:
```
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">... |
Possible to capture the returned value from a Python list comprehension for use a condition? | 8,761,437 | 7 | 2012-01-06T16:57:40Z | 8,761,552 | 10 | 2012-01-06T17:05:19Z | [
"python",
"list-comprehension"
] | I want to construct a value in a list comprehension, but also filter on that value. For example:
```
[expensive_function(x) for x in generator where expensive_function(x) < 5]
```
I want to avoid calling `expensive_function` twice per iteration.
The `generator` may return an infinite series, and list comprehensions ... | If `generator` may be infinite, you do not want to use a list comprehension. And not everything has to be a one-liner.
```
def filtered_gen(gen):
for item in gen:
result = expensive_function(item)
if result < 5:
yield result
``` |
Limiting Python input strings to certain characters and lengths | 8,761,778 | 6 | 2012-01-06T17:21:56Z | 8,761,818 | 11 | 2012-01-06T17:25:33Z | [
"python",
"string",
"limit",
"user-input"
] | I just started learning my first real programming language, Python. I'd like to know how to constrain user input in a `raw_input` to certain characters and to a certain length. For example, I'd like to show an error message if the user inputs a string that contains anything except the letters `a-z`, and I'd like to sho... | Regexes can also limit the number of characters.
```
r = re.compile("^[a-z]{1,15}$")
```
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long. |
Limiting Python input strings to certain characters and lengths | 8,761,778 | 6 | 2012-01-06T17:21:56Z | 8,761,880 | 8 | 2012-01-06T17:28:33Z | [
"python",
"string",
"limit",
"user-input"
] | I just started learning my first real programming language, Python. I'd like to know how to constrain user input in a `raw_input` to certain characters and to a certain length. For example, I'd like to show an error message if the user inputs a string that contains anything except the letters `a-z`, and I'd like to sho... | **Question 1: Restrict to certain characters**
You are right, this is easy to solve with [regular expressions](http://docs.python.org/library/re.html):
```
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()... |
Python tkinter StringVar() error on init | 8,762,747 | 4 | 2012-01-06T18:39:15Z | 8,762,889 | 7 | 2012-01-06T18:52:17Z | [
"python",
"tkinter"
] | (Python version: 3.1.1)
I am having a strange problem with StringVar in tkinter. While attempting to continuously keep a Message widget updated in a project, I kept getting an error while trying to create the variable. I jumped out to an interactive python shell to investigate and this is what I got:
```
>>> StringVa... | StringVar needs a master:
```
>>> StringVar(Tk())
<Tkinter.StringVar instance at 0x0000000004435208>
>>>
```
or more commonly:
```
>>> root = Tk()
>>> StringVar()
<Tkinter.StringVar instance at 0x0000000004435508>
```
When you instantiate Tk a new interpreter is created. Before that nothing works:
```
>>> from Tki... |
RuntimeError: dictionary changed size during iteration - During Iteration with iteritems on a defaultdict | 8,762,819 | 3 | 2012-01-06T18:46:06Z | 8,762,876 | 10 | 2012-01-06T18:50:49Z | [
"python",
"dictionary",
"iterator",
"runtime-error"
] | While answering a particular question here in SO I stumbled upon a peculiar issue which I couldn't explain. Unfortunately the first two Google Search page returned one [SO](http://stackoverflow.com/questions/2844837/how-to-fix-this-python-error-runtimeerror-dictionary-changed-size-during-itera) Page which was also not ... | Adding or deleting items of a dictionary while iterating over it is an error. Since `somehash` is a `defaultdict`, even what seems like a read-only access in the line
```
if somehash[maxkey] > k:
```
might add a new key -- resulting in the error you encountered. |
How to implement a simple button in PyQt | 8,762,870 | 3 | 2012-01-06T18:50:18Z | 8,763,339 | 13 | 2012-01-06T19:28:46Z | [
"python",
"button",
"pyqt",
"pyqt4",
"signals-slots"
] | I want to implement a simple button in pyqt which prints "Hello world" when clicked. How can i do that?
I am a real newbie in PyQt. I am using fedora.
Thanks all | If you're new to PyQt4, there are some useful tutorials on the [PyQt Wiki](http://wiki.python.org/moin/PyQt) to get you started.
But in the meantime, here's your "Hello World" example:
```
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
... |
How to handle urllib's timeout in Python 3? | 8,763,451 | 7 | 2012-01-06T19:36:45Z | 8,763,542 | 14 | 2012-01-06T19:45:33Z | [
"python",
"exception",
"urllib"
] | First off, my problem is quite similar to [this one](http://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python). I would like a timeout of urllib.urlopen() to generate an exception that I can handle.
Doesn't this fall under URLError?
```
try:
response = urllib.request.urlopen(url, timeout=10).re... | The exception is timeout from socket, so
```
from socket import timeout
try:
response = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
except (HTTPError, URLError) as error:
logging.error('Data of %s not retrieved because %s\nURL: %s', name, error, url)
except timeout:
logging.error('socket... |
Preprocessing 400 million tweets in Python -- faster | 8,764,066 | 5 | 2012-01-06T20:29:31Z | 8,764,229 | 7 | 2012-01-06T20:43:21Z | [
"python",
"twitter"
] | I have 400 million tweets ( actually I think its almost like 450 but never mind ) , in the form :
```
T "timestamp"
U "username"
W "actual tweet"
```
I want to write them to a file initially in the form "username \t tweet" and then load into a DB . The problem is that before loading into a db, there are a fe... | This is what [multiprocessing](http://docs.python.org/library/multiprocessing.html) is for.
You have a pipeline that can be broken into a large number of small steps. Each step is a `Process` which does to get for an item from the pipe, does a small transformation and puts an intermediate result to the next pipe.
You... |
scipy.linalg.eig return complex eigenvalues for covariance matrix? | 8,765,310 | 8 | 2012-01-06T22:29:02Z | 8,765,592 | 15 | 2012-01-06T22:58:20Z | [
"python",
"matlab",
"numpy",
"scipy",
"linear-algebra"
] | The eigenvalues of a covariance matrix should be real and non-negative because covariance matrices are symmetric and semi positive definite.
However, take a look at the following experiment with scipy:
```
>>> a=np.random.random(5)
>>> b=np.random.random(5)
>>> ab = np.vstack((a,b)).T
>>> C=np.cov(ab)
>>> eig(C)
7.90... | You have raised two issues:
1. The eigenvalues returned by `scipy.linalg.eig` are not real.
2. Some of the eigenvalues are negative.
Both of these issues are the result of errors introduced by truncation and rounding errors, which always happen with iterative algorithms using floating-point arithmetic. Note that the ... |
Scraping RSS scraping system | 8,766,261 | 2 | 2012-01-07T00:31:59Z | 8,766,290 | 7 | 2012-01-07T00:36:42Z | [
"python",
"email",
"rss",
"weather",
"alerts"
] | I am relatively new to python only about 2 months of learning mostly by myself and loving it. I have been trying to design a program that will scrape text RSS feeds from the National Weather Service but I have no idea where to start. I want something that will scan for severe weather aka tornado watches warnings exct a... | Don't reinvent the wheel, just use [FeedParser](http://code.google.com/p/feedparser/). It knows how to handle all corner cases and crazy markup better than you'll ever do. |
Displayin an Image in a QGraphicsScene | 8,766,584 | 3 | 2012-01-07T01:32:44Z | 8,768,134 | 7 | 2012-01-07T07:33:30Z | [
"python",
"pyqt",
"pyqt4"
] | I have a short script that modifies an image with PIL several times. I would like to be able to display the intermediate steps as it finishes with them, so I added a QGraphics Scene and I am trying to display the stages there. It will properly size and center the final stage (the last one posted before exiting the func... | It is hard to determine your problem without loop code and working example. But i have similar test application, hope it will help.
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import Image
import ImageQt
import ImageEnhance
import time
class TestW... |
Can I register event callbacks using the libvirt Python module with a QEMU backend? | 8,767,834 | 6 | 2012-01-06T18:00:56Z | 8,983,870 | 8 | 2012-01-24T08:32:00Z | [
"virtualization",
"python",
"libvirt",
"qemu"
] | I would like to write some code to monitor events for domains running under QEMU, managed by libvirt. However, trying to register an event handler yields the following error:
```
>>> import libvirt
>>> conn = libvirt.openReadOnly('qemu:///system')
>>> conn.domainEventRegister(callback, None)
libvir: Remote error : thi... | Make sure you have registered in the libvirt event loop (or set up your own) before registering for events.
There is a nice example of event handling shipped with the libvirt source (file is called event-test.py). I'm attaching an example based on that code;
```
import libvirt
import time
import threading
def callba... |
Using "or" in if statement conditions | 8,768,230 | 4 | 2012-01-07T07:56:13Z | 8,768,285 | 8 | 2012-01-07T08:05:44Z | [
"python"
] | I'm sure there is a really simple answer to this but I can't find it after searching around for a while.
```
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
if letter == "Q" or letter == "O":
print letter + "u" + suffix
else:
print letter + suffix
```
The above code works perfect... | Use one of the following solutions to implement the condition:
* list: `if letter in ['Q', 'O']`
* tuple: `if letter in ('Q', 'O')`
* string: `if letter in 'QO'`
**Update**: For completeness: Regexp: `re.match('[OQ]', letter)` (copied from [Paul Hankings answer](http://stackoverflow.com/a/8768250/672848) *(you should... |
Unresolved import csv Pydev Eclipse | 8,769,730 | 5 | 2012-01-07T12:36:48Z | 8,769,749 | 8 | 2012-01-07T12:40:29Z | [
"python",
"eclipse",
"pydev"
] | I have a love-hate relationship with Pydev on Eclipse. For some reason it is now telling me that it has an unresolved import on the code:
```
import csv
Traceback (most recent call last):
File "/Users/peterstannett/Documents/Programming/python/eclipse/workspace/myFirstPydev/csv.py", line 1, in <module>
import csv
... | Since your file is called `csv.py`, it is found before the csv module from the standard library when you `import csv`. Rename your file to something like `myCsv.py` to resolve the ambiguity. |
Does python have a built-in function for interleaving generators/sequences? | 8,769,829 | 11 | 2012-01-07T12:53:36Z | 8,769,863 | 8 | 2012-01-07T12:57:48Z | [
"python",
"functional-programming",
"itertools"
] | I noticed that `itertools` does not (it seems to me) have a function capable of interleaving elements from several other iterable objects (as opposed to zipping them):
```
def leaf(*args): return (it.next() for it in cycle(imap(chain,args)))
tuple(leaf(['Johann', 'Sebastian', 'Bach'], repeat(' '))) => ('Johann', ' ', ... | You're looking for the built-in [`zip`](http://docs.python.org/library/functions.html#zip) and [`itertools.chain.from_iterable`](http://docs.python.org/library/itertools#itertools.chain.from_iterable) to flatten the result:
```
>>> import itertools
>>> list(zip(['Johann', 'Sebastian', 'Bach'], itertools.repeat(' ')))
... |
How to speed up python loop | 8,770,791 | 9 | 2012-01-07T15:34:31Z | 8,771,427 | 9 | 2012-01-07T17:04:02Z | [
"python",
"performance",
"nested-loops"
] | I had a look at several dicussions on several sites and none of them gave me a solution.
This piece of code takes more than 5 seconds to run :
```
for i in xrange(100000000):
pass
```
I'm working on an integer optimization problem and I have to use an *O(n log n)* algorithm **edit : an O(n²/4) algorithm, where n s... | Not the prettiest coding style, but desperate times call for desperate coding. Try turning your nested nested loops into one big generator expression:
```
try:
i,j,i2,j2 = ((i,j,i2,j2)
for i in xrange(m)
for j in xrange(n)
for i2 in xrange(i + 1, m)
for j2 in xrange(j + ... |
Copy a dictionary into a new variable without maintaining the link with previous one | 8,771,808 | 3 | 2012-01-07T18:02:07Z | 8,771,850 | 8 | 2012-01-07T18:07:43Z | [
"python",
"python-3.x"
] | I want to copy a dictionary into a new variable without maintaining the link with previous variable. | ```
from copy import deepcopy
new_dict = deepcopy(orig_dict)
```
dict.copy() creates shallow copies, which means, if your dictionary contains other container-objects like list, tuples, etc. they will be referenced again and not duplicated!
You can try for yourself with:
```
a = {1:{1:2}}
print id(a[1])
>>> 15958484... |
Pyramid: how to get id of just created db row? | 8,772,317 | 4 | 2012-01-07T19:16:10Z | 8,772,868 | 10 | 2012-01-07T20:29:39Z | [
"python",
"sqlalchemy",
"pyramid"
] | In views:
```
model = Model('some_title', 'some text')
session.add(model)
return HTTPFound(location='/ads/%s/%s' % (model.id, model.title))
```
So, it must redirects me to `/ads/1/some_title` (if id=1), instead it redirects me to `/ads/None/some_title`.
How to get an `id` of this row after created db row in this pa... | at the point you ask for `model.id`, the new model has not yet reached the database; pyramid waits until the request handler returns before commiting the pending transaction. To get the id earlier, you must flush the session. Add:
```
model = Model('some_title', 'some text')
session.add(model)
session.flush()
return ... |
How to plot events on time on using matplotlib | 8,772,421 | 7 | 2012-01-07T19:32:20Z | 8,782,324 | 8 | 2012-01-08T23:24:58Z | [
"python",
"time",
"plot",
"matplotlib"
] | I have 3 lists, each containing numbers, representing a time. The time represents occuring of an event. For example, in this `A`, I have a number for each occurence of event `A`. I want to represent this data on a graph. In either of the following two ways:
1)
```
aabaaabbccacac
```
2)
```
a-> xx xxx x x
b-> x... | As an extension to the previous answers, you can use `plt.hbar`:
```
import matplotlib.pyplot as plt
import numpy as np
import string
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
y = np.array([0, 0, 1, 0, 0, 0, 1, 1, 2, 2, 0, 2, 0, 2])
labels = np.array(list(string.uppercase))
plt.barh(y, [1]*len... |
How to check if a key modifier is pressed (shift, ctrl, alt)? | 8,772,595 | 9 | 2012-01-07T19:55:33Z | 8,808,302 | 24 | 2012-01-10T18:16:41Z | [
"python",
"pyqt",
"pyqt4",
"modifier"
] | I am building a UI with QT designer and want buttons to perform different actions with different modifiers. So I thought I could call functions with dynamic string properties that would perform the action depending on the modifier.
If anyone knows a simpler way to do this I would appreciate it very much. | It looks like all you need to do is check [QApplication.keyboardModifiers](https://qt-project.org/doc/qt-4.8/qapplication.html#keyboardModifiers) in your button handler, and select a different action as appropriate:
```
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui... |
How to make a pretty Python web app? | 8,773,029 | 2 | 2012-01-07T20:52:18Z | 8,773,220 | 8 | 2012-01-07T21:20:53Z | [
"python",
"ajax",
"web",
"web-frameworks"
] | I'm looking for a python web framework that is easy to use and allows me to generate some nice looking user interfaces on the fly. I have not much experience with web development and don't want to spent much time to learn internals.
So far I use cherrypy and mako templating to serve the app. My problem is, it just loo... | Your user interface has nothing to do with the web framework you choose to use.
That said, you might find [Bootstrap](http://twitter.github.com/bootstrap/) useful:
> Bootstrap is a toolkit from Twitter designed to kickstart development
> of webapps and sites. It includes base CSS and HTML for typography,
> forms, but... |
Similar .rdata functionality in Python? | 8,773,074 | 5 | 2012-01-07T20:59:29Z | 8,773,217 | 8 | 2012-01-07T21:20:40Z | [
"python"
] | I'm starting to learn about doing data analysis in Python.
In R, you can load data into memory, then save variables into a `.rdata` file.
I'm trying to create an analysis "project", so I can load the data, store the scripts, then save the output so I can recall it should I need to.
Is there an equivalent function in... | What you're looking for is binary serialization. The most notable functionality for this in Python is `pickle`. If you have some standard scientific data structures, you could look at HDF5 instead. JSON works for a lot of objects as well, but it is not binary serialization - it is text-based.
If you expand your option... |
using Mysql and SqlAlchemy in Pyramid Framework | 8,773,380 | 2 | 2012-01-07T21:50:27Z | 8,773,446 | 13 | 2012-01-07T21:59:53Z | [
"python",
"mysql",
"sqlalchemy",
"pyramid"
] | Pyramid Framework comes with a sample tutorial of sql alchemy that uses sqlite. The problem is that i want to use mysql so i change this
```
sqlalchemy.url = sqlite:///%(here)s/tutorial.db
```
Into this
```
sqlalchemy.url = mysql://root:22password@localhost/alchemy
```
when i try to run
```
../bin/pserve developme... | Try adding `"MySQLdb"` to the requires list. It was fine with sqlite3 as that comes with python (as of version 2.5), MySQLdb doesn't and needs to be installed separately.
UPDATE:
Try `"mysql-python"` in the requires list instead. |
Downloading pictures with scrapy | 8,773,732 | 7 | 2012-01-07T22:43:20Z | 8,776,688 | 12 | 2012-01-08T10:01:43Z | [
"python",
"scrapy"
] | I'm starting with scrapy, and I have first real problem. It's downloading pictures. So this is my spider.
```
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from example.items import ProductItem
from sc... | I think the image URL you scraped is relative. To construct the absolute URL use [urlparse.urljoin](http://docs.python.org/library/urlparse.html#urlparse.urljoin):
```
def parse(self, response):
...
image_relative_url = hxs.select("...").extract()[0]
import urlparse
image_absolute_url = urlparse.urljoi... |
How to generate new content with Hyde? | 8,773,912 | 11 | 2012-01-07T23:12:38Z | 8,778,913 | 10 | 2012-01-08T15:52:42Z | [
"python",
"django",
"jekyll",
"hyde"
] | I'm starting to learn [Hyde](http://ringce.com/hyde) and I've cloned a few blogs written in Hyde from Github. I can successfully generate these sample blogs in my web browser and serve them locally; however, I can't seem to figure out how to actually generate new content. For example, how can I add a new file in HTML o... | Hyde does not have commands to create new files. You can create the file in your favorite editor and save it in the correct directory.
For example, if you want a blog post with this url:
<http://localhost:8080/blog/2012/01/05/a-new-post>,
you have do the following:
1. Create the directory `blog/2010/01/05` under you... |
Passed argument/parameter in function is still being changed after removing the reference/alias | 8,774,166 | 5 | 2012-01-07T23:54:43Z | 8,774,188 | 9 | 2012-01-07T23:57:45Z | [
"python"
] | I've spent the last 2 hours on this and I've probably read every question on here relating to variables being passed to functions. My issue is the common one of the parameter/argument being affected by changes made inside the function, even though I have removed the reference/alias by using `variable_cloned = variable[... | It looks like you need a deepcopy, instead of a shallow copy, which is what `[:]` gives you:
```
from copy import deepcopy
list2 = deepcopy(list1)
```
Here's a longer example comparing the two types of copy:
```
from copy import deepcopy
list1 = [[1], [1]]
list2 = list1[:] # while id(list1) != id(list2), it's ite... |
How "with" is better than try/catch to open a file in Python? | 8,774,830 | 16 | 2012-01-08T02:05:29Z | 8,775,008 | 20 | 2012-01-08T02:50:47Z | [
"python",
"exception",
"with-statement"
] | I got that the `with` statement help you to turn this:
```
try:
f = open(my_file)
do_stuff_that_fails()
except:
pass
finally:
f.close()
```
Into:
```
with open(my_file) as f:
do_stuff_that_fails()
```
But how is that better? You still got to handle the case with the file not being able to be ope... | For a start, it helps prevent the problem you've introduced in your `try ... finally ...` example.
The way you've structured it, if an exception is thrown while trying to open the file then you will never bind an open file to the name `f`, leading to either a `NameError` in the `finally` clause (if `f` has never been ... |
How "with" is better than try/catch to open a file in Python? | 8,774,830 | 16 | 2012-01-08T02:05:29Z | 8,775,108 | 11 | 2012-01-08T03:17:13Z | [
"python",
"exception",
"with-statement"
] | I got that the `with` statement help you to turn this:
```
try:
f = open(my_file)
do_stuff_that_fails()
except:
pass
finally:
f.close()
```
Into:
```
with open(my_file) as f:
do_stuff_that_fails()
```
But how is that better? You still got to handle the case with the file not being able to be ope... | In the example you give, it's *not* better. It's best practice to catch exceptions as close to the point they're thrown to avoid catching unrelated exceptions of the same type.
```
try:
file = open(...)
except OpenErrors...:
# handle open exceptions
else:
try:
# do stuff with file
finally:
... |
How to prevent auto escape in Django templates? | 8,774,902 | 11 | 2012-01-08T02:21:58Z | 8,774,932 | 19 | 2012-01-08T02:30:54Z | [
"python",
"django",
"templates",
"escaping"
] | In the docs it says:
> The only exceptions are variables that are already marked as âsafeâ from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied."
How does the "populated the variable" part work ? I'm actually looking for a way to declare a templat... | Django has a subclass of strings called *safe* strings (specifically `SafeUnicode` or `SafeString`), which can be created using `django.utils.safestring.mark_safe`. When the template engine comes across a safe string it doesn't perform HTML escaping on it:
```
>>> from django.utils.safestring import mark_safe
>>> from... |
KeyError in module 'threading' after a successful py.test run | 8,774,958 | 58 | 2012-01-08T02:37:23Z | 12,639,040 | 188 | 2012-09-28T11:21:18Z | [
"python",
"gevent",
"py.test"
] | I'm running a set of tests with py.test. They pass. Yippie! But I'm getting this message:
```
Exception KeyError: KeyError(4427427920,) in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'> ignored
```
How should I go about tracking down the source of that... | I observed a similar issue and decided to see what's going on exactly - let me describe my findings. I hope someone will find it useful.
## Short story
It is indeed related to monkey-patching the `threading` module. In fact, I can easily trigger the exception by importing the threading module before monkey-patching t... |
KeyError in module 'threading' after a successful py.test run | 8,774,958 | 58 | 2012-01-08T02:37:23Z | 18,455,952 | 19 | 2013-08-27T02:21:21Z | [
"python",
"gevent",
"py.test"
] | I'm running a set of tests with py.test. They pass. Yippie! But I'm getting this message:
```
Exception KeyError: KeyError(4427427920,) in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'> ignored
```
How should I go about tracking down the source of that... | You could use this:
```
import sys
if 'threading' in sys.modules:
del sys.modules['threading']
import gevent
import gevent.socket
import gevent.monkey
gevent.monkey.patch_all()
``` |
Python - PyQt - QTable Widget - adding rows | 8,775,447 | 9 | 2012-01-08T04:44:53Z | 8,776,125 | 13 | 2012-01-08T07:47:29Z | [
"python",
"pyqt",
"qtablewidget"
] | i am new to PyQt and still bit confused anyhow. I have a text file structure like this:
* Name Surname Telephone Email
Where spaces are actually tabs " \t " now when i read this file whit my method i wish to populate the QTable Widget.
My QTable Widget has 4 columns called `Name`, `Surname`, `Telephone`, `Email` now... | When you want to populate `QTableWidget`, you need to set row and column counts before inserting data [example in documentation](http://www.pyside.org/docs/pyside/PySide/QtGui/QTableWidget.html) (PySide documentation is better than PyQt). And you can't just insert text string separated by tabs into table, you need to p... |
MySQL Python LIKE wildcard | 8,775,460 | 6 | 2012-01-08T04:49:13Z | 8,775,579 | 9 | 2012-01-08T05:20:56Z | [
"python",
"mysql"
] | I want to do a Python MySQL query such as:
```
cursor = connection.cursor()
sql = "select text \
from steps \
where text like '%start%'"
cursor.execute(sql)
```
But the % isn't seen as a wildcard, it's expecting a variable, I guess. I get an error:
```
TypeError: not enough arguments for format string
... | I assume you're using python db-api.
You can try escaping `%` as `%%`.
As for passing the parameters there is a number of ways, for example:
```
cursor = connection.cursor()
sql = """select text
from steps
where text like %s"""
cursor.execute(sql, (('%' + 'start' + '%',))
```
You can see examples of the oth... |
Python, using multiprocess is slower than not using it | 8,775,475 | 9 | 2012-01-08T04:53:35Z | 8,775,489 | 9 | 2012-01-08T04:56:41Z | [
"python",
"multithreading",
"benchmarking",
"multiprocess"
] | After spending a lot of time trying to wrap my head around multiprocessing I came up with this code which is a benchmark test:
**Example 1:**
```
from multiprocessing import Process
class Alter(Process):
def __init__(self, word):
Process.__init__(self)
self.word = word
self.word2 = ''
... | This example is too small to benefit from multiprocessing.
There's a LOT of overhead when starting a new process. If there were heavy processing involved, it would be negligable. But your example really isn't all that intensive, and so you're bound to notice the overhead.
You'd probably notice a bigger difference wit... |
Python, using multiprocess is slower than not using it | 8,775,475 | 9 | 2012-01-08T04:53:35Z | 8,775,633 | 11 | 2012-01-08T05:34:04Z | [
"python",
"multithreading",
"benchmarking",
"multiprocess"
] | After spending a lot of time trying to wrap my head around multiprocessing I came up with this code which is a benchmark test:
**Example 1:**
```
from multiprocessing import Process
class Alter(Process):
def __init__(self, word):
Process.__init__(self)
self.word = word
self.word2 = ''
... | ETA: Now that you've posted your code, I can tell you there is a simple way to do what you're doing MUCH faster (>100 times faster).
I see that what you're doing is adding a frequency in parentheses to each item in a list of strings. Instead of counting all the elements each time (which, as you can confirm using cProf... |
Python, using multiprocess is slower than not using it | 8,775,475 | 9 | 2012-01-08T04:53:35Z | 8,776,446 | 8 | 2012-01-08T09:04:00Z | [
"python",
"multithreading",
"benchmarking",
"multiprocess"
] | After spending a lot of time trying to wrap my head around multiprocessing I came up with this code which is a benchmark test:
**Example 1:**
```
from multiprocessing import Process
class Alter(Process):
def __init__(self, word):
Process.__init__(self)
self.word = word
self.word2 = ''
... | Multiprocessing could be useful for what you're doing, but not in the way you're thinking about using it. As you're basically doing some computation on every member of a list, you could do it using the `multiprocessing.Pool.map` method, to do the computation on the list members in parallel.
Here is an example that sho... |
why extend a python list | 8,775,558 | 7 | 2012-01-08T05:15:55Z | 8,775,576 | 15 | 2012-01-08T05:20:05Z | [
"python",
"list",
"merge",
"append",
"extend"
] | Why use extend when you can just use the += operator? Which method is best?
Also what's the best way of joining multiple lists into one list
```
#my prefered way
_list=[1,2,3]
_list+=[4,5,6]
print _list
#[1, 2, 3, 4, 5, 6]
#why use extend:
_list=[1,2,3]
_list.extend([4,5,6])
print _list
#[1, 2, 3, 4, 5, 6]
_lists=... | `+=` can only be used to extend one list by **another list**, while `extend` can be used to extend one list by **an iterable object**
e.g.
you can do
```
a = [1,2,3]
a.extend(set([4,5,6]))
```
but you can't do
```
a = [1,2,3]
a += set([4,5,6])
```
For the second question
```
[item for sublist in l for item in su... |
start a background process with nohup using fabric | 8,775,598 | 19 | 2012-01-08T05:26:02Z | 10,336,997 | 21 | 2012-04-26T15:54:50Z | [
"python",
"fabric"
] | am trying to start a celerycam process using fabric using the below nohup command. Unfortunately, nothing is happening, manually using the same command i could start the process but not through fabric. Any advise on how i can solve this?
```
def start_celerycam():
'''Start celerycam daemon'''
with cd(env.proje... | I'm using Erich Heine's suggestion to use 'dtach' and it's working pretty well for me:
```
def runbg(cmd, sockname="dtach"):
return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s' % (sockname,cmd))
```
This was found [here](http://www.fabfile.org/faq.html#why-can-t-i-run-programs-in-the-background-with-it-makes-fabri... |
Exact figure size in matplotlib with title, axis labels | 8,775,622 | 17 | 2012-01-08T05:31:52Z | 8,776,862 | 9 | 2012-01-08T10:42:41Z | [
"python",
"matplotlib"
] | Similar questions have been asked before, but all of my search results don't
address my problem. Take the following example code:
```
from matplotlib.pyplot import *
fig = figure(1, figsize=(3.25, 3))
plot([0,1,5,2,9])
title('title')
xlabel('xAxis')
ylabel('yAxis')
fig.savefig('test.png',dpi=600)
```
The resulting fi... | In agreement with the comment from David Robinson, the figure produced here is 3.25 by 3 inches as measured by photoshop, although the xlabel does show cut-off (mpl 1.1.0 in python 2.6 64-bit, win7)
A solution to overcome the problem is to manually adjust the margins with `subplot_adjust`:
```
from matplotlib.pyplot ... |
Exact figure size in matplotlib with title, axis labels | 8,775,622 | 17 | 2012-01-08T05:31:52Z | 12,481,100 | 7 | 2012-09-18T16:23:20Z | [
"python",
"matplotlib"
] | Similar questions have been asked before, but all of my search results don't
address my problem. Take the following example code:
```
from matplotlib.pyplot import *
fig = figure(1, figsize=(3.25, 3))
plot([0,1,5,2,9])
title('title')
xlabel('xAxis')
ylabel('yAxis')
fig.savefig('test.png',dpi=600)
```
The resulting fi... | matplotlib 1.1.1 has added `figure.tight_layout()` ([doc](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.tight_layout)) that will do this for you. |
MySQL: Order by a function of two columns | 8,775,870 | 7 | 2012-01-08T06:43:38Z | 8,775,894 | 12 | 2012-01-08T06:50:51Z | [
"php",
"python",
"mysql",
"sql"
] | I have two integer fields A and B in table T .
I want to do something like "`SELECT * FROM T ORDER BY f(A,B) DESC`"
where `f(A,B)` is a linear combination of A and B ... i.e `f(A,B) = mA + nB`, where m and n are numbers.
What is the right syntax? | You have two options (at least):
```
SELECT (n * A + m * B) AS C, *
FROM T
ORDER BY C DESC; -- or ORDER BY 1 DESC
```
Or:
```
SELECT *
FROM T
ORDER BY (n * A + m * B) DESC;
```
One or the other - possibly both - should work for you in MySQL. The first should work even if the second does not. |
Is there a way to delist a list in python? | 8,775,913 | 2 | 2012-01-08T06:57:30Z | 8,775,922 | 7 | 2012-01-08T07:00:28Z | [
"python",
"data-structures"
] | I am looking for a method to dive into a list and directly access its elements. For example, the following is the normal way of getting the Cartesian product of for sets.
```
>>> list(itertools.product((0,1), (0,1),(0,1),(0,1)))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1... | ```
itertools.product((0,1), repeat=4)
```
The `product` function accepts an [optional `repeat` argument](http://docs.python.org/library/itertools.html#itertools.product). The above is equivalent to `itertools.product((0, 1), (0, 1), (0, 1), (0, 1))`.
---
In general, if you have a list
```
lst = [1, 2, 4, 6, 8, ...... |
SWIG interfacing C library to Python (Creating 'iterable' Python data type from C 'sequence' struct) | 8,776,328 | 5 | 2012-01-08T08:38:23Z | 8,828,454 | 14 | 2012-01-11T23:57:18Z | [
"python",
"c",
"swig"
] | I have written a Python extension for a C library. I have a data structure that looks like this:
```
typedef struct _mystruct{
double * clientdata;
size_t len;
} MyStruct;
```
The purpose of this datatype maps directly to the list data type in Python. I therefore, want to create 'list-like' behavior for the e... | The simplest solution to this is to implement [`__getitem__`](http://docs.python.org/reference/datamodel.html#object.__getitem__) and throw an [`IndexError`](http://docs.python.org/library/exceptions.html#exceptions.IndexError) exception for an invalid index.
I put together an example of this, using `%extend` and `%ex... |
python, lxml and how to get html code from subset | 8,776,466 | 2 | 2012-01-08T09:08:14Z | 8,776,480 | 11 | 2012-01-08T09:12:28Z | [
"python",
"html",
"lxml"
] | I use this function to get this section of the html doc.
```
for el in doc.find_class('plusShippingText'):
print el
```
What I need is the html code. How can I print the html code for el?
Thanks | Use [`lxml.html.tostring`](http://lxml.de/api/lxml.html-module.html#tostring)
```
print lxml.html.tostring(el)
``` |
Unable to restore stdout to original (only to terminal) | 8,777,152 | 6 | 2012-01-08T11:34:20Z | 8,777,172 | 10 | 2012-01-08T11:37:50Z | [
"python"
] | I need to output all my print statements to both terminal and file.
I've found a solution in [this stackoverflow question](http://stackoverflow.com/questions/616645/how-do-i-duplicate-sys-stdout-to-a-log-file-in-python)
So i use
```
class Tee(object):
def __init__(self, name):
self.file = open(name, "a")... | You need to save a reference to the original file-descriptor before reassignment:
```
oldstdout = sys.stdout
```
and afterwards reassign it to `sys.stdout`!
The `del` statement doesn't call `__del__` directly, but rather decreases the reference counter of your object. the `__del__` method is called if the reference ... |
Converting datetime.date to UTC timestamp in Python | 8,777,753 | 121 | 2012-01-08T13:03:31Z | 8,778,548 | 231 | 2012-01-08T15:02:28Z | [
"python",
"datetime",
"utc"
] | I am dealing with dates in Python and I need to convert them to UTC timestamps to be used
inside Javascript. The following code does not work:
```
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
```
Converting the date object ... | If `d = date(2011, 1, 1)` is in UTC:
```
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
```
If `d` is in local timezone:
```
>>> import time
>>> timestamp2 = time.mktime(d.timetu... |
Converting datetime.date to UTC timestamp in Python | 8,777,753 | 121 | 2012-01-08T13:03:31Z | 8,779,339 | 25 | 2012-01-08T16:53:52Z | [
"python",
"datetime",
"utc"
] | I am dealing with dates in Python and I need to convert them to UTC timestamps to be used
inside Javascript. The following code does not work:
```
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
```
Converting the date object ... | * **Assumption 1:** You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).
* **Assumption 2:** The date you present is not as... |
Profiled performance of len(set) vs. set.__len__() in Python 3 | 8,778,691 | 3 | 2012-01-08T15:24:02Z | 8,778,729 | 10 | 2012-01-08T15:29:09Z | [
"python",
"performance",
"profiling",
"set"
] | While profiling my Python's application, I've discovered that `len()` seems to be a very expensive one when using sets. See the below code:
```
import cProfile
def lenA(s):
for i in range(1000000):
len(s);
def lenB(s):
for i in range(1000000):
s.__len__();
def main():
s = set();
lenA... | Obviously, `len` has some overhead, since it does a function call and translates `AttributeError` to `TypeError`. Also, `set.__len__` is such a simple operation that it's bound to be very fast in comparison to just about anything, but I still don't find anything like the 14x difference when using `timeit`:
```
In [1]:... |
Django - Difference between import django.conf.settings and import settings | 8,780,756 | 68 | 2012-01-08T19:58:23Z | 8,780,907 | 94 | 2012-01-08T20:16:32Z | [
"python",
"django",
"settings",
"python-import"
] | What is the basic difference between the following import statements in a Django web app?
```
import settings
```
and
```
from django.conf import settings
``` | ```
import settings
```
Will import settings(.py) module of your Django project (if you are writing this code from the "root" package of your application, of course)
```
from django.conf import settings
```
Will import settings **object** from django.conf package (Django's provided files). [This is important](https:... |
How can I perform a least-squares fitting over multiple data sets fast? | 8,780,912 | 11 | 2012-01-08T20:17:06Z | 8,783,634 | 17 | 2012-01-09T03:31:13Z | [
"python",
"scipy",
"curve-fitting",
"gaussian",
"least-squares"
] | I am trying to make a gaussian fit over many data points. E.g. I have a 256 x 262144 array of data. Where the 256 points need to be fitted to a gaussian distribution, and I need 262144 of them.
Sometimes the peak of the gaussian distribution is outside the data-range, so to get an accurate mean result curve-fitting is... | The easiest thing to do is to linearlize the problem. You're using a non-linear, iterative method which will be slower than a linear least squares solution.
Basically, you have:
`y = height * exp(-(x - mu)^2 / (2 * sigma`^2))
To make this a linear equation, take the (natural) log of both sides:
```
ln(y) = ln(heigh... |
rounding float up $.01 in python | 8,781,429 | 5 | 2012-01-08T21:20:00Z | 8,781,456 | 13 | 2012-01-08T21:23:46Z | [
"python",
"floating-point",
"currency",
"rounding"
] | I am working on a program that stores numbers as floats which I eventually write to a file as currency. I am currently using the round() function to round it to 2 decimals, but the business area would like me to round to the next penny no matter what the third decimal is. For example:
```
x = 39.142
```
In this case ... | Using the [decimal module](http://docs.python.org/library/decimal.html):
```
import decimal
D = decimal.Decimal
cent = D('0.01')
x = D('39.142')
print(x.quantize(cent,rounding=decimal.ROUND_UP))
# 39.15
```
Decimals have many options for rounding. The options and their meanings can be found [here](http://docs.python... |
Python on Netbeans 7.1 | 8,782,118 | 4 | 2012-01-08T22:52:15Z | 8,782,342 | 10 | 2012-01-08T23:27:52Z | [
"python",
"plugins",
"netbeans",
"install"
] | I've tried to find a plugin for this, but couldn't.
I also tried to follow these instructions to manually install it, but the link is dead.
<https://techknowhow.library.emory.edu/blogs/sturnbu/2011/05/12/netbeans-7-and-python-ide>
Is there any other way to install it or is it not possible in netbeans 7.1? | The following link should work (add it into your plugin repository list as said in your given [source](https://techknowhow.library.emory.edu/blogs/sturnbu/2011/05/12/netbeans-7-and-python-ide)):
<http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastSuccessfulBuild/artifact/nbbuild/nbms/updates.xml.gz>
But keep... |
How to execute a script remotely in python using ssh? | 8,783,009 | 2 | 2012-01-09T01:26:39Z | 8,798,266 | 7 | 2012-01-10T03:40:03Z | [
"python",
"shell",
"ssh",
"paramiko"
] | ```
def execute(self,command):
to_exec = self.transport.open_session()
to_exec.exec_command(command)
print 'Command executed'
connection.execute("install.sh")
```
When I check the remote system, I found the script didn't run. Any clue? | The code below will do what you want and you can adapt it to your `execute` function:
```
from paramiko import SSHClient
host="hostname"
user="username"
client = SSHClient()
client.load_system_host_keys()
client.connect(host, username=user)
stdin, stdout, stderr = client.exec_command('./install.sh')
print "stderr: ", ... |
Python math module | 8,783,261 | 11 | 2012-01-09T02:17:37Z | 8,783,273 | 32 | 2012-01-09T02:19:50Z | [
"python",
"math",
"module",
"import",
"logarithm"
] | Whenever I try to use any of the built-in functions of Python's exponentiation and logarithms module, I get an error like this:
```
NameError: name 'sqrt' is not defined
```
I have tried using `math.sqrt(4)`,`sqrt(4)` and `sqrt(4.0)`, but none of them work. The exception is `pow`, which works as it's supposed to. Thi... | `pow` is built into the language(not part of the math library). The problem is that you haven't imported math.
Try this:
```
import math
math.sqrt(4)
``` |
Why doesn't recv block until it receives all of the data? | 8,783,578 | 8 | 2012-01-09T03:20:43Z | 8,783,608 | 9 | 2012-01-09T03:25:21Z | [
"python",
"c",
"sockets",
"network-programming"
] | Why doesn't the `recv` system call just block until all the data is received? Every time I have seen a `recv` call, it's in a while loop which just keeps on calling `recv` until all the data is there. Why not just have `recv` block in the first place? | You can request that recv block until all data is received, with the `MSG_WAITALL` flag. However, if a signal arrives, a system call that has performed some work (ie, receiving part of the data) *cannot* be automatically restarted to receive the rest. As such, even with `MSG_WAITALL`, there are cases where the recv cal... |
Python: delete the words between two delimeters | 8,784,396 | 11 | 2012-01-09T05:48:28Z | 8,784,436 | 17 | 2012-01-09T05:55:25Z | [
"python"
] | I have a noisy data..something like
```
<@ """@$ FSDF >something something <more noise>
```
now i just want to extract "something something"..
Is there a way on how to delete the text between those two delimeters"<" and ">"??
Thanks | Use [regular expressions](http://docs.python.org/library/re.html):
```
>>> import re
>>> s = '<@ """@$ FSDF >something something <more noise>'
>>> re.sub('<[^>]+>', '', s)
'something something '
```
[Update]
If you tried a pattern like `<.+>`, where the dot means any character and the plus sign means one or more, yo... |
Python: delete the words between two delimeters | 8,784,396 | 11 | 2012-01-09T05:48:28Z | 8,784,438 | 7 | 2012-01-09T05:56:05Z | [
"python"
] | I have a noisy data..something like
```
<@ """@$ FSDF >something something <more noise>
```
now i just want to extract "something something"..
Is there a way on how to delete the text between those two delimeters"<" and ">"??
Thanks | Of course, you can use regular expressions.
```
import re
s = #your string here
t = re.sub('<.*?>', '', s)
```
The above code should do it. |
Clearing specific cache in Django | 8,784,400 | 3 | 2012-01-09T05:48:56Z | 8,784,540 | 10 | 2012-01-09T06:12:40Z | [
"python",
"django",
"memcached",
"django-cache"
] | I am using view caching for a django project.
It says the cache uses the URL as the key, so I'm wondering how to clear the cache of one of the keys if a user updates/deletes the object.
An example: A user posts a blog post to `domain.com/post/1234/` .. If the user edits that, i'd like to delete the cached version of ... | From [django cache docs](https://docs.djangoproject.com/en/1.3/topics/cache/#the-low-level-cache-api), it says that `cache.delete('key')` should be enough. So, it comes to my mind two problems you might have:
1. Your imports are not correct, remember that you have to import `cache` from the `django.core.cache` module:... |
Why does Python's timeit() execute endlessly? | 8,784,752 | 2 | 2012-01-09T06:41:45Z | 8,784,838 | 7 | 2012-01-09T06:53:06Z | [
"python",
"cpython",
"timeit"
] | When trying to use the Python built-in module 'timeit' as follows:
```
timeit.Timer('print "hi"').timeit()
```
it prints more than one line; why is that? It keeps printing "hi" endlessly:
```
hi
hi
hi
hi
...
``` | `timeit` is designed to test extremely short code snippets, so it runs the code many times and averages them. As a default, it runs it 1000000 times.
You can change this by running it as follows:
```
timeit.Timer('print "hi"').timeit(number=1)
``` |
lstrip(), rstrip() for lists | 8,784,813 | 3 | 2012-01-09T06:49:52Z | 8,784,852 | 8 | 2012-01-09T06:54:49Z | [
"python",
"list"
] | I have a bunch of huge lists with integers. These lists may start or end with a couple of zeroes.
Is there an easy way for strip either the zeroes on the left or right side from the list?
Something analogous to `lstrip()` or `rstrip()` for strings?
The data looks like
```
[0,0,0,1,2,3,4]
```
or
```
[1,2,3,4,0,0,0]... | You could use [`itertools.dropwhile()`](http://docs.python.org/library/itertools.html#itertools.dropwhile):
```
>>> L = [0, 0, 1, 1, 2, 2, 0]
>>> list(itertools.dropwhile(lambda x: x == 0, L))
[1, 1, 2, 2, 0]
``` |
How do I insert a list at the front of another list? | 8,785,554 | 14 | 2012-01-09T08:24:48Z | 8,785,579 | 24 | 2012-01-09T08:27:09Z | [
"python"
] | ```
>>> a = ['foo.py']
>>> k = ['nice', '-n', '10']
>>> a.insert(0, k)
>>> a
[['nice', '-n', '10'], 'foo.py']
```
I want to list `k` to be on the same level as `foo.py`, rather than a sublist. | Apply slicing:
```
a[0:0] = k
```
Or do it manually:
```
a = k + a
```
The first approach remain the same for insertion at any place, i.e. `a[n:n] = k`
would insert k at position n, but the second approach would not be the same, that will be
```
a = a[:n] + k + a[n:]
``` |
How do I insert a list at the front of another list? | 8,785,554 | 14 | 2012-01-09T08:24:48Z | 8,785,601 | 9 | 2012-01-09T08:30:03Z | [
"python"
] | ```
>>> a = ['foo.py']
>>> k = ['nice', '-n', '10']
>>> a.insert(0, k)
>>> a
[['nice', '-n', '10'], 'foo.py']
```
I want to list `k` to be on the same level as `foo.py`, rather than a sublist. | instead of:
```
>>> a.insert(0, k)
```
use:
```
>>> k.extend(a)
>>> k
['nice', '-n', '10', 'foo.py']
```
this updates the "k" list "in place" instead of creating a copy.
the list concatenation (k + a) will create a copy.
the slicing option (a[0:0] = k) will also update "in place" but IMHO is harder to read. |
Hang in Python script using SQLAlchemy and multiprocessing | 8,785,899 | 7 | 2012-01-09T09:00:49Z | 8,786,557 | 11 | 2012-01-09T09:54:32Z | [
"python",
"postgresql",
"sqlalchemy",
"multiprocessing"
] | Consider the following Python script, which uses SQLAlchemy and the Python multiprocessing module.
This is with Python 2.6.6-8+b1(default) and SQLAlchemy 0.6.3-3 (default) on Debian squeeze.
This is a simplified version of some actual code.
```
import multiprocessing
from sqlalchemy import *
from sqlalchemy.orm import... | I believe the `TypeError` comes from `multiprocessing`'s `get`.
I've stripped out all the DB code from your script. Take a look at this:
```
import multiprocessing
import sqlalchemy.exc
def do(kwargs):
i = kwargs['i']
print i
raise sqlalchemy.exc.ProgrammingError("", {}, None)
return i
pool = multi... |
PyQt - how to detect and close UI if it's already running? | 8,786,136 | 6 | 2012-01-09T09:21:15Z | 8,795,563 | 14 | 2012-01-09T21:40:25Z | [
"python",
"pyqt",
"pyqt4",
"singleinstance"
] | I'm starting the UI from within Maya. If the UI hasn't been closed, running the UI again will completely freeze Maya (with the error "Event Loop is already running")
Manually closing the UI before re-running the script will prevent it from freezing up. But I guess that's not really practical.
Is there a way to detect... | There are a couple of fairly straightforward C++ solutions given [here](http://www.qtcentre.org/wiki/index.php?title=SingleApplication).
I have ported one of them to PyQt, and have provided a sample script below. The original C++ solution has been split into two classes, because the messaging facility may not be neede... |
PyQt - how to detect and close UI if it's already running? | 8,786,136 | 6 | 2012-01-09T09:21:15Z | 16,281,209 | 7 | 2013-04-29T14:28:29Z | [
"python",
"pyqt",
"pyqt4",
"singleinstance"
] | I'm starting the UI from within Maya. If the UI hasn't been closed, running the UI again will completely freeze Maya (with the error "Event Loop is already running")
Manually closing the UI before re-running the script will prevent it from freezing up. But I guess that's not really practical.
Is there a way to detect... | In case if someone want to run *@ekhumoro* solution with python3 there's need to make few adjustments to string operations, i'll share my copy where it was working **python 3**.
```
import sys
from PyQt4 import QtGui, QtCore, QtNetwork
class SingleApplication(QtGui.QApplication):
def __init__(self, argv, key):
... |
collecstatic modified files using s3boto and django-storages | 8,787,961 | 2 | 2012-01-09T11:49:56Z | 8,849,804 | 7 | 2012-01-13T11:24:16Z | [
"python",
"django",
"amazon-s3"
] | I checked out the following question: [Django StaticFiles and Amazon S3: How to detect modified files?](http://stackoverflow.com/questions/6618013/django-staticfiles-and-amazon-s3-how-to-detect-modified-files) and others but i'm still not able to run `collectstatic` on only modified files.
Besides not picking up on mo... | It turns out I was missing `python-dateutil`, which somehow didn't make into `django-storages` as a dependency. Make sure you have version 1.1.5 of `python-dateutil` installed or you will get the following error:
```
iter() returned non-iterator of type â_timelexâ
```
See also my blogpost about this problem and t... |
Reorder dictionary randomly | 8,788,153 | 2 | 2012-01-09T12:04:35Z | 8,788,232 | 8 | 2012-01-09T12:10:22Z | [
"python",
"random",
"dictionary",
"order"
] | Let's consider this dictionary
```
>>> test = {'to have': True, 'to get': False, 'having': False}
```
Imagine
```
>>> test.random_order()
{'having': False, 'to get': False, 'to have': True}
```
How can I reorder it randomly? Should I use `OrderedDict` and `random.shuffle`? If so, how can I combine them? | Just shuffle the key/value pairs (items) and pass them on to `OrderedDict`:
```
items = test.items()
random.shuffle(items)
OrderedDict(items)
``` |
Temporary directory persist across program runs | 8,789,172 | 7 | 2012-01-09T13:30:37Z | 8,789,188 | 8 | 2012-01-09T13:32:07Z | [
"python",
"tempdata",
"tempdir"
] | I need a temporary directory, but I want full control over its creation and deletion.
I will use this directory to place git repositories which I want to monitor for new commits, so I need to store them somewhere permanently.
Therefore I want to avoid `/tmp` dir, since it can be cleared by user(?). What is the best p... | [`tempfile.mkdtemp`](http://docs.python.org/library/tempfile.html#tempfile.mkdtemp) will create a temp dir for you and return its name. It will create it in `/tmp` by default (on Unix-like systems), but "in the most secure manner possible" and with read/write/list permissions only for the caller's user id.
```
>>> d =... |
Temporary directory persist across program runs | 8,789,172 | 7 | 2012-01-09T13:30:37Z | 8,789,192 | 8 | 2012-01-09T13:32:27Z | [
"python",
"tempdata",
"tempdir"
] | I need a temporary directory, but I want full control over its creation and deletion.
I will use this directory to place git repositories which I want to monitor for new commits, so I need to store them somewhere permanently.
Therefore I want to avoid `/tmp` dir, since it can be cleared by user(?). What is the best p... | I'd say that the best practice is to use [`tempfile.mkdtemp`](http://docs.python.org/library/tempfile.html#tempfile.mkdtemp).
If you don't wan to use `/tmp` then, you can take advantage of the `prefix` parameter:
```
import tempfile
tempfile.mkdtemp(prefix=<your_preferred_directory>)
```
Edit: Regarding what's the m... |
Fast way of merging huge files(>=7 GB) into one | 8,789,364 | 5 | 2012-01-09T13:46:53Z | 8,789,400 | 12 | 2012-01-09T13:50:27Z | [
"python",
"io"
] | I have three huge files, with just 2 columns, and I need both. I want to merge them into one file which I can then write to a SQLite database.
I used Python and got the job done, but it took >30 minutes and also hung my system for 10 of those. I was wondering if there is a faster way by using awk or any other unix-too... | The standard Unix way to merge files is `cat`. It may not be *much* faster but it will be faster.
```
cat file1 file2 file3 > bigfile
```
Rather than make a temporary file, you may be able to `cat` directly to sqlite
```
cat file1 file2 file3 | sqlite database
```
In python, you will probably get better performance... |
Dynamically import a method in a file, from a string | 8,790,003 | 25 | 2012-01-09T14:33:28Z | 8,790,051 | 8 | 2012-01-09T14:37:25Z | [
"python",
"dynamic",
"import",
"dynamic-import"
] | I have a string, say: `abc.def.ghi.jkl.myfile.mymethod`. How do I dynamically import `mymethod`?
Here is how I went about it:
```
def get_method_from_file(full_path):
if len(full_path) == 1:
return map(__import__,[full_path[0]])[0]
return getattr(get_method_from_file(full_path[:-1]),full_path[-1])
i... | For Python < 2.7 the builtin method [\_\_ import\_\_](http://docs.python.org/library/functions.html#__import__) can be used:
```
__import__('abc.def.ghi.jkl.myfile.mymethod', fromlist=[''])
```
For Python >= 2.7 or 3.1 the convenient method [importlib.import\_module](http://docs.python.org/py3k/library/importlib.html... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.