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 Equivalent to Ruby's #each_cons?
5,878,403
8
2011-05-04T04:06:27Z
5,878,445
9
2011-05-04T04:12:12Z
[ "python", "ruby", "enumerable", "equivalent" ]
Is there a Pythonic equivalent to Ruby's `#each_cons`? In Ruby you can do this: ``` array = [1,2,3,4] array.each_cons(2).to_a => [[1,2],[2,3],[3,4]] ```
For such things, `itertools` is the module you should be looking at: ``` from itertools import tee, izip def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b) ``` Then: ``` >>> list(pairwise([1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] ``` Fo...
Python Equivalent to Ruby's #each_cons?
5,878,403
8
2011-05-04T04:06:27Z
5,878,474
12
2011-05-04T04:17:30Z
[ "python", "ruby", "enumerable", "equivalent" ]
Is there a Pythonic equivalent to Ruby's `#each_cons`? In Ruby you can do this: ``` array = [1,2,3,4] array.each_cons(2).to_a => [[1,2],[2,3],[3,4]] ```
I don't think there is one, I looked through the built-in module `itertools`, which is where I would expect it to be. You can simply create one though: ``` def each_cons(x, size): return [x[i:i+size] for i in range(len(x)-size+1)] ```
What is the pythonic way to remove trailing spaces from a string?
5,879,033
3
2011-05-04T05:34:50Z
5,879,090
8
2011-05-04T05:41:25Z
[ "python" ]
The parameter to the function satisfy these rules: 1. It does not have any leading whitespace 2. It might have trailing whitespaces 3. There might be interleaved whitespaces in the string. Goal: remove duplicate whitespaces that are interleaved & strip trailing whitespaces. This is how I am doing it now: ``` # toks...
This is how I would do it: ``` " ".join(toks.split()) ``` PS. Is there a subliminal message in this question? ;-)
Run python script without the "python" keyword
5,879,869
8
2011-05-04T07:17:49Z
5,879,898
15
2011-05-04T07:20:22Z
[ "python", "osx", "terminal" ]
How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files? Right now I have to do this: `python script.py` What I like to do is this: `script.py`
in your python script add this as your first line ``` #!/usr/bin/python ``` then in terminal do this chmod +x ./yourpythonscript.py then from terminal execute as ./yourpythonscript.py
Run python script without the "python" keyword
5,879,869
8
2011-05-04T07:17:49Z
5,879,916
11
2011-05-04T07:21:50Z
[ "python", "osx", "terminal" ]
How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files? Right now I have to do this: `python script.py` What I like to do is this: `script.py`
Add a shebang: ``` #!/usr/bin/python ``` or ``` #!/usr/bin/env python ``` I prefer the second one, since Python can be anywhere like /usr/bin/python, /usr/local/bin/python etc. and second one ensure that you don't have to keep editing the shebang. And then you can just execute it as `./script.py` if it is executab...
Python: pass method as argument in function
5,881,615
6
2011-05-04T09:56:43Z
5,882,113
8
2011-05-04T10:39:06Z
[ "python", "methods", "arguments" ]
I've seen a lot of posts but none really addressing my question. With Python, I am trying to pass a method as an argument in a function which requires two arguments: ``` # this is a method within myObject def getAccount(self): account = (self.__username, self.__password) return account # this is a function fro...
You want to use [python argument unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists): ``` myData = myModule.logIn( * myObject.getAccount() ) ``` The `*` before an argument to a function signals that the following tuple should be split into its constituents and passed as positional ar...
How to calculate longitude using PyEphem
5,881,897
4
2011-05-04T10:21:50Z
6,221,380
11
2011-06-02T23:07:00Z
[ "python", "astronomy", "pyephem" ]
tried to calculate sun lat and long using PyEphem but not matching with ephemeris SUN: 2011 MAY 04 We 04 14:46:08 13TA12 = 43 degrees approx (As per website www.findyourfate.com) ``` a = Sun() a.compute('2011-05-04') >>> a.hlon 274:18:49.1 >>> a.hlat 0:00:00.1 ``` What could be wrong? How to calculate longitude of...
An interesting question, deserving a detailed answer. First problem. PyEphem takes its dates in the form `YYYY/mm/dd`, not `YYYY-mm-dd`. ``` >>> from ephem import * >>> Date('2011-05-04') 2010/6/26 00:00:00 >>> Date('2011/05/04') 2011/5/4 00:00:00 ``` (This behaviour seems extremely unhelpful. [I reported it to Bran...
python search and replace operation
5,882,221
5
2011-05-04T10:48:04Z
5,882,250
7
2011-05-04T10:50:43Z
[ "python", "replace" ]
i have a list which has url values like : <http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg> How can i change the \_s in the end to \_m for all occurences?
Try this: ``` str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg" str = str.replace("_s","_m") ``` If you want to be sure that only the las part is changed and you know all are `.jpg` files you can use: ``` str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg" str = str.replace(...
How to create a PDF document with differing page sizes in reportlab, python
5,882,636
8
2011-05-04T11:28:38Z
5,897,460
10
2011-05-05T12:14:08Z
[ "python", "pdf", "reportlab" ]
Is it possible to create a PDF document with differing page sizes in reportlab? I would like to create a document where the first page has a different size then the other pages. Can anyone help?
Yes, this should be possible, since PDF supports this, it's just a question of how to make it happen in ReportLab. I've never done this, but the following should work: ``` c = reportlab.pdfgen.canvas.Canvas("test.pdf") # draw some stuff on c c.showPage() c.setPageSize((700, 500)) #some page size, given as a tuple in p...
Recursion over a list of lists without isinstance()
5,882,728
5
2011-05-04T11:37:37Z
5,882,911
10
2011-05-04T11:52:11Z
[ "python", "isinstance" ]
I have just read ["isinstance() considered harmful"](http://www.canonical.org/~kragen/isinstance/), and it seems reasonable. In short, it argues for avoiding the use of this function. Well, just now I happen to be writing a program which takes inputs structured as a tree, and needs the tree's structure information. Wi...
Your situation is one of those where I would use `isinstance`. Your data structure is well-constrained, and you need to distinguish between a list and not a list. Use `isinstance` to ask if it is a list. You don't say, but I imagine strings might be among the leaves of your tree, and they are iterable as lists are, so ...
How to retry urlfetch.fetch a few more times in case of error?
5,883,116
5
2011-05-04T12:08:48Z
5,883,291
9
2011-05-04T12:23:09Z
[ "python", "google-app-engine", "exception-handling" ]
Quite often GAE is not able to upload the file and I am getting the following error: ``` ApplicationError: 2 Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__ handler.post(*groups) File "/base/data/home/apps/picas...
If you can, move this work into [the task queue](http://code.google.com/appengine/docs/python/taskqueue/overview.html). When tasks fail, they retry automatically. If they continue to fail, the system gradually backs off retry frequency to as slow as once-per hour. This is an easy way to handle API requests to rate-limi...
Python: Add item to list until a condition is true
5,883,265
6
2011-05-04T12:21:07Z
5,883,351
9
2011-05-04T12:27:30Z
[ "list", "python" ]
Normal list comprehensions occur this way: ``` new_list = [f(x) for x in l] ``` What is the most succinct and readable way to create new list in Python similar to this: ``` new_list = [f(x) while condition is True] ```
Keep it simple: ``` new_list = [] while condition: new_list.append(f(x)) ``` There is no benefit to forcing something into a single expression when it is more clearly written as separate statements.
Using Numpy with pypy
5,883,885
18
2011-05-04T13:06:19Z
5,886,538
21
2011-05-04T16:16:06Z
[ "python", "numpy", "pypy" ]
I am using some numpy tools (mainly arrays) and I wanted to run the script with pypy, but i can't make it work. The error that i get is: `ImportError: No module named multiarray.` I checked if the multiarray.so file was in the core folder. Can someone tell me if first: is possible to do what I am trying to do and se...
I've just posted a [blog post](http://morepypy.blogspot.com/2011/05/numpy-in-pypy-status-and-roadmap.html) explaining what's the status and what's the plan. In short numpy will not work with PyPy's cpyext and even if it does, it would be too slow for usage.
Using Numpy with pypy
5,883,885
18
2011-05-04T13:06:19Z
18,433,416
15
2013-08-25T20:34:34Z
[ "python", "numpy", "pypy" ]
I am using some numpy tools (mainly arrays) and I wanted to run the script with pypy, but i can't make it work. The error that i get is: `ImportError: No module named multiarray.` I checked if the multiarray.so file was in the core folder. Can someone tell me if first: is possible to do what I am trying to do and se...
The other answers are quite old. Here is the `the completely unscientific measure of "implemented functions" on` [numpypy status page](http://buildbot.pypy.org/numpy-status/latest.html) Some posts from the pypy blog about numpy: 1. [MAY 4, 2011](http://morepypy.blogspot.com.br/2011/05/numpy-in-pypy-status-and-roadma...
Using Numpy with pypy
5,883,885
18
2011-05-04T13:06:19Z
22,748,157
8
2014-03-30T18:40:58Z
[ "python", "numpy", "pypy" ]
I am using some numpy tools (mainly arrays) and I wanted to run the script with pypy, but i can't make it work. The error that i get is: `ImportError: No module named multiarray.` I checked if the multiarray.so file was in the core folder. Can someone tell me if first: is possible to do what I am trying to do and se...
Numpy status and build instruction has been changed recently. There is a special version of numpy which is ported to PyPy. If you want to get latest instruction just check [PyPy blog](http://morepypy.blogspot.com/) for a latest article about Numpy. For the time of writing the latest instruction are in [this post](http:...
Hashing a python dictionary
5,884,066
58
2011-05-04T13:19:38Z
5,884,123
51
2011-05-04T13:24:33Z
[ "python", "hash", "dictionary" ]
For caching purposes I need to generate a cache key from GET arguments which are present in a dict. Currently I'm using `sha1(repr(sorted(my_dict.items())))` (`sha1()` is a convenience method that uses hashlib internally) but I'm curious if there's a better way.
If your dictionary is not nested, you could make a frozenset with the dict's items and use [`hash()`](https://docs.python.org/2/library/functions.html#hash): ``` hash(frozenset(my_dict.items())) ``` This is much less computationally intensive than generating the JSON string or representation of the dictionary.
Hashing a python dictionary
5,884,066
58
2011-05-04T13:19:38Z
8,714,242
42
2012-01-03T15:05:37Z
[ "python", "hash", "dictionary" ]
For caching purposes I need to generate a cache key from GET arguments which are present in a dict. Currently I'm using `sha1(repr(sorted(my_dict.items())))` (`sha1()` is a convenience method that uses hashlib internally) but I'm curious if there's a better way.
**EDIT**: If *all your keys are strings*, then before continuing to read this answer, please see Jack O'Connor's significantly simpler (and faster) solution below (which also works for hashing nested dictionaries). Although an answer has been accepted, the title of the question is "Hashing a python dictionary", and th...
Hashing a python dictionary
5,884,066
58
2011-05-04T13:19:38Z
22,003,440
41
2014-02-25T02:29:57Z
[ "python", "hash", "dictionary" ]
For caching purposes I need to generate a cache key from GET arguments which are present in a dict. Currently I'm using `sha1(repr(sorted(my_dict.items())))` (`sha1()` is a convenience method that uses hashlib internally) but I'm curious if there's a better way.
Using `sorted(d.items())` isn't enough to get us a stable repr. Some of the values in `d` could be dictionaries too, and their keys will still come out in an arbitrary order. As long as all the keys are strings, I prefer to use: ``` json.dumps(d, sort_keys=True) ``` That said, if the hashes need to be stable across d...
Python: Assign print output to a variable
5,884,517
8
2011-05-04T13:54:35Z
5,884,567
15
2011-05-04T13:57:51Z
[ "python", "function", "unix", "variables" ]
I would like to know how to assign the output of the `print` function (or any function) to a variable. To give an example: ``` import eyeD3 tag = eyeD3.Tag() tag.link("/some/file.mp3") print tag.getArtist() ``` How do I assign the output of `print tag.getArtist` to a variable?
The `print` statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string: ``` a = str(tag.getArtist()) ```
NoSQL abstraction layer for Python
5,884,747
10
2011-05-04T14:12:11Z
5,891,041
8
2011-05-04T23:30:12Z
[ "python", "mongodb", "nosql", "redis" ]
Does anybody know of an abstraction layer for nosql databases for Python similar to [SQL Alchemy](http://sqlalchemy.org) for SQL? This would allow [redis](http://redis.io), [mongodb](http://mongodb.com), etc... to be pluggable backends without having to write for each one specifically.
> This would allow redis, mongodb, etc... to be pluggable backends without having to write for each one specifically. There is django-nonrel, but that library seems to be converting SQL actions into the various library actions. The major problem here is that these things are not really the same at all. In particular,...
skew normal distribution in scipy
5,884,768
10
2011-05-04T14:13:33Z
5,885,349
22
2011-05-04T14:49:53Z
[ "python", "statistics", "distribution", "scipy" ]
Does anyone know how to plot a skew normal distribution with scipy? I supose that stats.norm class can be used but I just can't figure out how. Furthermore, how can I estimate the parameters describing the skew normal distribution of a unidimensional dataset?
From the Wikipedia [description](http://en.wikipedia.org/wiki/Skew_normal_distribution), ``` from scipy import linspace from scipy import pi,sqrt,exp from scipy.special import erf from pylab import plot,show def pdf(x): return 1/sqrt(2*pi) * exp(-x**2/2) def cdf(x): return (1 + erf(x/sqrt(2))) / 2 def skew...
Installing Python eggs under PyPy
5,885,820
15
2011-05-04T15:23:08Z
5,894,355
13
2011-05-05T07:49:46Z
[ "python", "development-environment", "pypy" ]
**How do I install Python egg under PyPy?** During installation, PyPy created `/usr/lib64/pypy-1.5/site-packages/` directory. So, I tried using easy\_install with prefix set to this directory, however it complains that this is not a valid directory for eggs. Do I just copy eggs from `/usr/lib/python2.7/site-packages`,...
First, you need to make sure that you have distribute installed specifically for PyPy. I don't know how fedora packages things, but in general installing a package for cpython does not make it available also for PyPy. In particular, /usr/bin/easy\_install is probably CPython-only. If you use a "normal" install of PyPy...
thread dying without exception
5,885,928
2
2011-05-04T15:30:50Z
5,886,369
8
2011-05-04T16:02:05Z
[ "python", "multithreading" ]
I'm having an issue with some of my worker threads. I've added a catchall exception statement in the thread's run method like so: ``` try: """Runs the worker process, which is a state machine""" while self._set_exitcode is None : assert self._state in Worker.STATES state_method...
You could try examining the [execution trace of your program using the `trace` module](http://docs.python.org/library/trace.html). For example: ``` % python -m trace -c -t -C ./coverage test_exit.py ``` Source: ``` import sys import threading class Worker(object): def run(self): try: sys.exi...
In Python, why do I get an 'undefined local variable' error for counters but not for lists?
5,885,978
2
2011-05-04T15:34:09Z
5,886,001
9
2011-05-04T15:35:48Z
[ "python" ]
If I alter a variable declared at the top of the file/module from within a method (no classes involved), it only works in the case of lists/containers, but not if my variable was a simple counter. See the following code for example: ``` counter = 0 counterList = [] def incrementCounter(): counter += 1 def addToL...
Try ``` def incrementCounter(): global counter counter += 1 ``` The assignment to `counter` inside `incrementCounter()` otherwise implicitely makes `counter` local to that function. The line `counter += 1` does not actually change the integer object `counter` points to -- integers are immutable in Python. Th...
Print a stack trace to stdout on errors in Django while using manage.py runserver
5,886,275
14
2011-05-04T15:53:05Z
5,886,462
17
2011-05-04T16:09:15Z
[ "python", "django" ]
I did some searching, but I'm wondering if anyone has a snippet of a logging configuration to get Django to just output a stack trace to stdout (so I can see it in the Terminal window) when it encounters an error during a request. This is specifically for local development/debugging and mainly for when I do AJAX post r...
You can create a piece of middleware to do this. Here's a modified snippet I'm using for a project: ``` class ExceptionLoggingMiddleware(object): def process_exception(self, request, exception): import traceback print traceback.format_exc() ``` Place this handler in your middleware part of the Dja...
Print a stack trace to stdout on errors in Django while using manage.py runserver
5,886,275
14
2011-05-04T15:53:05Z
23,818,374
22
2014-05-22T22:54:58Z
[ "python", "django" ]
I did some searching, but I'm wondering if anyone has a snippet of a logging configuration to get Django to just output a stack trace to stdout (so I can see it in the Terminal window) when it encounters an error during a request. This is specifically for local development/debugging and mainly for when I do AJAX post r...
Another method is with *LOGGING*. Specifically you get a stacktrace when running `./manage.py runserver` by adding the following to the *settings.py* file: ``` LOGGING = { 'version': 1, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, },...
How to make a query that filters rows in which one column equals another one of the same table?
5,886,819
7
2011-05-04T16:40:45Z
5,886,867
11
2011-05-04T16:44:02Z
[ "python", "django", "django-queryset" ]
Say I have a model that looks like: ``` class StockRequest(models.Model): amount_requested = models.PositiveIntegerField(null=True) amount_approved = models.PositiveIntegerField(null=True) ``` Is there any way to make a django query that would show me all requests where there is some relationship between amou...
``` from django.db.models import F StockRequest.objects.filter(amount_requested=F("amount_approved")) ``` <http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model>
True or false output based on a probability
5,886,987
7
2011-05-04T16:52:08Z
5,887,040
26
2011-05-04T16:56:15Z
[ "python", "scientific-computing" ]
Is there a standard function for Python which outputs True or False probabilistically based on the input of a random number from 0 to 1? example of what I mean: ``` def decision(probability): ...code goes here... return ...True or False... ``` the above example if given an input of, say, 0.7 will return True...
``` import random def decision(probability): return random.random() < probability ```
SPARQL query on the remote remote endpoint RDFLib / Redland
5,888,020
7
2011-05-04T18:17:17Z
5,894,577
11
2011-05-05T08:12:33Z
[ "python", "rdf", "sparql", "rdflib", "redland" ]
I'm trying to query remote endpoints and get get owl:sameAs mappings, I've tried both RDFLib and Redland but neither worked for me, probably I'm not dealing with namespaces correctly. Here is my attempt in RDFLib: ``` import rdflib rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.pr...
Various things: You are right, you need to enclose any URI within `<` `>`. The correct query is: ``` SELECT ?s ?o WHERE { ?s a <http://purl.org/ontology/mo/MusicArtist>; <http://www.w3.org/2002/07/owl#sameAs> ?o . } limit 50 ``` ... see the results [here](http://api.talis.com/stores/bbc-back...
What's a convenient way of resolving a path /bar/foo/baz/../.. into /bar?
5,888,074
3
2011-05-04T18:21:05Z
5,888,104
9
2011-05-04T18:22:40Z
[ "python" ]
Is there a module capable of doing this, or should I write something myself?
What's about this : ``` >>> os.path.normpath("/bar/foo/baz/../..") "/bar" ```
Python regex matching in conditionals
5,888,213
11
2011-05-04T18:30:35Z
5,888,259
11
2011-05-04T18:35:00Z
[ "python", "regex", "conditional" ]
I am parsing file and I want to check each line against a few complicated regexs. Something like this ``` if re.match(regex1, line): do stuff elif re.match(regex2, line): do other stuff elif re.match(regex3, line): do still more stuff ... ``` Of course, to do the stuff, I need the match objects. I can only think of t...
You could define a function for the action required by each regex and do something like ``` def dostuff(): stuff def dootherstuff(): otherstuff def doevenmorestuff(): evenmorestuff actions = ((regex1, dostuff), (regex2, dootherstuff), (regex3, doevenmorestuff)) for regex, action in actions: m = re....
How do I compile a PyQt script (.py) to a single standalone executable file for windows (.exe) and/or linux?
5,888,870
19
2011-05-04T19:32:07Z
5,916,707
15
2011-05-06T20:33:20Z
[ "python", "qt4", "compilation", "executable", "pyqt4" ]
I started to fiddle with PyQt, and made a "beautiful" script from the pyqt whitepaper example app ([pastebin](http://pastebin.com/NZnpxv2F)) It works perfectly in Windows and Linux (with qt environment already installed on both). Now my question is: Since I am trying to use Qt because it is compiled (at least pure ol...
if you want completelly to create one stand alone executable, you can try this : <http://www.pyinstaller.org/> . i feel it's better to create one stand alone executable than cx\_freeze or py2exe (in my experience). and easy to use (full documentation available in the site). But unfortunatelly **PyInstaller** does not s...
AttributeError: 'module' object has no attribute 'maketrans' while running cProfile
5,889,466
5
2011-05-04T20:29:38Z
5,890,021
7
2011-05-04T21:20:57Z
[ "python", "profiler" ]
Using python 2.7 I get this error: ``` Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/cProfile.py",...
As the [Python tutorial on modules](http://docs.python.org/tutorial/modules.html#the-module-search-path) explains: > Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and th...
One liner to determine if dictionary values are all empty lists or not
5,889,611
7
2011-05-04T20:42:32Z
5,889,662
8
2011-05-04T20:47:53Z
[ "python" ]
I have a dict as follows: ``` someDict = {'a':[], 'b':[]} ``` I want to determine if this dictionary has any values which are not empty lists. If so, I want to return True. If not, I want to return False. Any way to make this a one liner?
Per my testing, the following one-liner (my original answer) has best time performance in all scenarios. See edits below for testing information. I do acknowledge that solutions using generator expressions will be much more memory efficient and should be preferred for large dicts. **EDIT: This is an aging answer and t...
How to make string check case insensitive in Python 3.2?
5,889,944
5
2011-05-04T21:13:17Z
5,889,970
13
2011-05-04T21:15:38Z
[ "python", "string", "printing" ]
I've started learning Python recently and as a practise I'm working on a text-based adventure game. Right now the code is really ineffective as it checks the user responce to see if it is the same as several variations on the same word. How do I change it so the string check is case insensitive in Python 3.2? Example ...
``` if 'power' in choice.lower(): ``` should do (assuming `choice` is a string). This will be true if `choice` *contains* the word `power`. If you want to check for equality, use `==` instead of `in`. Also, if you want to make sure that you match `power` only as a whole word (and not as a part of `horsepower` or `pow...
Stopwatch In Python
5,890,304
16
2011-05-04T21:53:23Z
5,890,406
20
2011-05-04T22:03:09Z
[ "python", "time" ]
I'm trying to create a simple game where the point is to collect as many blocks as you can in a certain amount of time, say 10 seconds. How can I get a stopwatch to begin ticking at the start of the program and when it reaches 10 seconds, do something (in this case, exit a loop)?
``` import time now = time.time() future = now + 10 while time.time() < future: # do stuff pass ``` Alternatively, if you've already got your loop: ``` while True: if time.time() > future: break # do other stuff ``` This method works well with [pygame](http://pygame.org), since it pretty muc...
NumPy array initialization (fill with identical values)
5,891,410
71
2011-05-05T00:34:20Z
5,891,447
53
2011-05-05T00:40:59Z
[ "python", "arrays", "numpy" ]
I need to create a NumPy array of length `n`, each element of which is `v`. Is there anything better than: ``` a = empty(n) for i in range(n): a[i] = v ``` I know `zeros` and `ones` would work for v = 0, 1. I could use `v * ones(n)`, but it won't work when `v` is `None`, and also would be much slower.
I believe [`fill`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html) is the fastest way to do this. ``` a = np.empty(10) a.fill(7) ``` You should also always avoid iterating like you are doing in your example. A simple `a[:] = v` will accomplish what your iteration does using numpy [broadca...
NumPy array initialization (fill with identical values)
5,891,410
71
2011-05-05T00:34:20Z
13,052,254
64
2012-10-24T15:19:40Z
[ "python", "arrays", "numpy" ]
I need to create a NumPy array of length `n`, each element of which is `v`. Is there anything better than: ``` a = empty(n) for i in range(n): a[i] = v ``` I know `zeros` and `ones` would work for v = 0, 1. I could use `v * ones(n)`, but it won't work when `v` is `None`, and also would be much slower.
**Updated for Numpy 1.7.0:**(Hat-tip to @Rolf Bartstra.) `a=np.empty(n); a.fill(5)` is fastest. In descending speed order: ``` %timeit a=np.empty(1e4); a.fill(5) 100000 loops, best of 3: 5.85 us per loop %timeit a=np.empty(1e4); a[:]=5 100000 loops, best of 3: 7.15 us per loop %timeit a=np.ones(1e4)*5 10000 loops...
NumPy array initialization (fill with identical values)
5,891,410
71
2011-05-05T00:34:20Z
13,233,386
11
2012-11-05T13:45:46Z
[ "python", "arrays", "numpy" ]
I need to create a NumPy array of length `n`, each element of which is `v`. Is there anything better than: ``` a = empty(n) for i in range(n): a[i] = v ``` I know `zeros` and `ones` would work for v = 0, 1. I could use `v * ones(n)`, but it won't work when `v` is `None`, and also would be much slower.
Apparently, not only the absolute speeds but also the speed *order* (as reported by user1579844) are machine dependent; here's what I found: `a=np.empty(1e4); a.fill(5)` is fastest; In descending speed order: ``` timeit a=np.empty(1e4); a.fill(5) # 100000 loops, best of 3: 10.2 us per loop timeit a=np.empty(1e4); a...
NumPy array initialization (fill with identical values)
5,891,410
71
2011-05-05T00:34:20Z
20,606,278
63
2013-12-16T08:24:09Z
[ "python", "arrays", "numpy" ]
I need to create a NumPy array of length `n`, each element of which is `v`. Is there anything better than: ``` a = empty(n) for i in range(n): a[i] = v ``` I know `zeros` and `ones` would work for v = 0, 1. I could use `v * ones(n)`, but it won't work when `v` is `None`, and also would be much slower.
NumPy 1.8 introduced [`np.full()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html), which is a more direct method than `empty()` followed by `fill()` for creating an array filled with a certain value: ``` >>> np.full((3, 5), 7) array([[ 7., 7., 7., 7., 7.], [ 7., 7., 7., 7., 7.], ...
Is there a Python Library that contains a list of all the ascii characters?
5,891,453
39
2011-05-05T00:42:45Z
5,891,469
74
2011-05-05T00:44:44Z
[ "python", "ascii" ]
Something like below: ``` import ascii print ascii.charlist() ``` Which would return something like [A, B, C, D...]
The `string` constants may be what you want. ([docs](http://docs.python.org/library/string.html#string-constants)) ``` >>> import string >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ``` If you want all printable characters: ``` >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST...
Is there a Python Library that contains a list of all the ascii characters?
5,891,453
39
2011-05-05T00:42:45Z
5,891,486
16
2011-05-05T00:47:05Z
[ "python", "ascii" ]
Something like below: ``` import ascii print ascii.charlist() ``` Which would return something like [A, B, C, D...]
Here it is: ``` [chr(i) for i in xrange(127)] ```
Is there a Python Library that contains a list of all the ascii characters?
5,891,453
39
2011-05-05T00:42:45Z
5,891,509
7
2011-05-05T00:50:53Z
[ "python", "ascii" ]
Something like below: ``` import ascii print ascii.charlist() ``` Which would return something like [A, B, C, D...]
ASCII defines 128 characters whose byte values range from 0 to 127 inclusive. So to get a string of all the ASCII characters, you could just do ``` ''.join([chr(i) for i in range(128)]) ``` Only some of those are printable, however- the printable ASCII characters can be accessed in Python via ``` import string strin...
python & numpy: sum of an array slice
5,891,523
6
2011-05-05T00:53:28Z
5,891,540
10
2011-05-05T00:57:21Z
[ "python", "arrays", "numpy" ]
I have 1-dimensional numpy array (`array_`) and a Python list (list\_). The following code works, but is inefficient because slices involve an unnecessary copy (certainly for Python lists, and I believe also for numpy arrays?): ``` result = sum(array_[1:]) result = sum(list_[1:]) ``` What's a good way to rewrite tha...
Slicing a numpy array *doesn't* make a copy, as it does in the case of a list. As a basic example: ``` import numpy as np x = np.arange(100) y = x[1:5] y[:] = 1000 print x[:10] ``` This yields: ``` [ 0 1000 1000 1000 1000 5 6 7 8 9] ``` Even though we modified the values in `y`, it's just a view i...
Is there a python interface to iptables?
5,891,779
14
2011-05-05T01:42:03Z
5,891,942
20
2011-05-05T02:14:22Z
[ "python", "linux", "sockets", "networking", "iptables" ]
Im trying to retrieve the current iptables chains configured on the system via python. If I strace the iptables command, it outputs: ``` strace iptables -L INPUT socket(PF_INET, SOCK_RAW, IPPROTO_RAW) = 3 getsockopt(3, SOL_IP, 0x40 /* IP_??? */, "filter\0\377`\2\351\1\0\210\377\377\210}\313\276\0\210\377\377\354\206\...
Have you seen [python-iptables](https://github.com/ldx/python-iptables)? > Python-iptables provides python bindings to iptables under Linux. Interoperability with iptables is achieved via using the iptables C libraries (libiptc, libxtables, and the iptables extensions), not calling the iptables binary and parsing its ...
Problems importing python-Xlib
5,892,297
9
2011-05-05T03:23:54Z
18,892,493
13
2013-09-19T10:42:21Z
[ "python", "module", "dependencies" ]
I installed a new module and it appears as if one of its dependencies was not already installed. The module is called Xlib.display. Here is the error message I received: ``` from Xlib.display import Display ImportError: No module named Xlib.display ``` Where can I find this module that I am apparently lacking? Google...
Please try. This shall install Xlib `sudo apt-get install python-xlib` Then you can check `>>from Xlib.display import Display` To install PyMouse if you want to control and capture mouse events please use: `sudo easy_install https://github.com/pepijndevos/PyMouse/zipball/master`
Python syntax inconsistency?
5,892,723
5
2011-05-05T04:38:37Z
5,892,748
12
2011-05-05T04:43:00Z
[ "python" ]
I've been reading up on python's [special class methods](http://www.diveintopython.net/object_oriented_framework/special_class_methods2.html) in [Dive into Python](http://www.diveintopython.net), and it seems like some methods have odd or inconsistent syntax. To get the items from a dictionary you would call the dicti...
Guido van Rossum [explained it thusly](http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm): (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics whi...
What is the purpose of the single underscore "_" variable in Python?
5,893,163
251
2011-05-05T05:44:18Z
5,893,186
110
2011-05-05T05:47:50Z
[ "python", "variables", "naming-conventions", "underscores", "metasyntactic-variable" ]
What is the meaning of `_` after `for` in this code? ``` if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 ```
It's just a variable name, and it's conventional in python to use `_` for throwaway variables. It just indicates that the loop variable isn't actually used.
What is the purpose of the single underscore "_" variable in Python?
5,893,163
251
2011-05-05T05:44:18Z
5,893,946
366
2011-05-05T07:10:47Z
[ "python", "variables", "naming-conventions", "underscores", "metasyntactic-variable" ]
What is the meaning of `_` after `for` in this code? ``` if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 ```
`_` has 3 main conventional uses in Python: 1. To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit 2. For translation lookup in i18n (imported from the corresponding C con...
Python: Convert simplejson dumped unicode datetime back to datetime object
5,893,853
4
2011-05-05T07:01:54Z
5,893,926
7
2011-05-05T07:08:38Z
[ "python", "json", "datetime", "unicode", "simplejson" ]
I have... ``` entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())}) ``` How do I convert the datetime (that was converted to unicode) back to datetime again? So that I can do something like... ``` entity2 = simplejson.loads(entity) #your answer here.. add5 = entity2["a"] + datetime.timedelta(minutes=...
``` DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' ``` Do the following before serializing: ``` time = datetime.strftime(time, DATETIME_FORMAT) ``` Do the following after unserializing: ``` time = datetime.strptime(time, DATETIME_FORMAT) ``` example: ``` >>> from datetime import datetime >>> DATETIME_FORMAT = '%Y-%m-%d %...
django MultiValueDictKeyError error, how do i deal with it
5,895,588
80
2011-05-05T09:40:14Z
5,895,615
9
2011-05-05T09:42:34Z
[ "python", "django", "exception" ]
Hay, I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error. The problems lies within the form, the is\_private is represented by a checkbox. If the check box is NOT selected, obvously nothing is passed. This is where the error gets chucked. How do i properly deal with this excep...
You get that because you're trying to get a key from a dictionary when it's not there. You need to test if it is in there first. try: ``` is_private = 'is_private' in request.POST ``` or ``` is_private = 'is_private' in request.POST and request.POST['is_private'] ``` depending on the values you're using.
django MultiValueDictKeyError error, how do i deal with it
5,895,588
80
2011-05-05T09:40:14Z
5,895,652
41
2011-05-05T09:45:49Z
[ "python", "django", "exception" ]
Hay, I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error. The problems lies within the form, the is\_private is represented by a checkbox. If the check box is NOT selected, obvously nothing is passed. This is where the error gets chucked. How do i properly deal with this excep...
Choose what is best for you: # 1 ``` is_private = request.POST.get('is_private', False); ``` If `is_private` key is present in request.POST the `is_private` variable will be equal to it, if not, then it will be equal to False. # 2 ``` if 'is_private' in request.POST: is_private = request.POST['is_private'] els...
django MultiValueDictKeyError error, how do i deal with it
5,895,588
80
2011-05-05T09:40:14Z
5,895,670
146
2011-05-05T09:47:33Z
[ "python", "django", "exception" ]
Hay, I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error. The problems lies within the form, the is\_private is represented by a checkbox. If the check box is NOT selected, obvously nothing is passed. This is where the error gets chucked. How do i properly deal with this excep...
Use the MultiValueDict's `get` method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist. ``` is_private = request.POST.get('is_private', False) ``` Generally, ``` my_var = dict.get(<key>, <default>) ```
python head, tail and backward read by lines of a text file
5,896,079
4
2011-05-05T10:17:27Z
5,896,210
16
2011-05-05T10:27:24Z
[ "python", "file", "reverse", "tail", "head" ]
How to implement somethig like the 'head' and 'tail' commands in python and backward read by lines of a text file?
This is my personal file class ;-) ``` class File(file): """ An helper class for file reading """ def __init__(self, *args, **kwargs): super(File, self).__init__(*args, **kwargs) self.BLOCKSIZE = 4096 def head(self, lines_2find=1): self.seek(0) #Rewind ...
HTTPS connection using PEM Certificate
5,896,380
6
2011-05-05T10:39:53Z
5,899,320
8
2011-05-05T14:24:38Z
[ "python", "ssl", "https", "certificate" ]
I'm trying to POST HTTPS requests using a PEM certificate like following: ``` import httplib CERT_FILE = '/path/certif.pem' conn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) conn.request("POST", "/") response = conn.getresponse() print response.status, response.reason conn.close() ...
It sounds like you need something similar to an answer I have provided before to perform [simple client certificate authentication](http://stackoverflow.com/questions/5700289/using-pyopenssl-to-create-urllib-custom-opener/5707951#5707951). Here is the code for convenience modified slightly for your question: ``` impor...
LDA and pLSA packages (preferably for Python)
5,897,082
6
2011-05-05T11:42:03Z
5,897,180
12
2011-05-05T11:50:20Z
[ "python", "machine-learning" ]
What packages for pLSA (Probabilistic Latent Semantic Analysis) and LDA (Latent Dirichlet Allocation) do you recommend for Python? Java and C++ are OK too, but Python preferred. Your experiences are highly appreciated. There are many libs, so I don't know which to choose.
[**Gensim**](http://nlp.fi.muni.cz/projekty/gensim/) seems to be most popular one. [It's on PyPI](http://pypi.python.org/pypi/gensim) so, you can just install it using ``` sudo easy_install gensim ```
datetime.strptime () throws 'does not match format' error
5,897,263
6
2011-05-05T11:56:54Z
5,897,318
17
2011-05-05T12:00:56Z
[ "python", "django" ]
I get ``` time data '19/Apr/2011:22:12:39' does not match format '%d/%b/%y:%H:%M:%S' ``` when using `datetime.strptime('19/Apr/2011:22:12:39','%d/%b/%y:%H:%M:%S')` What am I doing wrong?
Try `%d/%b/%Y:%H:%M:%S` instead - `%y` right now means 11. You can "debug" datetime formats easily using `date` (on the shell and not on python, I mean, assuming you're running GNU/Linux or similar): ``` date '+%d/%b/%Y:%H:%M:%S' 05/May/2011:09:00:41 ```
datetime.strptime () throws 'does not match format' error
5,897,263
6
2011-05-05T11:56:54Z
5,897,336
8
2011-05-05T12:02:47Z
[ "python", "django" ]
I get ``` time data '19/Apr/2011:22:12:39' does not match format '%d/%b/%y:%H:%M:%S' ``` when using `datetime.strptime('19/Apr/2011:22:12:39','%d/%b/%y:%H:%M:%S')` What am I doing wrong?
You're checking for a 2 digit year ( %y ) instead of a four digit ( %Y )
How do I use data in package_data from source code?
5,897,666
21
2011-05-05T12:31:05Z
5,899,643
28
2011-05-05T14:43:32Z
[ "python", "build", "setuptools", "distutils", "distribute" ]
In setup.py, I have specified package\_data like this: ``` packages=['hermes'], package_dir={'hermes': 'hermes'}, package_data={'hermes': ['templates/*.tpl']}, ``` And my directory structure is roughly ``` hermes/ | | docs/ | ... | hermes/ | | __init__.py | code.py | templates | ...
The standard [pkgutil module's `get_data()` function](http://docs.python.org/library/pkgutil.html#pkgutil.get_data) will calculate the path to your data, relative to your package, and retrieve the data for you via whatever module loader Python used to import the `hermes` package: ``` import pkgutil data = pkgutil.get_...
Python: How to access data from this type of list?
5,898,186
2
2011-05-05T13:08:04Z
5,898,220
9
2011-05-05T13:10:13Z
[ "python", "list", "nested" ]
Quick Python question: How do I access data from a nested list like this: ``` {'album': [u'Rumours'], 'comment': [u'Track 3'], 'artist': [u'Fleetwood Mac'], 'title': [u'Never Going Back Again'], 'date': [u'1977'], 'genre': [u'Rock'], 'tracknumber': [u'03']} ``` I tried `listname[0][0]` but it returns the error: `Att...
This is not a list, it is a dictionary. It takes an immutable type as key and any type as value for every `key,value` pair. In your case this is a dictionary with `str` type keys and `list`'s as values. You must first extract the list from the dictionary, and then the first element from the list, assuming you meant tha...
"as of" in numpy
5,898,617
7
2011-05-05T13:37:42Z
5,899,095
11
2011-05-05T14:11:00Z
[ "python", "loops", "numpy", "time-series" ]
I am looking for a way to implement an "as of" operator in `numpy`. Specifically, if: 1. `t1` is an `n`-vector of timestamps in a strictly increasing order; 2. `d1` is an `n x p` matrix of observations, with `i`-th row corresponding to `t1[i]`; 3. `t2` in an `m`-vector of timestamps, also in a strictly increasing orde...
Your best choice is [`numpy.searchsorted()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html): ``` d1[numpy.searchsorted(t1, t2, side="right") - 1] ``` This will search the indices where the values of `t2` would have to be inserted into `t1` to maintain order. The `side="right"` and `- 1` ...
Class with too many parameters: better design strategy?
5,899,185
29
2011-05-05T14:16:30Z
5,899,350
28
2011-05-05T14:26:13Z
[ "python", "oop", "neuroscience" ]
I am working with models of neurons. One class I am designing is a cell class which is a topological description of a neuron (several compartments connected together). It has many parameters but they are all relevant, for example: number of axon segments, apical bifibrications, somatic length, somatic diameter, apical...
Try this approach: ``` class Neuron(object): def __init__(self, **kwargs): prop_defaults = { "num_axon_segments": 0, "apical_bifibrications": "fancy default", ... } for (prop, default) in prop_defaults.iteritems(): setattr(self, prop, kwarg...
Class with too many parameters: better design strategy?
5,899,185
29
2011-05-05T14:16:30Z
5,899,352
7
2011-05-05T14:26:22Z
[ "python", "oop", "neuroscience" ]
I am working with models of neurons. One class I am designing is a cell class which is a topological description of a neuron (several compartments connected together). It has many parameters but they are all relevant, for example: number of axon segments, apical bifibrications, somatic length, somatic diameter, apical...
I'd say there is nothing wrong with this approach - if you need 15 parameters to model something, you need 15 parameters. And if there's no suitable default value, you have to pass in all 15 parameters when creating an object. Otherwise, you could just set the default and change it later via a setter or directly. Anot...
Checking file extension
5,899,497
49
2011-05-05T14:34:27Z
5,899,544
113
2011-05-05T14:37:47Z
[ "python", "file-extension" ]
I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this? ``` if m == *.mp3 .... elif m == *.flac .... ``` I'm not sure whether it will work. **EDIT:** When I use that, it tells me invalid syntax. So what do I do?
Assuming `m` is a string, you can use `endswith`: ``` if m.endswith('.mp3'): ... elif m.endswith('.flac'): ... ``` To be case-insensitive, and to eliminate a potentially large else-if chain: ``` m.lower().endswith(('.png', '.jpg', '.jpeg')) ``` (Thanks to Wilhem Murdoch for the list of args to `endswith`)
Checking file extension
5,899,497
49
2011-05-05T14:34:27Z
5,899,953
7
2011-05-05T15:03:35Z
[ "python", "file-extension" ]
I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this? ``` if m == *.mp3 .... elif m == *.flac .... ``` I'm not sure whether it will work. **EDIT:** When I use that, it tells me invalid syntax. So what do I do?
Look at module fnmatch. That will do what you're trying to do. ``` import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print file ```
Checking file extension
5,899,497
49
2011-05-05T14:34:27Z
5,900,590
33
2011-05-05T15:46:04Z
[ "python", "file-extension" ]
I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this? ``` if m == *.mp3 .... elif m == *.flac .... ``` I'm not sure whether it will work. **EDIT:** When I use that, it tells me invalid syntax. So what do I do?
`os.path` provides many functions for manipulating paths/filenames. ([docs](http://docs.python.org/library/os.path.html)) `os.path.splitext` takes a path and splits the file extension from the end of it. ``` import os filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"] for fp in filepaths: # ...
Class based view extending UpdateView not saving form correctly
5,899,810
5
2011-05-05T14:54:24Z
5,912,167
9
2011-05-06T13:31:00Z
[ "python", "django", "views", "django-views", "django-1.3" ]
Im trying to save a form using UpdateView in Django 1.3 and seemed to have run into a problem. When I am saving the form, it POST's to the current URL and the success url is the same url. When saving the form, the data seems to be changed because all the fields on the page are updated, but when I refresh, everything s...
Figured out the solution. The problem was happening because there was an error in the form that wasnt being reported. This seems to occur with hidden fields that need to be set in some way in order for the form to be valid. The solution is pretty simple. You just need to override the post function and account for any ...
pyqt: how to remove a widget?
5,899,826
16
2011-05-05T14:55:31Z
5,899,974
10
2011-05-05T15:04:04Z
[ "python", "qt", "widget", "pyqt" ]
I have a `QGroupBox` widget with children in it that I want to remove. How do I do that? I can't find any `removeWidget`, `removeChild`, `removeItem`, or anything similar in [the docs](http://doc.qt.nokia.com/latest/qwidget.html). I can only see how to remove things from a layout, but that, apparently, doesn't remove i...
Well, this works: on the widget i want to remove, call `widget.setParent(None)`. I like how adding to a layout adds a widget to the container, but removing from a layout doesn't... fun stuff.
pyqt: how to remove a widget?
5,899,826
16
2011-05-05T14:55:31Z
5,942,786
23
2011-05-09T21:38:31Z
[ "python", "qt", "widget", "pyqt" ]
I have a `QGroupBox` widget with children in it that I want to remove. How do I do that? I can't find any `removeWidget`, `removeChild`, `removeItem`, or anything similar in [the docs](http://doc.qt.nokia.com/latest/qwidget.html). I can only see how to remove things from a layout, but that, apparently, doesn't remove i...
If your widget have no child widgets that depend on it i think you can use: ``` layout.removeWidget(self.widget_name) self.widget_name.deleteLater() self.widget_name = None ``` in my tests when it is a widget that have childs you have to: ``` import sip layout.removeWidget(self.widget_name) sip.delete(self.widget_na...
Django DateTimeField auto_now_add not working
5,899,868
9
2011-05-05T14:58:40Z
5,900,221
10
2011-05-05T15:21:17Z
[ "python", "django", "datetime", "model" ]
In one of the model i have set one timestamp field as follows: ``` created_datetime = models.DateTimeField(auto_now_add = True) ``` While in shell i am able to create a obj and save it, however in my application it is raising a exception that created\_datetime field cannot be null. Confused where things went wrong!!...
As far as I know, best practice for default datetimes is to use the following: ``` created_datetime = models.DateTimeField(default=datetime.datetime.now) ``` Don't forget to import datetime
How does collections.defaultdict work?
5,900,578
146
2011-05-05T15:45:00Z
5,900,628
68
2011-05-05T15:48:56Z
[ "python" ]
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs ``` >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)] ``` and ``` >>> s = [...
`defaultdict` means that if a key is not found in the dictionary, then instead of a `KeyError` being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict. For example: ``` somedict = {} print(somedict[3]) # KeyError someddict = defaultdict(int) print(someddict[3]) # prin...
How does collections.defaultdict work?
5,900,578
146
2011-05-05T15:45:00Z
5,900,634
176
2011-05-05T15:49:23Z
[ "python" ]
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs ``` >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)] ``` and ``` >>> s = [...
Usually, a Python dictionary throws a `KeyError` if you try to get an item with a key that is not currently in the dictionary. The `defaultdict` in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that ...
How does collections.defaultdict work?
5,900,578
146
2011-05-05T15:45:00Z
17,012,454
13
2013-06-09T17:48:31Z
[ "python" ]
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs ``` >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)] ``` and ``` >>> s = [...
There is a great explanation of defaultdicts here: <http://ludovf.net/blog/python-collections-defaultdict/> Basically, the parameters **int** and **list** are functions that you pass. Remember that Python accepts function names as arguments. **int** returns 0 by default and **list** returns an empty list when called w...
How does collections.defaultdict work?
5,900,578
146
2011-05-05T15:45:00Z
29,179,405
28
2015-03-21T04:58:33Z
[ "python" ]
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs ``` >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)] ``` and ``` >>> s = [...
# defaultdict "The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, `defaultdict` lets the caller specify the default(value to be returned) up front when the container is initialized." as defined by *Doug Hellmann* in *The...
Using variables in Python regular expression
5,900,683
18
2011-05-05T15:51:57Z
5,900,723
19
2011-05-05T15:55:09Z
[ "python", "regex" ]
I'm parsing a file and looking in the lines for `username-#` where the username will change and there can be any number of digits `[0-9]` after the dash. I have tried nearly every combination trying to use the variable `username` in the regular expression. Am I even close with something like `re.compile('%s-\d*'%user...
Working as it should: ``` >>> user = 'heinz' >>> import re >>> regex = re.compile('%s-\d*'%user) >>> regex.match('heinz-1') <_sre.SRE_Match object at 0x2b27a18e3f38> >>> regex.match('heinz-11') <_sre.SRE_Match object at 0x2b27a2f7c030> >>> regex.match('heinz-12345') <_sre.SRE_Match object at 0x2b27a18e3f38> >>> regex....
Best practices for getting the most testing coverage with Django/Python?
5,901,139
16
2011-05-05T16:30:49Z
5,901,698
29
2011-05-05T17:18:50Z
[ "python", "django", "unit-testing", "testing", "code-coverage" ]
My tests are seriously lacking and I don't have a whole lot of faith in them. What are some of the best practices for getting the most testing coverage I can using Django/Python? I've been taking a look at [Freshen](https://github.com/rlisagor/freshen) and [Lettuce](http://lettuce.it), which look pretty promising, but ...
1. Stop coding. 2. Write the tests for the things your application is supposed to do. First, use the built-in Django testing. Write model tests as TestCase classes inside your models.py. Do that now. Before reading any further. Add `django.test.TestCase` classes right now that create, modify and retrieve model object...
Best practices for getting the most testing coverage with Django/Python?
5,901,139
16
2011-05-05T16:30:49Z
5,902,028
7
2011-05-05T17:48:39Z
[ "python", "django", "unit-testing", "testing", "code-coverage" ]
My tests are seriously lacking and I don't have a whole lot of faith in them. What are some of the best practices for getting the most testing coverage I can using Django/Python? I've been taking a look at [Freshen](https://github.com/rlisagor/freshen) and [Lettuce](http://lettuce.it), which look pretty promising, but ...
I'm assuming that you are done with [Testing Django Applications](http://docs.djangoproject.com/en/dev/topics/testing/). With the right set of helper tools you should be fine with the default unit testing using Django test framework. To get you started with measuring coverage you might want to look into [coverage](htt...
Best practices for getting the most testing coverage with Django/Python?
5,901,139
16
2011-05-05T16:30:49Z
5,906,236
10
2011-05-06T02:39:47Z
[ "python", "django", "unit-testing", "testing", "code-coverage" ]
My tests are seriously lacking and I don't have a whole lot of faith in them. What are some of the best practices for getting the most testing coverage I can using Django/Python? I've been taking a look at [Freshen](https://github.com/rlisagor/freshen) and [Lettuce](http://lettuce.it), which look pretty promising, but ...
Additionally this series of articles so far has some good advice on testing django apps: <http://toastdriven.com/blog/2011/apr/10/guide-to-testing-in-django/> My only criticism of the answer would be to not store everything in the `tests.py` file, but do as the article suggest. Create a `tests` directory and turn it ...
Name of Current App in Google App Engine (Python)
5,901,653
11
2011-05-05T17:14:51Z
5,901,750
30
2011-05-05T17:22:59Z
[ "python", "google-app-engine" ]
Using the Google App Engine Python API is there a way to access the name of the currently running application--i.e., the app name specified in your `app.yaml` file with `application: foobar`?
``` import os appname = os.environ['APPLICATION_ID'] ``` EDIT: I just noticed this because I got a new upvote on it today (shame on you, upvoter!), but this is no longer correct. ``` from google.appengine.api.app_identity import get_application_id appname = get_application_id() ``` should be used. The value in `os.e...
the bytes type in python 2.7 and PEP-358
5,901,706
20
2011-05-05T17:19:16Z
5,901,825
33
2011-05-05T17:30:21Z
[ "python", "types" ]
According to [PEP 358](http://www.python.org/dev/peps/pep-0358/), a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case. However, my python 2.7 says otherwise ``` >>> bytes([1,2,3]) '[1, 2, 3]' >>> bytes([280]) '[280]' >>> bytes is str True >>> bytes <type 'str'> ``` Do...
The new `bytes` **type** is **3.x only**. The 2.x `bytes` built-in is just an alias to the `str` type. There is no new type called `bytes` in 2.x; Just a new alias and literal syntax for `str`. Here's the [documentation snippet](http://docs.python.org/whatsnew/2.6.html#pep-3112-byte-literals) everybody loves: > *Pyth...
the bytes type in python 2.7 and PEP-358
5,901,706
20
2011-05-05T17:19:16Z
5,901,849
27
2011-05-05T17:32:23Z
[ "python", "types" ]
According to [PEP 358](http://www.python.org/dev/peps/pep-0358/), a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case. However, my python 2.7 says otherwise ``` >>> bytes([1,2,3]) '[1, 2, 3]' >>> bytes([280]) '[280]' >>> bytes is str True >>> bytes <type 'str'> ``` Do...
The `bytes` type was introduced in Python 3, but what's being discussed in the PEP is a mutable sequence (`bytes` is immutable) which was introduced in Python 2.6 under the name `bytearray`. The PEP clearly wasn't implemented as stated (and it does say that it was partially superseded by [PEP 3137](http://www.python.o...
pygame event handling
5,901,779
2
2011-05-05T17:25:46Z
5,901,850
17
2011-05-05T17:32:28Z
[ "python", "event-handling", "pygame" ]
Just a noob question about python and pygame event handling. I got the following code in a pygame tutorial: ``` while 1: for event in pygame.event.get(): if event.type in (QUIT, KEYDOWN): sys.exit() ``` ...but for some reason it returns this error: ``` if event.type in (QUIT, KEYDOWN): NameErr...
I think you meant this: ``` if event.type in (pygame.QUIT, pygame.KEYDOWN) ``` The tutorial probably used `from pygame import *`, and this example perfectly shows why this is a bad habit.
matplotlib bar chart with dates
5,902,371
17
2011-05-05T18:19:18Z
5,902,579
24
2011-05-05T18:39:37Z
[ "python", "datetime", "matplotlib", "bar-chart" ]
I know about `plot_date()` but is there a `bar_date()` out there? The general method would be to use `set_xticks` and `set_xticklabels`, but I'd like something that can handle time scales from a few hours out to a few years (this means involving the major and minor ticks to make things readable I think). **Edit:** I ...
All [`plot_date`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot_date) does is plot the function and the call [`ax.xaxis_date()`](http://matplotlib.org/examples/pylab_examples/finance_demo.html). All you should need to do is this: ``` import numpy as np import matplotlib.pyplot as plt import datetim...
What are the advantages of using with for opening files on Python 3?
5,902,432
7
2011-05-05T18:24:36Z
5,902,459
10
2011-05-05T18:28:18Z
[ "python-3.x", "python" ]
What are the real performance advantages of using ``` with open(__file__, 'r') as f: ``` instead of using: ``` open(__file__,'r') ``` in Python 3 for both writing and reading files?
Using `with` means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.
Convert C# decryption to Python PyDes
5,903,135
2
2011-05-05T19:33:09Z
5,903,535
7
2011-05-05T20:13:22Z
[ "c#", "python", "encryption", "tripledes" ]
I'm having trouble converting code from C# to Python. Over at [Martijn's C# Blog](http://www.dijksterhuis.org/encrypting-decrypting-string/) is an excellent program for encrypt/decrypt [enclosed below] but I can't get it to convert directly to the python version [pyDes](http://twhiteman.netfirms.com/des.html) [sample b...
Never mind --- figured it out. If you change this line in pyDes ``` print "Encrypted: %r" % d ``` to ``` print "Encrypted: %r" % d.encode('base64') ``` then the code matches up exactly. To compare, run the original code from Martijn's site: [Output] > ``` > Message: This world is round, not flat, don't believe t...
gdata-python-api + Analytics with simple auth
5,903,278
10
2011-05-05T19:46:11Z
10,262,031
12
2012-04-21T19:01:52Z
[ "python", "api", "oauth" ]
I'm working on converting a Python script using the Google gdata API client + user/pass authentication to something more suitable for production (an API key). I am pretty frustrated with the muddled state of their documentation on authentication. I admittedly don't have a great grasp of OAuth2, but it seems like it's w...
Greg, If you are already using the library [gdata-python-client](http://code.google.com/p/gdata-python-client/source/checkout), this is relatively easy to do if you are the only user that your application will be authorizing. The general mechanisms were detailed in a [blog post](http://googleappsdeveloper.blogspot.co...
Specifying Django Query Filters at Run Time
5,903,384
3
2011-05-05T19:58:18Z
5,903,439
9
2011-05-05T20:04:37Z
[ "python", "django", "runtime", "django-queryset" ]
How do I specify an arbitrary Django query filter at runtime? Normally one uses filters like so... ``` query_set = MyModel.objects.filter(name__iexact='foobar') ``` But what if I have the query filter specifier contained in a string? ``` query_specifier = "name_iexact='foobar'" query_set = MyModel.objects.filter(qu...
``` query_specifier = { 'name__iexact': 'foobar' } query_set = MyModel.objects.filter(**query_specifier) ```
AttributeError: StringIO instance has no attribute 'fileno'
5,903,501
15
2011-05-05T20:10:03Z
5,903,571
13
2011-05-05T20:17:20Z
[ "python" ]
``` def captureOutput(self, func, *args, **kwargs): pass sys.stdout.flush() sys.stderr.flush() (outfd, fn) = tempfile.mkstemp() fout = os.fdopen(outfd, 'r') os.unlink(fn) (errfd, fn) = tempfile.mkstemp() ferr = os.fdopen(errfd, 'r') os.unlink(fn) try: oldstdout = os.dup(s...
The `fileno()` method is not implemented in StringIO, as it is not a real file (so has no associated file descriptor). From the source: ``` - fileno() is left unimplemented so that code which uses it triggers an exception early. ``` It is possible that someone replaced `sys.stdout` with a StringIO instance, to captu...
Recursive diff of two python dictionaries (keys and values)
5,903,720
17
2011-05-05T20:32:23Z
5,904,056
8
2011-05-05T21:03:49Z
[ "python", "data-structures", "recursion", "diff", "dictionary" ]
So I have a python dictionary, call it `d1`, and a version of that dictionary at a later point in time, call it `d2`. I want to find all the changes between `d1` and `d2`. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs ...
Just a thought: You could try an object-oriented approach where you derive your own dictionary class that keeps track of any changes made to it (and reports them). Seems like this might have many advantages over trying to compare two dicts...one is noted at the end. To show how that might be done, here's a reasonably ...
Recursive diff of two python dictionaries (keys and values)
5,903,720
17
2011-05-05T20:32:23Z
26,171,760
11
2014-10-03T00:43:25Z
[ "python", "data-structures", "recursion", "diff", "dictionary" ]
So I have a python dictionary, call it `d1`, and a version of that dictionary at a later point in time, call it `d2`. I want to find all the changes between `d1` and `d2`. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs ...
In case you want the difference recursively, I have written a package for python: <https://github.com/seperman/deepdiff> ## Installation Install from PyPi: ``` pip install deepdiff ``` ## Example usage Importing ``` >>> from deepdiff import DeepDiff >>> from pprint import pprint >>> from __future__ import print_f...
Python: Don't know how to resolve IndentationError
5,903,739
3
2011-05-05T20:34:25Z
5,903,777
12
2011-05-05T20:38:47Z
[ "python", "indentation" ]
Please don't kill me. The last guy that asked this question got -5 points. However my IndentationError just seems so irresolvable, no matter what I do. Could I ask you to check my code for me, I know it's such a bother, but I really need help on this one: <http://pastebin.com/AFdnYcRc>.
You have a `try` block (starting on line 30) with no `except`
Python Multiprocessing with PyCUDA
5,904,872
13
2011-05-05T22:33:32Z
5,908,426
14
2011-05-06T07:57:13Z
[ "python", "cuda", "parallel-processing", "multiprocessing", "pycuda" ]
I've got a problem that I want to split across multiple CUDA devices, but I suspect my current system architecture is holding me back; What I've set up is a GPU class, with functions that perform operations on the GPU (strange that). These operations are of the style ``` for iteration in range(maxval): result[ite...
You need to get all your bananas lined up on the CUDA side of things first, then think about the best way to get this done in Python [shameless rep whoring, I know]. The CUDA multi-GPU model is pretty straightforward pre 4.0 - each GPU has its own context, and each context must be established by a different host threa...
Python monitor serial port (RS-232) handshake signals
5,904,895
10
2011-05-05T22:37:44Z
5,905,076
13
2011-05-05T23:05:14Z
[ "python", "serial-port" ]
I need to monitor the status of serial port signals (RI, DSR, CD,CTS). Looping and polling with 'serial' library, (eg. using functions getRI) is too cpu intensive and response time is not acceptable. Is there a solutions with python?
On Linux is possible to monitor che state change of a signal pin of an RS-232 port using interrupt based notification throught the blocking syscall TIOCMIWAIT: ``` from serial import Serial from fcntl import ioctl from termios import ( TIOCMIWAIT, TIOCM_RNG, TIOCM_DSR, TIOCM_CD, TIOCM_CTS ) ser =...
Python: how to print a dictionary's key?
5,904,969
78
2011-05-05T22:51:16Z
5,904,997
23
2011-05-05T22:53:50Z
[ "python", "dictionary", "key" ]
I found a my question in SO already, but it was not answered directly. I would like to print a specific Python dictionary key: ``` mydic = {} mydic['key_name'] = 'value_name' ``` Now I can check if `mydic.has_key('key_name')`, but what I would like to do is print the name of the key `'key_name'`. Of course I could us...
The name of the key 'key\_name' is key\_name, therefore `print 'key_name'` or whatever variable you have representing it.
Python: how to print a dictionary's key?
5,904,969
78
2011-05-05T22:51:16Z
5,905,090
24
2011-05-05T23:07:09Z
[ "python", "dictionary", "key" ]
I found a my question in SO already, but it was not answered directly. I would like to print a specific Python dictionary key: ``` mydic = {} mydic['key_name'] = 'value_name' ``` Now I can check if `mydic.has_key('key_name')`, but what I would like to do is print the name of the key `'key_name'`. Of course I could us...
Hmm, I think that what you might be wanting to do is print **all** the keys in the dictionary and their respective values? If so you want the following: ``` for key in mydic.keys(): print "the key name is" + key + "and its value is" + mydic[key] ``` Make sure you use +'s instead of ,' as well. The comma will put e...
Python: how to print a dictionary's key?
5,904,969
78
2011-05-05T22:51:16Z
5,905,166
170
2011-05-05T23:21:28Z
[ "python", "dictionary", "key" ]
I found a my question in SO already, but it was not answered directly. I would like to print a specific Python dictionary key: ``` mydic = {} mydic['key_name'] = 'value_name' ``` Now I can check if `mydic.has_key('key_name')`, but what I would like to do is print the name of the key `'key_name'`. Of course I could us...
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the `keys()` method, which gives you a python `list` of all the keys, and you have the `iteritems()` method, which returns key-value pairs, so ``` for key, value in mydic.iteritems() : print key, value ``` Python 3 versi...
Python: how to print a dictionary's key?
5,904,969
78
2011-05-05T22:51:16Z
13,941,920
11
2012-12-18T21:38:39Z
[ "python", "dictionary", "key" ]
I found a my question in SO already, but it was not answered directly. I would like to print a specific Python dictionary key: ``` mydic = {} mydic['key_name'] = 'value_name' ``` Now I can check if `mydic.has_key('key_name')`, but what I would like to do is print the name of the key `'key_name'`. Of course I could us...
``` dic = {"key 1":"value 1","key b":"value b"} #print the keys: for key in dic.iterkeys(): print key #print the values: for value in dic.itervalues(): print value #print key and values for key, value in dic.iteritems(): print key, value ```
Defining a class in Python
5,905,786
2
2011-05-06T01:04:08Z
5,905,809
8
2011-05-06T01:07:38Z
[ "python", "class", "class-design" ]
``` class Car: pass class Car(): pass ``` What is the difference between these two? and, ``` a = Car a = Car() ``` also, what is the difference between these two above? Best Regards
the first statement, `a = Car` simply makes `a` an alias to `Car` class. So after you do that, you could do `b = a()` and it would be the same as `b = Car()` Once you attach the `()` at the end, it makes python actually initialize the class (either `__call__` or just initialize, but you don't have to worry about that)...
What is the most common way to configure static files in debug and production for Django
5,906,197
4
2011-05-06T02:29:50Z
5,906,206
10
2011-05-06T02:33:02Z
[ "python", "django", "nginx" ]
When developing a Django application in debug mode, I serve static files using the following code: ``` if settings.DEBUG: urlpatterns += patterns('', (r'^m/(?P<path>.*)$', serve, { 'document_root' : os.path.join(os.path.dirname(__file__), "media") }) ) ``` I am using nginx as a fro...
Using Django 1.3 `django.contrib.staticfiles` will take care of serving everything for you during development. You don't need to do anything particular in the urls.py. I wrote a little guide for myself after the Django 1.3 update that covers the settings to use: ``` # idiom to get path of project import os PROJECT_PAT...
Serializing a Python namedtuple to json
5,906,831
38
2011-05-06T04:34:56Z
5,913,148
28
2011-05-06T14:52:48Z
[ "python", "json", "namedtuple" ]
What is the recommended way of serializing a [`namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple) to json with the field names retained? Serializing a `namedtuple` to json results in only the values being serialized and the field names being lost in translation. I would like the f...
This is pretty tricky, since `namedtuple()` is a factory which returns a new type derived from `tuple`. One approach would be to have your class also inherit from `UserDict.DictMixin`, but `tuple.__getitem__` is already defined and expects an integer denoting the position of the element, not the name of its attribute: ...