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 Global Interpreter Lock GIL problem
7,404,904
3
2011-09-13T16:00:50Z
7,404,998
10
2011-09-13T16:06:57Z
[ "python", "gil" ]
I want to provide a service on the web that people can test out the performance of an algo, which is written in python and running on the linux machine basically what I want to do is that, there is a very trivial PHP handler, let's say start\_algo.php, which accepts the request coming from browser, and in the php code...
If you are opening each script by invoking a new process; you will not run afoul of the GIL. Each process gets its own interpreter and therefore its own interpreter lock.
Create (sane/safe) filename from any (unsafe) string
7,406,102
19
2011-09-13T17:40:52Z
7,406,369
29
2011-09-13T18:04:19Z
[ "python", "cocoa", "filenames", "pyobjc" ]
I want to create a sane/safe filename (i.e. somewhat readable, no "strange" characters, etc.) from some random Unicode string (mich might contain just anything). (It doesn't matter for me wether the function is Cocoa, ObjC, Python, etc.) --- Of course, there might be infinite many characters which might be strange. ...
Python: ``` "".join([c for c in filename if c.isalpha() or c.isdigit() or c==' ']).rstrip() ``` this accepts Unicode characters but removes line breaks, etc. example: ``` filename = u"ad\nbla'{-+\)(ç?" ``` gives: `adblaç` **edit** *str.isalnum() does alphanumeric on one step. – comment from queueoverflow belo...
Python: Create a new list from a list when a certain condition is met
7,406,448
2
2011-09-13T18:09:43Z
7,406,468
8
2011-09-13T18:11:44Z
[ "python", "list", "append", "condition" ]
I want to make a new list from another list of words; when a certain condition of the word is met. In this case I want to add all words that have have the length of 9 to a new list. I have used : ``` resultReal = [y for y in resultVital if not len(y) < 4] ``` to remove all entries that are under the length of 4. How...
Sorry, realized you wanted length, 9, not length 9 or greater. ``` newlist = [word for word in words if len(word) == 9] ```
python: immutable private class variables?
7,406,943
6
2011-09-13T18:52:08Z
7,406,970
7
2011-09-13T18:54:24Z
[ "python", "oop", "class", "static" ]
Is there any way to translate this Java code into Python? ``` class Foo { final static private List<Thingy> thingies = ImmutableList.of(thing1, thing2, thing3); } ``` e.g. `thingies` is an immutable private list of `Thingy` objects that belongs to the `Foo` class rather than its instance. I know how to d...
You can't do either of those things in Python, not in the sense you do them in Java, anyway. By convention, names prefixed with an underscore are considered private and should not be accessed outside the implementation, but nothing in Python enforces this convention. It's considered more of a warning that you're messi...
python: immutable private class variables?
7,406,943
6
2011-09-13T18:52:08Z
7,407,122
10
2011-09-13T19:07:57Z
[ "python", "oop", "class", "static" ]
Is there any way to translate this Java code into Python? ``` class Foo { final static private List<Thingy> thingies = ImmutableList.of(thing1, thing2, thing3); } ``` e.g. `thingies` is an immutable private list of `Thingy` objects that belongs to the `Foo` class rather than its instance. I know how to d...
In Python the convention is to use a `_` prefix on attribute names to mean `protected` and a `__` prefix to mean `private`. This isn't enforced by the language; programmers are expected to know not to write code that relies on data that isn't public. If you really wanted to enforce immutability, you could use a metacl...
PIL for Python 3.2 on Windows or alternatives?
7,407,185
3
2011-09-13T19:14:17Z
8,131,947
8
2011-11-15T05:35:12Z
[ "python", "python-3.x", "tkinter" ]
I'm building my first Python program :) However, I installed Python 3.2 instead of 2.7, as the newer version has `TkInter` included. Now I can't find a way to use PIL in it. I have read [this question](http://stackoverflow.com/questions/3896286/image-library-for-python-3) but as a total newcomer it's not much help for...
Unofficial PIL for Python 3.2 is the answer <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
Unique combination of fields in SQLite?
7,407,506
4
2011-09-13T19:40:52Z
7,407,561
17
2011-09-13T19:45:38Z
[ "python", "sqlite", "database-design", "unique-constraint" ]
I'm trying to populate a new SQLite database with rows based on a set of data, but I'm having trouble with avoiding duplicate rows. I could accomplish this in Python, but there certainly must be a design option in SQLite to handle this. I need each row to exist for only a unique combination of three text fields. If I ...
``` CREATE TABLE (col1 typ , col2 typ , col3 typ , CONSTRAINT unq UNIQUE (col1, col2, col3)) ``` <http://www.sqlite.org/lang_createtable.html>
Python subprocess, subshells, and redirection
7,407,667
4
2011-09-13T19:55:03Z
7,407,744
9
2011-09-13T20:01:54Z
[ "python", "bash", "subprocess", "subshell" ]
I want to use the magic of subshells and redirection with the python subprocess module, but it doesn't seem to work, complaining about unexpected tokens are the parenthesis. For example, the command `cat <(head tmp)` when passed to subprocess gives this ``` >>> subprocess.Popen("cat <(head tmp)", shell=True) <subpro...
The `<(head tmp)` syntax is a `bash` feature called "process substitution". The basic/portable `/bin/sh` doesn't support it. (This is true even on systems where `/bin/sh` and `/bin/bash` are the same program; it doesn't allow this feature when invoked as plain `/bin/sh` so you won't inadvertently depend on a non-portab...
Format a number containing a decimal point with leading zeroes
7,407,766
3
2011-09-13T20:03:41Z
7,407,815
13
2011-09-13T20:09:05Z
[ "python", "string-formatting", "decimal-point" ]
I want to format a number with a decimal point in it with leading zeros. This ``` >>> '3.3'.zfill(5) 003.3 ``` considers all the digits and even the decimal point. Is there a function in python that considers only the whole part? I only need to format simple numbers with no more than five decimal places. Also, usin...
Is that what you look for? ``` >>> "%07.1f" % 2.11 '00002.1' ``` So according to your comment, I can come up with this one (although not as elegant anymore): ``` >>> fmt = lambda x : "%04d" % x + str(x%1)[1:] >>> fmt(3.1) 0003.1 >>> fmt(3.158) 0003.158 ```
How can I parse an external XML file with django/python
7,408,420
2
2011-09-13T21:00:20Z
7,408,548
8
2011-09-13T21:10:25Z
[ "python", "xml", "django", "parsing", "django-models" ]
I've done some research on trying to parse an XML file from another web server and came across something called [minidom](http://docs.python.org/library/xml.dom.minidom.html). I've tried implementing this in my view.py file: ``` from xml.dom import minidom import models def test(request): data={} doc=minido...
Apparently minidom cannot parse URLs. You have to do ``` import urllib2 doc = urllib2.urlopen(your_url) parsed = minidom.parse(doc) ```
python: easiest way to get a string of spaces of length N
7,408,874
3
2011-09-13T21:38:30Z
7,408,892
12
2011-09-13T21:40:15Z
[ "python", "string" ]
What's the easiest way to generate a string of spaces of length N in Python? (besides something like this, which is multiline and presumably inefficient for large n: ``` def spaces(n): s = '' for i in range(n): s += ' ' return s ``` )
try this, simple, only one line: ``` ' ' * n ```
Iterating Over Dictionary Key Values Corresponding to List in Python
7,409,078
63
2011-09-13T22:00:51Z
7,409,150
7
2011-09-13T22:07:46Z
[ "python", "list", "function", "dictionary", "loops" ]
Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list: ``` NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]} ``` I would like to be able to feed the dictionary into a function and iterate over each te...
You can very easily iterate over dictionaries, too: ``` for team, scores in NL_East.iteritems(): runs_scored = float(scores[0]) runs_allowed = float(scores[1]) win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000) print '%s: %.1f%%' % (team, win_percentage) ```
Iterating Over Dictionary Key Values Corresponding to List in Python
7,409,078
63
2011-09-13T22:00:51Z
7,409,280
103
2011-09-13T22:22:50Z
[ "python", "list", "function", "dictionary", "loops" ]
Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list: ``` NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]} ``` I would like to be able to feed the dictionary into a function and iterate over each te...
You have several options for iterating over a dictionary. If you iterate over the dictionary itself (`for team in league`), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (`league`) itself, `league.keys()`, or `league.it...
Reading entire file in Python
7,409,780
154
2011-09-13T23:44:12Z
7,409,814
294
2011-09-13T23:49:56Z
[ "python", "file-io", "filehandle" ]
If you read an entire file with `content = open('Path/to/file', 'r').read()` is the file handle left open until the script exits? Is there a more concise method to read a whole file?
the answer to that question depends somewhat on the particular python implementation. To understand what this is all about, pay particular attention to the actual `file` object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediatly after the `read()` call returns. Thi...
ValueError: Unable to configure filter 'require_debug_false': Cannot resolve 'django.utils.log.CallbackFilter': No module named CallbackFilter
7,410,151
4
2011-09-14T00:55:01Z
7,922,006
11
2011-10-27T20:33:28Z
[ "python", "django" ]
I'm setting up a simple db using Django and I got the above error when running 'python manage.py syncdb' Is this a problem in manage.py or my .db file? Suggestions for how to resolve? **EDIT: Adding full traceback** ``` Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settin...
I had the same problem Go to your settings.py and find the LOGGING settings ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG } }, ``` See the CallbackFilter t...
In python or coffeescript, why list.append not return the list itself ? recursion can be a lot simpler if so
7,410,850
3
2011-09-14T03:08:29Z
7,410,926
14
2011-09-14T03:26:57Z
[ "python", "functional-programming", "coffeescript" ]
consider the following code if insert() return the list itself. ``` def sieve(l): if not len(l): return [] return sieve(filter(lambda x: x%l[0] != 0, l)).insert(0, l[0]) ``` For now, we have to rely on a helper function to return the list after insertion. ``` def cons(a, l): l.insert(0, a) return l def ...
In Python, it is a big deal to get beginners to learn which objects are “immutable” and cannot be changed, and which are “mutable” and can be altered — in the latter case, *every* reference to the object sees the same change. This really seems to confuse newcomers. “I innocently called this function I wrote...
Debugging: stepping through Python script using gdb?
7,412,708
9
2011-09-14T07:26:55Z
7,920,256
16
2011-10-27T18:02:49Z
[ "python", "debugging", "gdb" ]
Let's say we have the following mega-simple Python script: ``` print "Initializing".... a=10 print "Variable value is %d" % (a) print "All done!" ``` ... and say, I'd like to debug this script by placing a breakpoint at line `a=10`, and then stepping through the script. Now, I'd like to use `gdb` for this, because I...
Very interesting question. Here's my approach. Create `signal_test.py`: ``` import os import signal PID = os.getpid() def do_nothing(*args): pass def foo(): print "Initializing..." a=10 os.kill(PID, signal.SIGUSR1) print "Variable value is %d" % (a) print "All done!" signal.signal(signal.SI...
Debugging: stepping through Python script using gdb?
7,412,708
9
2011-09-14T07:26:55Z
16,027,750
13
2013-04-16T02:26:05Z
[ "python", "debugging", "gdb" ]
Let's say we have the following mega-simple Python script: ``` print "Initializing".... a=10 print "Variable value is %d" % (a) print "All done!" ``` ... and say, I'd like to debug this script by placing a breakpoint at line `a=10`, and then stepping through the script. Now, I'd like to use `gdb` for this, because I...
Apologies for the longish post; I came back again to a similar problem with debugging - a case where you take a long trip to the debugger, to finally reveal there is no actual bug - so I'd just like to post my notes and some code here (I'm still on Python 2.7, Ubuntu 11.04). In respect to the OP question - in newer `gd...
Jinja 2 - Django Form : rendering encodes HTML
7,414,637
5
2011-09-14T10:17:05Z
7,414,858
23
2011-09-14T10:32:19Z
[ "python", "django", "jinja2" ]
I was testing Jinja2 in a Django project and have a strange output. When I render the form, some characters are HTML encoded (`&lt; &gt;` etc.) In the template : ``` {{ form.as_p() }} ``` It renders to the browser : ``` <p><label for="id_username">Utilisateur:</label> <input autocomplete="off" id="id_username" type...
Jinja2 tries to be safe by [HTML-escaping the data](http://jinja.pocoo.org/docs/templates/#html-escaping). So you have to use `|safe` [filter](http://jinja.pocoo.org/docs/templates/#builtin-filters). Though I haven't used Django with Jinja2, I believe this should work: ``` {{ form.as_p()|safe }} ```
numpy reverse multidimensional array
7,416,170
12
2011-09-14T12:17:30Z
7,416,357
20
2011-09-14T12:31:07Z
[ "python", "multidimensional-array", "numpy" ]
What is the simplest way in numpy to reverse the most inner values of an array like this: ``` array([[[1, 1, 1, 2], [2, 2, 2, 3], [3, 3, 3, 4]], [[1, 1, 1, 2], [2, 2, 2, 3], [3, 3, 3, 4]]]) ``` so that I get the following result: ``` array([[[2, 1, 1, 1], [3, 2, 2, 2], [4, 3, 3, 3]], ...
How about: ``` import numpy as np a = np.array([[[10, 1, 1, 2], [2, 2, 2, 3], [3, 3, 3, 4]], [[1, 1, 1, 2], [2, 2, 2, 3], [3, 3, 3, 4]]]) ``` and the reverse along the last dimension is: ``` b = a[:,:,::-1] ``` or ``` b = a[...,::-1] ``` although I like the later less since the first two dimensions are implicit ...
from . import XXXX
7,417,353
4
2011-09-14T13:45:08Z
7,417,441
7
2011-09-14T13:51:12Z
[ "python" ]
In one of my Python packages the `__init__.py` file contains the statement ``` from . import XXXX ``` What does the "." mean here? I got this technique by looking at another package, but I don't understand what it means. Thanks!
Its a relative import. From: <http://docs.python.org/py3k/reference/simple_stmts.html#the-import-statement> > When specifying what module to import you do not have to specify the > absolute name of the module. When a module or package is contained > within another package it is possible to make a relative import withi...
Python find out contents of compiled module?
7,418,115
3
2011-09-14T14:34:52Z
7,418,143
9
2011-09-14T14:36:55Z
[ "python", "module", "compiled", "pyd" ]
So have this Python .pyd module (C++), so I can't just open it in a text editor to find out what it contains. So how can I? I just want to know the function names inside it.
Python have full reflection. You can do the following (for a modulename.pyd) ``` python >>> import modulename as mtmp >>> dir(mtmp) >>> help(mtmp) ``` **EDIT** : Add help command as propose by Mike Graham
How do I resolve namespace conflicts in my Python packages with standard library package names?
7,418,996
9
2011-09-14T15:31:25Z
7,419,072
10
2011-09-14T15:37:06Z
[ "python", "namespaces", "packages", "package-structuring" ]
I am developing a package with the following structure on disk: ``` foo/ __init__.py xml.py bar.py moo.py ``` The `xml.py` package provides a class that does some custom XML parsing and translation for the other package components using a SAX stream parser. So it has in it: ``` import xml.sax import xml....
As mentioned [over here](http://stackoverflow.com/questions/1224741/python-import-with-name-conflicts/1224760#1224760), use ``` from __future__ import absolute_import ``` and use [relative imports](http://www.python.org/dev/peps/pep-0328/#guido-s-decision) if needed.
Python - Move and overwrite files and folders
7,419,665
37
2011-09-14T16:23:30Z
7,420,040
21
2011-09-14T16:54:18Z
[ "python", "file", "move", "overwrite" ]
I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist with the same name. So for example 'Src Directory\file.txt' needs to be...
Use `copy()` instead, which is willing to overwrite destination files. If you then want the first tree to go away, just `rmtree()` it separately once you are done iterating over it. <http://docs.python.org/library/shutil.html#shutil.copy> <http://docs.python.org/library/shutil.html#shutil.rmtree> **Update:** Do an ...
Python - Move and overwrite files and folders
7,419,665
37
2011-09-14T16:23:30Z
7,420,617
33
2011-09-14T17:41:49Z
[ "python", "file", "move", "overwrite" ]
I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist with the same name. So for example 'Src Directory\file.txt' needs to be...
This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory: ``` import os import shutil root_src_dir = 'Src Directory\\' root_dst_dir = 'Dst Directory\\' for src_dir, dirs, files in os.walk(root_src_dir...
A Few Python questions
7,420,019
4
2011-09-14T16:51:45Z
7,420,097
8
2011-09-14T16:57:53Z
[ "javascript", "python" ]
I'm trying to learn Python from a background in javascript. I saw someone make a recursive function to find the least common denominator and wondered why they didn't just use a loop, so, both for the experience and to amuse myself, I wrote a simpler one: I came up with: ``` def LCM(n,d): while(n%d++ != 0 ): ...
Python does not allow assignments (such as `i+=1`) in expressions since those can lead to confusing code, and Python is designed to make it hard to write confusing code, and make it simple to write obvious code. You can simply write this: ``` def LCM(n,d): while n%d != 0: d += 1 return d-1 print(LCM(9...
Randomly choose a number in a specific range with a specific multiple in python
7,420,720
4
2011-09-14T17:50:19Z
7,420,757
13
2011-09-14T17:53:35Z
[ "python", "random" ]
I have the following numbers: 100, 200, 300, 400 ... 20000 And I would like to pick a random number within that range. Again, that range is defined as 100:100:20000. Furthermore, by saying 'within that range', I don't mean randomly picking a number from 100->20000, such as 105. I mean randomly choosing a number from ...
Use [`random.randrange`](http://docs.python.org/library/random.html#random.randrange) : ``` random.randrange(100, 20001, 100) ```
run program in Python shell
7,420,937
10
2011-09-14T18:09:14Z
7,420,972
34
2011-09-14T18:11:59Z
[ "python", "executable" ]
this is a simple doubt. I save a demo file: `test.py` In windows console i can run the file with a : `C:\>test.py` instead, How i can execute the file in the Python shell? thanks
Use [`execfile`](http://docs.python.org/library/functions.html#execfile): ``` >>> execfile('C:\\test.py') ```
run program in Python shell
7,420,937
10
2011-09-14T18:09:14Z
7,420,983
18
2011-09-14T18:12:46Z
[ "python", "executable" ]
this is a simple doubt. I save a demo file: `test.py` In windows console i can run the file with a : `C:\>test.py` instead, How i can execute the file in the Python shell? thanks
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use: ``` python -i test.py ``` That will run the script and then drop you into a Python interpreter.
run program in Python shell
7,420,937
10
2011-09-14T18:09:14Z
7,421,048
8
2011-09-14T18:18:29Z
[ "python", "executable" ]
this is a simple doubt. I save a demo file: `test.py` In windows console i can run the file with a : `C:\>test.py` instead, How i can execute the file in the Python shell? thanks
It depends on what is in `test.py`. The following is an appropriate structure: ``` # suppose this is your 'test.py' file def main(): """This function runs the core of your program""" print("running main") if __name__ == "__main__": # if you call this script from the command line (the shell) it will # run the 'mai...
Measuring elapsed time in python
7,421,641
42
2011-09-14T19:06:01Z
7,421,707
21
2011-09-14T19:13:11Z
[ "python", "time", "duration" ]
Is there a simple way / module to *correctly* measure the elapsed time in python? I know that I can simply call `time.time()` twice and take the difference, but that will yield wrong results if the system time is changed. Granted, that doesn't happen very often, but it does indicate that I'm measuring the wrong thing. ...
For measuring elapsed CPU time, look at [time.clock()](http://mail.python.org/pipermail/python-list/2007-January/1121263.html). This is the equivalent of Linux's [times()](http://linux.die.net/man/2/times) user time field. For benchmarking, use [timeit](http://docs.python.org/library/timeit.html). The [datetime modul...
Measuring elapsed time in python
7,421,641
42
2011-09-14T19:06:01Z
7,424,304
10
2011-09-14T23:47:34Z
[ "python", "time", "duration" ]
Is there a simple way / module to *correctly* measure the elapsed time in python? I know that I can simply call `time.time()` twice and take the difference, but that will yield wrong results if the system time is changed. Granted, that doesn't happen very often, but it does indicate that I'm measuring the wrong thing. ...
What you seem to be looking for is a [monotonic timer](http://linux.die.net/man/3/clock_gettime). A [monotonic time reference](http://markmail.org/thread/54bb663vi47kjxnu) does not jump or go backwards. There have been several attempts to implement a cross platform monotomic clock for Python based on the OS reference ...
Measuring elapsed time in python
7,421,641
42
2011-09-14T19:06:01Z
15,358,108
7
2013-03-12T09:59:45Z
[ "python", "time", "duration" ]
Is there a simple way / module to *correctly* measure the elapsed time in python? I know that I can simply call `time.time()` twice and take the difference, but that will yield wrong results if the system time is changed. Granted, that doesn't happen very often, but it does indicate that I'm measuring the wrong thing. ...
Python 3.3 added a [monotonic timer](http://www.python.org/dev/peps/pep-0418/#time-monotonic) into the standard library, which does exactly what I was looking for. Thanks to Paddy3118 for pointing this out in ["How do I get monotonic time durations in python?"](http://stackoverflow.com/a/14416514/575615).
Python: A more concise syntax for variable assignment when accessing a NoneType object
7,421,706
3
2011-09-14T19:13:00Z
7,421,723
8
2011-09-14T19:14:51Z
[ "python" ]
Say, I have the following Python code ``` if obj is None: identifier = None else: identifier = obj.id ``` where `obj` is a Python object whose class definition is not included I barely remember there's a more concise syntax (like a one-line code?) that can achieve the same. If I wasn't dreaming, can someone plea...
``` identifier = None if obj is None else obj.id ```
Python change type of whole list?
7,422,453
2
2011-09-14T20:18:14Z
7,422,481
12
2011-09-14T20:20:16Z
[ "python", "list" ]
I would like to do something like this ``` def foo(x,dtype=long): return magic_function_changing_listtype_to_dtype(x) ``` i.e. a list full of str to a list full of int any easy way to do it for nested lists, i.e. change the type [['1'],['2']] -> int
``` map(int, ['1','2','3']) # => [1,2,3] ``` so: ``` def foo(l, dtype=long): return map(dtype, l) ```
WSGI servers for Python 3 (PEP 3333)
7,422,556
3
2011-09-14T20:25:05Z
7,423,182
8
2011-09-14T21:25:49Z
[ "python", "python-3.x", "wsgi" ]
What WSGI servers are available for Python 3 and [PEP 3333](http://www.python.org/dev/peps/pep-3333/)?
As pointed out by Gabriel, Apache/mod\_wsgi 3.X supports Python 3. Other options are [CherryPy](http://cherrypy.org/) WSGI server and [uWSGI](http://projects.unbit.it/uwsgi/).
WSGI servers for Python 3 (PEP 3333)
7,422,556
3
2011-09-14T20:25:05Z
9,482,737
8
2012-02-28T13:24:46Z
[ "python", "python-3.x", "wsgi" ]
What WSGI servers are available for Python 3 and [PEP 3333](http://www.python.org/dev/peps/pep-3333/)?
# Waitress [Waitress](http://docs.pylonsproject.org/projects/waitress/en/latest/) is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.6+ and Pyth...
Python List & for-each access (Find/Replace in built-in list)
7,423,118
14
2011-09-14T21:20:43Z
7,423,184
30
2011-09-14T21:26:14Z
[ "python", "list", "reference", "foreach", "replace" ]
I originally thought Python was a pure pass-by-reference language. Coming from C/C++ I can't help but think about memory management, and it's hard to put it out of my head. So I'm trying to think of it from a Java perspective and think of everything but primitives as a pass by reference. Problem: I have a list, conta...
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables. As noted in the comments, when you loop over a list with something like `for member in my_list` the `member` variable is bound to each successive list element. However, re-assigning that variable withi...
Python List & for-each access (Find/Replace in built-in list)
7,423,118
14
2011-09-14T21:20:43Z
7,423,918
10
2011-09-14T22:49:10Z
[ "python", "list", "reference", "foreach", "replace" ]
I originally thought Python was a pure pass-by-reference language. Coming from C/C++ I can't help but think about memory management, and it's hard to put it out of my head. So I'm trying to think of it from a Java perspective and think of everything but primitives as a pass by reference. Problem: I have a list, conta...
Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python. Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptio...
Python RPM I built won't install
7,423,300
16
2011-09-14T21:37:53Z
7,423,994
16
2011-09-14T22:58:24Z
[ "python", "rpm", "rpmbuild", "rpm-spec" ]
Because I have to install multiple versions of Python on multiple Oracle Linux servers which are built via a kickstart process, I wanted to build a python rpm for our yum repository. I was able to build Python manually using 'make altinstall' which doesn't install over your default system Python installation, so I thou...
You should be able to fix this issue by adding the following line to your spec file: > ``` > AutoReq: no > ``` Here is my understanding of why this is necessary. When rpmbuild runs across .py files with a #! (shebang) it will automatically add the binary that the shebang specifies as a requirement. Not only that, if ...
python dict: get vs setdefault
7,423,428
25
2011-09-14T21:52:20Z
7,423,475
10
2011-09-14T21:56:35Z
[ "python", "dictionary", "get", "setdefault" ]
The following two expressions seem equivalent to me. Which one is preferable? ``` data = [('a', 1), ('b', 1), ('b', 2)] d1 = {} d2 = {} for key, val in data: # variant 1) d1[key] = d1.get(key, []) + [val] # variant 2) d2.setdefault(key, []).append(val) ``` The results are the same but which version ...
You might want to look at `defaultdict` in the `collections` module. The following is equivalent to your examples. ``` from collections import defaultdict data = [('a', 1), ('b', 1), ('b', 2)] d = defaultdict(list) for k, v in data: d[k].append(v) ``` There's more [here](http://docs.python.org/library/collecti...
python dict: get vs setdefault
7,423,428
25
2011-09-14T21:52:20Z
7,423,648
16
2011-09-14T22:14:40Z
[ "python", "dictionary", "get", "setdefault" ]
The following two expressions seem equivalent to me. Which one is preferable? ``` data = [('a', 1), ('b', 1), ('b', 2)] d1 = {} d2 = {} for key, val in data: # variant 1) d1[key] = d1.get(key, []) + [val] # variant 2) d2.setdefault(key, []).append(val) ``` The results are the same but which version ...
Your two examples do the same thing, but that doesn't mean `get` and `setdefault` do. The difference between the two is basically manually setting `d[key]` to point to the list every time, versus `setdefault` automatically setting `d[key]` to the list only when it's unset. Making the two methods as similar as possibl...
python dict: get vs setdefault
7,423,428
25
2011-09-14T21:52:20Z
7,427,632
8
2011-09-15T08:03:43Z
[ "python", "dictionary", "get", "setdefault" ]
The following two expressions seem equivalent to me. Which one is preferable? ``` data = [('a', 1), ('b', 1), ('b', 2)] d1 = {} d2 = {} for key, val in data: # variant 1) d1[key] = d1.get(key, []) + [val] # variant 2) d2.setdefault(key, []).append(val) ``` The results are the same but which version ...
The accepted answer from agf isn't comparing like with like. After: ``` print timeit("d[0] = d.get(0, []) + [1]", "d = {1: []}", number = 10000) ``` `d[0]` contains a list with 10,000 items whereas after: ``` print timeit("d.setdefault(0, []) + [1]", "d = {1: []}", number = 10000) ``` `d[0]` is simply `[]`. i.e. th...
How can I display text over columns in a bar chart in matplotlib?
7,423,445
26
2011-09-14T21:54:04Z
7,423,575
34
2011-09-14T22:07:34Z
[ "python", "matplotlib", "bar-chart" ]
I have a bar chart and I want over each column to display some text,how can I do that ?
I believe this will point you in the right direction: <http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html>. The part that you are most interested in is: ``` def autolabel(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x()+rect.get_width()/2., 1.0...
How should I perform imports in a python module without polluting its namespace?
7,423,744
17
2011-09-14T22:26:19Z
7,424,025
7
2011-09-14T23:02:36Z
[ "python", "module", "python-import" ]
I am developing a Python package for dealing with some scientific data. There are multiple frequently-used classes and functions from other modules and packages, including numpy, that I need in virtually every function defined in any module of the package. What would be the Pythonic way to deal with them? I have consi...
Import the modile as a whole: `import foreignmodule`. What you claim as a drawback is actually a benefit. Namely, prepending tne module name makes your code easier to maintain and makes it more self-documenting. Six months from now when you look at a line of code like `foo = Bar(baz)` you may ask yourself which module...
How should I perform imports in a python module without polluting its namespace?
7,423,744
17
2011-09-14T22:26:19Z
7,424,390
12
2011-09-14T23:59:00Z
[ "python", "module", "python-import" ]
I am developing a Python package for dealing with some scientific data. There are multiple frequently-used classes and functions from other modules and packages, including numpy, that I need in virtually every function defined in any module of the package. What would be the Pythonic way to deal with them? I have consi...
Go ahead and do your usual `from W import X, Y, Z` and then use the `__all__` special symbol to define what actual symbols you intend people to import from your module: ``` __all__ = ('MyClass1', 'MyClass2', 'myvar1', …) ``` This defines the symbols that will be imported into a user's module if they `import *` from...
Python csv writer wrong separator?
7,423,869
8
2011-09-14T22:42:53Z
7,423,995
15
2011-09-14T22:58:31Z
[ "python", "excel", "csv", "localization" ]
Disclaimer: I'm in Europe. According to [this page](http://www.paessler.com/knowledgebase/en/topic/2293-i-have-trouble-opening-csv-files-with-microsoft-excel-is-there-a-quick-way-to-fix-this) Excel uses the semicolon `;` as default separator in Europe to "prevent conflicts" with the decimal comma. Now, I have this Py...
This is because the csv.excel dialect is not locale aware. If you wish to explicitly use semicolons as the delimiter then you need to either explicitly pass the delimiter to csv.open as ``` writer = csv.writer(open("data.csv", "wb"), delimiter=";") ``` or create a new dialect and register it ``` class excel_semicolo...
threading.Condition vs threading.Event
7,424,590
23
2011-09-15T00:29:45Z
7,424,818
24
2011-09-15T01:11:39Z
[ "python", "multithreading", "concurrency", "condition-variable" ]
I have yet to find a clear explanation of the differences between `Condition` and `Event` classes in the **`threading`** module. Is there a clear use case where one would be more helpful than the other? All the examples I can find use a producer-consumer model as an example, where `queue.Queue` would be the more straig...
Simply put, you use a Condition when threads are interested in waiting for something to become true, **and once its true, to have exclusive access to some shared resource.** Whereas you use an Event when threads are just interested in waiting for something to become true. In essence, Condition is an abstracted Event ...
How to install Python module on Ubuntu
7,426,677
12
2011-09-15T06:23:52Z
7,429,157
17
2011-09-15T10:08:22Z
[ "python", "python-module" ]
I just wrote a function on Python. Then, I wanted to make it module and install on my Ubuntu 11.04. Here is what I did. 1. Created setup.py along with function.py file. 2. Built distribution file using $Python2.7 setup.py sdist 3. Then installed it $Python2.7 setup.py install All was going fine. But, later I wanted t...
Most installation requires: `sudo python setup.py install` Otherwise, you won't be able to write to the installation directories. I'm pretty sure that (unless you were root), you got an error when you did `python2.7 setup.py install`
Trying to use Selenium 2 with Python bindings, but I'm getting an import error
7,426,851
15
2011-09-15T06:43:39Z
7,431,021
47
2011-09-15T12:43:05Z
[ "python", "webdriver", "selenium-webdriver" ]
I just installed Selenium 2 by doing `pip install selenium` and just copied some example tests to make sure that it's working: ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driv...
It sounds like you have some other module in your path named "selenium", and python is trying to import that one because it comes earlier in your python path. Did you name your file "selenium.py", for example? To debug, import selenium with a simple `import selenium` then print the name of the file that was imported w...
Trying to use Selenium 2 with Python bindings, but I'm getting an import error
7,426,851
15
2011-09-15T06:43:39Z
12,616,784
23
2012-09-27T08:09:02Z
[ "python", "webdriver", "selenium-webdriver" ]
I just installed Selenium 2 by doing `pip install selenium` and just copied some example tests to make sure that it's working: ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driv...
Old question, but I did the same thing too. Named my file 'selenium.py' and it gave this very error message. Renamed the file to something else, but still got the same error. The problem was, that the selenium.pyc file had been created, since I ran the script from the terminal. Removed the .pyc file and it ran like a c...
Dead simple argparse example wanted: 1 argument, 3 results
7,427,101
259
2011-09-15T07:11:46Z
7,427,376
200
2011-09-15T07:39:48Z
[ "python", "argparse" ]
The [documentation](http://docs.python.org/library/argparse.html) for the [argparse python module](http://www.doughellmann.com/PyMOTW/argparse/), while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command lin...
Here's the way I do it with `argparse` (with multiple args): ``` parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-f','--foo', help='Description for foo argument', required=True) parser.add_argument('-b','--bar', help='Description for bar argument', required=True) args =...
Dead simple argparse example wanted: 1 argument, 3 results
7,427,101
259
2011-09-15T07:11:46Z
8,493,862
127
2011-12-13T17:58:08Z
[ "python", "argparse" ]
The [documentation](http://docs.python.org/library/argparse.html) for the [argparse python module](http://www.doughellmann.com/PyMOTW/argparse/), while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command lin...
The `argparse` documentation is reasonably good but leaves out a few useful details which might not be obvious. (@Diego Navarro already mentioned some of this but I'll try to expand on his answer slightly.) Basic usage is as follows: ``` parser = argparse.ArgumentParser() parser.add_argument('-f', '--my-foo', default=...
Dead simple argparse example wanted: 1 argument, 3 results
7,427,101
259
2011-09-15T07:11:46Z
10,374,436
41
2012-04-29T17:48:21Z
[ "python", "argparse" ]
The [documentation](http://docs.python.org/library/argparse.html) for the [argparse python module](http://www.doughellmann.com/PyMOTW/argparse/), while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command lin...
Matt is asking about positional parameters in argparse, and I agree that the Python documentation is lacking on this aspect. There's not a single, complete example in the ~20 odd pages that shows both **parsing and using positional parameters**. None of the other answers here show a complete example of positional para...
Dead simple argparse example wanted: 1 argument, 3 results
7,427,101
259
2011-09-15T07:11:46Z
22,045,954
87
2014-02-26T15:31:21Z
[ "python", "argparse" ]
The [documentation](http://docs.python.org/library/argparse.html) for the [argparse python module](http://www.doughellmann.com/PyMOTW/argparse/), while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command lin...
My understanding of the original question is two-fold. First, in terms of the simplest possible argparse example, I'm surprised that I haven't seen it here. Of course, to be dead-simple, it's also all overhead with little power, but it might get you started. ``` import argparse parser = argparse.ArgumentParser() pars...
How can I fake request.POST and GET params for unit testing in Flask?
7,428,124
13
2011-09-15T08:43:29Z
7,428,881
14
2011-09-15T09:43:49Z
[ "python", "flask" ]
I would like to fake request parameters for unit testing. How can I achieve this in Flask? Thanks.
Did you read [Flask docs about testing](http://flask.pocoo.org/docs/testing/#logging-in-and-out)? You can use following: ``` self.app.post('/path-to-request', data=dict(var1='data1', var2='data2', ...)) self.app.get('/path-to-request') ```
How can I fake request.POST and GET params for unit testing in Flask?
7,428,124
13
2011-09-15T08:43:29Z
23,982,148
18
2014-06-01T16:48:00Z
[ "python", "flask" ]
I would like to fake request parameters for unit testing. How can I achieve this in Flask? Thanks.
POST: ``` self.app.post('/endpoint', data=params) ``` GET: ``` self.app.get('/endpoint', query_string=params) ```
Redefining logging root logger
7,428,426
6
2011-09-15T09:08:06Z
7,430,495
9
2011-09-15T12:04:27Z
[ "python", "logging" ]
At my current project there are thousand of code lines which looks like this: ``` logging.info("bla-bla-bla") ``` I don't want to change all these lines, but I would change log behavior. My idea is changing root logger to other `Experimental` logger, which is configured by ini-file: ``` [loggers] keys = Experimenta...
You're advised *not* to redefine the root logger in the way you describe. In general you should only use the root logger directly for small scripts - for larger applications, best practice is to use ``` logger = logging.getLogger(__name__) ``` in each module where you use logging, and then make calls to logger.info()...
Sparse coding in Python
7,428,741
3
2011-09-15T09:33:02Z
15,495,469
7
2013-03-19T09:17:56Z
[ "python", "machine-learning" ]
I'm looking for a library which implements the most common sparse coding and dictionary learning algorithms with a python interface, any suggestion?
Regarding this question; seems that a library which implements most of Sparse Coding algorithms is SPAMS <http://spams-devel.gforge.inria.fr/> which now offers Python support
how to get all the values from a numpy array excluding a certain index?
7,429,118
14
2011-09-15T10:05:00Z
7,429,338
8
2011-09-15T10:22:33Z
[ "python", "numpy" ]
I have a numpy array and I want to retrieve all the elements except a certain index. For example, consider the following array ``` a = [0,1,2,3,4,5,5,6,7,8,9] ``` if I specify index 3, then the resultant should be ``` a = [0,1,2,4,5,5,6,7,8,9] ```
``` a_new = np.delete(a,3,0) ``` 3 here is the index you wish to remove, 0 is the axis (zero in this case if using 1D array). See [numpy.delete](http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html)
how to get all the values from a numpy array excluding a certain index?
7,429,118
14
2011-09-15T10:05:00Z
7,429,344
25
2011-09-15T10:22:59Z
[ "python", "numpy" ]
I have a numpy array and I want to retrieve all the elements except a certain index. For example, consider the following array ``` a = [0,1,2,3,4,5,5,6,7,8,9] ``` if I specify index 3, then the resultant should be ``` a = [0,1,2,4,5,5,6,7,8,9] ```
Like resizing, removing elements from an numpy array is a slow operation (especially for large arrays since it requires allocating space and copying all the data from the original array to the new array). It should be avoided if possible. Often you can do avoid it by working with a [masked array](http://docs.scipy.org...
Debugging Python code in Notepad++
7,430,123
10
2011-09-15T11:35:38Z
7,430,185
8
2011-09-15T11:41:03Z
[ "python", "debugging", "notepad++" ]
I use Notepad++ for writing and running Python scripts. It is a great text editor, except for debugging. Is there a way to step through the code, use break points, view variable values etc. in Notepad++ like you can in Visual Studio?
I really hope someone tells me I'm wrong (I'd love to have that feature in Notepad++) but, Notepad++ is designed as a programmers editor, not an IDE. While it has a lot of cool functionality, that level of debugging isn't part of the core tool. Not seeing anything in the [npp-plugins](http://sourceforge.net/projects/n...
Debugging Python code in Notepad++
7,430,123
10
2011-09-15T11:35:38Z
7,433,655
9
2011-09-15T15:45:10Z
[ "python", "debugging", "notepad++" ]
I use Notepad++ for writing and running Python scripts. It is a great text editor, except for debugging. Is there a way to step through the code, use break points, view variable values etc. in Notepad++ like you can in Visual Studio?
Does such a plug-in exist? Not that I know of. I agree completely with qor72 on that note. Is it possible to create such a plugin / functionality? Possibly. After doing some quick digging, I did find a plugin that looks promising, [Python Script](http://npppythonscript.sourceforge.net/). In short it allows you to run...
Using reverse() in django forms
7,430,502
6
2011-09-15T12:05:20Z
7,430,924
9
2011-09-15T12:36:40Z
[ "python", "django", "django-forms" ]
I'm trying to use django's [reverse()](https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse) function in definition of django form for my custom widget, but am getting an error: ``` ImproperlyConfigured The included urlconf urls doesn't have any patterns in it ``` Here is the code: ``` class WorkForm(form...
The problem might be that the form is defined before the urls have been loaded. Django 1.4 will have a [`reverse_lazy`](https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy) feature that would solve this problem. You could implement it in your project yourself (see [changeset 16121](https://code.django...
Comparing dates to check for old files
7,430,928
7
2011-09-15T12:36:44Z
7,431,013
15
2011-09-15T12:42:18Z
[ "python", "time", "comparison", "filemtime" ]
I want to check if a file is older than a certain amount of time (e.g. 2 days). I managed to get the file creation time in such a way: ``` >>> import os.path, time >>> fileCreation = os.path.getctime(file) >>> file 1314015638 >>> time.ctime(os.path.getctime(file)) 'Mon Aug 22 14:20:38 2011' ``` How can I now check i...
``` now = time.time() twodays_ago = now - 60*60*24*2 # Number of seconds in two days if fileCreation < twodays_ago: print "File is more than two days old" ```
Comparing dates to check for old files
7,430,928
7
2011-09-15T12:36:44Z
18,126,680
12
2013-08-08T12:58:00Z
[ "python", "time", "comparison", "filemtime" ]
I want to check if a file is older than a certain amount of time (e.g. 2 days). I managed to get the file creation time in such a way: ``` >>> import os.path, time >>> fileCreation = os.path.getctime(file) >>> file 1314015638 >>> time.ctime(os.path.getctime(file)) 'Mon Aug 22 14:20:38 2011' ``` How can I now check i...
I know, it is an old question. But I was looking for something similar and came up with this alternative solution: ``` from os import path from datetime import datetime, timedelta two_days_ago = datetime.now() - timedelta(days=2) filetime = datetime.fromtimestamp(path.getctime(file)) if filetime < two_days_ago: pr...
list union with duplicates
7,430,934
6
2011-09-15T12:37:02Z
7,431,019
12
2011-09-15T12:42:52Z
[ "python" ]
I need to unite two lists in Python3,where duplicates can exist,and for one set of these the resulting list will contain as many as max in both lists.An example might clarify it: ``` [1,2,2,5]( some operator)[2,5,5,5,9]=[1,2,2,5,5,5,9] ``` Ideas?
You can use the [`collections.Counter`](http://docs.python.org/library/collections.html#counter-objects) class: ``` >>> from collections import Counter >>> combined = Counter([1,2,2,5]) | Counter([2,5,5,5,9]) >>> list(combined.elements()) [1, 2, 2, 5, 5, 5, 9] ``` It functions as a multiset (an unordered collection w...
Where is the sqlite database file created by Django?
7,431,138
11
2011-09-15T12:51:09Z
7,431,385
14
2011-09-15T13:09:01Z
[ "python", "django", "osx", "sqlite" ]
I've got python installed and sqlite is included with it... but where is the sqlite db file path that was created with `manage.py syncdb`? I'm on a mac.
In the `settings.py` file, there is a variable called `DATABASES`. It is a dict, and one of its keys is `default`, which maps to another dict. This subdict has a key, `NAME`, which has the path of the SQLite database. This is an example of a project of mine: ``` CURRENT_DIR= '/Users/brandizzi/Documents/software/netun...
Django - Template display model verbose_names & objects
7,432,142
5
2011-09-15T14:03:33Z
7,435,173
10
2011-09-15T17:41:23Z
[ "python", "django", "templates" ]
I need to display several models name & objects in a template Here is my **view** ``` def contents(request): """Lists contents""" objects = [ Model1.objects.all(), Model2.objects.all(), Model3.objects.all(), Model4.objects.all(), ] return render_to_response('content/contents.html', objs , co...
For accessing it in your template, you've probably noticed by now that Django doesn't let you use underscore prefixes to access attributes from templates. Thus, the easiest way to access the verbose name for any given object without having to create a model method on each model would be to just create a template tag: ...
Regular expression that matches the third instance of something? (python)
7,432,908
2
2011-09-15T14:52:57Z
7,432,947
9
2011-09-15T14:55:32Z
[ "python", "regex" ]
I'm trying to create a regular expression that will match the third instance of a / in a url, i.e. so that only the website's name itself will be recorded, nothing else. So <http://www.stackoverflow.com/questions/answers/help/> after being put through the regex will be <http://www.stackoverflow.com> I've been playing...
I suggest you use [`urlparse`](http://docs.python.org/library/urlparse.html) for parsing URLs: ``` In [1]: from urlparse import urlparse In [2]: urlparse('http://www.stackoverflow.com/questions/answers/help/').netloc Out[2]: 'www.stackoverflow.com' ``` `.netloc` includes the port number if present (e.g. `www.stackov...
Can Pickle handle multiple object references
7,433,963
6
2011-09-15T16:06:52Z
7,434,285
7
2011-09-15T16:30:34Z
[ "python", "pickle" ]
If I have objects `a` and `b` and both reference object `obj`, what happens when I Pickle and then restore the objects? Will the pickled data 'know' that `a` and `b` both referenced the same object and restore everything accordingly, or will the two get two different — and initially equal — objects?
As @aix points out, `pickle` understands multiple references to the same object, but only within a single pickling. That is, pickle always pickles a single object. If that object has references within it, those references will be properly shared in the unpickled object. But if you call pickle twice, to pickle two obje...
Python: "bad interpreter: No such file or directory" when running django-admin.py
7,434,484
3
2011-09-15T16:45:40Z
7,434,608
17
2011-09-15T16:55:31Z
[ "python", "django" ]
I've googled the hell out of this, but all of the solutions I've found seem to solve problems that are not mine. I created a project in a virtual environment in `/Users/[user]/Documents/projects/[project]` using `virtualenv` and installed Django. Later, I deleted that project and installed Django on my system outside...
I'm not sure how you did to produce this error, but the fix for you is to change `/usr/local/bin/django-admin.py` [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) to `#!/usr/bin/env python`. --- Actually if you install django in a virtualenv the `django-admin.py` will have the shebang set to the python inte...
How do I configure Tastypie to treat a field as unique?
7,435,986
7
2011-09-15T18:57:42Z
7,498,100
7
2011-09-21T10:14:20Z
[ "python", "django", "tastypie" ]
How do I configure Tastypie to treat a field as unique? My expectation would be to receive some sort of non-500 error (possibly a 409 conflict?) as a response if I try to insert duplicate entries for the field marked as unique. --- I've looked through the docs and it looks like it should be obvious to me, but for som...
Here is how I solved the problem: Based on the documentation for validation, I was able to implement a custom validator that checked the uniqueness of the field for me. <http://django-tastypie.readthedocs.org/en/latest/validation.html> In the CompanyResource, I added to the class meta a CustomValidation. I placed the...
Python: Transform a Dictionary into a list of lists
7,436,267
2
2011-09-15T19:20:43Z
7,436,314
10
2011-09-15T19:24:07Z
[ "python", "list", "dictionary", "python-2.7" ]
Basically, I have a dictionary that I want to transform into a list of lists (with each component list consisting of the key and value from the dictionary). The reason I am doing this is so that I can iterate through this new list with a for loop and do something with both the key and the value. If there is an easier ...
``` for key, value in my_dict.iteritems() ``` This will iterate through the dictionary, storing each key in `key` and each value in `value`. See the [docs](http://docs.python.org/library/stdtypes.html#dict.iteritems).
Identifying listening ports using Python
7,436,801
3
2011-09-15T20:02:26Z
7,436,912
8
2011-09-15T20:13:14Z
[ "python", "sockets", "ports" ]
In translating some scripts from bash, I am encountering many uses of netstat -an to find if one of our services is listening. While I know I can just use subprocess.call or other even popen I would rather use a pythonic solution so I am not leveraging the unix environment we are operating in. From what I have read th...
How about trying to connect... ``` import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex(('127.0.0.1', 3306)) if result == 0: print('socket is open') s.close() ```
How to generate a `kwargs` list?
7,437,213
7
2011-09-15T20:43:38Z
7,437,238
14
2011-09-15T20:45:37Z
[ "python", "kwargs" ]
From an external file I generate the following dictionary: ``` mydict = { 'foo' : 123, 'bar' : 456 } ``` Given a function that takes a `**kwargs` argument, how can generate the keyword-args from that dictionary?
``` def foo(**kwargs): pass foo(**{ 'foo' : 123, 'bar' : 456 }) ```
How is it possible to use raw_input() in a Python Git hook?
7,437,261
10
2011-09-15T20:48:22Z
7,437,724
13
2011-09-15T21:36:10Z
[ "python", "git", "githooks" ]
I am writing a pre-commit hook for Git that runs pyflakes and checks for tabs and trailing spaces in the modified files ([code on Github](https://github.com/badzil/miscellaneous/blob/master/pre-commit)). I would like to make it possible to override the hook by asking for user confirmation as follows: ``` answer = raw_...
You could use: ``` sys.stdin = open('/dev/tty') answer = raw_input('Commit anyway? [N/y] ') if answer.strip().lower().startswith('y'): ... ``` --- `git commit` calls `python .git/hooks/pre-commit`: ``` % ps axu ... unutbu 21801 0.0 0.1 6348 1520 pts/1 S+ 17:44 0:00 git commit -am line 5a unutbu ...
Disable IPython Exit Confirmation
7,438,112
72
2011-09-15T22:21:16Z
7,438,144
16
2011-09-15T22:23:46Z
[ "python", "ipython" ]
It's really irritating that every time I type `exit()`, I get prompted with a confirmation to exit; of course I want to exit! Otherwise, I would not have written `exit()`!!! Is there a way to override IPython's default behaviour to make it exit without a prompt?
just type `Exit`, with capital `E`. Alternatively, start IPython with: ``` $ ipython -noconfirm_exit ``` Or for newer versions of IPython: ``` $ ipython --no-confirm-exit ```
Disable IPython Exit Confirmation
7,438,112
72
2011-09-15T22:21:16Z
8,020,342
79
2011-11-05T13:05:14Z
[ "python", "ipython" ]
It's really irritating that every time I type `exit()`, I get prompted with a confirmation to exit; of course I want to exit! Otherwise, I would not have written `exit()`!!! Is there a way to override IPython's default behaviour to make it exit without a prompt?
If you also want `Ctrl-D` to exit without confirmation, in IPython 0.11, add `c.TerminalInteractiveShell.confirm_exit = False` to your config file. If you don't have a config file yet, run `ipython profile create` to create one. Note [this ticket](https://code.djangoproject.com/ticket/17078) if you're working within ...
Disable IPython Exit Confirmation
7,438,112
72
2011-09-15T22:21:16Z
15,167,804
15
2013-03-01T22:16:52Z
[ "python", "ipython" ]
It's really irritating that every time I type `exit()`, I get prompted with a confirmation to exit; of course I want to exit! Otherwise, I would not have written `exit()`!!! Is there a way to override IPython's default behaviour to make it exit without a prompt?
In ipython version 0.11 or higher, 1. Run with `--no-confirm-exit` OR 2. Exit via 'exit' instead of control-D OR 3. Make sure the directory exists (or run `ipython profile create` to create it) and add these lines to $HOME/.ipython/profile\_default/ipython\_config.py: ``` c = get_config() c.TerminalInteract...
Duplicate virtualenv
7,438,681
53
2011-09-15T23:43:01Z
7,438,771
77
2011-09-15T23:54:32Z
[ "python", "django", "virtualenv" ]
I have an existing environment in virtualenv, with a lot of packages, but an old Django version. What if I want to **duplicate** this environment, so I can have another environment in which I can install a newer Django version, but keeping all packages that are already in the other environment?
The easiest way is to use pip to generate a requirements file. A requirements file is basically a file that contains a list of all the python packages you want to install (or have already installed in case of file generated by pip), and what versions they're at. To generate a requirements file, go into your original v...
Duplicate virtualenv
7,438,681
53
2011-09-15T23:43:01Z
16,732,402
10
2013-05-24T10:02:35Z
[ "python", "django", "virtualenv" ]
I have an existing environment in virtualenv, with a lot of packages, but an old Django version. What if I want to **duplicate** this environment, so I can have another environment in which I can install a newer Django version, but keeping all packages that are already in the other environment?
Another option is to use [`virtualenv-clone`](https://github.com/edwardgeorge/virtualenv-clone) package: > A script for cloning a non-relocatable virtualenv.
Why do python functions have a __dict__?
7,439,023
4
2011-09-16T00:41:30Z
7,439,100
7
2011-09-16T00:57:18Z
[ "python" ]
In Python, functions created using `def` and `lambda` have a `__dict__` attribute so you can dynamically add attributes to them. Having a `__dict__` for every function has a memory cost. An empty `dict` uses 140 bytes in CPython 2.6. Adding attributes to a function isn't a particularly common thing to do, and you can ...
[PEP 232](http://www.python.org/dev/peps/pep-0232/) has an extensive discussion about this, you might wanna take a look.
python - Count number of occurences of each number
7,439,578
8
2011-09-16T02:37:25Z
7,439,601
8
2011-09-16T02:42:33Z
[ "python", "json" ]
I have a long string of numbers seperated by commas. I can search and count the number of occurences of most numbers, or more accurately, 2 digit numbers. IF I have a number sequences like: `1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2` and I want to count how many times the number `1` appears I should really get `5`. Howeve...
On 2.7+, just `split` and use the `collections.Counter`: ``` from collections import Counter numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2" numcount = Counter(numstring.split(',')) ``` or, Pre-2.7: ``` from collections import defaultdict numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2" numcount = defaultdict(i...
Email parsing: TypeError: parse() takes at least 2 arguments (2 given)
7,440,284
11
2011-09-16T04:46:33Z
7,440,357
7
2011-09-16T05:06:04Z
[ "python" ]
I am getting the following error while calling a built-in function to parse an email in Python. ``` txt = parser.Parser.parse(fd, headersonly=False) ``` And the error i got is ``` TypeError: parse() takes at least 2 arguments (2 given). ``` Can anybody tell me the way to solve this problem?
This is because `.parse()` is an instance method, not a class method. Instead, try `Parser().parse(…)` or possibly [email.message\_from\_file](http://docs.python.org/library/email.parser.html#email.message_from_file)/[email.message\_from\_string](http://docs.python.org/library/email.parser.html#email.message_from_st...
Email parsing: TypeError: parse() takes at least 2 arguments (2 given)
7,440,284
11
2011-09-16T04:46:33Z
14,976,438
13
2013-02-20T09:33:12Z
[ "python" ]
I am getting the following error while calling a built-in function to parse an email in Python. ``` txt = parser.Parser.parse(fd, headersonly=False) ``` And the error i got is ``` TypeError: parse() takes at least 2 arguments (2 given). ``` Can anybody tell me the way to solve this problem?
I got the same basic error for a different reason: specifying an argument that has a default value but forgetting to give an argument that doesn't have any default value. For instance, ``` def greeting(name,root = "Hello, "): print root + name greeting(root = "Good morning, ") ``` returns ``` TypeError: greeting...
Problem importing 'time' as a module in python
7,441,269
3
2011-09-16T07:08:27Z
7,441,338
7
2011-09-16T07:16:11Z
[ "python" ]
I am trying to import the `time` module to be able to use the `time.sleep(secs)` functionality. The problem I think which might be there is the fact that I have also imported `datetime` and that might be messing it up ``` import datetime import time . . some code utilizing `datetime` . . time.sleep(seconds) ``` The ...
You've almost certainly defined a variable or a function called `time`. Try renaming it.
Understanding django loaddata or right way to dumpdata for fixutes
7,441,927
3
2011-09-16T08:20:29Z
10,323,028
7
2012-04-25T20:11:55Z
[ "python", "django" ]
I have serialized 4 apps from my project with manage.py dumpdata. But when I'm trying to load it in test as a fixture - i'm getting "Validation Error : This value must be True or False". How to understand, which line of dump is wrong? Or in which model I got this error? UPD: Problem is coming from invalid fixture. Bu...
First of all are you using any custom/3rd party Fields? Although if you did and django's dumpdata couldn't serialize it, it would raise an exception I suppose. Anyway since last time I checked there was not any sufficient documentation for writing a custom django serializer, here is an example for serializing a custom...
try / else with return in try block
7,442,133
23
2011-09-16T08:40:39Z
7,442,169
36
2011-09-16T08:44:04Z
[ "python", "exception-handling" ]
I came across a strange behavior in python. I could not find information about this in the python help or on SE so here it is: ``` def divide(x, y): print 'entering divide' try: return x/y except: print 'error' else: print 'no error' finally: print 'exit' print divi...
<http://docs.python.org/reference/compound_stmts.html#the-try-statement> > The optional else clause is executed if and when control flows off the > end of the try clause. > > Currently, control “flows off the end” except in the case of an > exception or the execution of a return, continue, or break statement.
how to get the neighboring elements in a numpy array with taking boundaries into account?
7,442,570
3
2011-09-16T09:22:23Z
7,442,855
7
2011-09-16T09:46:00Z
[ "python", "numpy" ]
I want to get the neighbors of the certain element in the numpy array. Lets consider following example ``` a = numpy.array([0,1,2,3,4,5,6,7,8,9]) ``` So I want to specify position 5 and want to get three neighbors from both sides. It can be done ``` index = 5 num_neighbor=3 left = a[index-num_neighbor:i...
``` left = a[max(0,index-num_neighbor):index] ```
Do JavaScript arrays have an equivalent of Python’s “if a in list”?
7,442,850
3
2011-09-16T09:45:20Z
7,442,880
7
2011-09-16T09:47:50Z
[ "javascript", "python" ]
If I have a list in Python, I can check whether a given value is in it using the `in` operator: ``` >>> my_list = ['a', 'b', 'c'] >>> 'a' in my_list True >>> 'd' in my_list False ``` If I have an array in JavaScript, e.g. ``` var my_array = ['a', 'b', 'c']; ``` Can I check whether a value is in it in a similar wa...
``` var my_array = ['a', 'b', 'c']; alert(my_array.indexOf('b')); alert(my_array.indexOf('dd')); ``` if element not found, you will receive **-1**
How do I do dependency parsing in NLTK?
7,443,330
11
2011-09-16T10:26:49Z
33,808,164
19
2015-11-19T15:36:30Z
[ "python", "nlp", "grammar", "nltk" ]
Going through the NLTK book, it's not clear how to generate a dependency tree from a given sentence. The relevant section of the book:[sub-chapter on dependency grammar](http://nltk.googlecode.com/svn/trunk/doc/book/book.html#dependency-grammar) gives an [example figure](http://nltk.googlecode.com/svn/trunk/doc/book/c...
We can use Stanford parser from NLTK. First, download stanford core nlp tools from [here](http://nlp.stanford.edu/software/corenlp.shtml). Then, extract the zip file anywhere you like. Next, load the model and use it through NLTK ``` from nltk.parse.stanford import StanfordDependencyParser path_to_jar = 'path_to/sta...
How to detect if the console does support ANSI escape codes in Python?
7,445,658
21
2011-09-16T13:45:53Z
7,445,778
8
2011-09-16T13:55:13Z
[ "python", "console", "stdout", "ansi-escape", "windows-controls" ]
In order to detect if console, correctly `sys.stderr` or `sys.stdout`, I was doing the following test: ``` if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): if platform.system()=='Windows': # win code (ANSI not supported but there are alternatives) else: # use ANSI escapes else: # no col...
I can tell you how others have solved this problem, but it's not pretty. If you look at ncurses as an example (which needs to be able to run on all kinds of different terminals), you'll see that they use a [terminal capabilities database](http://www.gnu.org/software/termutils/manual/termcap-1.3/html_mono/termcap.html) ...
How to detect if the console does support ANSI escape codes in Python?
7,445,658
21
2011-09-16T13:45:53Z
22,254,892
9
2014-03-07T16:02:28Z
[ "python", "console", "stdout", "ansi-escape", "windows-controls" ]
In order to detect if console, correctly `sys.stderr` or `sys.stdout`, I was doing the following test: ``` if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): if platform.system()=='Windows': # win code (ANSI not supported but there are alternatives) else: # use ANSI escapes else: # no col...
Django users can use `django.core.management.color.supports_color` function. ``` if supports_color(): ... ``` The code they use is: ``` def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform =...
" RuntimeError: thread.__init__() not called" when subclassing threading.Thread
7,445,742
12
2011-09-16T13:52:48Z
7,445,805
19
2011-09-16T13:56:54Z
[ "python", "multithreading" ]
I need to run as many threads of class Observer as there are elements in list dirlist. When I run it python console it works all right. ``` class Observer(Thread): def run(self): naptime = random.randint(1,10) print(self.name + ' starting, running for %ss.' % naptime) time.sleep(naptime) ...
``` >>> master_thread.start() RuntimeError: thread.__init__() not called ``` Make sure to call `Thread.__init__()` in your `Master.__init__`: ``` class Master(Thread): def __init__(self, dirlist): super(Master, self).__init__() self.dirlist = dirlist ```
No module named pkg_resources
7,446,187
246
2011-09-16T14:26:54Z
10,538,412
461
2012-05-10T16:29:28Z
[ "python", "django", "virtualenv", "setuptools", "pip" ]
I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: ``` Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources ``` pkg\_r...
I encountered the same `ImportError` today while trying to use pip. Somehow the `setuptools` package had been deleted in my Python environment. To fix the issue, run the setup script for `setuptools`: ``` wget https://bootstrap.pypa.io/ez_setup.py -O - | python ``` (or if you don't have `wget` installed (e.g. OS X),...
No module named pkg_resources
7,446,187
246
2011-09-16T14:26:54Z
12,547,749
23
2012-09-22T21:13:04Z
[ "python", "django", "virtualenv", "setuptools", "pip" ]
I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: ``` Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources ``` pkg\_r...
It also happened to me. I think the problem will happen if the requirements.txt contains a "distribute" entry while the virtualenv uses setuptools. Pip will try to patch setuptools to make room for distribute, but unfortunately it will fail half way. The easy solution is delete your current virtualenv then make a new ...
No module named pkg_resources
7,446,187
246
2011-09-16T14:26:54Z
19,514,783
20
2013-10-22T10:06:07Z
[ "python", "django", "virtualenv", "setuptools", "pip" ]
I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: ``` Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources ``` pkg\_r...
I have seen this error while trying to install rhodecode to a virtualenv on ubuntu 13.10. For me the solution was to run ``` pip install --upgrade setuptools pip install --upgrade distribute ``` before I run easy\_install rhodecode.
No module named pkg_resources
7,446,187
246
2011-09-16T14:26:54Z
23,396,459
12
2014-04-30T19:26:51Z
[ "python", "django", "virtualenv", "setuptools", "pip" ]
I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: ``` Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources ``` pkg\_r...
I had this error earlier and the highest rated answer gave me an error trying to download the `ez_setup.py` file. I found another source so you can run the command: `curl http://peak.telecommunity.com/dist/ez_setup.py | python` I found that I also had to use `sudo` to get it working, so you may need to run: `sudo cu...
No module named pkg_resources
7,446,187
246
2011-09-16T14:26:54Z
26,955,537
43
2014-11-16T09:31:20Z
[ "python", "django", "virtualenv", "setuptools", "pip" ]
I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: ``` Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources ``` pkg\_r...
``` sudo apt-get install --reinstall python-pkg-resources ``` fixed it for me in Debian. Seems like uninstalling some .deb packages (twisted set in my case) has broken the path python uses to find packages