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 |
|---|---|---|---|---|---|---|---|---|---|
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 5,844,680 | 19 | 2011-04-30T21:23:36Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | The [del statement](http://docs.python.org/tutorial/datastructures.html#the-del-statement) is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:
```
del foo['bar']
```
Note that this permanently modifies the dictionary being operated on. If yo... |
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 5,844,685 | 10 | 2011-04-30T21:24:48Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | ```
d = {1: 2, '2': 3, 5: 7}
del d[5]
print 'd = ', d
```
Result: d = {1: 2, '2': 3} |
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 5,844,692 | 651 | 2011-04-30T21:25:39Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | The [`del` statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-del_stmt) removes an element:
```
del d[key]
```
However, this mutates the existing dictionary so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a *new* dictionary, make ... |
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 5,844,700 | 39 | 2011-04-30T21:26:40Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | I think your solution is best way to do it. But if you want another solution, you can create a new dictionary with using the keys from old dictionary without including your specified key, like this:
```
>>> a
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> {i:a[i] for i in a if i!=0}
{1: 'one', 2: 'two', 3: 'three'}
`... |
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 22,564,121 | 39 | 2014-03-21T16:22:18Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | maybe I dont get your question but
pop mutates the dictionary...
```
>>>lol = {"hello":"gdbye"}
>>>lol.pop("hello")
'gdbye'
>>> lol
{}
```
if you want to keep the original I guess you could just copy it |
Delete an element from a dictionary | 5,844,672 | 432 | 2011-04-30T21:20:57Z | 28,811,205 | 7 | 2015-03-02T13:39:10Z | [
"python",
"dictionary"
] | Is there a way to delete an element from a dictionary in Python?
I know I can just call `.pop` on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary *minus* the element in question.
At present I have a helper function that accepts the dictionary in ... | Simply call del d['key'].
However, in production, it is always a good practice to check if 'key' exists in d.
```
if 'key' in d:
del d['key']
``` |
Unable to reverse lists in Python, getting "Nonetype" as list | 5,846,004 | 9 | 2011-05-01T02:28:12Z | 5,846,048 | 22 | 2011-05-01T02:38:59Z | [
"python",
"list"
] | I have a `.py` file that takes a list, finds the lowest number, puts it into a new array, removes the lowest number from the first array, and repeats until the original array returns contains no more items:
```
def qSort(lsort):
listlength = len(lsort)
sortedlist = list()
if listlength == 0:
return... | As jcomeau mentions, the `.reverse()` function changes the list in place. It does not return the list, bur rather leaves `qSort` altered.
If you want to 'return' the reversed list, so it can be used like you attempt in your example, you can do a slice with a direction of -1
So replace `print qSort.reverse()` with `pr... |
how to change default python version? | 5,846,167 | 21 | 2011-05-01T03:10:52Z | 5,846,177 | 37 | 2011-05-01T03:13:50Z | [
"python",
"osx"
] | I have installed python 3.2 in my mac. After I run **/Applications/Python 3.2/Update Shell Profile.command**, it's confusing that when I type **python -V** in Terminal it says that **Python 2.6.1**, how can I change the default python version? | This is probably desirable for backwards compatibility.
Python3 breaks backwards compatibility, and programs invoking 'python' probably expect python2. You probably have many programs and scripts which you are not even aware of which expect python=python2, and changing this would break those programs and scripts.
The... |
how to change default python version? | 5,846,167 | 21 | 2011-05-01T03:10:52Z | 5,846,204 | 9 | 2011-05-01T03:22:46Z | [
"python",
"osx"
] | I have installed python 3.2 in my mac. After I run **/Applications/Python 3.2/Update Shell Profile.command**, it's confusing that when I type **python -V** in Terminal it says that **Python 2.6.1**, how can I change the default python version? | Change the "default" Python by putting it ahead of the system Python on your path, for instance:
```
export PATH=/usr/local/bin:$PATH
``` |
how to change default python version? | 5,846,167 | 21 | 2011-05-01T03:10:52Z | 5,846,430 | 21 | 2011-05-01T04:27:22Z | [
"python",
"osx"
] | I have installed python 3.2 in my mac. After I run **/Applications/Python 3.2/Update Shell Profile.command**, it's confusing that when I type **python -V** in Terminal it says that **Python 2.6.1**, how can I change the default python version? | On Mac OS X using the python.org installer as you apparently have, you need to invoke Python 3 with `python3`, not `python`. That is currently reserved for Python 2 versions. You could also use `python3.2` to specifically invoke that version.
```
$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Pytho... |
Decentralized networking in Python - How? | 5,846,209 | 13 | 2011-05-01T03:23:53Z | 5,846,248 | 7 | 2011-05-01T03:37:35Z | [
"python",
"networking"
] | I want to write a Python script that will check the users local network for other instances of the script currently running.
For the purposes of this question, let's say that I'm writing an application that runs solely via the command line, and will just update the screen when another instance of the application is "f... | One of the ways to do this would be the Application under question is broadcasting UDP packets and your application is receiving that from different nodes and then displaying it. [Twisted Networking Framework](http://twistedmatrix.com/documents/current/core/howto/index.html) provides facilities for doing such a job. Th... |
opencv python osx | 5,846,745 | 13 | 2011-05-01T05:50:11Z | 6,087,778 | 39 | 2011-05-22T11:58:20Z | [
"python",
"osx",
"opencv",
"macports"
] | **(Step 1)**
I'm trying to get openCV to run from python on my mac using the MacPorts install <http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port>, and also trying to follow [The Petite Geek's guide](http://thepetitegeek.blogspot.com/2009/09/installing-opencv-on-mac-os-x-with.html):
```
sudo port -v install ope... | I struggled for a while with Python on Mac. Here is how I finally (and easily!) installed it. Remove all the things Python you have on there already. They will probably be located at /Library/Frameworks/Python.Framework and /opt/local/var/macports/software/py26\*
First download Python with Macports.
```
sudo port ins... |
Learning pyramid (python) and am struggling with the @view_config decorator. Should it just work out of the box? | 5,847,030 | 4 | 2011-05-01T07:05:08Z | 5,848,816 | 7 | 2011-05-01T13:55:02Z | [
"python",
"decorator",
"pyramid"
] | I am still learning pyramid, and I am at a point where I am trying to learn how to use decorators. Below is a copy of my test view callable.
```
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.renderers import render_to_response
def my_blog(request):
return {'project':'tric... | In order for the configurations added via @view\_config to work, you need to call config.scan() at some point. |
Django is sooo slow? errno 32 broken pipe? dcramer-django-sentry-? static folder? | 5,847,580 | 9 | 2011-05-01T09:27:12Z | 6,410,746 | 7 | 2011-06-20T11:56:55Z | [
"python",
"django",
"performance"
] | I've been using Django 1.3 with Python 2.6 on Ubuntu 10.10. I have 3 questions.
1. I recall having this problem on Windows 7 when I used Django a while ago. However, I also remember that when I first used Django this problem didn't occur.
When I access Django via `127.0.0.1:8000`, after starting a brand new project, ... | this issue is also discussed here [Django + WebKit = Broken pipe](http://stackoverflow.com/questions/2868059/django-webkit-broken-pipe) |
wtforms Form class subclassing and field ordering | 5,848,252 | 15 | 2011-05-01T12:11:10Z | 18,475,322 | 9 | 2013-08-27T20:56:23Z | [
"python",
"subclassing",
"wtforms"
] | I have a UserForm class:
```
class UserForm(Form):
first_name = TextField(u'First name', [validators.Required()])
last_name = TextField(u'Last name', [validators.Required()])
middle_name = TextField(u'Middle name', [validators.Required()])
username = TextField(u'Username', [validators.Required()])
... | In regards to your first question about reording the fields when iterating over the form object, this is what I did:
```
class BaseForm(Form):
def __iter__(self):
field_order = getattr(self, 'field_order', None)
if field_order:
temp_fields = []
for name in field_order:
... |
Django admin hangs (until timeout error) for a specific model when trying to edit/create | 5,848,319 | 13 | 2011-05-01T12:24:41Z | 5,849,040 | 17 | 2011-05-01T14:40:36Z | [
"python",
"django",
"django-admin"
] | This one is driving me nuts right now. It was not happening before (even got screenshots I had to do for the user-manual since the customer required it).
I first noticed it on production server and then I checked and also happens in the dev server that comes with Django. The model appears on the main-page of the djang... | In your admin.py file, under the appropriate admin class, set
```
raw_id_fields = ('zipcode',)
```
This will display the zipcode's PK instead of a dropdown.
Is there a reason that you are setting up zipcode as it's own model instead of using a CharField or an actual zipcode [modelfield](http://docs.djangoproject.com... |
django: how to do caculation inside the template html page? | 5,848,967 | 9 | 2011-05-01T14:25:32Z | 5,848,988 | 19 | 2011-05-01T14:30:12Z | [
"python",
"html",
"django"
] | Hi I am using thumbnail plugin to get the image's width and height, now I want to define the padding of the img tag using the gotten height from thumbnail plugin, like:
```
<img style="padding-top: {{ img.height / 2 }}" src=""/>
```
But I got error here, does django not allow calculate like this? | Unfortunately not. You need to use filters, like the `add` one which is built in:
```
{{ img.height|add:1 }}
```
The `div` is not, however; you can implement it yourself, though:
```
from django import template
register = template.Library()
@register.filter
def div( value, arg ):
'''
Divides the value; argu... |
tic, toc functions analog in Python | 5,849,800 | 40 | 2011-05-01T16:46:34Z | 5,849,861 | 68 | 2011-05-01T16:55:13Z | [
"python",
"matlab"
] | What is the best analog of MATLAB tic and toc functions ( <http://www.mathworks.com/help/techdoc/ref/tic.html>) in Python? | Apart from `timeit` which ThiefMaster mentioned, a simple way to do it is just (after importing `time`):
```
t = time.time()
# do stuff
elapsed = time.time() - t
```
I have a helper class I like to use:
```
class Timer(object):
def __init__(self, name=None):
self.name = name
def __enter__(self):
... |
tic, toc functions analog in Python | 5,849,800 | 40 | 2011-05-01T16:46:34Z | 18,903,019 | 10 | 2013-09-19T19:12:49Z | [
"python",
"matlab"
] | What is the best analog of MATLAB tic and toc functions ( <http://www.mathworks.com/help/techdoc/ref/tic.html>) in Python? | The absolute best analog of tic and toc would be to simply define them in python.
```
def tic():
#Homemade version of matlab tic and toc functions
import time
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
import time
if 'startTime_for_tictoc' in globals():
p... |
tic, toc functions analog in Python | 5,849,800 | 40 | 2011-05-01T16:46:34Z | 26,695,514 | 9 | 2014-11-02T02:44:46Z | [
"python",
"matlab"
] | What is the best analog of MATLAB tic and toc functions ( <http://www.mathworks.com/help/techdoc/ref/tic.html>) in Python? | I had the same question when I migrated to python from Matlab. With the help of this thread I was able to construct an *exact* analog of the Matlab `tic()` and `toc()` functions. Simply insert the following code at the top of your script.
```
import time
def TicTocGenerator():
# Generator that returns time differ... |
How to make tar backup using python | 5,849,999 | 4 | 2011-05-01T17:16:52Z | 5,853,754 | 10 | 2011-05-02T05:33:40Z | [
"python",
"shell",
"backup"
] | I have directory /home/user1 , user2 .
I want to loop through all usernames home dir and then make the tar.gz file and then store it in /backups directory.
I am new to python so confused how to start | This should work:
```
import os
import tarfile
home = '/home/'
backup_dir = '/backup/'
home_dirs = [ name for name in os.listdir(home) if os.path.isdir(os.path.join(home, name)) ]
for directory in home_dirs:
full_dir = os.path.join(home, directory)
tar = tarfile.open(os.path.join(backup_dir, directory+'.tar... |
How to unread a line in python | 5,850,127 | 6 | 2011-05-01T17:38:42Z | 5,850,176 | 9 | 2011-05-01T17:45:45Z | [
"python",
"file-io"
] | I am new to Python (2.6), and have a situation where I need to un-read a line I just read from a file. Here's basically what I am doing.
```
for line in file:
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
```
However I notice that "zz" and "line" are not the same. Where am I g... | I don't think `for line in file:` and `seek` make a good combination. Try something like this:
```
while True:
line = file.readline()
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
# Make sure this loop ends somehow
``` |
how can I plot 4 histograms on the same graph | 5,850,207 | 4 | 2011-05-01T17:50:10Z | 5,850,223 | 10 | 2011-05-01T17:52:02Z | [
"python",
"histogram",
"matplotlib"
] | I have the following problem:
I am using hist() in matplotlib.pyplot
I am trying to create 4 histograms on the same graph. and an approximation gaussian for each one of them.
how can I plot the 4 histograms on the same graph, without them blocking each other (side by side)? any ideas? | There are several examples in the [matplotlib documentation](http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html). This one looks like it answers your question:
```
import numpy as np
import pylab as P
#
# first create a single histogram
#
mu, sigma = 200, 25
x = mu + sigma*P.randn(1... |
FSharp runs my algorithm slower than Python | 5,850,243 | 34 | 2011-05-01T17:54:31Z | 5,850,557 | 43 | 2011-05-01T18:53:30Z | [
"python",
"algorithm",
"performance",
"f#",
"dynamic-programming"
] | Years ago, I solved a problem via dynamic programming:
<https://www.thanassis.space/fillupDVD.html>
The solution was coded in Python.
As part of expanding my horizons, I recently started learning OCaml/F#. What better way to test the waters, than by doing a direct port of the imperative code I wrote in Python to F# ... | Dr Jon Harrop, whom I contacted over e-mail, explained what is going on:
> The problem is simply that the program has been optimized for Python. This is common when the programmer is more familiar with one language than the other, of course. You just have to learn a different set of rules that dictate how F# programs ... |
FSharp runs my algorithm slower than Python | 5,850,243 | 34 | 2011-05-01T17:54:31Z | 5,858,238 | 7 | 2011-05-02T14:14:40Z | [
"python",
"algorithm",
"performance",
"f#",
"dynamic-programming"
] | Years ago, I solved a problem via dynamic programming:
<https://www.thanassis.space/fillupDVD.html>
The solution was coded in Python.
As part of expanding my horizons, I recently started learning OCaml/F#. What better way to test the waters, than by doing a direct port of the imperative code I wrote in Python to F# ... | As Jon Harrop has pointed out, simply constructing the dictionaries using `Dictionary(HashIdentity.Structural)` gives a major performance improvement (a factor of 3 on my computer). This is almost certainly the minimally invasive change you need to make to get better performance than Python, and keeps your code idiomat... |
How to test or mock "if __name__ == '__main__'" contents | 5,850,268 | 29 | 2011-05-01T17:59:36Z | 5,850,288 | 8 | 2011-05-01T18:04:35Z | [
"python",
"unit-testing",
"testing",
"mocking",
"python-import"
] | Say I have a module with the following:
```
def main():
pass
if __name__ == "__main__":
main()
```
I want to write a unit test for the bottom half (I'd like to achieve 100% coverage). I discovered the *runpy* builtin module that performs the import/`__name__`-setting mechanism, but I can't figure out how to ... | You can do this using the `imp` module rather than the `import` statement. The problem with the `import` statement is that the test for `'__main__'` runs as part of the import statement before you get a chance to assign to `runpy.__name__`.
For example, you could use `imp.load_source()` like so:
```
import imp
runpy ... |
How to test or mock "if __name__ == '__main__'" contents | 5,850,268 | 29 | 2011-05-01T17:59:36Z | 5,850,364 | 25 | 2011-05-01T18:20:24Z | [
"python",
"unit-testing",
"testing",
"mocking",
"python-import"
] | Say I have a module with the following:
```
def main():
pass
if __name__ == "__main__":
main()
```
I want to write a unit test for the bottom half (I'd like to achieve 100% coverage). I discovered the *runpy* builtin module that performs the import/`__name__`-setting mechanism, but I can't figure out how to ... | I will choose another alternative which is to exclude the `if __name__ == '__main__'` from the coverage report , of course you can do that only if you already have a test case for your main() function in your tests.
As for why i choose to exclude rather than writing a new test case for the whole script is because if a... |
How to chunk a list in Python 3? | 5,850,536 | 18 | 2011-05-01T18:49:45Z | 5,850,582 | 29 | 2011-05-01T18:57:30Z | [
"python",
"list",
"python-3.x"
] | I found the following code that is compatible with python2
```
from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
```
However, **this isn't working wit... | In Python 3's `itertools` there is a function called `zip_longest`. It should do the same as `izip_longest` from Python 2.
Why the change in name? You might also notice that `itertools.izip` is now gone in Python 3 - that's because in Python 3, the `zip` built-in function now returns an iterator, whereas in Python 2 i... |
Using Scrapy with authenticated (logged in) user session | 5,850,755 | 29 | 2011-05-01T19:26:03Z | 5,850,928 | 33 | 2011-05-01T19:54:12Z | [
"python",
"scrapy"
] | In the [Scrapy docs](http://doc.scrapy.org/en/latest/topics/request-response.html#topics-request-response-ref-request-userlogin), there is the following example to illustrate how to use an authenticated session in Scrapy:
```
class LoginSpider(BaseSpider):
name = 'example.com'
start_urls = ['http://www.example... | In the code above, the `FormRequest` that is being used to authenticate has the `after_login` function set as its callback. This means that the after\_login function will be called and passed the page that the login attempt got as a response.
It is then checking that you are successfully logged in by searching the pag... |
Joining elements of a list - Python | 5,850,986 | 60 | 2011-05-01T20:03:22Z | 5,851,033 | 58 | 2011-05-01T20:09:07Z | [
"python",
"string",
"list",
"join"
] | I'm fairly new to python (a couple of weeks) and have run into a problem joining a list. Now, I know that a list can be joined to make one long string as in:
```
x = ['a', 'b', 'c', 'd']
print ''.join(x)
```
Obviously this would output:
```
'abcd'
```
However, what I am trying to do is simply join the f... | You can use slice notation with steps:
```
>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
```
Same logic applies for lists too. String lenght doesn't matter, because y... |
Joining elements of a list - Python | 5,850,986 | 60 | 2011-05-01T20:03:22Z | 5,851,246 | 19 | 2011-05-01T20:40:07Z | [
"python",
"string",
"list",
"join"
] | I'm fairly new to python (a couple of weeks) and have run into a problem joining a list. Now, I know that a list can be joined to make one long string as in:
```
x = ['a', 'b', 'c', 'd']
print ''.join(x)
```
Obviously this would output:
```
'abcd'
```
However, what I am trying to do is simply join the f... | Use an iterator.
**List comprehension:**
```
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> [c+next(si, '') for c in si]
['abcde', 'fghijklmn', 'opqr']
```
* Very efficient for memory usage.
* Exactly one traversal of s
**Generator expression:**
```
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq'... |
best algorithm for finding distance for all pairs where edges' weight is 1 | 5,851,154 | 14 | 2011-05-01T20:23:55Z | 5,851,221 | 11 | 2011-05-01T20:36:07Z | [
"python",
"algorithm",
"dijkstra",
"shortest-path",
"graph-algorithm"
] | As the title said, I'm trying to implement an algorithm that finds out the distances between all pairs of nodes in given graph. But there is more: (Things that might help you)
* **The graph is unweighted. *Meaning that all the edges can be considered as having weight of 1*.**
* `|E| <= 4*|V|`
* The graph is pretty big... | There is space for improvement because in unweighted graphs, you gain an additional attribute which does not hold for weighted graphs, namely:
> For any edge directly connecting A to C, you know for sure that there is no shorter path via a third node B.
With this in mind, you should be able to simplify Dijkstra's Alg... |
best algorithm for finding distance for all pairs where edges' weight is 1 | 5,851,154 | 14 | 2011-05-01T20:23:55Z | 5,851,436 | 9 | 2011-05-01T21:10:25Z | [
"python",
"algorithm",
"dijkstra",
"shortest-path",
"graph-algorithm"
] | As the title said, I'm trying to implement an algorithm that finds out the distances between all pairs of nodes in given graph. But there is more: (Things that might help you)
* **The graph is unweighted. *Meaning that all the edges can be considered as having weight of 1*.**
* `|E| <= 4*|V|`
* The graph is pretty big... | Run a breadth-first search from each node. Total time: O(|V| |E|) = O(|V|2), which is optimal. |
Crawling with an authenticated session in Scrapy | 5,851,213 | 23 | 2011-05-01T20:34:32Z | 5,857,202 | 42 | 2011-05-02T12:37:36Z | [
"python",
"scrapy"
] | In my [previous question](http://stackoverflow.com/q/5850755/445210), I wasn't very specific over my problem (scraping with an authenticated session with Scrapy), in the hopes of being able to deduce the solution from a more general answer. I should probably rather have used the word `crawling`.
So, here is my code so... | **Do not override the `parse` function in a `CrawlSpider`:**
When you are using a `CrawlSpider`, you shouldn't override the `parse` function. There's a warning in the `CrawlSpider` documentation here: <http://doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule>
This is because with a `CrawlSpider`,... |
Difference between __file__ and sys.argv[0] | 5,851,588 | 10 | 2011-05-01T21:39:01Z | 5,851,608 | 7 | 2011-05-01T21:41:31Z | [
"python"
] | Is there any difference between:
`__file__`
and
`sys.argv[0]`
Because both seem to be doing the same thing: they hold the name of the script.
If there is no difference, then why is it that `__file__` is used in almost all someplaces whereas I have never seen `sys.argv[0]` being used. | `__file__` is the name of the current file, which may be different from the main script if you are inside a module or if you start a script using `execfile()` rather than by invoking `python scriptname.py`. `__file__` is generally your safer bet. |
Python equivalent of php's foreach($array as $key => &$value) | 5,851,753 | 24 | 2011-05-01T22:01:33Z | 5,851,779 | 35 | 2011-05-01T22:06:22Z | [
"python",
"for-loop"
] | is there any equivalent to this PHP notation, which changes the original array (be aware of reference operator)?
```
// increase value of all items by 1
foreach ($array as $k => &$v) {
$v++;
}
```
I know only this way, which is not so elegant:
```
for i in range(len(array)):
array[i] += 1
``` | When the built in [`enumerate()`](http://docs.python.org/library/functions.html#enumerate) function is called on a list, it returns an object that can be iterated over, returning a count and the value returned from the list.
```
for i, val in enumerate(array):
array[i] += 1
``` |
Changing the font on a wxPython TextCtrl widget | 5,851,932 | 9 | 2011-05-01T22:37:27Z | 5,852,031 | 14 | 2011-05-01T22:56:43Z | [
"python",
"fonts",
"wxpython",
"textctrl"
] | I'd like to set the font of a **wx.TextCtrl** widget to Consolas, or at least another monospaced font. How would I go about this? | ```
font1 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas')
myTextCtrl.SetFont(font1)
``` |
How do i find the scalar product of a Numpy Matrix ? | 5,852,495 | 9 | 2011-05-02T00:40:14Z | 5,852,522 | 7 | 2011-05-02T00:45:24Z | [
"python",
"matrix",
"numpy"
] | I'm wondering if there is a simple way to multiply a numpy matrix by a scalar. Essentially I want all values to be multiplied by the constant 40. This would be an nxn matrix with 40's on the diagonal, but I'm wondering if there is a simpler function to use to scale this matrix. Or how would I go about making a matrix w... | Easy:
```
N = 100
a = np.eye(N) # Diagonal Identity 100x100 array
b = 40*a # multiply by a scalar
```
If you actually want a numpy matrix vs an array, you can do `a = np.asmatrix(np.eye(N))` instead. But in general `*` is element-wise multiplication in numpy. |
How do i find the scalar product of a Numpy Matrix ? | 5,852,495 | 9 | 2011-05-02T00:40:14Z | 5,854,620 | 9 | 2011-05-02T07:40:33Z | [
"python",
"matrix",
"numpy"
] | I'm wondering if there is a simple way to multiply a numpy matrix by a scalar. Essentially I want all values to be multiplied by the constant 40. This would be an nxn matrix with 40's on the diagonal, but I'm wondering if there is a simpler function to use to scale this matrix. Or how would I go about making a matrix w... | If you want a matrix with 40 on the diagonal and zeros everywhere else, you can use NumPy's function `fill_diagonal()` on a matrix of zeros. You can thus directly do:
```
N = 100; value = 40
b = np.fill_diagonal(np.zeros((N, N)), value)
```
This involves only setting elements to a certain value, and is therefore like... |
Python: How do I display a timer in a terminal | 5,852,981 | 4 | 2011-05-02T02:20:02Z | 5,853,003 | 8 | 2011-05-02T02:26:08Z | [
"python",
"timer"
] | I'm new to python programming and using ubuntu to do so. In a program I have done I used a delay of 1 minute until it executes the code again. How can I program a timer to be displayed in the terminal based on the value of the delayed time? Thanks in advance... | The simplest way is as follows.
```
import time
import sys
for remaining in range(10, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rComplete! \n")
```
`"\r"` returns the text cursor to th... |
How to get last inserted id in Postgresql with OpenERP | 5,853,948 | 3 | 2011-05-02T06:07:39Z | 5,853,998 | 7 | 2011-05-02T06:16:06Z | [
"python",
"postgresql",
"openerp"
] | I have a insert query and I want to get last inserted id in OpenERP. Here is the code:
```
query = "INSERT INTO foo SELECT * FROM bar"
cr.execute(query) # cr => cursor
```
How to get last inserted id(s)? What happened when insertion is empty? | Look at the [RETURNING clause](http://www.postgresql.org/docs/8.3/interactive/sql-insert.html).
```
INSERT INTO table [ ( column [, ...] ) ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
[ RETURNING * | output_expression [ AS output_name ] [, ...] ]
```
> Insert a single row... |
Large plot: ~20 million samples, gigabytes of data | 5,854,515 | 41 | 2011-05-02T07:25:39Z | 5,855,129 | 12 | 2011-05-02T08:43:02Z | [
"python",
"performance",
"matplotlib",
"scientific-computing"
] | I have got a problem (with my RAM) here: it's not able to hold the data I want to plot. I do have sufficient HD space. Is there any solution to avoid that "shadowing" of my data-set?
Concretely I deal with Digital Signal Processing and I have to use a high sample-rate. My framework (GNU Radio) saves the values (to avo... | You can certainly optimize the reading of your file: you could directly read it into a NumPy array, so as to leverage the raw speed of NumPy. You have a few options. If RAM is an issue, you can use [memmap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html), which keeps most of the file on disk (ins... |
Large plot: ~20 million samples, gigabytes of data | 5,854,515 | 41 | 2011-05-02T07:25:39Z | 5,858,061 | 47 | 2011-05-02T13:58:27Z | [
"python",
"performance",
"matplotlib",
"scientific-computing"
] | I have got a problem (with my RAM) here: it's not able to hold the data I want to plot. I do have sufficient HD space. Is there any solution to avoid that "shadowing" of my data-set?
Concretely I deal with Digital Signal Processing and I have to use a high sample-rate. My framework (GNU Radio) saves the values (to avo... | So your data isn't that big, and the fact that you're having trouble plotting it points to issues with the tools. Matplotlib.... isn't that good. It has lots of options and the output is fine, but it's a huge memory hog and it fundamentally assumes your data is small. But there are other options out there.
So as an ex... |
What is the source code of the "this" module doing? | 5,855,758 | 66 | 2011-05-02T09:56:38Z | 5,855,793 | 65 | 2011-05-02T10:00:02Z | [
"python"
] | If you open a Python interpreter, and type "import this", as you know, it prints:
> The Zen of Python, by Tim Peters
>
> Beautiful is better than ugly.
> Explicit is better than implicit.
> Simple is better than complex.
> Complex is better than complicated.
> Flat is better than nested.
> Sparse is better t... | This is called [rot13](http://en.wikipedia.org/wiki/ROT13) encoding:
```
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
```
Builds the translation table, for both uppercase (this is what 65 is for) and lowercase (this is what 97 is for) chars.
```
print "".join([d.get(c,... |
What is the source code of the "this" module doing? | 5,855,758 | 66 | 2011-05-02T09:56:38Z | 5,856,320 | 12 | 2011-05-02T11:00:12Z | [
"python"
] | If you open a Python interpreter, and type "import this", as you know, it prints:
> The Zen of Python, by Tim Peters
>
> Beautiful is better than ugly.
> Explicit is better than implicit.
> Simple is better than complex.
> Complex is better than complicated.
> Flat is better than nested.
> Sparse is better t... | If you want to make the **ROT13** substitution by hand - or in your head - you can check that because 13\*2 = 26 (the number of the letters of the English alphabet), it's essentially an interchange:
```
a <-> n
b <-> o
c <-> p
...
m <-> z
A <-> N
B <-> O
C <-> P
...
M <-> Z
```
Vs lbh cenpgvfr ybat rabhtu, lbh'yy ri... |
python doctest: expected result is the same as the "got" result but the test failed | 5,856,502 | 6 | 2011-05-02T11:20:22Z | 5,856,618 | 10 | 2011-05-02T11:32:23Z | [
"python",
"doctest"
] | I am on a learning stage of using python as a tool for software QA.
I wrote the next simple test in order to find the letter 'a' in a text file number matrix.
problem is that the test fails even though the expect equals to what i got.
Why is that? Can you tell me what am I doing wrong?
**test script:**
```
fin = op... | You've got an extra space after the 97 - if you remove it, your test should run fine. |
Abstract methods in Python | 5,856,963 | 8 | 2011-05-02T12:11:09Z | 5,857,041 | 20 | 2011-05-02T12:19:22Z | [
"python",
"oop",
"python-3.x",
"abstract-class"
] | I need something like an `abstract protected` method in Python (3.2):
```
class Abstract:
def use_concrete_implementation(self):
print(self._concrete_method())
def _concrete_method(self):
raise NotImplementedError()
class Concrete(Abstract):
def _concrete_method(self):
return 2 *... | In Python, you usually avoid having such abstract methods alltogether. You define an interface by the documentation, and simply assume the objects that are passed in fulfil that interface ("duck typing").
If you really want to define an abstract base class with abstract methods, this can be done using the [`abc`](http... |
Using Django minus the web server | 5,858,392 | 11 | 2011-05-02T14:29:44Z | 5,858,461 | 13 | 2011-05-02T14:35:26Z | [
"python",
"django",
"model-view-controller",
"qt",
"hybrid"
] | I'm writing a syndication client, with the aim being to have a client for devices, and a web site that has the same functionality. I shall develop the website using Django - this is already decided; the client shall be written in python with both a CLI and a PyQt4 GUI. I have been writing the clinet first, and it's fai... | Read up on [standalone Django scripts](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) and you'll be on your path to victory. Basically all you're really doing is referencing the Django settings.py (which Django expects) and then [using models without web views or urls](http://jystewart.net/2008/02... |
Find array item in a string | 5,858,916 | 4 | 2011-05-02T15:17:08Z | 5,858,943 | 19 | 2011-05-02T15:20:22Z | [
"python",
"arrays",
"string",
"find",
"match"
] | I know can use `string.find()` to find a substring in a string.
But what is the easiest way to find out if one of the array items has a substring match in a string without using a loop?
Pseudocode:
```
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
string.find(search) # == True
``` | You could use a generator expression (which somehow *is* a loop)
```
any(x in string for x in search)
```
The generator expression is the part inside the parentheses. It creates an iterable that returns the value of `x in string` for each `x` in the tuple `search`. `x in string` in turn returns whether `string` conta... |
Has anyone used ActionChains of Webdriver(python binding)? | 5,859,119 | 6 | 2011-05-02T15:36:54Z | 6,130,144 | 7 | 2011-05-25T19:59:21Z | [
"python",
"webdriver"
] | Im trying to trigger mouse over event using move\_to\_element in ActionChains, Couldn't get it working. Any help is appreciated. Thanks. | I've been toying with ActionChains in python today as well and realized that the double\_click doesn't work only click. So what's your code look like. To do any action change you have to run perform.
```
def setUp(self):
self.webdriver = webdriver.Ie()
self.mouse = webdriver.ActionChains(self.webdriver)
s... |
Shift all indices in NumPy array | 5,859,144 | 8 | 2011-05-02T15:39:52Z | 5,859,167 | 13 | 2011-05-02T15:41:37Z | [
"python",
"numpy"
] | I have a numpy array like this:
```
x=np.array([0,1,2,3,4])
```
and want to create an array where the value in index 0 is in index 1, index 1 is in index 2, etc.
The output I want is:
```
y=np.array([0,0,1,2,3]).
```
I'm guessing there's an easy way to do this without iterating through the full array. How can I do... | You can use
```
y = numpy.roll(x, 1)
y[0] = 0
```
or
```
y = numpy.r_[0, x[:-1]]
``` |
for statement in python | 5,859,539 | 3 | 2011-05-02T16:18:44Z | 5,859,577 | 8 | 2011-05-02T16:21:23Z | [
"python"
] | I'm confused about "x" in the python code below.
```
>>> # Grocery list
... grocery_list = ['apples', 'bananas', 'oranges', 'milk']
>>> for x in grocery_list:
... print(x, len(x))
```
I am confused about x's role in the for statement above. Is "x" a variable that is being defined within the for statement, or is i... | Yes it's defined within the for statement. It's just a placeholder for an element in the list and can be called anything, e.g.
```
grocery_list = ['apples', 'bananas', 'oranges', 'milk']
for grocery in grocery_list:
print(grocery, len(grocery))
``` |
Variable size list of Checkboxes in Tkinter? | 5,860,675 | 5 | 2011-05-02T18:05:21Z | 5,862,477 | 10 | 2011-05-02T21:05:48Z | [
"python",
"checkbox",
"tkinter"
] | I'm working on a programming task. I'm working in `Python`, and using `Tkinter` for our GUI. I cannot change language or GUI tool, nor can I use any additional packages (for example `Tix`).
I need to make a list of items to pull. The first thing I thought of was a check box. However, so far as I know, Tkinter does not... | Tkinter supports a relatively unlimited number of checkboxes, limited mostly by practical matters such as system memory and usability constraints.
There are at least three techniques for making a scrollable container for widgets. Both canvases and text widgets support scrolling, so the generally accepted practice is t... |
Django forms error 'got multiple values for keyword argument 'choices'' | 5,861,053 | 3 | 2011-05-02T18:44:00Z | 5,861,233 | 7 | 2011-05-02T19:00:07Z | [
"python",
"django",
"forms"
] | Getting a strange error when defining my django forms. I get the error:
```
__init__() got multiple values for keyword argument 'choices'
```
This happens with both TestForm and SpeciesForm (quoted below); basically both forms with the 'choices' keyword argument. **init**() is never explicitly called, and the forms a... | <http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L647>
```
647 def __init__(self, choices=(), required=True, widget=None, label=None,
648 initial=None, help_text=None, *args, **kwargs):
649 super(ChoiceField, self).__init__(required=required, widget=widget, label=... |
Python - Read a complicated file into dictionary | 5,861,303 | 3 | 2011-05-02T19:06:47Z | 5,861,357 | 7 | 2011-05-02T19:11:57Z | [
"python",
"file-io",
"dictionary"
] | My input file is:
```
-150 150 -90 130 1
-150 150 -150 170 1
-150 150 -110 140 1
-150 160 -80 -20 1
-150 170 -140 160 1
-150 170 -70 -40 1
-140 -170 -110 150 1
-140 130 -120 110 1
-140 140 160 -... | ```
from collections import defaultdict
bigdict = defaultdict(dict)
for ln in file:
a,b,c,d,e = ln.split()
bigdict[(a,b)][(c,d)] = e
```
If you want string keys, replace `(a,b)` with `'%s %s' % (a, b)` and similarly for `(c,d)`. |
Fast way to copy dictionary in Python | 5,861,498 | 85 | 2011-05-02T19:25:22Z | 5,861,564 | 12 | 2011-05-02T19:32:25Z | [
"python",
"performance",
"dictionary",
"copy"
] | I have a Python program that works with dictionaries a lot. I have to make copies of dictionaries thousands of times. I need a copy of both the keys and the associated contents. The copy will be edited and must not be linked to the original (e.g. changes in the copy must not affect the original.)
Keys are Strings, Val... | Can you provide a code sample so I can see how you are using copy() and in what context?
You could use
```
new = dict(old)
```
But I dont think it will be faster. |
Fast way to copy dictionary in Python | 5,861,498 | 85 | 2011-05-02T19:25:22Z | 5,861,653 | 48 | 2011-05-02T19:39:10Z | [
"python",
"performance",
"dictionary",
"copy"
] | I have a Python program that works with dictionaries a lot. I have to make copies of dictionaries thousands of times. I need a copy of both the keys and the associated contents. The copy will be edited and must not be linked to the original (e.g. changes in the copy must not affect the original.)
Keys are Strings, Val... | Appearantly dict.copy is faster, as you say.
```
[utdmr@utdmr-arch ~]$ python -m timeit -s "d={1:1, 2:2, 3:3}" "new = d.copy()"
1000000 loops, best of 3: 0.238 usec per loop
[utdmr@utdmr-arch ~]$ python -m timeit -s "d={1:1, 2:2, 3:3}" "new = dict(d)"
1000000 loops, best of 3: 0.621 usec per loop
[utdmr@utdmr-arch ~]$... |
Fast way to copy dictionary in Python | 5,861,498 | 85 | 2011-05-02T19:25:22Z | 5,861,694 | 62 | 2011-05-02T19:42:15Z | [
"python",
"performance",
"dictionary",
"copy"
] | I have a Python program that works with dictionaries a lot. I have to make copies of dictionaries thousands of times. I need a copy of both the keys and the associated contents. The copy will be edited and must not be linked to the original (e.g. changes in the copy must not affect the original.)
Keys are Strings, Val... | Looking at the [C source](http://hg.python.org/cpython/file/tip/Objects/dictobject.c) for the Python `dict` operations, you can see that they do a pretty naive (but efficient) copy. It essentially boils down to a call to `PyDict_Merge`:
```
PyDict_Merge(PyObject *a, PyObject *b, int override)
```
This does the quick ... |
Can set any property of Python object | 5,862,159 | 10 | 2011-05-02T20:34:16Z | 5,862,315 | 12 | 2011-05-02T20:49:15Z | [
"python",
"class",
"object",
"properties"
] | For example, this code is Python:
```
a = object()
a.b = 3
```
throws `AttributeError: 'object' object has no attribute 'b'`
But, this piece of code:
```
class c(object): pass
a = c()
a.b = 3
```
is just fine. Why can I assign property b, when class x does not have that property? How can I make my classes have onl... | The `object` type is a built-in class written in C and doesn't let you add attributes to it. It has been expressly coded to prevent it.
The easiest way to get the same behavior in your own classes is to use the `__slots__` attribute to define a list of the exact attributes you want to support. Python will reserve spac... |
Passing Numpy arrays to a C function for input and output | 5,862,915 | 28 | 2011-05-02T21:55:51Z | 5,863,539 | 12 | 2011-05-02T23:21:17Z | [
"python",
"numpy",
"ctypes",
"ffi"
] | **Oh my word I'm a fool.**
I was simply omitting the second and third arguments when calling the function.
Like a fool.
Because that's what I am.
Original silly question follows:
This seems like it must be a very common thing to do, but I can't find a relevant tutorial, and I'm too ignorant about `Numpy` and `ctypes` ... | Just pass all four arguments to the C function. Change your Python code from:
```
fun(ctypes.c_void_p(indata.ctypes.data), ctypes.c_void_p(outdata.ctypes.data))
```
To:
```
fun(ctypes.c_void_p(indata.ctypes.data), ctypes.c_int(5), ctypes.c_int(6),
ctypes.c_void_p(outdata.ctypes.data))
``` |
Passing Numpy arrays to a C function for input and output | 5,862,915 | 28 | 2011-05-02T21:55:51Z | 5,868,051 | 42 | 2011-05-03T10:16:43Z | [
"python",
"numpy",
"ctypes",
"ffi"
] | **Oh my word I'm a fool.**
I was simply omitting the second and third arguments when calling the function.
Like a fool.
Because that's what I am.
Original silly question follows:
This seems like it must be a very common thing to do, but I can't find a relevant tutorial, and I'm too ignorant about `Numpy` and `ctypes` ... | While not a direct answer to your original question, here's a much more convenient way to call your function. First, make the prototype of your C function exactly as you would do it in plain C. Since you don't need `rowcount` and `colcount` separately, I'll collapse them into a single `size` parameter:
```
void cfun(c... |
Python Cut Example | 5,863,999 | 7 | 2011-05-03T00:55:52Z | 5,864,013 | 10 | 2011-05-03T00:57:32Z | [
"python",
"cut"
] | I'm looking for a way in python to achieve similar functionality to the unix `cut` utility. I know I can make a system call and process my data that way but I'd like to make it a bit more "pythonic" and do it with python libraries.
Example text
```
abcde:12345
```
I'd like to delimit on `:` and keep the second field... | You can do:
```
string.split(":")[1]
```
where string is your text |
return statement in for loops | 5,864,166 | 2 | 2011-05-03T01:28:26Z | 5,864,245 | 12 | 2011-05-03T01:44:49Z | [
"python"
] | I have been working on this assignment for school and I just can't figure out what why I cant get this program to work properly. I am trying to get the program to allow the user to enter three animals. It is only allowing me to enter one. I know it has to do with my placement of the return statement in the make\_list f... | I'm only answering this again, because I notice that your subject already states the problem, and nobody's given a.. theoretical explanation, here.. theoretical being too big a word in this case, but whatever.
Your problem is, precisely, that you're putting the return statement inside the for-loop. The for-loop runs e... |
Reverse a string in Python two characters at a time (Network byte order) | 5,864,271 | 27 | 2011-05-03T01:48:53Z | 5,864,313 | 21 | 2011-05-03T01:59:03Z | [
"python",
"string",
"reverse"
] | Say you have this string:
```
ABCDEFGH
```
And you want to reverse it so that it becomes:
```
GHEFCDAB
```
What would be the most efficient / pythonic solution? I've tried a few different things but they all look horrible...
Thanks in advance!
**Update**:
In case anyone's interested, this wasn't for homework. I ... | A concise way to do this is:
```
"".join(reversed([a[i:i+2] for i in range(0, len(a), 2)]))
```
This works by first breaking the string into pairs:
```
>>> [a[i:i+2] for i in range(0, len(a), 2)]
['AB', 'CD', 'EF', 'GH']
```
then reversing that, and finally concatenating the result back together. |
Reverse a string in Python two characters at a time (Network byte order) | 5,864,271 | 27 | 2011-05-03T01:48:53Z | 5,864,372 | 13 | 2011-05-03T02:07:52Z | [
"python",
"string",
"reverse"
] | Say you have this string:
```
ABCDEFGH
```
And you want to reverse it so that it becomes:
```
GHEFCDAB
```
What would be the most efficient / pythonic solution? I've tried a few different things but they all look horrible...
Thanks in advance!
**Update**:
In case anyone's interested, this wasn't for homework. I ... | Lots of fun ways to do this
```
>>> s="ABCDEFGH"
>>> "".join(map(str.__add__, s[-2::-2] ,s[-1::-2]))
'GHEFCDAB'
``` |
Reverse a string in Python two characters at a time (Network byte order) | 5,864,271 | 27 | 2011-05-03T01:48:53Z | 5,864,723 | 9 | 2011-05-03T03:26:41Z | [
"python",
"string",
"reverse"
] | Say you have this string:
```
ABCDEFGH
```
And you want to reverse it so that it becomes:
```
GHEFCDAB
```
What would be the most efficient / pythonic solution? I've tried a few different things but they all look horrible...
Thanks in advance!
**Update**:
In case anyone's interested, this wasn't for homework. I ... | If anybody is interested, this is the timing for all\* the answers.
EDIT (had got it wrong the first time):
```
import timeit
import struct
string = "ABCDEFGH"
# Expected resutlt => GHEFCDAB
def rev(a):
new = ""
for x in range(-1, -len(a), -2):
new += a[x-1] + a[x]
return new
def rev2(a):
... |
how to use exclude option with pep8.py | 5,865,767 | 13 | 2011-05-03T06:15:30Z | 5,866,006 | 9 | 2011-05-03T06:43:26Z | [
"python",
"pep8"
] | I have a directory structure like this
```
/path/to/dir/a/foo
/path/to/dir/b/foo
```
and want to run pep8 on the directory `/path/to/dir/` excluding `/path/to/dir/a/foo`
```
pep8 --exclude='/path/to/dir/a/foo' /path/to/dir
```
and the expected output of pep8 is, it should not include the files from `/a/foo/`
but p... | You can try something like this:
```
pep8 --exclude='*/a/foo*' /path/to/dir
```
The exclude portion uses fnmatch to match against the path as seen in the [source code](https://github.com/jcrocholl/pep8/blob/master/pep8.py).
```
def excluded(filename):
"""
Check if options.exclude contains a pattern that matc... |
Neo4j and django models | 5,866,635 | 9 | 2011-05-03T07:52:15Z | 7,761,360 | 7 | 2011-10-13T22:52:56Z | [
"python",
"django",
"nosql",
"neo4j"
] | So, I'm looking into the Django and Neo4j integration, but there's not much about it out there ... What I want to know is if I have a model like the one here:
If I want to add a new property to a model, it would be as simple as doing:
```
node.setProperty( "newProperty", "something" );
```
??
Moreover, all the queri... | We've been working on updating the Neo4j/Django integration to work with [neo4j-rest-client](http://github.com/versae/neo4j-rest-client) - the fruits of our labor are [on GitHub](http://github.com/scholrly/neo4django), with some quick comments on my [blog](https://mattluongo.com/post/when-to-open-source).
There are so... |
Generating all dates within a given range in python | 5,868,130 | 6 | 2011-05-03T10:25:39Z | 5,868,217 | 13 | 2011-05-03T10:36:52Z | [
"python",
"datetime"
] | I have two string variables which contain dates in yyyy-mm-dd format as follows :
```
date1 = '2011-05-03'
date2 = '2011-05-10'
```
I want to write code that generates all dates in the range date1 to date2. How can this be done in Python? | ```
from dateutil import rrule, parser
date1 = '2011-05-03'
date2 = '2011-05-10'
dates = list(rrule.rrule(rrule.DAILY,
dtstart=parser.parse(date1),
until=parser.parse(date2)))
print dates
```
Since [**dateutil**](http://niemeyer.net/python-dateutil) is not a standar... |
Generating all dates within a given range in python | 5,868,130 | 6 | 2011-05-03T10:25:39Z | 5,869,460 | 13 | 2011-05-03T12:30:35Z | [
"python",
"datetime"
] | I have two string variables which contain dates in yyyy-mm-dd format as follows :
```
date1 = '2011-05-03'
date2 = '2011-05-10'
```
I want to write code that generates all dates in the range date1 to date2. How can this be done in Python? | Dates can be compared to each other just like numbers, and you can do date-related math with the datetime.timedelta object. There's no reason to use dateutil here, and there's no reason to hard-code the number of iterations a la 'range(9)'. This really becomes similar to how you'd deal with plain old numbers.
```
>>> ... |
Convert a string to datetime object in python | 5,868,374 | 4 | 2011-05-03T10:53:56Z | 5,868,392 | 8 | 2011-05-03T10:55:38Z | [
"python"
] | I have a date string defined as followed:
```
datestr = '2011-05-01'
```
I want to convert this into a datetime object so i used the following code
```
dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d')
print dateobj
```
But what gets printed is: 2011-05-01 00:00:00. I just need 2011-05-01. What needs to be c... | `dateobj.date()` will give you the `datetime.date` object, such as `datetime.date(2011, 5, 1)`
Use:
```
dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d').date()
```
See also: Python documentation on [datetime](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior). |
Backwards-compatible input calls in Python | 5,868,506 | 10 | 2011-05-03T11:05:21Z | 5,868,543 | 18 | 2011-05-03T11:08:24Z | [
"python",
"input",
"python-3.x",
"raw-input"
] | I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
In Python 2.x, raw\_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
One solution is to check the version ... | Since the Python 2.x version of `input()` is essentially useless, you can simply overwrite it by `raw_input`:
```
try:
input = raw_input
except NameError:
pass
```
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and ... |
Wtforms: How to generate blank value using select fields with dynamic choice values | 5,868,718 | 7 | 2011-05-03T11:24:38Z | 5,868,780 | 11 | 2011-05-03T11:30:36Z | [
"python",
"google-app-engine",
"flask",
"wtforms"
] | I'm using [Flask](http://flask.pocoo.org/) with WTForms ([doc](http://wtforms.simplecodes.com/docs/0.6/fields.html)) on Google App Engine. What is the best way to generate an field with an empty value for a select field?
```
form.group_id.choices = [(g.key().id(), g.name) for g in Group.all().order('name')]
```
Is th... | Can you just prepend an empty pair to the list?
```
form.group_id.choices.insert(0, ('', ''))
``` |
Python regex strange behavior | 5,869,650 | 9 | 2011-05-03T12:47:05Z | 5,869,740 | 9 | 2011-05-03T12:53:32Z | [
"python",
"regex"
] | I've discovered something that I can't explain in Python re module.
Compilation of `(a*)*` or `(a*|b)*` throws an error:
> raise error, v # invalid expression
> sre\_constants.error: nothing to repeat
I've tested this regexp in javascript and it seems to be ok.
Is it a bug? | Yes, it's a bug (or at least a misfeature). It's complaining that if `a*` matches nothing, it doesn't know how to capture 0 or more "nothings". |
How to calculate the axis of orientation? | 5,869,891 | 7 | 2011-05-03T13:06:17Z | 5,873,296 | 7 | 2011-05-03T17:27:11Z | [
"python",
"image-processing"
] | Previously, I calculated the axis of orientation based on anatomical structures, such as the toes in a paw.

But I found that this doesn't work when I can't distinguish between the toes very well or if the 'heel' (blue square) is way off. So I decided... | Well, here's an implementation doing the same thing as your code above (and rotating the image by the relevant angle).
However, in the case of your paws, I'm not sure it's going to work as well as it does for a human foot.
First off, for a dog's paw, the "long" axis defined this way is along the breadth of the paw in... |
Class-based (generic) views in Flask | 5,869,899 | 5 | 2011-05-03T13:07:03Z | 5,870,277 | 11 | 2011-05-03T13:35:11Z | [
"python",
"web-frameworks",
"flask",
"class-based-views"
] | What's the best way to write generic views using the Flask web framework?
Does the @app.route decorator support callable classes? Or am I thinking about this in entirely the wrong fashion?
Any help or advice would be greatly appreciated! | Starting with Python 2.6 you can apply the decorators to classes as well. There is no builtin pattern for callable classes because there are too many ways to implement them, but essentially the trick would be to override `__call__` on the class and to have a wrapper decorator that instanciates the class.
I was plannin... |
Does Flask support regular expressions in its URL routing? | 5,870,188 | 72 | 2011-05-03T13:28:02Z | 5,870,243 | 41 | 2011-05-03T13:33:17Z | [
"python",
"regex",
"flask"
] | I understand that Flask has the int, float and path converters, but the application we're developing has more complex patterns in its URLs.
Is there a way we can use regular expressions, as in Django? | You can hook in custom converters that match for arbitrary expressions: [Custom Converter](http://werkzeug.pocoo.org/docs/routing/#custom-converters)
```
from random import randrange
from werkzeug.routing import Rule, Map, BaseConverter, ValidationError
class BooleanConverter(BaseConverter):
def __init__(self, u... |
Does Flask support regular expressions in its URL routing? | 5,870,188 | 72 | 2011-05-03T13:28:02Z | 5,872,904 | 139 | 2011-05-03T16:52:45Z | [
"python",
"regex",
"flask"
] | I understand that Flask has the int, float and path converters, but the application we're developing has more complex patterns in its URLs.
Is there a way we can use regular expressions, as in Django? | Even though Armin beat me to the punch with an accepted answer I thought I'd show an abbreviated example of how I implemented a regex matcher in Flask just in case anyone wants a working example of how this could be done.
```
from flask import Flask
from werkzeug.routing import BaseConverter
app = Flask(__name__)
cl... |
Does Flask support regular expressions in its URL routing? | 5,870,188 | 72 | 2011-05-03T13:28:02Z | 16,929,323 | 11 | 2013-06-04T23:52:55Z | [
"python",
"regex",
"flask"
] | I understand that Flask has the int, float and path converters, but the application we're developing has more complex patterns in its URLs.
Is there a way we can use regular expressions, as in Django? | You could also write a catch all type of route and do complex routing within the method:
```
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'], defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST'])
def catch_all(path):
return 'You want path: %s' % path
if ... |
How to fake a soap response in Python? | 5,870,893 | 3 | 2011-05-03T14:19:56Z | 5,871,154 | 7 | 2011-05-03T14:35:47Z | [
"python",
"testing",
"soap",
"web.py",
"simplexmlrpcserver"
] | I am trying to test a function in company product. Our software will make a SOAP request like this:
**Request Header**
```
POST /testfunction.php HTTP/1.1
Accept: application/soap+xml, application/xml, text/xml
SOAPAction: "http://www.abc.com/testfunction#test"
Host: soap.abc.com
Content-Length: 461
Connection: Keep-... | You could use [soaplib](http://soaplib.github.com/soaplib/2_0/) to create a real SOAP service which implements your interface and returns dummy data. This should be a bit easier to maintain then creating handwritten static responses, and the code shouldn't be much longer than your web.py-based example.
Here's a [Hello... |
How can I subtract or add 100 years to a datetime field in the database in Django? | 5,871,168 | 14 | 2011-05-03T14:36:19Z | 5,871,888 | 33 | 2011-05-03T15:28:34Z | [
"python",
"django",
"datetime",
"django-database"
] | How can I subtract or add 100 years to a `datetime` field in the database in Django?
The date is in database, I just want to directly update the field without retrieving it out to calculate and then insert. | I would use the relativedelta function of the dateutil.relativedelta package, which will give you are more accurate 'n-years ago' calculation:
```
from dateutil.relativedelta import relativedelta
import datetime
years_ago = datetime.datetime.now() - relativedelta(years=5)
```
Then simply update the date field as oth... |
Compiling vim with specific version of Python | 5,872,079 | 22 | 2011-05-03T15:44:00Z | 5,873,320 | 13 | 2011-05-03T17:29:30Z | [
"python",
"vim"
] | I'm working on several Python projects who run on various versions of Python. I'm hoping to set up my vim environment to use ropevim, pyflakes, and pylint but I've run into some issues caused by using a single vim (compiled for a specific version of Python which doesn't match the project's Python version).
I'm hoping ... | I'd recommend building vim against the 2 interpreters, then invoking it using the shell script I provided below to point it to a particular virtualenv.
I was able to build vim against Python 2.7 using the following command (2.7 is installed under $HOME/root):
```
% LD_LIBRARY_PATH=$HOME/root/lib PATH=$HOME/root/bin:$... |
Compiling vim with specific version of Python | 5,872,079 | 22 | 2011-05-03T15:44:00Z | 23,095,537 | 7 | 2014-04-15T22:14:58Z | [
"python",
"vim"
] | I'm working on several Python projects who run on various versions of Python. I'm hoping to set up my vim environment to use ropevim, pyflakes, and pylint but I've run into some issues caused by using a single vim (compiled for a specific version of Python which doesn't match the project's Python version).
I'm hoping ... | For what it's worth, and no one seems to have answered this here, I had some luck using a command line like the following:
vi\_cv\_path\_python=/usr/bin/python26 ./configure --includedir=/usr/include/python2.6/ --prefix=/home/bcrowder/local --with-features=huge --enable-rubyinterp --enable-pythoninterp --disable-selin... |
Generating json in python for app engine | 5,872,144 | 9 | 2011-05-03T15:48:39Z | 5,872,179 | 18 | 2011-05-03T15:51:41Z | [
"python",
"json",
"google-app-engine"
] | I am somewhat new to python and I am wondering what the best way is to generate json in a loop. I could just mash a bunch of strings together in the loop, but I'm sure there is a better way. Here's some more specifics. I am using app engine in python to create a service that returns json as a response.
So as an exampl... | Creating your own JSON is silly. Use `json` or `simplejson` for this instead.
```
>>> json.dumps(dict(foo=42))
'{"foo": 42}'
``` |
Generating json in python for app engine | 5,872,144 | 9 | 2011-05-03T15:48:39Z | 5,872,508 | 7 | 2011-05-03T16:17:40Z | [
"python",
"json",
"google-app-engine"
] | I am somewhat new to python and I am wondering what the best way is to generate json in a loop. I could just mash a bunch of strings together in the loop, but I'm sure there is a better way. Here's some more specifics. I am using app engine in python to create a service that returns json as a response.
So as an exampl... | > My question is how do I add to the
> dictionary dynamically? So foreach
> record in my list of records, add a
> record to the dictionary.
You may be looking to create a list of dictionaries.
```
records = []
record1 = {"name":"Bob", "email":"bob@email.com"}
records.append(record1)
record2 = {"name":"Bob2", "ema... |
Converting a hexadecimal character to an int in Python | 5,873,072 | 2 | 2011-05-03T17:06:38Z | 5,873,097 | 8 | 2011-05-03T17:08:56Z | [
"python",
"numpy",
"pyglet"
] | I'm using the graphics library [Pyglet](http://en.wikipedia.org/wiki/Pyglet) to do some drawing and want to get the resulting image out as a Python list (so I can convert it to a [NumPy](http://en.wikipedia.org/wiki/NumPy) array).
Pyglet gives me a string of hex characters, like this: '\xff' (indicating a value of 255... | To get a NumPy array straight from a Python string, you can use
```
s = "\xff\x03"
a = numpy.frombuffer(s, numpy.uint8)
```
To get a list you can use
```
a = map(ord, s)
```
An alternative to a list in Python 2.6 or above is to use `bytesarray(s)`. |
Python: How to pass arguments to the __code__ of a function? | 5,874,558 | 21 | 2011-05-03T19:24:41Z | 5,874,844 | 8 | 2011-05-03T19:47:09Z | [
"python",
"function",
"exec",
"eval",
"argument-passing"
] | The following works:
```
def spam():
print "spam"
exec(spam.__code__)
```
> spam
But what if `spam` takes arguments?
```
def spam(eggs):
print "spam and", eggs
exec(spam.__code__)
```
> TypeError: spam() takes exactly 1 argument (0 given)
Given, that I don't have access to the function itself but only to ... | Can you change the function to *not* take any arguments? The variables is then looked up from the locals/globals where you can supply into `exec`:
```
>>> def spam():
... print "spam and", eggs
...
>>> exec(spam.__code__, {'eggs':'pasta'})
spam and pasta
```
(Why not just send the whole function as a string? Pickl... |
Python: How to pass arguments to the __code__ of a function? | 5,874,558 | 21 | 2011-05-03T19:24:41Z | 5,874,866 | 13 | 2011-05-03T19:49:07Z | [
"python",
"function",
"exec",
"eval",
"argument-passing"
] | The following works:
```
def spam():
print "spam"
exec(spam.__code__)
```
> spam
But what if `spam` takes arguments?
```
def spam(eggs):
print "spam and", eggs
exec(spam.__code__)
```
> TypeError: spam() takes exactly 1 argument (0 given)
Given, that I don't have access to the function itself but only to ... | **I am completely against this use of \_\_code\_\_.**
Although I am a curious person, and this is what someone theoretically could do:
```
code # This is your code object that you want to execute
def new_func(eggs): pass
new_func.__code__ = code
new_func('eggs')
```
Again, I never want to see this used, ever. You m... |
Is there a native HTML parsing module for Python 3.2? | 5,874,648 | 2 | 2011-05-03T19:33:17Z | 5,874,686 | 8 | 2011-05-03T19:36:17Z | [
"python",
"html",
"python-3.x"
] | I am trying to parse some html. I would like something like `sgmllib` but it is deprecated in python 3.2.
Is there an alternate module that I can use?
Thanks. | Built-in HTMLParser module:
<http://docs.python.org/py3k/library/html.parser.html>
Not native but worth to mention;
BeautifulSoup:
<http://www.crummy.com/software/BeautifulSoup/> |
Running a specific test case in Django when your app has a tests directory | 5,875,111 | 64 | 2011-05-03T20:11:34Z | 5,875,223 | 72 | 2011-05-03T20:20:41Z | [
"python",
"django",
"unit-testing"
] | The Django documentation (<http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests>) says that you can run individual test cases by specifying them:
```
$ ./manage.py test animals.AnimalTestCase
```
This assumes that you have your tests in a tests.py file in your Django application. If this is true, then t... | Checkout [django-nose](https://github.com/jbalogh/django-nose). It allows you to specify tests to run like:
```
python manage.py test another.test:TestCase.test_method
``` |
Running a specific test case in Django when your app has a tests directory | 5,875,111 | 64 | 2011-05-03T20:11:34Z | 21,985,517 | 79 | 2014-02-24T10:46:31Z | [
"python",
"django",
"unit-testing"
] | The Django documentation (<http://docs.djangoproject.com/en/1.3/topics/testing/#running-tests>) says that you can run individual test cases by specifying them:
```
$ ./manage.py test animals.AnimalTestCase
```
This assumes that you have your tests in a tests.py file in your Django application. If this is true, then t... | Since Django 1.6 you can run a complete test case, or single test, using the complete dot notation for the element you want to run.
Automatic test discovery will now find tests in any file that starts with **test** under the working directory, so addressing the question you would have to rename your files, but you can... |
How to close a socket left open by a killed program? | 5,875,177 | 25 | 2011-05-03T14:14:31Z | 5,875,178 | 26 | 2011-05-03T15:00:44Z | [
"python",
"linux",
"sockets",
"networking",
"tcp"
] | I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time.
The next time I go to run the program I get this error... | Assume your socket is named `s`... you need to set `socket.SO_REUSEADDR` on the server's socket before binding to an interface... this will allow you to immediately restart a TCP server...
```
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ADDR, PORT))
``` |
How to close a socket left open by a killed program? | 5,875,177 | 25 | 2011-05-03T14:14:31Z | 5,877,406 | 10 | 2011-05-04T01:04:04Z | [
"python",
"linux",
"sockets",
"networking",
"tcp"
] | I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time.
The next time I go to run the program I get this error... | You might want to try using Twisted for your networking. Mike gave the correct low-level answer, `SO_REUSEADDR`, but he didn't mention that this isn't a very good option to set on Windows. This is the sort of thing that Twisted takes care of for you automatically. There are many, many other examples of this kind of bor... |
Weird: logger only uses the formatter of the first handler for exceptions | 5,875,225 | 8 | 2011-05-03T20:20:48Z | 5,879,524 | 8 | 2011-05-04T06:40:15Z | [
"python",
"logging"
] | I'm witnessing the logging module behaving in a funny way. Am I missing something ?
I'm doing the usual thing of having two handlers: a StreamHandler for logging only INFO and higher to the console, and a FileHandler that will also handle all the DEBUG information.
It worked fine until I decided to have a different f... | This is the code I came up with. It does the job :).
```
class CachelessFormatter(logging.Formatter):
# I came up with that after reading the answers to
# http://stackoverflow.com/questions/5875225/
# which pointed me to
# http://bugs.python.org/issue6435
# I still think Vinay Sajip has a b... |
Python and vim on windows? | 5,875,883 | 8 | 2011-05-03T21:24:22Z | 5,876,030 | 7 | 2011-05-03T21:37:10Z | [
"python",
"windows",
"vim",
"ide"
] | I started learning vim a couple of days ago and surprisingly it felt quite natural to me, I also want to get back to learning python. I thought, why not combine the two?
So now I'm looking how to set up a proper python development environment, all my searches turned up either guides for other OSes (which I just could... | Good choice on VIM!
Have a look here though:
<http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/> |
In a Python object, how can I see a list of properties that have been defined with the @property decorator? | 5,876,049 | 11 | 2011-05-03T21:39:44Z | 5,876,258 | 12 | 2011-05-03T22:01:20Z | [
"python",
"python-2.6",
"python-2.7"
] | I can see first-class member variables using `self.__dict__`, but I'd like also to see a dictionary of properties, as defined with the [@property](http://docs.python.org/library/functions.html#property) decorator. How can I do this? | You could add a function to your class that looks something like this:
```
def properties(self):
class_items = self.__class__.__dict__.iteritems()
return dict((k, getattr(self, k))
for k, v in class_items
if isinstance(v, property))
```
This looks for any properties in the cl... |
Pause before retry connection in Python | 5,876,159 | 2 | 2011-05-03T21:50:13Z | 5,876,175 | 7 | 2011-05-03T21:51:58Z | [
"python",
"python-3.x",
"urllib"
] | I am trying to connect to a server. Sometimes I cannot reach the server and would like to pause for a few seconds before trying again. How would I implement the pause feature in Python. Here is what I have so far. Thank you.
```
while True:
try:
response = urllib.request.urlopen(http)
ex... | This will block the thread for 2 seconds before continuing:
```
import time
time.sleep(2)
``` |
reversing list using slice notation | 5,876,998 | 32 | 2011-05-03T23:45:54Z | 5,877,008 | 52 | 2011-05-03T23:48:15Z | [
"python",
"list",
"syntax",
"slice"
] | in the following example:
```
foo = ['red', 'white', 'blue', 1, 2, 3]
```
where: `foo[0:6:1]` will print all elements in foo. However, `foo[6:0:-1]` will omit the 1st or 0th element.
```
>>> foo[6:0:-1]
[3, 2, 1, 'blue', 'white']
```
I understand that I can use foo.reverse() or foo[::-1] to print the list in revers... | Slice notation in short:
```
[ <first element to include> : <first element to exclude> : <step> ]
```
If you want to include the first element when reversing a list, leave the middle element empty, like this:
```
foo[::-1]
```
You can also find some good information about Python slices in general here:
[The Pytho... |
Python * imports | 5,877,218 | 12 | 2011-05-04T00:25:29Z | 5,877,250 | 9 | 2011-05-04T00:30:53Z | [
"python",
"pyqt",
"python-import"
] | I've generally been told that the following is bad practice.
```
from module import *
```
The main reasoning (or so I've been told), is that you could possibly import something you didn't want, and it could shadow a similarly named function or class from another module.
However, what about PyQt
```
from PyQt4.QtCor... | This can sort of turn into a religious war. It's a matter of whether you want to be explicit or whether you want to avoid being too verbose. In general, following the [Zen of Python](http://www.python.org/dev/peps/pep-0020/), it's better to be explicit, but sometimes people just don't find it practical to list every im... |
Django non blocking email? Downsides to threading.thread or subprocess? | 5,877,658 | 5 | 2011-05-04T01:56:26Z | 5,877,718 | 9 | 2011-05-04T02:08:47Z | [
"python",
"django",
"multithreading"
] | I have a django site. Certain actions by the end user send email to the rest of users in a group.
When the number of users gets to be > 20 it can add 1-3 seconds to the request cycle, which I don't like. I'd like to be able to send the email from a non-blocking function.
I know RabbitMQ and Celery in conjunction can ... | Offloading the work to some other external process is really the right thing to do, and once you've done it, it's not likely to be the last time you do it. Celery/RabbitMQ is a decent solution, and the nice thing is they're already there. Recent RabbitMQ releases have a decent web-based management app and a decent mana... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.