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 |
|---|---|---|---|---|---|---|---|---|---|
Thread vs. Threading | 5,568,555 | 33 | 2011-04-06T15:01:51Z | 5,568,584 | 24 | 2011-04-06T15:03:42Z | [
"python",
"multithreading"
] | What's the difference between the `threading` and `thread` modules in Python? | `threading` is just a higher level module that interfaces `thread`.
See here for the `threading` docs:
<http://docs.python.org/library/threading.html> |
Thread vs. Threading | 5,568,555 | 33 | 2011-04-06T15:01:51Z | 5,568,844 | 7 | 2011-04-06T15:22:46Z | [
"python",
"multithreading"
] | What's the difference between the `threading` and `thread` modules in Python? | If I'm not mistaken, `thread` allows you to run a *function* as a separate thread, whereas with `threading` you ~~have to~~ create a *class*, but get more functionality.
EDIT: This is not precisely correct. `threading` module provides different ways of creating a thread:
* `threading.Thread(target=function_name).star... |
Thread vs. Threading | 5,568,555 | 33 | 2011-04-06T15:01:51Z | 5,578,141 | 47 | 2011-04-07T08:30:24Z | [
"python",
"multithreading"
] | What's the difference between the `threading` and `thread` modules in Python? | In Python 3, `thread` has been renamed to `_thread`. It is infrastructure code that is used to implement `threading`, and normal Python code shouldn't be going anywhere near it.
`_thread` exposes a fairly raw view of the underlying OS level processes. This is almost never what you want, hence the rename in Py3k to ind... |
usleep in Python | 5,568,646 | 15 | 2011-04-06T15:08:57Z | 5,568,681 | 22 | 2011-04-06T15:11:26Z | [
"python"
] | I was searching for a usleep() function in Python 2.7.
Does anybody know if it does exist (maybe with another function name)?
Thanks | Since `usleep` generally means you want to delay execution for x microseconds, you must divide the seconds value by 1000000.
```
import time
time.sleep(seconds/1000000.0)
```
`time.sleep()` takes seconds as a parameter.
<http://docs.python.org/library/time.html#time.sleep> |
usleep in Python | 5,568,646 | 15 | 2011-04-06T15:08:57Z | 5,568,837 | 15 | 2011-04-06T15:22:25Z | [
"python"
] | I was searching for a usleep() function in Python 2.7.
Does anybody know if it does exist (maybe with another function name)?
Thanks | ```
import time
usleep = lambda x: time.sleep(x/1000000.0)
usleep(100) #sleep during 100μs
``` |
Required commandline options in Python using argparse | 5,571,998 | 4 | 2011-04-06T19:36:40Z | 5,572,081 | 7 | 2011-04-06T19:43:33Z | [
"python",
"argparse"
] | I have the following scenario for command line argument. If there is a particular option then there should be some other required options. For example if there is -- create then there should be --name. Also if there is --remove then there should be --id. Is it possible to implement this scenario with argparse? or someo... | This can be done with [subcommands](http://docs.python.org/library/argparse.html#sub-commands) as long as you don't mind `create` and `remove` not being preceded with hyphens. This may make sense anyway, since those verbs are often used as actions rather than options. |
Text escaped when I want it to show up as html in Flask/jinja2 | 5,572,225 | 14 | 2011-04-06T19:55:36Z | 5,572,558 | 11 | 2011-04-06T20:30:03Z | [
"python",
"jinja2",
"flask"
] | I pull a feed from rss and store the data in a appengine db. The rss feed content includes the entire html. So I have this python code:
```
@app.route("/rssRead")
def pullRss():
feedItem = db.getFeedItemByName(request.args.get('title',None), request.args.get('key',None))
return render_template("rss.html", data... | Have you tried `data=Markup(feedItem.html)` instead of `data=Markup(feedItem.html).unescape()`?
Assuming that feedItem.html hasn't been escaped in the first place, unescape() would have nothing to do. More importantly, it would return a string/unicode object instead of a Markup object, giving Jinja2 no way to know tha... |
Text escaped when I want it to show up as html in Flask/jinja2 | 5,572,225 | 14 | 2011-04-06T19:55:36Z | 5,584,567 | 70 | 2011-04-07T16:43:17Z | [
"python",
"jinja2",
"flask"
] | I pull a feed from rss and store the data in a appengine db. The rss feed content includes the entire html. So I have this python code:
```
@app.route("/rssRead")
def pullRss():
feedItem = db.getFeedItemByName(request.args.get('title',None), request.args.get('key',None))
return render_template("rss.html", data... | This should work too.
```
{% extends "layout.html" %}
{% block body %}
{{ data|safe }}
{% endblock %}
``` |
How to find XML Elements via XPath in Python in a namespace-agnostic way? | 5,572,247 | 12 | 2011-04-06T19:57:54Z | 5,573,253 | 8 | 2011-04-06T21:36:23Z | [
"python",
"xml",
"xpath",
"lxml",
"elementtree"
] | since I had this annoying issue for the 2nd time, I thought that asking would help.
Sometimes I have to get Elements from XML documents, but the ways to do this are awkward.
Iâd like to know a python library that does what I want, a elegant way to formulate my XPaths, a way to register the namespaces in prefixes au... | The `*[local-name() = "elem"]` syntax should work, but to make it easier you can create a function to simplify construction of the partial or full "wildcard namespace" XPath expressions.
I'm using **python-lxml 2.2.4 on Ubuntu 10.04** and the script below works for me. You'll need to customize the behavior depending o... |
Converting a StringIO object to a Django ImageFile | 5,572,466 | 7 | 2011-04-06T20:21:20Z | 5,572,897 | 14 | 2011-04-06T21:01:14Z | [
"python",
"django",
"stringio"
] | I'm trying to take data from a StringIO (or cStringIO, more specifically) and convert it to a django.core.files.images.ImageFile.
But it doesn't work. Any by that, I mean that it fails in a multitude of ways, and Google has failed me.
So far I've got:
```
pi = ProductImage(product=product)
image = ImageFile(image_fi... | Use django.core.files.base.ContentFile(image\_file):
```
pi = ProductImage(product=product)
pi.source_image.save(image_name, ContentFile(image_file.read()))
pi.save()
``` |
Matplotlib - Contour plot with with single value | 5,572,500 | 4 | 2011-04-06T20:24:36Z | 5,572,683 | 10 | 2011-04-06T20:42:36Z | [
"python",
"matplotlib",
"contour",
"colorbar"
] | I want to make a contour plot of some data, but it is possible that all values in the field at the same value. This causes an error in matplotlib, which makes sense since there really isn't a contour to be created. For example, if you run the code below, you will get an error, but delete the second definition of zi and... | Well, `contourf` handles it perfectly, it's `contour` that chokes.
Why not just do this:
```
import numpy as np
import matplotlib.pyplot as plt
xi = np.array([0., 0.5, 1.0])
yi = np.array([0., 0.5, 1.0])
zi = np.ones((3,3))
try:
CS = plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
except ValueError:
... |
Python Scientific Notation precision normalizing | 5,572,635 | 15 | 2011-04-06T20:38:54Z | 5,572,740 | 26 | 2011-04-06T20:47:43Z | [
"python",
"format",
"notation",
"exponential"
] | I've been looking everywhere for an answer without success, but hopefully I'm just overlooking something simple.
I am fairly new to Python. My goal is simply to convert a string such as "1.2" to scientific notation without adding additional precision. The problem is that I always end up with superfluous 0s at the end ... | You can specify precision in the format:
```
print '{:.2e}'.format(float(input))
```
This will always give 2 decimals of precision. The amount of precision you want must be determined by yourself. If you need any help with that post in the comments. |
Python Scientific Notation precision normalizing | 5,572,635 | 15 | 2011-04-06T20:38:54Z | 6,098,154 | 7 | 2011-05-23T13:53:29Z | [
"python",
"format",
"notation",
"exponential"
] | I've been looking everywhere for an answer without success, but hopefully I'm just overlooking something simple.
I am fairly new to Python. My goal is simply to convert a string such as "1.2" to scientific notation without adding additional precision. The problem is that I always end up with superfluous 0s at the end ... | Just going back through and cleaning up old questions. I ended up solving this by writing a little function to intuit the initial precision of a number and then using it to format the output result.
```
#used to determine number of precise digits in a string
def get_precision(str_value):
vals = str_value.split('.... |
How to specify floating point decimal precision from variable? | 5,573,736 | 5 | 2011-04-06T22:28:42Z | 5,573,788 | 17 | 2011-04-06T22:36:30Z | [
"python",
"string",
"floating-point",
"floating-point-precision"
] | I have the following repetitive simple code repeated several times that I would like to make a function for:
```
for i in range(10):
id = "some id string looked up in dict"
val = 63.4568900932840928 # some floating point number in dict corresponding to "id"
tabStr += '%-15s = %6.1f\n' % (id,val)
```
I wa... | ```
tabStr += '%-15s = %6.*f\n' % (id, i, val)
```
where `i` is the number of decimal places.
---
BTW, in the recent Python where `.format()` has superseded `%`, you could use
```
"{0:<15} = {2:6.{1}f}".format(id, i, val)
```
for the same task. |
String slugification in Python | 5,574,042 | 45 | 2011-04-06T23:08:55Z | 8,366,771 | 20 | 2011-12-03T09:29:05Z | [
"python",
"slug"
] | I am in search of the best way to "slugify" string [what "slug" is](http://stackoverflow.com/questions/427102/in-django-what-is-a-slug), and my current solution is based on [this recipe](http://code.activestate.com/recipes/577257-slugify-make-a-string-usable-in-a-url-or-filename/)
I have changed it a little bit to:
`... | Install unidecode form [from here](http://pypi.python.org/pypi/Unidecode#downloads) for unicode support
> pip install unidecode
```
# -*- coding: utf-8 -*-
import re
import unidecode
def slugify(text):
text = unidecode.unidecode(text).lower()
return re.sub(r'\W+', '-', text)
text = u"My custom Ñ
елло в... |
String slugification in Python | 5,574,042 | 45 | 2011-04-06T23:08:55Z | 14,887,397 | 68 | 2013-02-15T02:12:36Z | [
"python",
"slug"
] | I am in search of the best way to "slugify" string [what "slug" is](http://stackoverflow.com/questions/427102/in-django-what-is-a-slug), and my current solution is based on [this recipe](http://code.activestate.com/recipes/577257-slugify-make-a-string-usable-in-a-url-or-filename/)
I have changed it a little bit to:
`... | There is a python package named `python-slugify`, which does a pretty good job of slugifying:
```
pip install python-slugify
```
Works like this:
```
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self... |
C Pointer arithmetic in Python | 5,574,159 | 4 | 2011-04-06T23:26:48Z | 5,574,180 | 10 | 2011-04-06T23:28:34Z | [
"python",
"c",
"arrays",
"math",
"pointers"
] | I'm trying to convert a simple C program into Python but as I don't know anything about C and a little about Python its just difficult for me..
I'm stuck at C pointers.
There is a function that takes an unsigned long int pointer and adds its values to some variables within a while-loop:
```
uint32_t somename(const u... | A similar code snippet in Python might be:
```
def somename(z):
i = 0
while (....):
a += z[i]
b += z[i+1]
c += z[i+2]
i += 3
```
In C, `z` works sort of like an array index, except it starts at whatever the address of the start of the array is, rather than starting at 0. There ... |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 5,574,737 | 310 | 2011-04-07T01:03:21Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | `sys.stderr.write()` is my choice, just more readable and saying exactly what you intend to do and portable across versions.
Edit: being 'pythonic' is a third thought to me over readability and performance... with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the 'bi... |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 5,574,749 | 24 | 2011-04-07T01:05:24Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | I would say that your first approach:
```
print >> sys.stderr, 'spam'
```
is the "One . . . **obvious** way to do it" The others don't satisfy rule #1 ("Beautiful is better than ugly.") |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 8,054,613 | 100 | 2011-11-08T17:29:52Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | My choice is:
`print >> sys.stderr, 'spam'`
Because you can simply print lists/dicts etc. without convert it to string.
`print >> sys.stderr, {'spam': 'spam'}`
instead of:
`sys.stderr.write(str('spam': 'spam'))` |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 12,757,834 | 15 | 2012-10-06T07:42:50Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | This will mimic the standard print function but output on stderr
```
def print_err(*args):
sys.stderr.write(' '.join(map(str,args)) + '\n')
``` |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 14,981,125 | 486 | 2013-02-20T13:31:54Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | I found this to be the only one short + flexible + portable + readable:
```
from __future__ import print_function
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
```
The function `eprint` can be used in the same was as the standard `print` function:
```
>>> print("Test")
Test
>>>... |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 15,808,105 | 56 | 2013-04-04T10:00:16Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | `print >> sys.stderr` is gone in Python3.
<http://docs.python.org/3.0/whatsnew/3.0.html> says:
```
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
```
Unfortunately, this is quite ugly. Alternatively, use
```
sys.stderr.write("fatal error\n")
```
but note that `write` is not a 1:1 ... |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 20,830,343 | 17 | 2013-12-29T21:40:08Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | I did the following using Python 3:
```
from sys import stderr
def print_err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
```
So now I'm able to add keyword arguments, for example, to avoid carriage return:
```
print_err("Error: end of the file reached. The word ", end='')
print_err(word, "was not foun... |
How to print to stderr in Python? | 5,574,702 | 672 | 2011-04-07T00:59:10Z | 20,832,405 | 10 | 2013-12-30T02:13:49Z | [
"python",
"printing",
"stderr",
"zen"
] | I've come across at least three ways to print to stderr:
```
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spam\n')
from __future__ import print_function
print('spam', file=sys.stderr)
```
It seems to contradict *zen of Python #13* â, so what's the preferred way to do it? Are there any advantages ... | To make it even easier, here's a version that uses 'partial', which is a big help in wrapping functions.
```
from __future__ import print_function
import sys
from functools import partial
error = partial(print, file=sys.stderr)
```
You then use it like so
```
error('An error occured!')
```
You can check that it's ... |
Difference between "axes" and "axis" in matplotlib? | 5,575,451 | 22 | 2011-04-07T03:00:56Z | 5,575,468 | 32 | 2011-04-07T03:05:40Z | [
"python",
"matplotlib"
] | I'm confused about what the different between `axes` and `axis` is in matplotlib. Could someone please explain in an easy-to-understand way? | Axis is the axis of the plot, the thing that gets ticks and tick labels. The axes is the area your plot appears in. |
convert IP to hostname | 5,576,744 | 2 | 2011-04-07T06:07:52Z | 5,576,987 | 7 | 2011-04-07T06:39:31Z | [
"python",
"linux"
] | I want to write a python script to convert IP addresses to hostnames. I am using a Linux box.
I don't see this information in whois command. Are there any commands that always give the correct hostnames (as accurately as possible)? | [Socket](http://docs.python.org/library/socket.html#gethostbyaddr) library has an API to do [reverse DNS lookups](http://en.wikipedia.org/wiki/Reverse_DNS_lookup).
```
import socket
socket.gethostbyaddr("8.8.8.8")
>>> ('google-public-dns-a.google.com', [], ['8.8.8.8'])
```
Keep in mind that not all IP addresses will ... |
Is it possible to pass a python string by reference through ctypes? | 5,576,925 | 4 | 2011-04-07T06:30:40Z | 5,577,110 | 12 | 2011-04-07T06:52:42Z | [
"python",
"ctypes"
] | I'm sorry, but I generally have a hard time reading the current ctypes docs...
If I have a C function that takes a `const char *` pointer, and I *know* it will neither modify the passed in string, nor keep a reference to it beyond the function call, it really makes sense to pass in a pointer directly to the bytes of a... | > Assigning a new value to instances of the pointer types c\_char\_p, c\_wchar\_p, and c\_void\_p changes the memory location they point to, not the contents of the memory block (of course not, because Python strings are immutable):
```
>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World'... |
How do I use Selenium to login to sites that require username and password? | 5,577,065 | 5 | 2011-04-07T06:47:39Z | 6,657,543 | 8 | 2011-07-11T22:39:35Z | [
"python",
"selenium"
] | I am developing an automated test scripts using selenium api with python. But when i run the script from selenium rc its goes to the login page. How will I be able to put in my username and password on that page as it does not contain any sessions or cookies? | Here's the suggestion that was made to me by [Adam Goucher](http://adam.goucher.ca/) on the Selenium IRC channel ( irc://irc.freenode.net/selenium ):
Take advantage of the situation of a completely clean browser cache/cookie history. Code your test to do the login.
However, instead of hard-coding into your code a use... |
How to tell if string starts with a number? | 5,577,501 | 37 | 2011-04-07T07:33:48Z | 5,577,536 | 69 | 2011-04-07T07:37:03Z | [
"python"
] | I have a string that starts with a number (from 0-9)
I know I can "or" 10 test cases using startswith() but there is probably a neater solution
so instead of writing
```
if (string.startswith('0') || string.startswith('2') ||
string.startswith('3') || string.startswith('4') ||
string.startswith('5') || string... | Python's `string` library has `isdigit()` method:
```
string[0].isdigit()
``` |
How to tell if string starts with a number? | 5,577,501 | 37 | 2011-04-07T07:33:48Z | 5,577,537 | 22 | 2011-04-07T07:37:03Z | [
"python"
] | I have a string that starts with a number (from 0-9)
I know I can "or" 10 test cases using startswith() but there is probably a neater solution
so instead of writing
```
if (string.startswith('0') || string.startswith('2') ||
string.startswith('3') || string.startswith('4') ||
string.startswith('5') || string... | ```
>>> string = '1abc'
>>> string[0].isdigit()
True
``` |
python logging to multiple files | 5,577,637 | 9 | 2011-04-07T07:45:55Z | 5,577,806 | 13 | 2011-04-07T08:02:54Z | [
"python",
"django",
"logging"
] | Does someone has an example of logging in python to 2 or more different logfiles.
I want to log for example to '/tmp/foo.log' and '/tmp/bar.log'
Thanks in advance
T | Here's an example:
```
import logging
logger1 = logging.getLogger('1')
logger1.addHandler(logging.FileHandler('/tmp/logger1'))
logger2 = logging.getLogger('2')
logger2.addHandler(logging.FileHandler('/tmp/logger2'))
logger1.error('1')
logger2.error('2')
```
Then,
```
$ cat /tmp/logger1
1
$ cat /tmp/logger2
2
``... |
Can I use my own Python class with numpy or some other matrix library? | 5,578,172 | 9 | 2011-04-07T08:33:11Z | 5,578,211 | 7 | 2011-04-07T08:36:27Z | [
"python",
"matrix",
"numpy"
] | I'd like to be able to do matrix operations using a Python class as the elementsâin this case, a simple [Galois field](http://en.wikipedia.org/wiki/Galois_field) implementation. It implements the necessary `__add__`, `__mul__`, `__sub__` etc.
At first, I thought this should be possible with [numpy arrays](http://doc... | You can use `object` as the `dtype`, which will allow arbitrary Python objects. I don't think there's any way of specializing a numpy array to accept only one particular class of Python object. |
How can I rewrite python __version__ with git? | 5,581,722 | 27 | 2011-04-07T13:18:42Z | 5,582,128 | 25 | 2011-04-07T13:45:56Z | [
"python",
"git"
] | I would like to define a `__version__` variable in my module which should be automatically updated on git commit similarly to what [SVN keywords](http://stackoverflow.com/questions/1790235/adding-version-control-numbering-to-python-project) do. Is there a way to achieve it in Git? Does anyone have a working example?
I... | It might be better to do this as part of your packaging, rather than after every commit.
There are two primary options:
* Use [`git-archive`](http://www.kernel.org/pub/software/scm/git/docs/git-archive.html) to package, and use the [`export-subst` attribute](http://git-scm.com/docs/gitattributes#_tt_export_subst_tt).... |
How can I rewrite python __version__ with git? | 5,581,722 | 27 | 2011-04-07T13:18:42Z | 7,071,192 | 8 | 2011-08-15T21:46:19Z | [
"python",
"git"
] | I would like to define a `__version__` variable in my module which should be automatically updated on git commit similarly to what [SVN keywords](http://stackoverflow.com/questions/1790235/adding-version-control-numbering-to-python-project) do. Is there a way to achieve it in Git? Does anyone have a working example?
I... | Here is a working example of this functionality with git due to Brian Warner:
source code:
<https://github.com/warner/python-ecdsa/blob/9e21c3388cc98ba90877a1e4dbc2aaf66c67d365/setup.py#L33>
I assume his implementation was inspired by a similar thing with darcs that he and I worked on together previously:
README:
... |
Python how to reduce on a list of tuple? | 5,582,264 | 8 | 2011-04-07T13:55:14Z | 5,582,408 | 9 | 2011-04-07T14:04:28Z | [
"python",
"sum",
"reduce",
"map-function"
] | Hi I am able to use `map` and `sum` to achieve this functionality, but how to use `reduce`?
There are 2 lists: `a`, `b`, they have same number of values. I want to calculate
```
a[0]*b[0]+a[1]*b[1]+...+a[n]*b[n]
```
The working version I wrote using `map` is
```
value = sum(map(lambda (x,y): x*y, zip(a, b)))
```
... | The first argument of the lambda function is the sum so far and the second argument is the next pair of elements:
```
value = reduce(lambda sum, (x, y): sum + x*y, zip(a, b), 0)
``` |
Python how to reduce on a list of tuple? | 5,582,264 | 8 | 2011-04-07T13:55:14Z | 5,582,416 | 7 | 2011-04-07T14:05:05Z | [
"python",
"sum",
"reduce",
"map-function"
] | Hi I am able to use `map` and `sum` to achieve this functionality, but how to use `reduce`?
There are 2 lists: `a`, `b`, they have same number of values. I want to calculate
```
a[0]*b[0]+a[1]*b[1]+...+a[n]*b[n]
```
The working version I wrote using `map` is
```
value = sum(map(lambda (x,y): x*y, zip(a, b)))
```
... | I would do it this way (I don't think you need lambda)...
```
sum(x*y for x, y in zip(a, b))
```
This also seems slightly more explicit. Zip AB, multiply them, and sum up the terms. |
Python how to reduce on a list of tuple? | 5,582,264 | 8 | 2011-04-07T13:55:14Z | 5,582,519 | 7 | 2011-04-07T14:12:29Z | [
"python",
"sum",
"reduce",
"map-function"
] | Hi I am able to use `map` and `sum` to achieve this functionality, but how to use `reduce`?
There are 2 lists: `a`, `b`, they have same number of values. I want to calculate
```
a[0]*b[0]+a[1]*b[1]+...+a[n]*b[n]
```
The working version I wrote using `map` is
```
value = sum(map(lambda (x,y): x*y, zip(a, b)))
```
... | A solution using `reduce` and `map`,
```
from operator import add,mul
a = [1,2,3]
b = [4,5,6]
print reduce(add,map(mul,a,b))
``` |
Django: How to access original (unmodified) instance in post_save signal | 5,582,410 | 18 | 2011-04-07T14:04:36Z | 5,583,194 | 29 | 2011-04-07T15:00:29Z | [
"python",
"django",
"postgresql",
"denormalization",
"django-signals"
] | I want to do a data denormalization for better performance, and put a sum of votes my blog post receives inside Post model:
```
class Post(models.Model):
""" Blog entry """
author = models.ForeignKey(User)
title = models.CharField(max_length=255)
text = models.TextField()
... | I believe `post_save` is too late to retrieve the unmodified version. As the name implies the data has already been written to the db at that point. You should use `pre_save` instead. In that case you can retrieve the model from the db via pk: `old = Vote.objects.get(pk=instance.pk)` and check for differences in the cu... |
Need to avoid subprocess deadlock without communicate | 5,582,933 | 20 | 2011-04-07T14:43:21Z | 5,594,930 | 8 | 2011-04-08T12:18:11Z | [
"python",
"subprocess",
"pipe",
"stdout",
"deadlock"
] | I need a execute a command that produces a lot of output and takes a lot of time to execute (> 30 minutes). I was thinking of using subprocess.Popen to do it. I need to capture the output of the command, so I pass PIPE to stdout and stderr.
A deadlock problem when using Popen.wait() is well documented on a lot of foru... | * to workaround [python bug #1124861](http://bugs.python.org/issue1124861) on Python2.4 you could attach `stdin` to a `NUL` device
```
import os
from subprocess import PIPE, STDOUT, Popen
lines = []
p = Popen(cmd, bufsize=1, stdin=open(os.devnull), stdout=PIPE, stderr=STDOUT)
for line in iter(p.stdout.readline, ''):
... |
Django settings.py: Separate local and global configuration | 5,583,077 | 3 | 2011-04-07T14:52:56Z | 5,583,253 | 12 | 2011-04-07T15:04:35Z | [
"python",
"django",
"git",
"configuration",
"project-management"
] | I was wondering if it was possible to separate the "local" configuration in Django (Local path to static, templates content which have to be absolute, local DB info, etc...) from the "global" configuration (URL, Middleware classes, installed apps, etc...) so that several people can work on a same project over Git or SV... | Yes, definitely. The settings.py file is just Python, so you can do anything in there - including setting things dynamically, and importing other files to override.
So there's two approaches here. The first is not to hard-code any paths, but calculate them dynamically.
```
PROJECT_ROOT = os.path.abspath(os.path.dirna... |
serialize datetime to json in Django | 5,583,401 | 15 | 2011-04-07T15:14:48Z | 5,781,657 | 63 | 2011-04-25T18:25:42Z | [
"python",
"django"
] | Hi how do i get DateTimeField from mysql database in django in json format. I got an error when i executed the code 'Date.time cannot be serialized in json'(data holds a lot of values)
```
data = json.dumps(data)
```
but this was fixed by adding
```
ALL_data = serializers.serialize("json", data, ensure_ascii=False)
... | This solved my problem.
```
import json
from django.core.serializers.json import DjangoJSONEncoder
data = json.dumps(data, cls=DjangoJSONEncoder)
``` |
Is the builtin hash method of Python2.6 stable across architectures? | 5,583,907 | 11 | 2011-04-07T15:51:40Z | 5,584,007 | 10 | 2011-04-07T15:59:22Z | [
"python"
] | I need to compute a hash that needs to be stable across architectures. Is python's hash() stable?
To be more specific, the example below shows hash() computing the same value on two different hosts/architectures:
```
# on OSX based laptop
>>> hash((1,2,3,4))
485696759010151909
# on x86_64 Linux host
>>> hash((1,2,3,4... | If you need a well defined hash, you can use one out of [hashlib](http://docs.python.org/library/hashlib.html#module-hashlib). |
Find the division remainder of a number | 5,584,586 | 41 | 2011-04-07T16:44:16Z | 5,584,604 | 66 | 2011-04-07T16:45:29Z | [
"python",
"integer-division"
] | How could I go about finding the division remainder of a number in Python?
For example:
If the number is 26 and divided number is 7, then the division remainder is 5.
(since 7+7+7=21 and 26-21=5.) | you are looking for the modulo operator:
```
a % b
```
for example:
```
26 % 7
```
Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either. |
Find the division remainder of a number | 5,584,586 | 41 | 2011-04-07T16:44:16Z | 5,848,159 | 88 | 2011-05-01T11:49:22Z | [
"python",
"integer-division"
] | How could I go about finding the division remainder of a number in Python?
For example:
If the number is 26 and divided number is 7, then the division remainder is 5.
(since 7+7+7=21 and 26-21=5.) | The remainder of a division can be discovered using the operator `%`:
```
>>> 26%7
5
```
In case you need both the quotient and the modulo, there's the builtin `divmod` function:
```
>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)
``` |
Find the division remainder of a number | 5,584,586 | 41 | 2011-04-07T16:44:16Z | 17,636,181 | 10 | 2013-07-14T03:07:58Z | [
"python",
"integer-division"
] | How could I go about finding the division remainder of a number in Python?
For example:
If the number is 26 and divided number is 7, then the division remainder is 5.
(since 7+7+7=21 and 26-21=5.) | If you want to avoid modulo, you can also use a combination of the four basic operations :)
```
26 - (26 // 7 * 7) = 5
``` |
what's the difference between python objects and json objects? | 5,584,943 | 4 | 2011-04-07T17:14:09Z | 5,584,965 | 12 | 2011-04-07T17:16:14Z | [
"javascript",
"python",
"django",
"json",
"node.js"
] | On the surface it appears that python uses json natively. The only exception I can think of is the fact that json can store js functions.
Here's my issue:
I need to pass json to a python file through the terminal.
Why should or shouldn't I just use eval()? | JSON does not have objects per se, and cannot store JavaScript functions. Its syntax may appear similar to JavaScript literals, but trying to use it as such all the time will cause nothing but pain.
And there should be no need to use `eval()`; both JavaScript and Python have JSON parsers and serializers readily availa... |
what's the difference between python objects and json objects? | 5,584,943 | 4 | 2011-04-07T17:14:09Z | 5,585,962 | 19 | 2011-04-07T18:44:16Z | [
"javascript",
"python",
"django",
"json",
"node.js"
] | On the surface it appears that python uses json natively. The only exception I can think of is the fact that json can store js functions.
Here's my issue:
I need to pass json to a python file through the terminal.
Why should or shouldn't I just use eval()? | No, Python does not use JSON natively. This stuff you think is JSON is, in fact, a dictionary, *one* of many kinds of objects in Python. The (easy) syntax for building a dictionary in Python is pretty close to JSON but it is incidental. As you can create a dictionary this way:
```
a = {'a' : 2, 'b' : 3}
```
you can c... |
Getting the return value of Javascript code in Selenium | 5,585,343 | 64 | 2011-04-07T17:48:25Z | 5,585,345 | 103 | 2011-04-07T17:48:40Z | [
"javascript",
"python",
"selenium-webdriver"
] | I'm using Selenium2 for some automated tests of my website, and I'd like to be able to get the return value of some Javascript code. If I have a `foobar()` Javascript function in my webpage and I want to call that and get the return value into my Python code, what can I call to do that? | To return a value, simply use the `return` JavaScript keyword in the string passed to the `execute_script()` method, e.g.
```
>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execu... |
Running generated nose tests | 5,585,670 | 6 | 2011-04-07T18:18:52Z | 5,588,314 | 7 | 2011-04-07T22:15:36Z | [
"python",
"nose"
] | Suppose I define a testFile.py python module with as follows.
```
def test_evens():
for i in range(0, 5):
yield check_even, i, i*3
def check_even(n, nn):
assert n % 2 == 0 or nn % 2 == 0
```
When I let nose identify the tests in collect-only mode I get
```
testFile.test_evens(0, 0) ... ok
testFile.t... | Nose cannot do this by default, to my knowledge. Here are some options:
**1. Fake it from the command line**
Probably not what you're looking for, but I had to mention it. You could also
create a wrapper script to simplify this:
```
python -c 'import testFile; testFile.check_even(2, 6)'
```
**2. Create a custom nos... |
datetime.datetime.strptime not present in Python 2.4.1 | 5,585,706 | 11 | 2011-04-07T18:21:39Z | 5,585,789 | 18 | 2011-04-07T18:28:39Z | [
"python",
"datetime"
] | Our team is required to use Python 2.4.1 in certain circumstances. `strptime` is not present in the `datetime.datetime` module in Python 2.4.1:
```
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dateti... | Note that `strptime` is still in the `time` module, even as of 2.7.1, as well as in `datetime`.
If, however, you look at the [documentation for datetime](http://docs.python.org/library/datetime.html) in a recent version, you will see this under `strptime`:
> This is equivalent to `datetime(*(time.strptime(date_string... |
datetime.datetime.strptime not present in Python 2.4.1 | 5,585,706 | 11 | 2011-04-07T18:21:39Z | 7,226,819 | 11 | 2011-08-29T06:24:23Z | [
"python",
"datetime"
] | Our team is required to use Python 2.4.1 in certain circumstances. `strptime` is not present in the `datetime.datetime` module in Python 2.4.1:
```
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dateti... | I had a similar problem as well.
Based on Daniel's answer, this works for me when you're not sure under which Python version (2.4 vs 2.6) the script will be running:
```
from datetime import datetime
import time
if hasattr(datetime, 'strptime'):
#python 2.6
strptime = datetime.strptime
else:
#python 2.4 ... |
What is the official "preferred" way to install pip and virtualenv systemwide? | 5,585,875 | 76 | 2011-04-07T18:36:35Z | 5,586,450 | 16 | 2011-04-07T19:24:25Z | [
"python",
"virtualenv",
"setuptools",
"pip",
"easy-install"
] | Is it this, which people seem to recommend most often:
```
$ sudo apt-get install python-setuptools
$ sudo easy_install pip
$ sudo pip install virtualenv
```
Or this, which I got from <http://www.pip-installer.org/en/latest/installing.html>:
```
$ curl -O https://github.com/pypa/virtualenv/raw/master/virtualenv.py
$... | This answer comes from @webology on Twitter:
```
$ sudo apt-get install python-setuptools
$ sudo easy_install pip
$ sudo pip install --upgrade pip virtualenv virtualenvwrapper
```
My added notes:
* On Mac/Windows (and Linux if the apt repo is outdated) you'd replace the first step with downloading setuptools from <h... |
What is the official "preferred" way to install pip and virtualenv systemwide? | 5,585,875 | 76 | 2011-04-07T18:36:35Z | 5,590,714 | 21 | 2011-04-08T05:11:37Z | [
"python",
"virtualenv",
"setuptools",
"pip",
"easy-install"
] | Is it this, which people seem to recommend most often:
```
$ sudo apt-get install python-setuptools
$ sudo easy_install pip
$ sudo pip install virtualenv
```
Or this, which I got from <http://www.pip-installer.org/en/latest/installing.html>:
```
$ curl -O https://github.com/pypa/virtualenv/raw/master/virtualenv.py
$... | <http://www.pip-installer.org/en/latest/installing.html> is really the canonical answer to this question.
Specifically, the systemwide instructions are:
```
$ curl -O http://python-distribute.org/distribute_setup.py
$ python distribute_setup.py
$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ pyt... |
What is the official "preferred" way to install pip and virtualenv systemwide? | 5,585,875 | 76 | 2011-04-07T18:36:35Z | 17,601,159 | 75 | 2013-07-11T18:53:03Z | [
"python",
"virtualenv",
"setuptools",
"pip",
"easy-install"
] | Is it this, which people seem to recommend most often:
```
$ sudo apt-get install python-setuptools
$ sudo easy_install pip
$ sudo pip install virtualenv
```
Or this, which I got from <http://www.pip-installer.org/en/latest/installing.html>:
```
$ curl -O https://github.com/pypa/virtualenv/raw/master/virtualenv.py
$... | If you can install the latest Python (2.7.9 and up) Pip is now bundled with it.
See: <https://docs.python.org/2.7//installing/index.html>
If not :
**Update (from the release notes):**
> Beginning with v1.5.1, pip does not require setuptools prior to running get-pip.py. Additionally, if setuptools (or distribute) i... |
Problem with lxml xpath for html table extracting | 5,586,296 | 13 | 2011-04-07T19:10:46Z | 5,586,627 | 32 | 2011-04-07T19:38:30Z | [
"python",
"html",
"table",
"xpath",
"lxml"
] | i have a html doc similar to following:
```
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
<div id="Symbols" class="cb">
<table class="quotes">
<tr><th>Code</th><th>Name</th>
<th style="text-align:right;">High</th>
<th style="text-align:right;">Low</th>
... | You are probably looking at the HTML in Firebug, correct? The browser will insert the implicit tag `<tbody>` when it is not present in the document. The lxml library will only process the tags present in the raw HTML string.
Omit the **tbody** level in your XPath. For example, this works:
```
tree = lxml.html.fromstr... |
Emulating the list.insert() method as a subclass of Python's list | 5,586,533 | 5 | 2011-04-07T19:31:51Z | 5,590,612 | 7 | 2011-04-08T04:55:32Z | [
"python",
"subclass",
"subclassing"
] | I'm trying to build a class that inherits methods from Python's list, but also does some additional things on top... it's probably easier just to show code at this point...
```
class Host(object):
"""Emulate a virtual host attached to a physical interface"""
def __init__(self):
# Insert class properties he... | If you can possibly avoid it, don't inherit from builtin classes. (You *can*, but that doesn't mean you *should* without a really compelling reason)
Those classes are optimised for speed, and that makes inheriting from them correctly quite tedious, since you end up having to override almost everything.
Inheriting fro... |
Scipy interpolation how to resize/resample 3x3 matrix to 5x5? | 5,586,719 | 10 | 2011-04-07T19:47:09Z | 5,586,898 | 8 | 2011-04-07T20:01:38Z | [
"python",
"numpy",
"scipy",
"interpolation",
"resampling"
] | **EDIT:** Paul has solved this one below. Thanks!
I'm trying to resample (upscale) a 3x3 matrix to 5x5, filling in the intermediate points with either interpolate.interp2d or interpolate.RectBivariateSpline (or whatever works).
If there's a simple, existing function to do this, I'd like to use it, but I haven't found... | Only two small problems:
1) Your xx,yy is outside the bounds of x,y (you *can* extrapolate, but I'm guessing you don't want to.)
2) Your sample size is too small for a kx and ky of 3 (default). Lower it to 2 and get a quadratic fit instead of cubic.
```
import numpy, scipy
from scipy import interpolate
kernelIn = n... |
Scipy interpolation how to resize/resample 3x3 matrix to 5x5? | 5,586,719 | 10 | 2011-04-07T19:47:09Z | 5,587,339 | 7 | 2011-04-07T20:39:09Z | [
"python",
"numpy",
"scipy",
"interpolation",
"resampling"
] | **EDIT:** Paul has solved this one below. Thanks!
I'm trying to resample (upscale) a 3x3 matrix to 5x5, filling in the intermediate points with either interpolate.interp2d or interpolate.RectBivariateSpline (or whatever works).
If there's a simple, existing function to do this, I'd like to use it, but I haven't found... | If you are using scipy already, I think `scipy.ndimage.interpolate.zoom` can do what you need:
```
import numpy
import scipy.ndimage
a = numpy.array([[0.,-2.,0.], [-2.,11.,-2.], [0.,-2.,0.]])
out = numpy.round(scipy.ndimage.interpolation.zoom(input=a, zoom=(5./3), order = 2),1)
print out
#[[ 0. -1. -2. -1. ... |
Django template filters, tags, simple_tags, and inclusion_tags | 5,586,774 | 21 | 2011-04-07T19:51:35Z | 5,586,860 | 33 | 2011-04-07T19:58:51Z | [
"python",
"django"
] | This is more of a general question about the distinctions between these four different kinds of django tags. I just read the documentation page on template tags:
<http://docs.djangoproject.com/en/dev/howto/custom-template-tags/>
But I'm finding it difficult to know when I should use one variation over another. For exa... | **Template filters** can operate on any object (and at most two at once). They're just functions that take one or two arguments. e.g.
```
# filter implementation
@filter
def myfilter(arg1, arg2):
....
# usage in template
{{ arg1|myfilter:arg2 }}
```
They are limited in that they cannot access the template contex... |
Cache problem with Django forms | 5,586,803 | 2 | 2011-04-07T19:54:02Z | 5,586,919 | 8 | 2011-04-07T20:02:48Z | [
"javascript",
"python",
"django",
"cache-control",
"browser-cache"
] | i'm populating the choices of a form choicefield in django, it's a year select field, i get years from the database and put them in a list of tuples in the field. My code looks like this
```
def get_years():
choices = []
years = []
for en in Encuesta.objects.all().order_by('fecha'):
years.append(en... | Update the years when you initialize a form instance.
```
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['year'].choices = self.get_years()
``` |
numpy array subclass unexpedly shares attributes across instances | 5,587,582 | 8 | 2011-04-07T21:00:09Z | 5,592,432 | 14 | 2011-04-08T08:25:09Z | [
"python",
"numpy"
] | I am having a weird subclass numpy.ndarray issue that feels like
[Values of instance variables of superclass persist across instances of subclass](http://stackoverflow.com/questions/5561294/values-of-instance-variables-of-superclass-persist-across-instances-of-subclass)
But I have not been able to understand fully ... | The problem is here:
```
def __new__(cls, input_array, attrs={})
```
Never do this `attrs={}` in a function header. The expected result is (probably) not what you think it is. This is a common Python Pitfall. See here [Default Parameter Values in Python](http://effbot.org/zone/default-values.htm)
The right way how t... |
Inheritance and inner classes in Python? | 5,587,653 | 9 | 2011-04-07T21:04:54Z | 5,587,869 | 9 | 2011-04-07T21:26:38Z | [
"python",
"oop",
"class",
"inheritance",
"inner-classes"
] | In the following code class `B` has inherited `yay` attribute from class `A`, I expected this. I'd also expect that inner class `B.Foo` behaves the same way but it doesn't.
How to make `B.Foo` to inherit `alice` attribute from class `A`? I need that the inner subclass `Foo` in `B` has both the attributes `alice` and `... | The reason why `B.Foo.alice` gave you an error is because there's no connection between `Foo` attribute of class `A` and `Foo` attribute of class `B`.
In `B`, attribute `Foo` has a class object value that completely replaces class object value inherited from `A`.
This should fix it:
```
class B(A):
nay = False
... |
adding an attribute in suds | 5,588,403 | 6 | 2011-04-07T22:26:59Z | 7,177,594 | 8 | 2011-08-24T14:55:31Z | [
"python",
"web-services",
"suds"
] | I have to do soap request with suds and Python
```
<soap:Body>
<registerOrder>
<order merchantOrderNumber="" description="" amount="" currency="" language="" xmlns="">
<returnUrl>http://mysafety.com</returnUrl>
</order>
</registerOrder>
</soap:Body>
```
How to add an attr... | A more dynamic version of the MessagePlugin would be:
```
from suds.sax.attribute import Attribute
from suds.plugin import MessagePlugin
class _AttributePlugin(MessagePlugin):
"""
Suds plug-in extending the method call with arbitrary attributes.
"""
def __init__(self, **kwargs):
self.kwargs = ... |
Joining a list of python objects with __str__ method | 5,588,685 | 3 | 2011-04-07T23:10:22Z | 5,588,714 | 7 | 2011-04-07T23:13:55Z | [
"python",
"string"
] | I've already looked at [this question on representing strings in Python](http://stackoverflow.com/questions/3558474/how-to-apply-str-function-when-printing-a-list-of-objects-in-python) but my question is slightly different.
Here's the code:
```
>>> class WeirdThing(object):
... def __init__(self):
... sel... | You have to stringify your objects before you can join them. This is because `str.join` expects a series of strings, and you must give it a series of strings.
For the sake of less typing at the cost of readability, you can do `"\n".join(map(str, list_of_things)`. |
Distinguishing between GET and POST data in CherryPy? | 5,588,887 | 4 | 2011-04-07T23:46:28Z | 5,588,976 | 7 | 2011-04-08T00:04:11Z | [
"python",
"cherrypy",
"web-frameworks"
] | I've been deciding between Python web frameworks for a project of mine and I've really liked how lightweight, flexible, and concise CherryPy is compared to others. The only problem I'm having is I can't find any documentation on how to distinguish between data sent via GET and via POST.
For example, I don't want users... | See [the docs](https://cherrypy.readthedocs.org/en/3.3.0/refman/_cprequest.html#cherrypy._cprequest.Request.method).
> A string containing the HTTP method, such as "GET" or "POST". Set
> in the "run" phase.
looks like checking cherrypy.request.method is what you want to do. |
Does web2py have these? | 5,589,230 | 7 | 2011-04-08T00:44:50Z | 5,589,356 | 13 | 2011-04-08T01:06:51Z | [
"python",
"web2py"
] | I am finishing up a project in PHP with Yii and phing. Even though Yii is the best web framework I've used to date, I prefer writing Python over PHP. So, I've been looking at web2py and have some questions:
1. Does web2py provide Javascript form validation? Yii has <http://www.yiiframework.com/extension/jformvalidate/... | > Does web2py provide Javascript form validation?
Out of the box web2py does server-side validation, client side js pre-validation of int, double and calendar popup for date/time/datetime. There are jQuery plugins to add more client-side validation. web2py is mostly serverside, not clientside.
> Does web2py have a mo... |
Try/catch or validation for speed? | 5,589,532 | 35 | 2011-04-08T01:39:57Z | 5,591,737 | 75 | 2011-04-08T07:15:27Z | [
"python",
"performance",
"exception-handling",
"typechecking"
] | I'm working with Python and whenever I've had to validate function input, I assumed that the input worked, and then caught errors.
In my case, I had a universal `Vector()` class which I used for a few different things, one of which is addition. It functioned both as a `Color()` class and as a `Vector()`, so when I add... | I upvoted Matt Joiner's answer, but wanted to include some additional observations to make it clear that, along with a couple of other factors, there are **4** times that matter when choosing between pre-checking conditions (known as LBYL or "Look Before You Leap") and just handling exceptions (known as EAFP or "Easier... |
Python list + list vs. list.append() | 5,589,549 | 5 | 2011-04-08T01:43:06Z | 5,589,584 | 10 | 2011-04-08T01:48:50Z | [
"python",
"list"
] | Today I spent about 20 minutes trying to figure out why
this worked as expected:
```
users_stories_dict[a] = s + [b]
```
but this would have a `None` value:
```
users_stories_dict[a] = s.append(b)
```
Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this... | `append` works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by `append` is None. In other words, what one wants is:
`s.append(b)`
and then:
`users_stories_dict[a] = s`
But, you've already figured that much out. As to why it was done this way, while I don't ... |
Python list + list vs. list.append() | 5,589,549 | 5 | 2011-04-08T01:43:06Z | 5,589,600 | 8 | 2011-04-08T01:52:59Z | [
"python",
"list"
] | Today I spent about 20 minutes trying to figure out why
this worked as expected:
```
users_stories_dict[a] = s + [b]
```
but this would have a `None` value:
```
users_stories_dict[a] = s.append(b)
```
Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this... | The append() method returns a None, because it modifies the list it self by adding the object appended as an element, while the `+` operator concatenates the two lists and return the resulting list
eg:
```
a = [1,2,3,4,5]
b = [6,7,8,9,0]
print a+b # returns a list made by concatenating the lists a and b
>>> ... |
How to set value of hidden form in Mechanize/Python? | 5,592,088 | 8 | 2011-04-08T07:50:05Z | 5,592,508 | 24 | 2011-04-08T08:31:25Z | [
"python",
"screen-scraping",
"mechanize"
] | I'm scraping a site that uses a hidden form as a means of a countermeasure against exactly what I'm trying to do. This form:
```
<input style="width: 2px; height: 25px" type="hidden" size="1" name="TestJavaScript" />
```
is the culprit. The form expects that this input's value will be set to "OK" by some JavaScript t... | As posted [elsewhere](http://wwwsearch.sourceforge.net/mechanize/faq.html) (namely on the mechanize library's FAQ page):
```
form.find_control("foo").readonly = False # allow changing .value of control foo
form.set_all_readonly(False) # allow changing the .value of all controls
``` |
Merge 2 images using google app engine and python? | 5,594,708 | 5 | 2011-04-08T11:57:35Z | 5,595,237 | 12 | 2011-04-08T12:47:08Z | [
"python",
"google-app-engine",
"python-imaging-library"
] | I want to merge 2 images and that too at specific location of 1st image.
Example:
1st image: `x.png` (400 X 400px)
2nd image: `y.png` (at `100,100` co-ordinates)
How can i do this using python in google appengine.?
If you can provide some codes for this ... or any reference to this code... will be appreciated.
Than... | This can be done using the very cut down imaging library which emulates some of the functions of PIL. The function you need is [composite](http://code.google.com/appengine/docs/python/images/functions.html)
```
from google.appengine.api import images
xpng = #Load data from x.png here, or read from BlobProperty
ypng =... |
Fabric's cd context manager does not work | 5,594,933 | 28 | 2011-04-08T12:18:17Z | 5,595,021 | 48 | 2011-04-08T12:27:29Z | [
"python",
"fabric"
] | I have set up my development environment on a new PC and seems I am having strange error with Fabric. Its 'cd' context manager seems does not change the current directory, and thus a lot of my commands don't work. I have written the test and it showed me results I have not expected to get:
```
from __future__ import w... | You're looking for [`lcd`](http://docs.fabfile.org/en/1.0.1/api/core/context_managers.html?highlight=cd#fabric.context_managers.lcd) (`l` for local) rather than `cd` (which is remote). |
PyDev Eclipse Python interpreters Error: stdlib not found | 5,595,276 | 25 | 2011-04-08T12:50:08Z | 5,644,277 | 7 | 2011-04-13T04:06:47Z | [
"python",
"eclipse",
"pydev"
] | I have been trying to use Eclipse 3.6 as a Python editor.
I install the latest version of PyDev, and then try to set the Interpreter - Python field of the preferences, on my mac.
My python version is 2.6 and the path is "/usr/bin/python". When I enter this, and I select the items to add to the system PYTHONPATH I get ... | just found an answer to my own question, thought it might enlighten other users with similar problems. I will try it out later to see if it works.
On SourceForge: <http://sourceforge.net/projects/pydev/forums/forum/293649/topic/4480085>:
* tim-erwin writes:
"I downloaded the Python source release and simply dropped ... |
PyDev Eclipse Python interpreters Error: stdlib not found | 5,595,276 | 25 | 2011-04-08T12:50:08Z | 5,940,607 | 28 | 2011-05-09T17:54:17Z | [
"python",
"eclipse",
"pydev"
] | I have been trying to use Eclipse 3.6 as a Python editor.
I install the latest version of PyDev, and then try to set the Interpreter - Python field of the preferences, on my mac.
My python version is 2.6 and the path is "/usr/bin/python". When I enter this, and I select the items to add to the system PYTHONPATH I get ... | Had the same problem. Eclipse wouldn't find all the required path using the default installed python (2.6). I downloaded python 2.7, went through the install. My new "which python" path became:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python.
When I tried to set up the interpreter this time, specified th... |
PyDev Eclipse Python interpreters Error: stdlib not found | 5,595,276 | 25 | 2011-04-08T12:50:08Z | 13,389,249 | 7 | 2012-11-14T23:34:37Z | [
"python",
"eclipse",
"pydev"
] | I have been trying to use Eclipse 3.6 as a Python editor.
I install the latest version of PyDev, and then try to set the Interpreter - Python field of the preferences, on my mac.
My python version is 2.6 and the path is "/usr/bin/python". When I enter this, and I select the items to add to the system PYTHONPATH I get ... | When I upgraded to Mountain Lion (10.8.2) I had this problem. The solution was to install XCode 4.5.2, then in XCode > Preferences > Components, there is an option to install the Command Line Tools. I installed them and then I was able install Interpreter. |
What is the best way to compare floats for almost-equality in Python? | 5,595,425 | 83 | 2011-04-08T13:02:41Z | 5,595,453 | 33 | 2011-04-08T13:05:10Z | [
"python",
"floating-point"
] | It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
For example:
<http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>
What is the recommended way to deal with this in Python?
Surely there is a standard library function for this somewhere? | Is something as simple as the following not good enough?
```
return abs(f1 - f2) <= allowed_error
``` |
What is the best way to compare floats for almost-equality in Python? | 5,595,425 | 83 | 2011-04-08T13:02:41Z | 5,595,454 | 8 | 2011-04-08T13:05:12Z | [
"python",
"floating-point"
] | It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
For example:
<http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>
What is the recommended way to deal with this in Python?
Surely there is a standard library function for this somewhere? | Use Python's [`decimal`](http://docs.python.org/library/decimal.html) module, which provides the `Decimal` class.
From the comments:
> It is worth noting that if you're
> doing math-heavy work and you don't
> absolutely need the precision from
> decimal, this can really bog things
> down. Floats are way, way faster t... |
What is the best way to compare floats for almost-equality in Python? | 5,595,425 | 83 | 2011-04-08T13:02:41Z | 5,595,523 | 11 | 2011-04-08T13:10:16Z | [
"python",
"floating-point"
] | It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
For example:
<http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>
What is the recommended way to deal with this in Python?
Surely there is a standard library function for this somewhere? | I'm not aware of anything in the Python standard library (or elsewhere) that implements Dawson's `AlmostEqual2sComplement` function. If that's the sort of behaviour you want, you'll have to implement it yourself. (In which case, rather than using Dawson's clever bitwise hacks you'd probably do better to use more conven... |
What is the best way to compare floats for almost-equality in Python? | 5,595,425 | 83 | 2011-04-08T13:02:41Z | 16,925,316 | 13 | 2013-06-04T18:49:56Z | [
"python",
"floating-point"
] | It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
For example:
<http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>
What is the recommended way to deal with this in Python?
Surely there is a standard library function for this somewhere? | I would agree that Gareth's answer is probably most appropriate as a lightweight function/solution.
But I thought it would be helpful to note that if you are using numpy or are considering it, there is a packaged function for this.
```
numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
```
A little dis... |
What is the best way to compare floats for almost-equality in Python? | 5,595,425 | 83 | 2011-04-08T13:02:41Z | 33,024,979 | 54 | 2015-10-08T20:04:04Z | [
"python",
"floating-point"
] | It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.
For example:
<http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm>
What is the recommended way to deal with this in Python?
Surely there is a standard library function for this somewhere? | Python 3.5 adds the [`math.isclose` and `cmath.isclose` functions](https://docs.python.org/3/whatsnew/3.5.html#pep-485-a-function-for-testing-approximate-equality) as described in [PEP 485](http://www.python.org/dev/peps/pep-0485).
If you're using an earlier version of Python, the equivalent function is given in the [... |
Run ffmpeg without outputting configuration information? | 5,596,135 | 16 | 2011-04-08T13:54:04Z | 22,705,820 | 22 | 2014-03-28T06:35:36Z | [
"python",
"logging",
"ffmpeg",
"subprocess",
"stderr"
] | I'm invoking [`ffmpeg`](http://www.ffmpeg.org/) with [`subprocess.Popen`](http://docs.python.org/py3k/library/subprocess.html#subprocess.Popen), and trying to capture the [`stderr`](http://docs.python.org/py3k/library/subprocess.html#subprocess.Popen.stderr) output and write it to [`logging`](http://docs.python.org/py3... | This is now possible as of FFmpeg 2.2 with the [`-hide_banner`](https://ffmpeg.org/ffmpeg.html#Generic-options) option. See also the relevant [commit](https://github.com/FFmpeg/FFmpeg/commit/b4c89c90ffc723c38282fbf061bf65da67e011b2) and [ticket](https://trac.ffmpeg.org/ticket/3246). |
Python os.system without the output | 5,596,911 | 14 | 2011-04-08T14:55:26Z | 5,596,929 | 20 | 2011-04-08T14:56:50Z | [
"python",
"subprocess",
"os.system"
] | I'm running this:
```
os.system("/etc/init.d/apache2 restart")
```
It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:
`* Restarting web server apache2 ...`
`waiting [ OK ]`
However, I don't want it to actually output it in my app. How can... | You should use the `subprocess` module using which you can control the `stdout` and `stderr` in a flexible fashion. `os.system` is deprecated.
The `subprocess` module allows you to create an object which represents a running external process. You can read it from it's stdout/stderr, write to it's stdin, send it signal... |
Python os.system without the output | 5,596,911 | 14 | 2011-04-08T14:55:26Z | 5,597,008 | 15 | 2011-04-08T15:05:30Z | [
"python",
"subprocess",
"os.system"
] | I'm running this:
```
os.system("/etc/init.d/apache2 restart")
```
It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:
`* Restarting web server apache2 ...`
`waiting [ OK ]`
However, I don't want it to actually output it in my app. How can... | Depending on your OS (and that's why as Noufal said, you should use subprocess instead) you can try something like
```
os.system("/etc/init.d/apache restart > /dev/null")
```
or (to mute also the error)
```
os.system("/etc/init.d/apache restart > /dev/null 2>&1")
``` |
Python os.system without the output | 5,596,911 | 14 | 2011-04-08T14:55:26Z | 5,597,017 | 25 | 2011-04-08T15:06:24Z | [
"python",
"subprocess",
"os.system"
] | I'm running this:
```
os.system("/etc/init.d/apache2 restart")
```
It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:
`* Restarting web server apache2 ...`
`waiting [ OK ]`
However, I don't want it to actually output it in my app. How can... | Avoid `os.system()` by all means, and use subprocess instead:
```
with open(os.devnull, 'wb') as devnull:
subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT)
```
This is the `subprocess` equivalent of the `/etc/init.d/apache2 restart &> /dev/null`.
There is [`subpr... |
Django: When to customize save vs using post-save signal | 5,597,378 | 16 | 2011-04-08T15:33:27Z | 5,597,433 | 17 | 2011-04-08T15:38:14Z | [
"python",
"django",
"save",
"receiver"
] | I have a series of tests and cases in a database. Whenever a test is obsoleted, it gets end dated, and any sub-cases of that test should also be end dated. I see two ways to accomplish this:
1) Modify the save function to end date sub-cases.
2) Create a receiver which listens for Test models being saved, and then en... | I generally use this rule of thumb:
* If you have to modify data so that the save won't fail, then override `save()` (you don't really have another option). For example, in an app I'm working on, I have a model with a text field that has a list of choices. This interfaces with old code, and replaces an older model tha... |
Django: When to customize save vs using post-save signal | 5,597,378 | 16 | 2011-04-08T15:33:27Z | 5,597,456 | 7 | 2011-04-08T15:39:33Z | [
"python",
"django",
"save",
"receiver"
] | I have a series of tests and cases in a database. Whenever a test is obsoleted, it gets end dated, and any sub-cases of that test should also be end dated. I see two ways to accomplish this:
1) Modify the save function to end date sub-cases.
2) Create a receiver which listens for Test models being saved, and then en... | In my understanding, signals are a means for decoupling modules. Since your task seems to happen in only one module I'd customize save. |
I need larger image to get pulled from facebook when user signs up | 5,597,788 | 5 | 2011-04-08T16:04:48Z | 5,603,823 | 14 | 2011-04-09T08:30:00Z | [
"python",
"django",
"facebook",
"twitter"
] | When a user signs up to my site their facebook profile image automatically gets pulled and used as their profile image. The image is tiny so it looks pixelated. Is there any way to pull a larger version of the profile image? The same also happens for users who sign up using twitter.
Thanks. | You can use the different options on the graph api to get images of different sizes and shapes:
```
http://graph.facebook.com/{{ user.uid }}/picture?type=small
http://graph.facebook.com/{{ user.uid }}/picture?type=normal
http://graph.facebook.com/{{ user.uid }}/picture?type=large
http://graph.facebook.com/{{ user.uid ... |
Embed (create) an interactive python shell inside a python program | 5,597,836 | 37 | 2011-04-08T16:08:46Z | 5,597,918 | 40 | 2011-04-08T16:15:21Z | [
"python"
] | Is it possible to start an interactive python shell inside a python program?
I want to use such an interactive python shell (which is running *inside* my program's execution) to inspect some program-internal variables. | The [code](http://docs.python.org/library/code.html) module provides an interactive console:
```
import readline # optional, will allow Up/Down/History in the console
import code
vars = globals().copy()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()
``` |
Embed (create) an interactive python shell inside a python program | 5,597,836 | 37 | 2011-04-08T16:08:46Z | 16,717,949 | 9 | 2013-05-23T15:26:19Z | [
"python"
] | Is it possible to start an interactive python shell inside a python program?
I want to use such an interactive python shell (which is running *inside* my program's execution) to inspect some program-internal variables. | In ipython 0.13+ you need to do this:
```
from IPython import embed
embed()
``` |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 5,598,212 | 32 | 2011-04-08T16:42:02Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | Use `sys.stdout.write('Installing XXX... ')` and `sys.stdout.write('Done')`. In this way, you have to add the new line by hand with `"\n"` if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this. |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 5,598,220 | 9 | 2011-04-08T16:43:15Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | `sys.stdout.write` will print without return carriage
```
import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")
```
<http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines> |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 5,598,349 | 116 | 2011-04-08T16:56:35Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | You can use the `print` statement to do this without importing `sys`.
```
def install_xxx():
print("Installing XXX... "),
install_xxx()
print "[DONE]"
```
The comma on the end of the `print` line prevents `print` from issuing a new line (you should note that there will be an extra space at the end of the out... |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 15,410,817 | 57 | 2013-03-14T13:35:20Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | You can simply use this:
```
print 'something',
...
print ' else',
```
and the output will be
```
something else
```
no need to overkill by `import sys`. Pay attention to comma symbol at the end. |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 17,794,672 | 10 | 2013-07-22T18:23:47Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:
```
def print_no_newline(string):
import sys
sys.stdout.write(string)
sys.stdout.flush()
```
To test it:
```
import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print... |
Python print on same line | 5,598,181 | 86 | 2011-04-08T16:38:58Z | 22,757,416 | 17 | 2014-03-31T08:57:01Z | [
"python",
"printing"
] | I want to run a script, which basicly shows things like:
```
Installing XXX... [DONE]
```
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the... | **CORRECT ANSWER!** You must use backspace '**\r**' or ('**\x08**') char to go back on previous position in console output
Python 3:
```
import time
import sys
def backspace(n):
# print((b'\x08' * n).decode(), end='') # use \x08 char to go back
print('\r' * n, end='') # use '\r' to go back
... |
Regular expression group capture with multiple matches | 5,598,340 | 7 | 2011-04-08T16:55:55Z | 5,598,482 | 12 | 2011-04-08T17:10:54Z | [
"python",
"regex"
] | Quick regular expression question.
I'm trying to capture multiple instances of a capture group in python (don't think it's python specific), but the subsequent captures seems to overwrite the previous.
In this over-simplified example, I'm essentially trying to split a string:
```
x = 'abcdef'
r = re.compile('(\w){6... | You can't use groups for this, I'm afraid. Each group can match only once, I believe all regexes work this way. A possible solution is to try to use findall() or similar.
```
r=re.compile(r'\w')
r.findall(x)
# 'a', 'b', 'c', 'd', 'e', 'f'
``` |
Can I remove script tags with BeautifulSoup? | 5,598,524 | 40 | 2011-04-08T17:14:32Z | 5,598,678 | 79 | 2011-04-08T17:31:11Z | [
"python",
"html",
"beautifulsoup"
] | Can script tags and all of their contents be removed from HTML with BeautifulSoup, or do I have to use Regular Expressions or something else? | ```
>>> soup = BeautifulSoup('<script>a</script>baba<script>b</script>')
>>> [s.extract() for s in soup('script')]
>>> soup
baba
``` |
Can I remove script tags with BeautifulSoup? | 5,598,524 | 40 | 2011-04-08T17:14:32Z | 5,598,705 | 8 | 2011-04-08T17:33:44Z | [
"python",
"html",
"beautifulsoup"
] | Can script tags and all of their contents be removed from HTML with BeautifulSoup, or do I have to use Regular Expressions or something else? | As stated in the ([official documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html)) you can use the `extract` method to remove all the subtree that matches the search.
```
import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x ... |
Python: Pass a generic dictionary as a command line arguments | 5,599,022 | 10 | 2011-04-08T18:04:17Z | 5,599,114 | 12 | 2011-04-08T18:12:58Z | [
"python",
"command-line-arguments"
] | I have a script that needs to take in the name of a file and a set of key=value pairs. The set of key=value pairs is not defined. They are dependent on the file that was passed in.
eg:
```
Script.py file1 bob=1 sue=2 ben=3 # file 1 needs bob, sue, and ben
Script.py file2 mel=1 gorge=3 steve=3 # file 2 needs mel, go... | That should be fairly easy to parse yourself. Use of the helper libraries would be complicated by not knowing the keys in advance. The filename is in sys.argv[1]. You can build the dictionary with a list of strings split with the '=' character as a delimiter.
```
import sys
filename = sys.argv[1]
args = dict([arg.spli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.