title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python function handle ala Matlab | 5,743,291 | 7 | 2011-04-21T11:12:39Z | 5,743,325 | 14 | 2011-04-21T11:16:58Z | [
"python",
"matlab"
] | In MATLAB it is possible to create [`function handles`](http://www.mathworks.co.uk/help/techdoc/ref/function_handle.html) with something like
```
myfun=@(arglist)body
```
This way you can create functions on the go without having to create M-files.
Is there an equivalent way in Python to declare functions and variab... | Python's lambda functions are somewhat similar:
```
In [1]: fn = lambda x: x**2 + 3*x - 4
In [2]: fn(3)
Out[2]: 14
```
However, you can achieve similar effects by simply defining `fn()` as a function:
```
In [1]: def fn(x):
...: return x**2 + 3*x - 4
...:
In [2]: fn(4)
Out[2]: 24
```
"Normal" (as opposed... |
Python function handle ala Matlab | 5,743,291 | 7 | 2011-04-21T11:12:39Z | 10,941,428 | 8 | 2012-06-07T23:53:56Z | [
"python",
"matlab"
] | In MATLAB it is possible to create [`function handles`](http://www.mathworks.co.uk/help/techdoc/ref/function_handle.html) with something like
```
myfun=@(arglist)body
```
This way you can create functions on the go without having to create M-files.
Is there an equivalent way in Python to declare functions and variab... | This is not quite the full answer. In matlab, one can make a file called funct.m:
```
function funct(a,b)
disp(a*b)
end
```
At the command line:
```
>> funct(2,3)
6
```
Then, one can create a function handle such as:
```
>> myfunct = @(b)funct(10,b))
```
Then one can do:
```
>> myfunct(3)
30
``... |
Passing data into django forms | 5,744,327 | 3 | 2011-04-21T12:49:40Z | 5,744,438 | 9 | 2011-04-21T12:59:57Z | [
"python",
"django"
] | ```
class Test(forms.Form):
def set_choices(self, choices):
self.choices = choices
def get_choices(self):
return self.choices
options = forms.ChoiceField(choices=get_choices())
f = Test()
f.set_choices(...)
```
Why isn't this possible?
How else can I achieve the goal of passing data ... | This is a basic Python issue. You need to think about the order these commands are executed in, and their scope.
First, you define a form class called Test. That class has three attributes: a `set_choices` method, a `get_choices` method, and an `options` field. These definitions are evaluated when the class itself is ... |
Getting Host field from HTTP request in BaseHTTPRequestHandler | 5,744,511 | 4 | 2011-04-21T13:05:47Z | 5,744,845 | 10 | 2011-04-21T13:35:33Z | [
"python",
"basehttpserver"
] | I'm writing a script using BaseHTTPRequestHandler class. And in `do_GET(self)` method I need to get the content of the `Host` field from the HTTP request. I can do it by regexping the `str(self.headers)` like proposed here: [Determine site domain in BaseHTTPServer](http://stackoverflow.com/questions/2958408/determine-s... | The attribute `self.headers` is a dictionary, so you can do this:
```
def do_GET(self):
host = self.headers.get('Host')
``` |
Taking the results of a bash command and using it in python | 5,744,980 | 4 | 2011-04-21T13:48:16Z | 5,745,133 | 8 | 2011-04-21T14:00:28Z | [
"python",
"bash",
"operating-system",
"command"
] | I am trying to write a code in python that will take some information from top and put it into a file.
I want to just write the name of the application and generate the file. The problem i am having is that i can't get the output of the pidof command so i can use it in python. My code looks like this :
```
import os
... | First up, the use of `input()` is discouraged as it expects the user to type in valid Python expressions. Use `raw_input()` instead:
```
app = raw_input('Name of the application: ')
```
Next up, the return value from `system('pidof')` isn't the PID, it's the exit code from the `pidof` command, i.e. zero on success, n... |
Django create custom UserCreationForm | 5,745,197 | 11 | 2011-04-21T14:05:37Z | 5,745,488 | 13 | 2011-04-21T14:29:00Z | [
"python",
"django",
"django-authentication"
] | I enabled the user auth module in Django, but when I use `UserCreationForm` he ask me only username and the two password/password confirmation fields. I want also email and fullname fields, and set to required fields.
I've done this:
```
from django.contrib.auth.forms import UserCreationForm
from django import forms
... | There is no such field called `fullname` in the User model.
If you wish to store the name using the original model then you have to store it separately as a first name and last name.
**Edit:** If you want just one field in the form and still use the original User model use the following:
You can do something like th... |
Fast way to remove a few items from a list/queue | 5,745,881 | 10 | 2011-04-21T14:59:46Z | 5,746,071 | 13 | 2011-04-21T15:12:35Z | [
"python",
"list",
"queue",
"time-complexity",
"optimization"
] | This is a follow up to a similar [question](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python/1207461#comment-6561137) which asked the best way to write
```
for item in somelist:
if determine(item):
code_to_remove_item
```
and it seems the consensus was on some... | The list comprehension is the asymptotically optimal solution:
```
somelist = [x for x in somelist if not determine(x)]
```
It only makes one pass over the list, so runs in O(n) time. Since you need to call determine() on each object, any algorithm will require at least O(n) operations. The list comprehension does ha... |
calling python script from ajax got: malformed header from script. Bad header | 5,746,745 | 6 | 2011-04-21T16:04:58Z | 5,747,055 | 17 | 2011-04-21T16:32:40Z | [
"python",
"jquery"
] | I am writting a application using jquery(ajax) and python. When I send the request using ajax to call a php script, everything works. But when I tried to call a python script, I got this error.
malformed header from script. Bad header=AAAAAA
I am not sure what I am missing. The only difference is the type of script a... | PHP was designed for web programming so it automatically attaches `Content-type` to HTTP headers but Python doesn't. Prepend this to `main()`:
```
print "Content-Type: text/html\n"
``` |
BeautifulSoup findall with class attribute- unicode encode error | 5,746,888 | 6 | 2011-04-21T16:18:02Z | 5,746,959 | 7 | 2011-04-21T16:24:47Z | [
"python",
"beautifulsoup"
] | I am using BeautifulSoup to extract news stories(just the titles) from [Hacker News](http://news.ycombinator.com) and have this much up till now-
```
import urllib2
from BeautifulSoup import BeautifulSoup
HN_url = "http://news.ycombinator.com"
def get_page():
page_html = urllib2.urlopen(HN_url)
return page_... | Because BeautifulSoup works internally with unicode strings. Printing unicode strings to the console will cause Python to try the conversion of unicode to the default encoding of Python which is usually ascii. This will in general fail for non-ascii web-site. You may learn the basics about Python and Unicode by googlin... |
Django form multiple choice | 5,747,188 | 11 | 2011-04-21T16:46:41Z | 5,747,533 | 10 | 2011-04-21T17:18:50Z | [
"python",
"django"
] | I am a newbie in Django and I would really appreciate it if you could offer me some guidance. I am trying to create a form that allows a user to tick one or more options. I understood that I must use MultipleChoiceField field with a CheckboxSelectMultiple widget but the Django documentation doesn't offer an example on ... | hope this helps :D
```
from django import forms
class Test(forms.Form):
OPTIONS = (
("a", "A"),
("b", "B"),
)
name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=OPTIONS)
``` |
Django form multiple choice | 5,747,188 | 11 | 2011-04-21T16:46:41Z | 5,747,729 | 33 | 2011-04-21T17:38:49Z | [
"python",
"django"
] | I am a newbie in Django and I would really appreciate it if you could offer me some guidance. I am trying to create a form that allows a user to tick one or more options. I understood that I must use MultipleChoiceField field with a CheckboxSelectMultiple widget but the Django documentation doesn't offer an example on ... | forms.py
```
class SomeForm(forms.Form):
CHOICES = (('a','a'),
('b','b'),
('c','c'),
('d','d'),)
picked = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple())
```
views.py
```
def some_view(request):
if request.method == 'POST':
... |
Python package structure | 5,747,598 | 13 | 2011-04-21T17:24:06Z | 5,747,654 | 18 | 2011-04-21T17:30:28Z | [
"python",
"packages"
] | I have a Python package with several subpackages.
```
myproject/
__init__.py
models/
__init__.py
...
controllers/
__init__.py
..
scripts/
__init__.py
myscript.py
```
Within myproject.scripts.myscript, how can I access myproject.models? I've tried
```
from myproject import models # No ... | This is the correct version:
```
from myproject import models
```
If it fails with `ImportError: No module named foo` it is because you haven't set `PYTHONPATH` to include the directory which contains `myproject/`.
I'm afraid other people will suggest tricks to let you avoid setting `PYTHONPATH`. I urge you to disre... |
What is the standard Python module for SQL queries? | 5,748,610 | 5 | 2011-04-21T19:07:08Z | 5,748,652 | 7 | 2011-04-21T19:10:36Z | [
"python",
"sql",
"oracle"
] | I am wondering what is the standard Python module for SQL queries?
I am writing queries for an Oracle database in particular. I am looking to write quick, easy, and direct queries, in the context of both scripts and small programs. | Each SQL database has their own module which implements [DB-API 2.0](http://www.python.org/dev/peps/pep-0249/). Oracle uses [cx\_Oracle](http://cx-oracle.sourceforge.net/). |
Should I use numpy (or pylab) as a python environment by using `from numpy import *`? | 5,748,895 | 11 | 2011-04-21T19:32:58Z | 5,748,987 | 18 | 2011-04-21T19:41:14Z | [
"numpy",
"coding-style",
"python"
] | I use pylab (more specifically numpy) in all of my python programsÂ. The exceptions are very rare, if any. So far, I have taken the habit of importing numpy in the following way:
```
from numpy import *
```
This has the advantage of making it look like numpy was part of python from the beginning. Is there something ... | 1. `from module import *` should always
be avoided in scripts because it
makes it harder to trace where
functions and values come from. The problem becomes more apparent when you use more than one import statement of this form. For example:
```
from numpy import *
from numpy.random import *
```
2.... |
Should I use numpy (or pylab) as a python environment by using `from numpy import *`? | 5,748,895 | 11 | 2011-04-21T19:32:58Z | 5,749,505 | 11 | 2011-04-21T20:35:43Z | [
"numpy",
"coding-style",
"python"
] | I use pylab (more specifically numpy) in all of my python programsÂ. The exceptions are very rare, if any. So far, I have taken the habit of importing numpy in the following way:
```
from numpy import *
```
This has the advantage of making it look like numpy was part of python from the beginning. Is there something ... | Just to elaborate on what other people have said, numpy is an *especially* bad module to use `import *` with.
`pylab` is meant for interactive use, and it's fine there. No one wants to type `pylab.zeros` over and over in a shell when they could just type `zeros`. However, as soon as you start writing code, everything ... |
Pythonic way to resolve circular import statements? | 5,748,946 | 15 | 2011-04-21T19:37:41Z | 5,749,020 | 35 | 2011-04-21T19:44:36Z | [
"python",
"pageobjects"
] | I just inherited some code which makes me uneasy: There is a testing library, full of classes corresponding to webpages on our site, and each webpage class has methods to automate the functionality on that page.
There are methods to click the link between pages, which returns the class of the linked page. Here's a sim... | Resolving these constructs usually involves techniques like [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection).
It is, however, rather simple to fix this error:
In calendarLib.py:
```
import homePageLib
class CalendarPage(object):
def clickHomePageLink(self):
[...]
return ... |
How can I split and parse a string in Python? | 5,749,195 | 56 | 2011-04-21T20:02:01Z | 5,749,208 | 71 | 2011-04-21T20:03:25Z | [
"python",
"string",
"parsing",
"split"
] | I am trying to split this string in python: `2.7.0_bf4fda703454`
I want to split that string on the underscore `_` so that I can use the value on the left side. | `"2.7.0_bf4fda703454".split("_")` gives a list of strings:
```
In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']
```
This splits the string at *every* underscore. If you want it to stop after the first split, use `"2.7.0_bf4fda703454".split("_", 1)`.
If you know for a fact that the string con... |
How can I split and parse a string in Python? | 5,749,195 | 56 | 2011-04-21T20:02:01Z | 5,749,278 | 16 | 2011-04-21T20:09:39Z | [
"python",
"string",
"parsing",
"split"
] | I am trying to split this string in python: `2.7.0_bf4fda703454`
I want to split that string on the underscore `_` so that I can use the value on the left side. | If it's always going to be an even LHS/RHS split, you can also use the `partition` method that's built into strings. It returns a 3-tuple as `(LHS, separator, RHS)` if the separator is found, and `(original_string, '', '')` if the separator wasn't present:
```
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf... |
How can I split and parse a string in Python? | 5,749,195 | 56 | 2011-04-21T20:02:01Z | 20,985,070 | 35 | 2014-01-08T00:54:13Z | [
"python",
"string",
"parsing",
"split"
] | I am trying to split this string in python: `2.7.0_bf4fda703454`
I want to split that string on the underscore `_` so that I can use the value on the left side. | ## Python string parsing walkthrough
**Split a string on space, get a list, show its type, print it out:**
```
el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"
>>> mylist = mystring.split(" ")
>>> print type(mylist)
<type 'list'>
>>> print mylist
['What', 'does', 'the', 'fox', 'say?']
```
**If you ... |
PIL Check pixel that it's on with eval function | 5,749,794 | 2 | 2011-04-21T21:06:09Z | 5,750,066 | 8 | 2011-04-21T21:39:03Z | [
"python",
"transparency",
"python-imaging-library",
"rgb",
"pixel"
] | Is there any way using the `eval` function in PIL to run through all pixels, while checking to see what each value is? The program runs through an image to see if each pixel is a certain rgb, and if it is, then it will turn that pixel into transparency. the `eval` function in PIL seems it would do the job, but can my f... | **Updated**: Ahh, I see what you want to do. Here is an example using only PIL. It converts all white pixels to red with 50% alpha:
```
import Image
img = Image.open('stack.png').convert('RGBA')
width, _ = img.size
for i, px in enumerate(img.getdata()):
if px[:3] == (255, 255, 255):
y = i / width
... |
pydev does not recognize django installation | 5,749,871 | 5 | 2011-04-21T21:16:46Z | 5,760,414 | 9 | 2011-04-22T21:47:38Z | [
"python",
"django",
"pydev"
] | I have python 2.6.1 installed with django 1.3 and PyDev 2.0. I am able to import django and print the version from commandline. However, when I try to create a Django project with pydev or even import django I get an error. When creating the django project, I get "Django not found." error.
I have tried removing and ad... | Probably the PYTHONPATH configured in your interpreter is not correct...
I.e.: if you have a structure with
```
/my/path/django
/my/path/django/__init__.py
```
you have to make sure that
```
/my/path
```
is added to the PYTHONPATH (and /my/path/django is NOT)
Another thing to note is that right after installing D... |
Invalid Django TIME_ZONE | 5,750,150 | 6 | 2011-04-21T21:49:28Z | 5,750,267 | 21 | 2011-04-21T22:02:49Z | [
"python",
"django"
] | Doing a recent build, I ran Django's syncdb, and I'm getting the error:
```
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/management/__init__.py", line 438, in execute_manager
utili... | According to the error message:
> **ValueError: Incorrect timezone
> setting: America/New\_York EST5EDT
> SystemV/EST5EDT US/Eastern**
it seems that `TIME_ZONE`, in `settings.py`, is equal to : `America/New_York EST5EDT SystemV/EST5EDT US/Eastern`
You must write only `America/New_York`.
If it's not the case, check ... |
Render HTML in django template (not unicode but ASCII) | 5,750,383 | 5 | 2011-04-21T22:19:14Z | 5,750,527 | 8 | 2011-04-21T22:38:54Z | [
"python",
"django",
"templates"
] | I understand that this is a little perverse, but I have a legacy database with some entries as formatted html. I'd like to just push this into my django templates as ASCII and let the browser display it.
Django kindly converts my fields to unicode, and so the browser displays the entire text `<p> </p>` etc. intact.
I... | From <http://docs.djangoproject.com/en/dev/ref/templates/builtins/> what you want is:
```
{{ obj.text|safe }}
``` |
Python: Iterating through a dictionary gives me "int object not iterable" | 5,750,664 | 20 | 2011-04-21T22:58:13Z | 5,750,699 | 30 | 2011-04-21T23:01:58Z | [
"python",
"dictionary",
"loops"
] | Here's my function:
```
def printSubnetCountList(countList):
print type(countList)
for k, v in countList:
if value:
print "Subnet %d: %d" % key, value
```
Here's the output when the function is called with the dictionary passed to it:
```
<type 'dict'>
Traceback (most recent call last):
... | Try this
```
for k in countList:
v= countList[k]
```
Or this
```
for k, v in countList.items():
```
Read this, please: <http://docs.python.org/library/stdtypes.html#mapping-types-dict> |
Python: Iterating through a dictionary gives me "int object not iterable" | 5,750,664 | 20 | 2011-04-21T22:58:13Z | 5,750,736 | 9 | 2011-04-21T23:06:53Z | [
"python",
"dictionary",
"loops"
] | Here's my function:
```
def printSubnetCountList(countList):
print type(countList)
for k, v in countList:
if value:
print "Subnet %d: %d" % key, value
```
Here's the output when the function is called with the dictionary passed to it:
```
<type 'dict'>
Traceback (most recent call last):
... | The `for k, v` syntax is a short form of the tuple unpacking notation, and could be written as `for (k, v)`. This means that every element of the iterated collection is expected to be a sequence consisting of exactly two elements. But iteration on dictionaries yields only keys, not values.
The solution is it use eithe... |
How to get current import paths in Python? | 5,751,292 | 19 | 2011-04-22T00:49:56Z | 5,751,327 | 28 | 2011-04-22T00:55:11Z | [
"python",
"import",
"importerror"
] | I get an `ImportError` exception somewhere in the code, but the same module can be imported safely at startup of the application. I'm curious to see which paths Python looks for modules to import, so that I can trace why this problem occurs. I found this:
`print sys.path`
Is this the list of ALL paths that system loo... | The path locations that python checks by default can be inspected by checking [`sys.path`](http://docs.python.org/library/sys.html?highlight=sys.path#sys.path).
```
import sys
print sys.path
``` |
configuration fail nginx setting for tornadoweb, unknown directive "user" | 5,751,455 | 8 | 2011-04-22T01:21:39Z | 7,485,230 | 16 | 2011-09-20T12:34:15Z | [
"python",
"nginx"
] | I've got this error in nginx version 1.0.0
```
nginx: [emerg] unknown directive "user" in /etc/nginx/sites-enabled/
tornado:1
```
if I remove user www-data the worker processes got error
```
nginx: [emerg] unknown directive "worker_processes" in /etc/nginx/
sites-enabled/tornado:1
```
I've search on google but stil... | Probably a bit overdue, but if anyone stumbles on this here's a hint:
Probably config collision, check in /etc/nginx for a .conf file with same directive. |
modify text file | 5,752,286 | 2 | 2011-04-22T04:28:12Z | 5,752,356 | 8 | 2011-04-22T04:44:36Z | [
"python",
"regex",
"perl"
] | I need to modify all files that has a ".txt" extension within a directory in the following way:
remove all text lines beginning with the line that starts with "xxx" and the line that ends with "xxx", inclusive.
I know how to do this in Java or C++, but can someone show me a simple script that can get this done?
Than... | I assume that you want to lose start and end, and those words appear by themselves on the lines you want lost.
```
perl -ni.bak -e 'print unless /^start$/../^end$/' *.txt
```
Note that I made a backup of the modified files so that you can inspect the change and fix it if you want. |
Soap call in Python | 5,752,923 | 2 | 2011-04-22T06:38:55Z | 5,760,667 | 10 | 2011-04-22T22:27:19Z | [
"python",
"soap",
"soappy"
] | I tried to call a soap service. My call is success but its returns empty value.Below i attached my soap request and response schema. Its takes 1d array as input and return that array.
> Request Schema
```
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns... | Here's a working version that uses [`suds` client](https://fedorahosted.org/suds/):
```
#!/usr/bin/env python
from suds.xsd.doctor import Import, ImportDoctor
from suds.client import Client
# enable logging to see transmitted XML
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').... |
Is it Pythonic to use list comprehensions for just side effects? | 5,753,597 | 54 | 2011-04-22T08:22:01Z | 5,753,614 | 44 | 2011-04-22T08:24:33Z | [
"python",
"list-comprehension"
] | Think about a function that I'm calling for it's side effects, not return values(like printing to screen, updating gui, printing to a file, etc.).
```
def fun_with_side_effects(x):
...side effects...
return y
```
Now, is it *Pythonic* to use list comprehensions to call this func:
```
[fun_with_side_effects(x... | It is very anti-Pythonic to do so, and any seasoned Pythonista will give you hell over it. The intermediate list is thrown away after it is created, and it could potentially be very, very large, and therefore expensive to create. |
Is it Pythonic to use list comprehensions for just side effects? | 5,753,597 | 54 | 2011-04-22T08:22:01Z | 5,753,635 | 14 | 2011-04-22T08:27:27Z | [
"python",
"list-comprehension"
] | Think about a function that I'm calling for it's side effects, not return values(like printing to screen, updating gui, printing to a file, etc.).
```
def fun_with_side_effects(x):
...side effects...
return y
```
Now, is it *Pythonic* to use list comprehensions to call this func:
```
[fun_with_side_effects(x... | List comprehensions are for creating lists. And unless you are actually creating a list, you should *not* use list comprehensions.
So I would got for the second option, just iterating over the list and then call the function when the conditions apply. |
Is it Pythonic to use list comprehensions for just side effects? | 5,753,597 | 54 | 2011-04-22T08:22:01Z | 5,753,656 | 7 | 2011-04-22T08:30:02Z | [
"python",
"list-comprehension"
] | Think about a function that I'm calling for it's side effects, not return values(like printing to screen, updating gui, printing to a file, etc.).
```
def fun_with_side_effects(x):
...side effects...
return y
```
Now, is it *Pythonic* to use list comprehensions to call this func:
```
[fun_with_side_effects(x... | Second is better.
Think of the person who would need to understand your code. You can get bad karma easily with the first :)
You could go middle between the two by using filter(). Consider the example:
```
y=[1,2,3,4,5,6]
def func(x):
print "call with %r"%x
for x in filter(lambda x: x>3, y):
func(x)
``` |
Is it Pythonic to use list comprehensions for just side effects? | 5,753,597 | 54 | 2011-04-22T08:22:01Z | 5,753,722 | 18 | 2011-04-22T08:38:35Z | [
"python",
"list-comprehension"
] | Think about a function that I'm calling for it's side effects, not return values(like printing to screen, updating gui, printing to a file, etc.).
```
def fun_with_side_effects(x):
...side effects...
return y
```
Now, is it *Pythonic* to use list comprehensions to call this func:
```
[fun_with_side_effects(x... | You shouldn't use a *list* comprehension, because as people have said that will build a large temporary list that you don't need. The following two methods are equivalent:
```
consume(side_effects(x) for x in xs)
for x in xs:
side_effects(x)
```
with the definition of `consume` from the `itertools` man page:
``... |
performing set operations on custom classes in python | 5,754,440 | 14 | 2011-04-22T10:16:40Z | 5,754,539 | 16 | 2011-04-22T10:32:01Z | [
"python",
"set"
] | I'd like to use Python's built-in set class with a custom class that I've created. If I want
to create sets containing instances of my custom class, what functions do I need to implement so that I can perform tests, like set\_a - set\_b? | It will work out of the box, however, there might be cases, when it makes sense to overload [`__eq__`](https://docs.python.org/3.4/reference/datamodel.html#object.__eq__), [`__ne__`](https://docs.python.org/3.4/reference/datamodel.html#object.__ne__) and [`__hash__`](https://docs.python.org/3.4/reference/datamodel.html... |
Sum one number to every element in a list (or array) in Python | 5,754,571 | 9 | 2011-04-22T10:36:23Z | 5,754,581 | 15 | 2011-04-22T10:37:56Z | [
"python",
"list",
"sum"
] | Here I go with my basic questions again, but please bear with me.
In Matlab, is fairly simple to add a number to elements in a list:
```
a = [1,1,1,1,1]
b = a + 1
```
`b` then is `[2,2,2,2,2]`
In python this doesn't seem to work, at least on a list.
Is there a simple fast way to add up a single number to the entir... | using List Comprehension:
```
>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>>
```
which roughly translates to using a for loop:
```
>>> newL = []
>>> for x in L:
... newL+=[x+1]
...
>>> newL
[2, 2, 2, 2, 2]
```
or using map:
```
>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>>
``` |
Sum one number to every element in a list (or array) in Python | 5,754,571 | 9 | 2011-04-22T10:36:23Z | 5,754,606 | 22 | 2011-04-22T10:42:14Z | [
"python",
"list",
"sum"
] | Here I go with my basic questions again, but please bear with me.
In Matlab, is fairly simple to add a number to elements in a list:
```
a = [1,1,1,1,1]
b = a + 1
```
`b` then is `[2,2,2,2,2]`
In python this doesn't seem to work, at least on a list.
Is there a simple fast way to add up a single number to the entir... | if you want to operate with list of numbers it is better to use arrays:
```
import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2
```
gives
```
[3, 3, 3, 3, 3]
``` |
Why to use __setattr__ in python? | 5,755,023 | 14 | 2011-04-22T11:37:49Z | 5,755,087 | 26 | 2011-04-22T11:47:19Z | [
"python",
"setter"
] | I don't know for why using `__setattr__` instead simple referencing like `x.a=1`.
I understand this example:
```
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
x=Rectangle()
x.width=20
x.__setattr__('height',30)
setattr(x,'width',99)
```
but don't get why using code dependi... | You don't call it yourself. Period. If you need to use a string because you don't know the name beforehand (*very* bad idea in 99% of all cases where one might think they need this, nearly always a dict or list is a better/saner choice), you use the built-in `setattr` function.
However, it is called for you - when you... |
Why to use __setattr__ in python? | 5,755,023 | 14 | 2011-04-22T11:37:49Z | 5,755,099 | 9 | 2011-04-22T11:48:58Z | [
"python",
"setter"
] | I don't know for why using `__setattr__` instead simple referencing like `x.a=1`.
I understand this example:
```
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
x=Rectangle()
x.width=20
x.__setattr__('height',30)
setattr(x,'width',99)
```
but don't get why using code dependi... | `__setattr__` is a class method that is called by `setattr` builtin method. That is, if `__setattr__` is defined in given class. Most often you do not declare your own version of `__setattr__` so I assume you are asking of what use is the `setattr` method.
Suppose you have a var with the name of the attribute you want... |
Where to find a complete Tkinter reference? | 5,755,174 | 11 | 2011-04-22T12:01:39Z | 5,755,290 | 7 | 2011-04-22T12:14:25Z | [
"python",
"tkinter"
] | Can somebody point me to a **complete** online reference for Python's *tkinter* module? Of course I've tried to find one by myself, but for some reason I can't, maybe I'm using the wrong keywords?
I'm **not** looking for a tutorial, instead I'd like to have a reference for all the available classes and attributes.
Fo... | I found this reference useful - not always perfect, but usually useful: <http://infohost.nmt.edu/tcc/help/pubs/tkinter/index.html>
Also contains explanations of layout management and the event model. Since it's for Python 2.5, the code examples won't run out of the box on Python 3, but the method names shouldn't have ... |
Using assert within methods - Python | 5,755,485 | 3 | 2011-04-22T12:40:25Z | 5,755,517 | 7 | 2011-04-22T12:44:07Z | [
"python",
"exception-handling",
"assert"
] | is it bad practice to use asserts within methods?
e.g.
```
def add(x, y):
assert isinstance(x, int) and isinstance(y, int)
return x + y
```
---
Any ideas? | Not at all.
In your sample, provided you have documented that `add` expects integers, `assert`ing this constraint at the beginning of the method is actually great practice.
Just imagine the other choices you have and how bad they are:
* don't verify your arguments. This means, the method will fail later with a stran... |
Creating a raw HTTP request with sockets | 5,755,507 | 9 | 2011-04-22T12:42:52Z | 5,755,612 | 10 | 2011-04-22T12:55:05Z | [
"python",
"http",
"sockets"
] | I would like to be able to construct a raw HTTP request and send it with a socket. Obviously, you would like me to use something like urllib and urllib2 but I do not want to use that.
It would have to look something like this:
```
import socket
tcpsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsoc.bind((... | Most of what you need to know is in the HTTP/1.1 spec, which you should definitely study if you want to roll your own HTTP implementation: <http://www.w3.org/Protocols/rfc2616/rfc2616.html> |
Creating a raw HTTP request with sockets | 5,755,507 | 9 | 2011-04-22T12:42:52Z | 23,050,458 | 12 | 2014-04-14T01:14:19Z | [
"python",
"http",
"sockets"
] | I would like to be able to construct a raw HTTP request and send it with a socket. Obviously, you would like me to use something like urllib and urllib2 but I do not want to use that.
It would have to look something like this:
```
import socket
tcpsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsoc.bind((... | ```
#!/usr/bin/python
import socket
import urlparse
import re
import os
socket.setdefaulttimeout = 0.50
os.environ['no_proxy'] = '127.0.0.1,localhost'
linkRegex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')
CRLF = "\r\n\r\n"
def GET(url):
url = urlparse.urlparse(url)
path = url.path
if path == "":
... |
How to build many-to-many relations using SQLAlchemy: a good example | 5,756,559 | 7 | 2011-04-22T14:42:30Z | 23,424,290 | 7 | 2014-05-02T08:54:03Z | [
"python",
"many-to-many",
"sqlalchemy",
"associations"
] | I have read the SQLAlchemy documentation and tutorial about building many-to-many relation but I could not figure out how to do it properly when the association table contains more than the 2 foreign keys.
I have a table of items and every item has many details. Details can be the same on many items, so there is a man... | From the comments I see you've found the answer. But the SQLAlchemy documentation is quite overwhelming for a 'new user' and I was struggling with the same question. So for future reference:
```
ItemDetail = Table('ItemDetail',
Column('id', Integer, primary_key=True),
Column('itemId', Integer, ForeignKey('Item... |
Adding elements to a tuple when I know I shouldn't be able to | 5,756,768 | 5 | 2011-04-22T15:08:24Z | 5,756,824 | 12 | 2011-04-22T15:13:12Z | [
"python",
"tuples"
] | [Dive Into Python](http://www.diveintopython.net/native_data_types/tuples.html "Dive Into Python") is one of many sources that says:
> You can't add elements to a tuple.
But it looks as if I was allowed to do just that. My code:
```
from string import find
def subStringMatchExact(target, key):
t = (99,)
loc... | You are concatenating 2 tuples in a new one.
You are not modifying the original.
```
> a = (1,)
> b = a
> b == a
True
> a += (2,)
> b == a
False
``` |
Decimal zero padding | 5,757,094 | 3 | 2011-04-22T15:40:56Z | 5,757,190 | 7 | 2011-04-22T15:48:58Z | [
"python"
] | I need to output decimal numbers in a price format,
i.e.
10 = 10.00
11.1 = 11.10
How can I achieve this using decimal.Decimal class ?
```
pad_zero(Decimal('10.0'))
>>>Decimal('10.00')
```
\**EDIT:*\*format method does not fit my need because I need to pass it on as decimal, I understand though, that i can convert ... | try this :
```
Decimal('10.0').quantize(Decimal('1.00'))
``` |
condition of tuple of integers | 5,757,491 | 4 | 2011-04-22T16:18:17Z | 5,757,517 | 15 | 2011-04-22T16:20:54Z | [
"python",
"tuples",
"condition"
] | how do I write a concise/neat boolean condition to test if all the integers in a tuple are in a given range? Something like
```
0 < (1,2,3) < 50
```
would be perfect - of course that doesn't work because it uses lexicographical ordering, so also
```
0 < (1,2,-3) < 50
```
evaluates to True. Instead I would want it t... | ```
all(0 < n < 50 for n in thetuple)
```
should be a relatively concise solution. it may not be the shortest piece of code, but it is almost self-documenting. |
How can I get a specific field of a csv file? | 5,757,743 | 15 | 2011-04-22T16:45:46Z | 5,757,809 | 21 | 2011-04-22T16:52:19Z | [
"python",
"csv"
] | I need a way to get a specific item(field) of a CSV. Say I have a CSV with 100 rows and 2 columns (comma seperated). First column emails, second column passwords. For example I want to get the password of the email in row 38. So I need only the item from 2nd column row 38...
Say I have a csv file:
```
aaaaa@aaa.com,b... | ```
import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
text = row[1]
```
Following the comments to the SO question [here](http://stackoverflow.com/questions/4249185/using-python-to-append-csv-files/4250021#4250021), a best, more robust code would be:
```
import csv
with open(myfilepath, 'rb') as f:
... |
How can I get a specific field of a csv file? | 5,757,743 | 15 | 2011-04-22T16:45:46Z | 5,758,901 | 7 | 2011-04-22T18:52:32Z | [
"python",
"csv"
] | I need a way to get a specific item(field) of a CSV. Say I have a CSV with 100 rows and 2 columns (comma seperated). First column emails, second column passwords. For example I want to get the password of the email in row 38. So I need only the item from 2nd column row 38...
Say I have a csv file:
```
aaaaa@aaa.com,b... | ```
#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.
USAGE:
%prog csv_filename row_number column_number
"""
import csv
import sys
filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]
with open(filename, 'rb') as f:
rows = li... |
Python, __slots__, inheritance, and class variables ==> attribute is read-only bug | 5,757,924 | 12 | 2011-04-22T17:05:16Z | 5,758,040 | 14 | 2011-04-22T17:16:10Z | [
"python"
] | I have a big tree with hundreds of thousands of nodes, and I'm using `__slots__` to reduce the memory consumption. I just found a very strange bug and fixed it, but I don't understand the behavior that I saw.
Here's a simplified code sample:
```
class NodeBase(object):
__slots__ = ["name"]
def __init__(self, ... | A smaller example:
```
class C(object):
__slots__ = ('x',)
x = 0
C().x = 1
```
The [documentation on slots](http://docs.python.org/reference/datamodel.html#slots) states at one point:
> `__slots__` are implemented at the class level by creating descriptors (Implementing Descriptors) for each variable name. ... |
Is there an interactive graphing library for python | 5,759,878 | 44 | 2011-04-22T20:46:30Z | 5,759,954 | 7 | 2011-04-22T20:55:43Z | [
"python",
"graph",
"interactive"
] | I'm looking for an interactive graphing library for Python.
By "[graph](http://en.wikipedia.org/wiki/Graph_%28mathematics%29)", I meant a set of nodes connected by a set of vertices (not a plot of values over x-y axis, nor a grid of pixels).
By "interactive", I meant I can drag-and-drop the nodes around and I need to... | You should definitely look at the [igraph](http://igraph.sourceforge.net/) library if you haven't.
It's a powerful library that can handle large graphs and different layout styles. It can also be used for directed graphs and for interactive and non-interactive visualitzations in 2D and 3D according to the list of [fea... |
Is there an interactive graphing library for python | 5,759,878 | 44 | 2011-04-22T20:46:30Z | 5,818,458 | 21 | 2011-04-28T12:17:38Z | [
"python",
"graph",
"interactive"
] | I'm looking for an interactive graphing library for Python.
By "[graph](http://en.wikipedia.org/wiki/Graph_%28mathematics%29)", I meant a set of nodes connected by a set of vertices (not a plot of values over x-y axis, nor a grid of pixels).
By "interactive", I meant I can drag-and-drop the nodes around and I need to... | Looks like Nodebox might be what you want:
<http://nodebox.net/code/index.php/Graph> **Mac OSX**
<http://www.cityinabottle.org/nodebox/> **Windows** (using OpenGL)

> The graph object has functionality for mouse interaction as well, bundled
> in the `graph.ev... |
Python range() builtin function, erm... malfunctioning with Django | 5,760,378 | 3 | 2011-04-22T21:44:22Z | 5,760,432 | 9 | 2011-04-22T21:50:02Z | [
"python",
"django",
"date-range",
"builtin"
] | What, if anything, is wrong with this line of python code:
```
daterange = [begin + timedelta(n) for n in range((end - begin).days)]
```
Where `begin` and `end` are `datetime.date` objects with valid values.
I'm using this in a Django view to process some data, but everytime the view this is in gets called I get the... | There's nothing wrong with Django. You create a local variable `range` in the same scope (by assigning one). For instance `range = None` in the very last line of a function makes Python consider an occurrence of `range` in the first line of the same function a reference to that local variable. Since it doesn't have a v... |
PyQt4: Create a custom dialog that returns parameters | 5,760,622 | 6 | 2011-04-22T22:20:08Z | 5,760,796 | 12 | 2011-04-22T22:51:49Z | [
"python",
"user-interface",
"pyqt4"
] | I'm attempting to add a custom dialog box to my current GUI that can be launched for the user to set some parameters. Ideally, I would like to create the custom dialog using QtDesigner. Below is the code generated by `pyuic4` from the QtDesigner ui code for the dialog box.
```
from PyQt4 import QtCore, QtGui
class Ui... | ```
class StartSub2(QtGui.QDialog, Ui_Dialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setupUi(self)
```
should resolve your first problem of getting the dialog to initialize.
To get info back I usually add a method called something like `getValues` to `StartSub2`,... |
Handle wrongly encoded character in Python unicode string | 5,760,936 | 12 | 2011-04-22T23:18:51Z | 5,761,000 | 7 | 2011-04-22T23:29:52Z | [
"python",
"string",
"unicode",
"character-encoding"
] | I am dealing with unicode strings returned by the python-lastfm library.
I assume somewhere on the way, the library gets the encoding wrong and returns a unicode string that may contain invalid characters.
For example, the original string i am expecting in the variable a is "Glück"
```
>>> a
u'Gl\xfcck'
>>> print a... | Your unicode string is fine:
```
>>> unicodedata.name(u"\xfc")
'LATIN SMALL LETTER U WITH DIAERESIS'
```
The problem you see at the interactive prompt is that the interpreter doesn't know what encoding to use to output the string to your terminal, so it falls back to the "ascii" codec -- but that codec only knows how... |
Handle wrongly encoded character in Python unicode string | 5,760,936 | 12 | 2011-04-22T23:18:51Z | 5,762,461 | 10 | 2011-04-23T05:47:02Z | [
"python",
"string",
"unicode",
"character-encoding"
] | I am dealing with unicode strings returned by the python-lastfm library.
I assume somewhere on the way, the library gets the encoding wrong and returns a unicode string that may contain invalid characters.
For example, the original string i am expecting in the variable a is "Glück"
```
>>> a
u'Gl\xfcck'
>>> print a... | You have to convert your unicode string into a standard string using some encoding e.g. utf-8:
```
some_unicode_string.encode('utf-8')
```
Apart from that: this is a dupe of
[BeautifulSoup findall with class attribute- unicode encode error](http://stackoverflow.com/questions/5746888/beautifulsoup-findall-with-class-... |
Python: Convert email address to HTML link | 5,761,090 | 2 | 2011-04-22T23:47:53Z | 5,761,177 | 8 | 2011-04-23T00:02:06Z | [
"python",
"html",
"regex",
"string",
"email-validation"
] | I'm looking for a stand-alone python function that will take in a string and return a string with the email addresses converted to links.
Example:
```
>>>s = 'blah blah blah a@at.com blah blah blah'
>>>link(s)
'blah blah blah <a href="mailto:a@at.com">a@at.com</a> blah blah blah'
``` | Something like this?
```
import re
import xml.sax.saxutils
def anchor_from_email_address_match(match):
address = match.group(0)
return "<a href=%s>%s</a>" % (
xml.sax.saxutils.quoteattr("mailto:" + address),
xml.sax.saxutils.escape(address))
def replace_email_addresses_with_anchors(text):
... |
Pyramid authorization for stored items | 5,761,617 | 17 | 2011-04-23T01:56:06Z | 5,761,901 | 48 | 2011-04-23T03:12:46Z | [
"python",
"authorization",
"policy",
"pyramid"
] | I'm trying to create an authorization policy that takes "item" ownership into account. For example some user X "owns" items A, B, C. Those are accessed via URLs like `/item/{item}/some_options`.
How can I get the information about `{item}` to the authorization policy object (permits() call)? Is putting additional info... | You can do this using the `ACLAuthorizationPolicy` combined with URL Dispatch by using a custom resource tree designed for this purpose.
For example, you have permissions for `Foo` objects, and permissions for `Bar` objects. These ACLs can be found by traversing the resource tree using the urls:
```
/foos/{obj}
/bars... |
how to transform a OpenCV cvMat back to ndarray in numpy ï¼ | 5,762,440 | 8 | 2011-04-23T05:41:54Z | 5,885,218 | 9 | 2011-05-04T14:41:29Z | [
"python",
"opencv",
"numpy"
] | I follow the code in OpenCV cookbook for python interface to transform cvMat to numpy array:
```
mat = cv.CreateMat(3,5,cv.CV_32FC1)
cv.Set(mat,7)
a = np.asarray(mat)
```
but with OpenCV 2.1 on my PC, it does not work. The result **a** here is a object array, using **"print a"** does not print all element in **a**, o... | Try using appending `[:,:]` to the matrix (ie. use `mat[:,:]` instead of `mat`) in your call to `np.asarray` - doing this will also allows `asarray` to work on images.
Your example:
```
>>> import cv
>>> import numpy as np
>>> mat = cv.CreateMat( 3 , 5 , cv.CV_32FC1 )
>>> cv.Set( mat , 7 )
>>> a = np.asarray( mat[:,:... |
How to filter list of dictionaries with matching values for a given key | 5,762,643 | 4 | 2011-04-23T06:27:30Z | 5,762,662 | 9 | 2011-04-23T06:31:18Z | [
"python"
] | With an interface like `a = copyf(dictlist, key, valuelist)`.
```
>>> dictlist = [{'first': 'James',
'last': 'Joule'},
{'first': 'James',
'last': 'Watt'},
{'first': 'Christian',
'last': 'Doppler'}]
>>> valuelist = ['James', 'John']
>>> ... | **Update:** taking into account the reedited question of the OP:
```
def copyf(dictlist, key, valuelist):
return [dictio for dictio in dictlist if dictio[key] in valuelist]
``` |
How to get pydoc command working in Windows 7 cmd? | 5,762,712 | 6 | 2011-04-23T06:43:20Z | 15,837,860 | 15 | 2013-04-05T15:32:07Z | [
"python",
"windows-7"
] | I'm learning to program Python from the "Learning Python the Hard Way". On one of the chapters it tells me to use pydoc command. The windows 7 cmd failed miserably with that command.
When I typed in `pydoc raw_input()` on cmd following error codes were generated:
```
'pydoc' is not recognized as internal or external ... | To get help on python when in the PowerShell window, type:
```
python -m pydoc raw_input
```
substituting your function name for raw\_input. |
Python: Problem with raw_input reading a number | 5,762,938 | 6 | 2011-04-23T07:34:19Z | 5,762,951 | 11 | 2011-04-23T07:39:05Z | [
"python",
"raw-input"
] | unfortunately raw\_input is not doing what I need it to do. What I am trying to do is get totPrimes = whatever I type in at the prompt. If i replace `while count < totPrimes` with `while count < 50` this script works. If I type 50 into the prompt, this script doesnt work, I'm afraid raw\_input isn't the function im loo... | Do
```
totPrimes = int(totPrimes)
while count < totPrimes:
# code
```
`raw_input` gives you a string you must convert to an integer or float before making any numeric comparison. |
How to use Python virtualenv | 5,764,494 | 10 | 2011-04-23T13:44:35Z | 5,764,842 | 15 | 2011-04-23T14:47:48Z | [
"python",
"virtualenv"
] | The scenario is: I am on Ubuntu 11 which comes with Python 2.7, I want to run Mozilla JetPack which supports Python 2.5/2.6 and Google App Engine which only supports Python 2.5.
Read that its not a good idea to remove Python 2.7 as Ubuntu maybe using it. So the correct way is to use `virtualenv`. But I am quite lost u... | **Outline:**
* First cd to `/usr/local/python25/bin`
* Download setuptools for Python2.5 ([setuptools-0.6c11-py2.5.egg](http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c11-py2.5.egg#md5=64c94f3bf7a72a13ec83e0b24f2749b2))
* Install it (`sh setuptools-0.6c11-py2.5.egg`).
* Now install pip (`easy_install p... |
Python dynamic decorators - why so many wraps? | 5,764,922 | 10 | 2011-04-23T15:01:26Z | 5,764,955 | 23 | 2011-04-23T15:07:14Z | [
"python",
"decorator"
] | So I'm still kind of new to Python decorators - I've used them before, but I've never made my own. I'm reading [this tutorial](http://www.siafoo.net/article/68#run-time-tranformations) (that particular paragraph) and I don't seem to understand why do we need three levels of functions? Why can't we do something like thi... | Well, what would happen if you called that decorator on a function?
```
@decorator
def foo(): pass
```
This code would immediately call foo, which we don't want. Decorators are called and their return value replaces the function. It's the same as saying
```
def foo(): pass
foo = decorator(foo)
```
So if we have a d... |
Loading a DER-encoded RSA key using M2Crypto | 5,764,960 | 3 | 2011-04-23T15:08:42Z | 5,765,576 | 10 | 2011-04-23T16:54:43Z | [
"python",
"m2crypto"
] | The method `M2Crypto.RSA.RSA().save_key_der()` can be used to save a key in the DER format. However, I do not see a corresponding method `M2Crypto.RSA.load_key_der()` as I would expect.
Is there a way to load a DER-encoded RSA key using M2Crypto? | The PEM format is base64-encoded DER data with some additional header and footer lines. You can just read DER as binary, transform it to PEM and pass that to `RSA.load_key_string`:
```
import base64
from M2Crypto import RSA
TEMPLATE = """
-----BEGIN RSA PRIVATE KEY-----
%s
-----END RSA PRIVATE KEY-----
"""
raw = open... |
select from sqlite table where rowid in list using python sqlite3 â DB-API 2.0 | 5,766,230 | 9 | 2011-04-23T18:55:43Z | 5,766,293 | 12 | 2011-04-23T19:07:53Z | [
"python",
"sqlite"
] | The following works:
```
>>> cursor.execute("select * from sqlitetable where rowid in (2,3);")
```
The following doesn't:
```
>>> cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
```
Is there a way to pass in a p... | Unfortunately not. Each value must be given its own parameter mark (`?`).
Since the argument list can (presumably) have arbitrary length, you must use string formating to build the correct number of parameter marks. Happily, that isn't so hard:
```
args=[2,3]
sql="select * from sqlitetable where rowid in ({seq})".form... |
problem with import qt in python | 5,766,539 | 7 | 2011-04-23T19:56:00Z | 5,766,548 | 11 | 2011-04-23T19:58:10Z | [
"python"
] | I want to use qt with python.
"import qt" return me :"ImportError: No module named qt". I already instaled pyqt.
what I hve to install in order to activate "import qt"
Thank You | The current PyQt comes in the `PyQt4` package, which has several modules. You almost always need to start with:
```
from PyQt4 import QtCore
from PyQt4 import QtGui
```
Add other imports as necessary if you need additional sub-modules of PyQt (like `QtNetwork`, `QtSql` etc).
---
Tip for the future: find the `lib/si... |
using emacs CEDET completion for python | 5,766,832 | 10 | 2011-04-23T20:46:28Z | 5,770,424 | 8 | 2011-04-24T12:14:34Z | [
"python",
"emacs",
"code-completion",
"cedet"
] | In default installation of cedet-1.0 completion can only track global scope symbols in current file. This is not much differs from built-in completion functions (dabbrev-expand or hippie-expand).
It can complete symbols from neither imported modules, nor class properties.
Not saying it cannot handle 'self'.
Is it pos... | CEDET support for each language is slightly different. In the case of python, the 1.0 release for CEDET hadn't been configured to convert a python import into a file-name. In addition, 'self' is similar to 'this' in c++, which needs to be added by completion logic since it isn't declared. These two features were added ... |
Why is Button parameter âcommandâ executed when declared? | 5,767,228 | 6 | 2011-04-23T21:59:39Z | 5,771,787 | 21 | 2011-04-24T16:35:57Z | [
"python",
"tkinter"
] | My code is:
```
from Tkinter import *
admin = Tk()
def button(an):
print an
print 'het'
b = Button(admin, text='as', command=button('hey'))
b.pack()
mainloop()
```
The button doesn't work, it prints 'hey' and 'het' once without my command, and then, when I press the button nothing happens. | The `command` option takes a reference to a function, which is a fancy way of saying you need to pass it the name of the function. When you do `button('hey')` you are calling the function `button`, *and the result of that is being given to the `command` option*.
To pass a reference you must use the name only, without ... |
What is the syntax for adding a GET parameter to a URL? python; google app engine | 5,767,464 | 12 | 2011-04-23T22:43:09Z | 5,767,509 | 20 | 2011-04-23T22:52:13Z | [
"python",
"google-app-engine",
"url",
"get"
] | I need to get access to certain webpage by adding some elements to the url.
What is the syntax for adding a get parameter to a url? | You put `?` in the end of the url. After the `?` you put `var1=val1&var2=val2& ...`.
For example, if your raw url (without the get parameters) is <http://www.example.com/> and you have two parameters, `param1=7` and `param2=seven`, then the full url should be:
<http://www.example.com/?param1=7¶m2=seven>.
If you ... |
How do I remove a \ from a string in python | 5,767,954 | 3 | 2011-04-24T00:52:56Z | 5,768,000 | 8 | 2011-04-24T01:07:48Z | [
"python",
"string",
"replace",
"backslash"
] | I'm having trouble getting a replace() to work
I've tried `my_string.replace('\\', '')` and `re.sub('\\', '', my_string)`, but neither one works.
I thought \ was the escape code for backslash, am I wrong?
The string in question looks like
`'<2011315123.04C6DACE618A7C2763810@\x82\xb1\x82\xea\x82\xa9\x82\xe7\x8c\xa9\... | You don't have any backslashes in your string. What you don't have, you can't remove.
Consider what you are showing as `'\x82'` ... this is a one-byte string.
```
>>> s = '\x82'
>>> len(s)
1
>>> ord(s)
130
>>> hex(ord(s))
'0x82'
>>> print s
é # my sys.stdout.encoding is 'cp850'
>>> print repr(s)
'\x82'
>>>
```
What... |
Algorithm for finding the busiest period? | 5,768,642 | 22 | 2011-04-24T04:28:28Z | 5,768,747 | 25 | 2011-04-24T05:04:24Z | [
"python",
"algorithm",
"dynamic-programming"
] | I have some data like this:
```
1: 2 - 10
2: 3 - 15
3: 4 - 9
4: 8 - 14
5: 7 - 13
6: 5 - 10
7: 11 - 15
```
I will attempt a representation to make it clearer:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 |--------------------------------------X-... | ```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 |--------------------------------------X---------|
2 |--------------------------------X--------------------------------------------|
3 |------------------------... |
What is a Python code object? | 5,768,684 | 16 | 2011-04-24T04:44:46Z | 5,768,692 | 21 | 2011-04-24T04:47:41Z | [
"python"
] | While trying to use Python's "exec" statement, I got the following error:
```
TypeError: exec: arg 1 must be a string, file, or code object
```
I don't want to pass in a string or a file, but what is a code object, and how do I create one? | One way to create a code object is to use `compile` built-in function:
```
>>> compile('sum([1, 2, 3])', '', 'single')
<code object <module> at 0x19ad730, file "", line 1>
>>> exec compile('sum([1, 2, 3])', '', 'single')
6
>>> compile('print "Hello world"', '', 'exec')
<code object <module> at 0x19add30, file "", line... |
What is a Python code object? | 5,768,684 | 16 | 2011-04-24T04:44:46Z | 5,768,709 | 10 | 2011-04-24T04:51:22Z | [
"python"
] | While trying to use Python's "exec" statement, I got the following error:
```
TypeError: exec: arg 1 must be a string, file, or code object
```
I don't want to pass in a string or a file, but what is a code object, and how do I create one? | Code objects are described [here](http://docs.python.org/2.7/reference/datamodel.html#index-59):
> Code objects represent *byte-compiled*
> executable Python code, or *bytecode*.
> The difference between a code object
> and a function object is that the
> function object contains an explicit
> reference to the functio... |
What is a Python code object? | 5,768,684 | 16 | 2011-04-24T04:44:46Z | 13,469,876 | 9 | 2012-11-20T09:13:39Z | [
"python"
] | While trying to use Python's "exec" statement, I got the following error:
```
TypeError: exec: arg 1 must be a string, file, or code object
```
I don't want to pass in a string or a file, but what is a code object, and how do I create one? | There is also an excellent blog post by Dan Crasta explaining this topic:
> [Exploring Python Code Objects](http://late.am/post/2012/03/26/exploring-python-code-objects) |
manage.py runserver | 5,768,797 | 40 | 2011-04-24T05:20:22Z | 5,768,813 | 7 | 2011-04-24T05:24:24Z | [
"python",
"django"
] | I am running
python manage.py runserver
from a machine A
when I am trying to check in machine B
The url I typed is <http://A:8000/>
I am getting an error like
The system returned: (111) Connection refused | You need to tell manage.py the local ip address **and** the port to bind to. Something like `python manage.py runserver 192.168.23.12:8000`. Then use that same ip and port from the other machine. You can read more about it [here](http://docs.djangoproject.com/en/1.3/ref/django-admin/#runserver-port-or-address-port) in ... |
manage.py runserver | 5,768,797 | 40 | 2011-04-24T05:20:22Z | 5,768,853 | 76 | 2011-04-24T05:39:33Z | [
"python",
"django"
] | I am running
python manage.py runserver
from a machine A
when I am trying to check in machine B
The url I typed is <http://A:8000/>
I am getting an error like
The system returned: (111) Connection refused | You can run it for machines in your network by
> ./manage.py runserver 0.0.0.0:8000
And than you will be able to reach you server from any machine in your network.
Just type on other machine in browser `http://192.168.0.1:8000` where `192.168.0.1` is IP of you server... and it ready to go....
or in you case:
1. On ... |
Setting up Python in Netbeans | 5,769,000 | 5 | 2011-04-24T06:13:58Z | 6,032,738 | 11 | 2011-05-17T14:54:55Z | [
"python",
"netbeans",
"python-3.x"
] | I remember successfully doing this countless times before with a bit of trial and error, but after a new reinstall of Snow Leopard, I would like to just ask the Stackoverflow community this for once and for all...
I installed Netbeans 7 (for C++). For some reason, I didn't see any way to install Python plugins here, s... | Unfortunately Netbeans seem to have dropped support for Python in version 7. I find it pretty annoying as it seems to work ok in 6.9.1 (although I resort to Eclipse for serious Python programming as PyDev has better code completion).
So, your options are
* Download 6.9.1, and get the python plugin via tools--> plugin... |
Soap Client using Suds | 5,769,128 | 4 | 2011-04-24T06:48:14Z | 5,769,849 | 7 | 2011-04-24T09:53:47Z | [
"python",
"soap",
"suds"
] | > [Soap call in Python](http://stackoverflow.com/questions/5752923/soap-call-in-python/5760667)
Hi above is my previous question regarding soap. In there i am passing a 1D array. Now my problem is i need to pass the 2D array to the following Soap schema.
> Request Schema
```
<?xml version="1.0" encoding="utf-8"?>
<s... | You pass invalid arguments to `CalculateWeb2DObjectArray()` function.
To find out what type of arguments `CalculateWeb2DObjectArray()` accepts, you could add to your script:
```
print client
```
The output contains:
```
CalculateWeb2DObjectArray(xs:string HCID,
ArrayOfArrayOfAnyType jagged... |
Can I put a breakpoint in a running Python program that drops to the interactive terminal? | 5,769,382 | 9 | 2011-04-24T07:55:43Z | 5,769,398 | 20 | 2011-04-24T08:00:11Z | [
"python"
] | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's... | <http://docs.python.org/library/pdb.html>
```
import pdb
pdb.set_trace()
``` |
Can I put a breakpoint in a running Python program that drops to the interactive terminal? | 5,769,382 | 9 | 2011-04-24T07:55:43Z | 5,769,400 | 7 | 2011-04-24T08:00:42Z | [
"python"
] | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's... | A *one-line* solution is simply to put `1/0` where you want the breakpoint: this will raise an exception, which will be caught by the debugger. Two advantages of this approach are:
* Breakpoints set this way are robust against code modification (no dependence on a particular line number);
* One does not need to `impor... |
Can I put a breakpoint in a running Python program that drops to the interactive terminal? | 5,769,382 | 9 | 2011-04-24T07:55:43Z | 5,769,851 | 20 | 2011-04-24T09:53:53Z | [
"python"
] | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's... | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* yo... |
Django: accessing model attributes | 5,769,678 | 2 | 2011-04-24T09:14:19Z | 5,769,695 | 7 | 2011-04-24T09:19:33Z | [
"python",
"django",
"django-models"
] | Apologies for the noobish question, I am completely new to both Python and Django and trying to make my first app.
I have a simple class
```
class About(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date = models.DateTimeField('date added')
```
to which I've add... | In your case, `about` is a [QuerySet object](http://docs.djangoproject.com/en/1.3/ref/models/querysets/), not an instance of your model. Try
```
print about[0].title
```
Alternatively, use [get() to retrieve a single instance of the model](http://docs.djangoproject.com/en/1.3/topics/db/queries/#retrieving-a-single-ob... |
How to assign an operation like sum or substitute, etc., to a variable | 5,769,696 | 2 | 2011-04-24T09:19:34Z | 5,769,700 | 9 | 2011-04-24T09:21:07Z | [
"python"
] | I want to do something like
```
class A:
def __init__( self, left, right, op ):
self.left = left
self.right = right
self.op = op
def calculate( self ):
self.number = op( self.left, self.right )
return self.number
```
and use it, for example, like this:
```
a = A( 1, 2,... | See the [`operator`](http://docs.python.org/library/operator.html) module.
```
a = A( 1, 2, operator.add )
``` |
Ordered Dictionary in Python: add to MongoDB | 5,770,959 | 3 | 2011-04-24T14:07:07Z | 5,771,170 | 7 | 2011-04-24T14:47:52Z | [
"python",
"mongodb"
] | I have a list of two element tuples, where the first element is a string (name of some parameter) and the second element is a float (the value of that parameter). For example,
```
thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000),
('numpeople':300)]
```
There are many more such tuple... | Pymongo offers a subclass of dict, bson.son.SON: <http://api.mongodb.org/python/current/api/bson/son.html> which is ordered for cases where you need that such as sending commands. |
How to import multiple locations to PYTHONPATH (bash) | 5,771,376 | 9 | 2011-04-24T15:21:02Z | 5,771,390 | 13 | 2011-04-24T15:22:57Z | [
"python",
"bash",
"pythonpath"
] | I know you can add multiple locations to python path by separating them by colons ie:
```
export PYTHONPATH=~/one/location:~/second/location
```
etc.
I have several locations to add and it looks messy using the above method. Is there a way of adding them in multiple lines? This is what I tried and the last line eras... | ```
PYTHONPATH=~/one/location:$PYTHONPATH
PYTHONPATH=~/second/location:$PYTHONPATH
export PYTHONPATH
```
Note the order here: I've made them so that each has higher precedence than the one before; you could switch what goes on each side of the colon if you want later entries to have lower precedence. |
Python: Using Dictionary get method to return empty list by default returns None instead! | 5,772,148 | 5 | 2011-04-24T17:43:23Z | 5,772,161 | 8 | 2011-04-24T17:46:37Z | [
"python",
"list",
"dictionary"
] | In python I would like to build up an dictionary of arrays using the dictionary get method to by default supply an empty list to then populate with information e.g.:
```
dict = {}
for i in range( 0, 10 ):
for j in range( 0, 100 ):
dict[i] = dict.get( i, [] ).append( j )
```
However when I try the above co... | To solve this you need to use Python's `defaultdict`.
<http://docs.python.org/library/collections.html#defaultdict-examples>
```
from collections import defaultdict
dict = defaultdict(list)
for i in range( 0, 10 ):
for j in range( 0, 100 ):
dict[i].append( j )
``` |
Python: Using Dictionary get method to return empty list by default returns None instead! | 5,772,148 | 5 | 2011-04-24T17:43:23Z | 5,772,177 | 10 | 2011-04-24T17:47:56Z | [
"python",
"list",
"dictionary"
] | In python I would like to build up an dictionary of arrays using the dictionary get method to by default supply an empty list to then populate with information e.g.:
```
dict = {}
for i in range( 0, 10 ):
for j in range( 0, 100 ):
dict[i] = dict.get( i, [] ).append( j )
```
However when I try the above co... | It's not `dict.get( i, [] )` that's returning `None`, it's `append`. You probably want to use `dict.setdefault(i, []).append(j)` or just use a `defaultdict` in the first place.
Here's how you would do it:
```
d = {}
for i in range( 0, 10 ):
for j in range( 0, 100 ):
d.setdefault( i, [] ).append( j )
```
... |
Django: 'unique_together' and 'blank=True' | 5,772,176 | 17 | 2011-04-24T17:47:53Z | 5,772,272 | 8 | 2011-04-24T18:05:57Z | [
"python",
"sql",
"django"
] | I have a Django model which looks like this:
```
class MyModel(models.Model):
parent = models.ForeignKey(ParentModel)
name = models.CharField(blank=True, max_length=200)
... other fields ...
class Meta:
unique_together = ("name", "parent")
```
This works as expected; If there is the same 'n... | Using `unique_together`, you're telling Django that you don't want any two `MyModel` instances with the same `parent` and `name` attributes -- which applies even when `name` is an empty string.
This is enforced at the database level using the `unique` attribute on the appropriate database columns. So to make any excep... |
Django: 'unique_together' and 'blank=True' | 5,772,176 | 17 | 2011-04-24T17:47:53Z | 5,776,613 | 10 | 2011-04-25T08:29:22Z | [
"python",
"sql",
"django"
] | I have a Django model which looks like this:
```
class MyModel(models.Model):
parent = models.ForeignKey(ParentModel)
name = models.CharField(blank=True, max_length=200)
... other fields ...
class Meta:
unique_together = ("name", "parent")
```
This works as expected; If there is the same 'n... | Firstly, blank (empty string) IS NOT same as null (`'' != None`).
Secondly, Django CharField when used through forms will be storing **empty string** when you leave field empty.
So if your field was something else than CharField you should just add `null=True` to it. **But in this case** you need to do more than that... |
python library to create a video file from images | 5,772,831 | 9 | 2011-04-24T19:50:01Z | 5,772,886 | 7 | 2011-04-24T19:57:25Z | [
"python"
] | I was looking for a light weight python library which would allow me to create a simple video (a slideshow) from a bunch of images. I looked into PyFFMpeg and Pymedia, but they seem really old, and was wondering if anyone knows of any other libraries I could use, (or has had success using PyFFMpeg/Pymedia recently).
T... | Go for [opencv](http://opencv.willowgarage.com/wiki/)
And a bit of help from [Here](http://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python) |
Why doesn't a sub-function inherit scope in Python? | 5,772,935 | 5 | 2011-04-24T20:07:04Z | 5,773,115 | 14 | 2011-04-24T20:41:09Z | [
"python",
"scope"
] | I don't understand why the following doesn't work:
```
def foo( x ):
n = 1
summe = 0
def bar():
n -= 1
for i in range(0,10):
y = x+i+n
x += i
summe += y
print "{0} = {1} + {2} + {3}".format(y,x,i,n)
bar()
print "summe =", summe
return summe
```
W... | [PEP 3104](http://www.python.org/dev/peps/pep-3104/) provides an explanation and a solution for this problem. The issue is Python treats any assignment to a name as a *local* variable declaration.
```
>>> n = 1
>>> def bar():
>>> n = n + 1
>>>
>>> bar()
Traceback (most recent call last):
File "<pyshell#8>", lin... |
Saving KDTree object in Python? | 5,773,216 | 7 | 2011-04-24T20:58:18Z | 5,774,145 | 8 | 2011-04-25T00:27:05Z | [
"python",
"serialization",
"numpy",
"scipy",
"pickle"
] | I am using Scipy's KDTree implementation to read a large file of 300 MB. Now, is there a way I can just save the datastructure to disk and load it again or am I stuck with reading raw points from file and constructing the data structure each time I start my program? I am constructing the KDTree as follows:
```
def bui... | KDtree uses nested classes to define its node types (innernode, leafnode). Pickle only works on module-level class definitions, so a nested class trips it up:
```
import cPickle
class Foo(object):
class Bar(object):
pass
obj = Foo.Bar()
print obj.__class__
cPickle.dumps(obj)
<class '__main__.Bar'>
cPick... |
Converting a deque object into list | 5,773,397 | 13 | 2011-04-24T21:37:41Z | 5,773,404 | 28 | 2011-04-24T21:40:20Z | [
"python",
"list",
"queue",
"deque"
] | currently I fetch "list" data from my storage, "deque" it to work with that data.
After processing the fetched data I have to put them back into the storage.
This won't be a problem as long as I am not forced (at least I think so) to use python's standard "list" object to save this data.
Storage Service: Google Appeng... | ```
>>> list(collections.deque((1, 2, 3)))
[1, 2, 3]
``` |
How to clear form fields after a submit in Django | 5,773,408 | 9 | 2011-04-24T21:41:11Z | 5,773,856 | 13 | 2011-04-24T23:13:38Z | [
"python",
"django",
"django-forms"
] | I've this:
```
def profile(request, username):
if request.method == 'POST':
if request.user.is_authenticated():
new_message = Message(author = request.user)
form = MessagesForm(request.POST, instance = new_message)
else:
form = MessagesForm(request.POST)
if form.is_valid():
... | It's standard to redirect after form submission to prevent duplicates.
Just return a redirect to your form on success.
```
if form.is_valid():
form.save()
return http.HttpResponseRedirect('')
``` |
How to clear form fields after a submit in Django | 5,773,408 | 9 | 2011-04-24T21:41:11Z | 16,773,478 | 9 | 2013-05-27T12:42:18Z | [
"python",
"django",
"django-forms"
] | I've this:
```
def profile(request, username):
if request.method == 'POST':
if request.user.is_authenticated():
new_message = Message(author = request.user)
form = MessagesForm(request.POST, instance = new_message)
else:
form = MessagesForm(request.POST)
if form.is_valid():
... | After saving form instead of showing post dict assign the empty form
```
form = EmployeeForm()
if request.method == "POST":
pDict = request.POST.copy()
form = EmployeeForm(pDict) #if not valid shows error with previous post values in corresponding field
if form.is_valid():
form... |
Python - What is the most efficient way to generate padding? | 5,773,607 | 4 | 2011-04-24T22:18:53Z | 5,773,669 | 9 | 2011-04-24T22:31:17Z | [
"python",
"padding"
] | Here's the problem: I'm reading binary files in fairly large blocks (512 KiB) and wish to pad the last block with zeros whenever it is shorter than the block size.
Currently, I'm doing something like this:
```
bytes = f.read(self.chunksize)
if len(bytes) > 0:
len_diff = self.chunksize - len(bytes)
if len_diff... | Couldn't you just use [`ljust()`](http://docs.python.org/library/stdtypes.html#str.ljust) to do the padding since we're dealing with string objects here?
```
bytes = f.read(self.chunksize)
if bytes:
bytes = bytes.ljust(self.chunksize, '\0')
``` |
WSGI - Set content type to JSON | 5,773,619 | 7 | 2011-04-24T22:21:42Z | 5,773,741 | 13 | 2011-04-24T22:43:19Z | [
"python",
"google-app-engine",
"rest",
"wsgi"
] | I'm crazy green to WSGI on Google App Engine (GAE).
How do I set the content type to JSON? This is what I have so far:
```
class Instructions(webapp.RequestHandler):
def get(self):
response = {}
response["message"] = "This is an instruction object"
self.response.out.write(json.dumps(respo... | You can set the proper *Content-Type* with something like this:
```
self.response.headers['Content-Type'] = "application/json"
self.response.out.write(json.dumps(response))
```
[WSGI](http://en.wikipedia.org/wiki/Wsgi) is not a framework but a specification; the framework you are currently using is the [webapp](http:... |
Django auth.user with unique email | 5,773,970 | 4 | 2011-04-24T23:36:16Z | 5,774,333 | 7 | 2011-04-25T01:04:09Z | [
"python",
"django",
"django-authentication"
] | I use the django.auth system and I've this:
```
class RegisterForm(UserCreationForm):
username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."})
email = forms.EmailField(label = "Email")
... | add this to your form. But this isn't perfect way. race condition is available by only using this form. I recommend you to add unique constraint at db level.
```
def clean_email(self):
data = self.cleaned_data['email']
if User.objects.filter(email=data).exists():
raise forms.ValidationError("This email... |
Django auth.user with unique email | 5,773,970 | 4 | 2011-04-24T23:36:16Z | 12,708,590 | 8 | 2012-10-03T12:35:51Z | [
"python",
"django",
"django-authentication"
] | I use the django.auth system and I've this:
```
class RegisterForm(UserCreationForm):
username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."})
email = forms.EmailField(label = "Email")
... | Somewhere in your models:
```
from django.contrib.auth.models import User
User._meta.get_field('email')._unique = True
```
Notice the underscore before `unique`. This is where the information is actually held. `User._meta.get_field('email').unique` is just a `@property` which looks into it.
This should work for sync... |
How to make a double 'continue' in a loop? | 5,774,200 | 2 | 2011-04-25T00:37:35Z | 5,774,211 | 7 | 2011-04-25T00:39:57Z | [
"python"
] | Is it possible to make a double continue and jump to the item after the next item in the list in python? | Not really, but you can use a variable telling it to `continue` again after the first continue:
```
continue_again = False
for thing in things:
if continue_again:
continue_again = False
continue
# ...
if some_condition:
# ...
continue_again = True
continue
# ...
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.