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
Shuffle an array with python, randomize array item order with python
473,973
120
2009-01-23T18:34:29Z
19,631,040
7
2013-10-28T09:23:27Z
[ "python", "arrays", "random", "order" ]
What's the easiest way to shuffle an array with python?
When dealing with regular Python lists, `random.shuffle()` will do the job just as the previous answers show. But when it come to `ndarray`(`numpy.array`), `random.shuffle` seems to break the original `ndarray`. Here is an example: ``` import random import numpy as np import numpy.random a = np.array([1,2,3,4,5,6]) ...
Which GTK widget combination to use for scrollable column of widgets?
474,034
3
2009-01-23T18:53:35Z
474,134
7
2009-01-23T19:23:01Z
[ "python", "gtk", "pygtk", "widget" ]
I'm working with PyGTK, trying to come up with a combination of widgets that will do the following: * Let me add an endless number of widgets in a column * Provide a vertical scrollbar to get to the ones that run off the bottom * Make the widgets' width adjust to fill available horizontal space when the window is resi...
* An endless number of widgets in a column: Sounds like a GtkVBox. * Vertical scrollbar: Put your VBox in a GtkScrolledWindow. * Horizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to mostly handle this (You wi...
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
68
2009-01-23T21:07:05Z
474,543
78
2009-01-23T21:09:33Z
[ "python", "timer" ]
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C). This code will run as a daemon and is effectively like calling the python script every min...
Use the [sched](http://docs.python.org/library/sched.html) module, which implements a general purpose event scheduler. ``` import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print "Doing stuff..." # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_somet...
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
68
2009-01-23T21:07:05Z
474,570
30
2009-01-23T21:14:06Z
[ "python", "timer" ]
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C). This code will run as a daemon and is effectively like calling the python script every min...
You might want to consider [Twisted](http://twistedmatrix.com/trac/) which is a python networking library that implements the [Reactor Pattern](http://en.wikipedia.org/wiki/Reactor_pattern). ``` from twisted.internet import task from twisted.internet import reactor timeout = 60.0 # Sixty seconds def doWork(): #d...
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
68
2009-01-23T21:07:05Z
13,217,744
21
2012-11-04T10:26:10Z
[ "python", "timer" ]
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C). This code will run as a daemon and is effectively like calling the python script every min...
The easier way I believe to be: ``` import time def executeSomething(): #code here time.sleep(60) while True: executeSomething() ``` This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
68
2009-01-23T21:07:05Z
25,251,804
31
2014-08-11T20:25:25Z
[ "python", "timer" ]
I want to repeatedly execute a function in Python every 60 seconds forever (just like an [NSTimer](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html) in Objective C). This code will run as a daemon and is effectively like calling the python script every min...
Just lock your time loop to the system clock. Easy. ``` import time starttime=time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0)) ```
Python Applications: Can You Secure Your Code Somehow?
475,216
6
2009-01-24T00:40:09Z
475,246
12
2009-01-24T00:56:39Z
[ "python", "security", "reverse-engineering" ]
If there is truly a 'best' way, what *is* the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general? If there isn't a 'best' way, what are the different options available? Background: I love coding in Python and would love to release more apps with it...
Security through obscurity *never* works. If you must use a proprietary license, enforce it through the law, not half-baked obfuscation attempts. If you're worried about them learning your security (e.g. cryptography) algorithm, the same applies. Real, useful, security algorithms (like AES) are secure even though the ...
Python Applications: Can You Secure Your Code Somehow?
475,216
6
2009-01-24T00:40:09Z
475,394
7
2009-01-24T03:02:04Z
[ "python", "security", "reverse-engineering" ]
If there is truly a 'best' way, what *is* the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general? If there isn't a 'best' way, what are the different options available? Background: I love coding in Python and would love to release more apps with it...
Even if you use a compiled language like C# or Java, people can perform reverse engineering if they are motivated and technically competent. Obfuscation is not a reliable protection against this. You can add prohibition against reverse-engineering to your end-user license agreement for your software. Most proprietary ...
group by in django
475,552
3
2009-01-24T05:15:15Z
476,156
12
2009-01-24T15:37:28Z
[ "python", "django", "django-models" ]
How can i create simple group by query in trunk version of django? I need something like ``` SELECT name FROM mytable GROUP BY name ``` actually what i want to do is simply get all entries with distinct names.
If you need all the distinct names, just do this: ``` Foo.objects.values('name').distinct() ``` And you'll get a list of dictionaries, each one with a **name** key. If you need other data, just add more attribute names as parameters to the .values() call. Of course, if you add in attributes that may vary between rows...
Python - why use "self" in a class?
475,871
68
2009-01-24T11:13:19Z
475,873
107
2009-01-24T11:17:47Z
[ "python", "oop" ]
How do these 2 classes differ? ``` class A(): x=3 class B(): def __init__(self): self.x=3 ``` Is there any significant difference?
`A.x` is a *class variable*. `B`'s `self.x` is an *instance variable*. i.e. `A`'s `x` is shared between instances. It would be easier to demonstrate the difference with something that can be modified like a list: ``` #!/usr/bin/env python class A: x = [] def add(self): self.x.append(1) class B: ...
Python - why use "self" in a class?
475,871
68
2009-01-24T11:13:19Z
475,905
17
2009-01-24T11:41:32Z
[ "python", "oop" ]
How do these 2 classes differ? ``` class A(): x=3 class B(): def __init__(self): self.x=3 ``` Is there any significant difference?
A.x is a class variable, and will be shared across all instances of A, unless specifically overridden within an instance. B.x is an instance variable, and each instance of B has its own version of it. I hope the following Python example can clarify: ``` >>> class Foo(): ... i = 3 ... def bar(self)...
Python - why use "self" in a class?
475,871
68
2009-01-24T11:13:19Z
475,919
42
2009-01-24T11:57:59Z
[ "python", "oop" ]
How do these 2 classes differ? ``` class A(): x=3 class B(): def __init__(self): self.x=3 ``` Is there any significant difference?
Just as a side note: `self` is actually just a randomly chosen word, that everyone uses, but you could also use `this`, `foo`, or `myself` or anything else you want, it's just the first parameter of every non static method for a class. This means that the word `self` is not a language construct but just a name: ``` >>...
Python - why use "self" in a class?
475,871
68
2009-01-24T11:13:19Z
11,342,486
13
2012-07-05T10:30:27Z
[ "python", "oop" ]
How do these 2 classes differ? ``` class A(): x=3 class B(): def __init__(self): self.x=3 ``` Is there any significant difference?
I used to explain it with this example ``` # By TMOTTM class Machine: # Class Variable counts how many machines have been created. # The value is the same for all objects of this class. counter = 0 def __init__(self): # Notice: no 'self'. Machine.counter += 1 # Instance var...
Order a QuerySet by aggregate field value
476,017
24
2009-01-24T13:26:58Z
476,024
9
2009-01-24T13:34:36Z
[ "python", "database", "django", "order" ]
Let's say I have the following model: ``` class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( Use...
You can write your own sort in Python very simply. ``` def getScore( anObject ): return anObject.score() objects= list(Contest.objects.get( pk = id ).image_set) objects.sort( key=getScore ) ``` This works nicely because we sorted the list, which we're going to provide to the template.
Order a QuerySet by aggregate field value
476,017
24
2009-01-24T13:26:58Z
476,033
44
2009-01-24T13:44:37Z
[ "python", "database", "django", "order" ]
Let's say I have the following model: ``` class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( Use...
Oh, of course I forget about new aggregation support in Django and its `annotate` functionality. So query may look like this: ``` Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' ) ```
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
12
2009-01-24T16:14:12Z
476,382
13
2009-01-24T17:39:41Z
[ "python", "file", "mp3", "duplicates", "id3" ]
How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect? I know I can do an [MD5](http://en.wikipedia.org/wiki/MD5) checksum of the files content but that won't work for different bitrates. And I don't k...
The exact same question that people at the old AudioScrobbler and currently at [MusicBrainz](http://musicbrainz.org/) have worked on since long ago. For the time being, the Python project that can aid in your quest, is [Picard](http://musicbrainz.org/doc/PicardDownload), which will tag audio files (not only MPEG 1 Laye...
Django "Did you mean?" query
476,394
3
2009-01-24T17:47:30Z
476,420
9
2009-01-24T18:07:09Z
[ "python", "django", "spell-checking" ]
I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string. ``` Entry.objects.filter(headline__contains=query) ``` This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are loo...
You could try using python's [difflib](http://docs.python.org/library/difflib) module. ``` >>> from difflib import get_close_matches >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('app...
Resolving a relative url path to its absolute path
476,511
43
2009-01-24T19:09:59Z
476,521
70
2009-01-24T19:20:19Z
[ "python", "url", "path" ]
Is there a library in python that works like this? ``` >>> resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html") 'http://www.asite.com/folder/anotherpage.html' >>> resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html") 'http://www.asite.com/folder/folder2/anot...
Yes, there is [`urlparse.urljoin`](https://docs.python.org/2/library/urlparse.html#urlparse.urljoin), or [`urllib.parse.urljoin`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin) for Python 3. ``` >>> try: from urlparse import urljoin # Python2 ... except ImportError: from urllib.parse import ...
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
476,586
13
2009-01-24T20:10:48Z
476,641
18
2009-01-24T21:00:00Z
[ "python", "metaprogramming", "design-patterns", "factory", "metaclass" ]
I recently discovered metaclasses in python. Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, e...
This reminds me of the eternal quest some people seem to be on to make a "generic implementation of a pattern." Like a factory that can create any object ([including another factory](http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12)), or a general-purpose dependency injection framework that is far more co...
Resources for TDD aimed at Python Web Development
476,668
15
2009-01-24T21:19:07Z
476,858
13
2009-01-24T23:08:13Z
[ "python", "tdd", "testing" ]
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed...
I wrote a series of blogs on [TDD in Django](http://blog.cerris.com/category/django-tdd/) that covers some TDD with the [nose testing framework](http://somethingaboutorange.com/mrl/projects/nose/). There are a lot of free online resources out there for learning about TDD: * [The c2 wiki article](http://c2.com/cgi-bin...
Resources for TDD aimed at Python Web Development
476,668
15
2009-01-24T21:19:07Z
10,648,767
8
2012-05-18T07:50:46Z
[ "python", "tdd", "testing" ]
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed...
Can I plug my own tutorial, which covers the materials from the official Django tutorial, but uses full TDD all the way - including "proper" functional/acceptance tests using the Selenium browser-automation tool... <http://tdd-django-tutorial.com> [update 2014-01] I now have a book, just about to be published by OReil...
python string join performance
476,772
10
2009-01-24T22:26:13Z
476,788
12
2009-01-24T22:32:32Z
[ "python", "performance", "string" ]
There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join I tried the following: concatenating two strings as part of a directory path: three approaches: 1. '+' which i should not do 2. s...
Most of the performance issues with string concatenation are ones of asymptotic performance, so the differences become most significant when you are concatenating many long strings. In your sample, you are performing the same concatenation many times. You aren't building up any long string, and it may be that the pytho...
Splitting a large XML file in Python
476,949
9
2009-01-25T00:22:01Z
476,982
9
2009-01-25T00:49:08Z
[ "python", "xml" ]
I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file. My issue is trying to find a clean way to note the start and end of the tags, so that I can g...
There are two common ways to handle XML data. One is called DOM, which stands for Document Object Model. This style of XML parsing is probably what you have seen when looking at documentation, because it reads the entire XML into memory to create the object model. The second is called SAX, which is a streaming method...
Using a java library from python
476,968
25
2009-01-25T00:41:22Z
476,977
8
2009-01-25T00:46:46Z
[ "java", "python", "jython" ]
I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) **Clarification** (at the cost of a long question: apo...
Take a look at [Jython](http://www.jython.org/). It's kind of like JNI, but replace C with Python, i.e. you can call Python from Java and vice versa. It's not totally clear what you're trying to do or why your current approach isn't what you want.
Using a java library from python
476,968
25
2009-01-25T00:41:22Z
3,793,496
37
2010-09-25T10:51:57Z
[ "java", "python", "jython" ]
I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) **Clarification** (at the cost of a long question: apo...
Sorry to ressurect the thread, but there was no accepted answer... You could also use [Py4J](http://py4j.sourceforge.net/index.html). There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods: ``` >>> from py4j.java...
How to read Unicode input and compare Unicode strings in Python?
477,061
26
2009-01-25T02:19:21Z
477,084
14
2009-01-25T02:38:34Z
[ "python", "unicode" ]
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of `raw_input`? Also, I would like to test Unicode strings for equality and it looks like a standard `==` does not work. Thank you for your help !
It should work. `raw_input` returns a byte string which you must decode using the correct encoding to get your `unicode` object. For example, the following works for me under Python 2.5 / Terminal.app / OSX: ``` >>> bytes = raw_input() 日本語 Ελληνικά >>> bytes '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xce\x95...
How to read Unicode input and compare Unicode strings in Python?
477,061
26
2009-01-25T02:19:21Z
477,496
48
2009-01-25T10:25:54Z
[ "python", "unicode" ]
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of `raw_input`? Also, I would like to test Unicode strings for equality and it looks like a standard `==` does not work. Thank you for your help !
[`raw_input()`](https://docs.python.org/2/library/functions.html#raw_input "raw_input()") returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following: ``` import sys, locale text= raw_input().decode(sys.stdin.encoding or locale.getpreferreden...
Python import coding style
477,096
46
2009-01-25T03:06:09Z
477,103
18
2009-01-25T03:19:08Z
[ "python", "coding-style" ]
I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of ``` import foo from bar.baz import quux def myFunction(): foo.this.that(quux...
A few problems with this approach: * It's not immediately obvious when opening the file which modules it depends on. * It will confuse programs that have to analyze dependencies, such as `py2exe`, `py2app` etc. * What about modules that you use in many functions? You will either end up with a lot of redundant imports ...
Python import coding style
477,096
46
2009-01-25T03:06:09Z
477,107
48
2009-01-25T03:24:50Z
[ "python", "coding-style" ]
I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of ``` import foo from bar.baz import quux def myFunction(): foo.this.that(quux...
This does have a few disadvantages. # Testing On the off chance you want to test your module through runtime modification, it may make it more difficult. Instead of doing ``` import mymodule mymodule.othermodule = module_stub ``` You'll have to do ``` import othermodule othermodule.foo = foo_stub ``` This means t...
Python import coding style
477,096
46
2009-01-25T03:06:09Z
477,116
8
2009-01-25T03:32:28Z
[ "python", "coding-style" ]
I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of ``` import foo from bar.baz import quux def myFunction(): foo.this.that(quux...
Another useful thing to note is that the `from module import *` syntax inside of a function has been removed in Python 3.0. There is a brief mention of it under "Removed Syntax" here: <http://docs.python.org/3.0/whatsnew/3.0.html>
Python import coding style
477,096
46
2009-01-25T03:06:09Z
4,789,963
63
2011-01-25T04:23:27Z
[ "python", "coding-style" ]
I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of ``` import foo from bar.baz import quux def myFunction(): foo.this.that(quux...
The (previously) [top-voted answer](http://stackoverflow.com/questions/477096/python-import-coding-style/477107#477107) to this question is nicely formatted but absolutely wrong about performance. Let me demonstrate # Performance ## Top Import ``` import random def f(): L = [] for i in xrange(1000): ...
How to list the files in a static directory?
477,135
8
2009-01-25T03:59:08Z
477,887
7
2009-01-25T16:23:31Z
[ "python", "google-app-engine" ]
I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use. **app.yaml** ``` - url: /data static_dir: data ``` **Python code to list the files** ``` myFiles = [] for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/...
<https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers> They're not where you think they are, GAE puts static content into GoogleFS which is equivalent of a CDN. The idea is that static content is meant to be served directly to your users and not act as a file store ...
Generating and submitting a dynamic number of objects in a form with Django
477,183
2
2009-01-25T05:02:30Z
477,194
8
2009-01-25T05:17:59Z
[ "python", "html", "django", "forms", "web-applications" ]
I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help. Model: ``` class Customer(Model.models): name = models.CharField(max_length=100) active = models.BooleanField() ``` Fo...
[Formsets](http://docs.djangoproject.com/en/dev/topics/forms/formsets/)! Also, the equivalent for forms generated directly models are [model formsets](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1).
How do I simulate flip of biased coin in python?
477,237
20
2009-01-25T06:13:00Z
477,248
37
2009-01-25T06:17:59Z
[ "python", "random", "coin-flipping" ]
In unbiased coin flip H or T occurs 50% of times. But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'. something like this: ``` def flip(p): '''this function return H with probability p''' # do something return result >> [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H...
`random.random()` returns a *uniformly distributed* pseudo-random floating point number in the range [0, 1). This number is less than a given number `p` in the range [0,1) with probability `p`. Thus: ``` def flip(p): return 'H' if random.random() < p else 'T' ``` Some experiments: ``` >>> N = 100 >>> flips = [fl...
How do I simulate flip of biased coin in python?
477,237
20
2009-01-25T06:13:00Z
478,513
7
2009-01-25T23:24:57Z
[ "python", "random", "coin-flipping" ]
In unbiased coin flip H or T occurs 50% of times. But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'. something like this: ``` def flip(p): '''this function return H with probability p''' # do something return result >> [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H...
Do you want the "bias" to be based in symmetric distribuition? Or maybe exponential distribution? Gaussian anyone? Well, here are all the methods, extracted from random documentation itself. First, an example of triangular distribution: ``` print random.triangular(0, 1, 0.7) ``` > **`random.triangular(low, high, mo...
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
477,506
22
2009-01-25T10:32:01Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
Increase the magnitude of `i` for the loop and then reduce it when you need it. ``` for i * 100 in range(0, 100, 10): print i / 100.0 ``` **EDIT: I honestly cannot remember why I thought that would work syntactically** ``` for i in range(0, 11, 1): print i / 10.0 ``` That should have the desired output.
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
477,507
7
2009-01-25T10:32:43Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step. I'd say just use a while loop: ``` i = 0.0 while i <= 1.0: print i i += 0.1 ``` If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be ...
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
477,513
109
2009-01-25T10:35:25Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead: ``` [x * 0.1 for x in range(0, 10)] ``` (Replace the call to range with that expression.) For the more general case, you may want to write a custom function or generator.
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
477,610
132
2009-01-25T11:57:17Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
Building on ['xrange([start], stop[, step])'](http://docs.python.org/library/functions.html#xrange), you can define a generator that accepts and produces any type you choose (stick to types supporting `+` and `<`): ``` >>> def drange(start, stop, step): ... r = start ... while r < stop: ... yield r ... ...
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
477,635
343
2009-01-25T12:26:08Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
You can also use the [NumPy](http://en.wikipedia.org/wiki/NumPy) library (which isn't part of standard library but is relatively easy to obtain) which has the `arange` function: ``` >>> import numpy as np >>> np.arange(0,1,0.1) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) ``` as well as the `li...
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
10,986,098
12
2012-06-11T19:10:53Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
Similar to [R's](http://en.wikipedia.org/wiki/R_%28programming_language%29) `seq` function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value. ``` def seq(start, stop, step=1): n = int(round((stop - start)/float(step))) if n > 1: return([st...
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
12,310,785
7
2012-09-07T02:01:56Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
``` import numpy as np for i in np.arange(0, 1, 0.1): print i ```
Python decimal range() step value
477,486
283
2009-01-25T10:20:43Z
23,715,956
16
2014-05-17T20:50:03Z
[ "python", "floating-point", "range" ]
Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: ``` for i in range(0, 1, 0.1): print i ``` Instead, it says that the step argument cannot be zero, which I did not expect.
`scipy` has a built in function `arange` which generalizes Python's `range()` constructor to satisfy your requirement of float handling. `from scipy import arange`
Easy_install of wxpython has "setup script" error
477,573
11
2009-01-25T11:25:02Z
478,200
9
2009-01-25T20:19:45Z
[ "python", "wxpython", "easy-install" ]
I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command ``` sudo /sw/bin/easy_install wxPython ``` to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installat...
There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation. Instead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
477,820
12
2009-01-25T15:29:44Z
477,839
26
2009-01-25T15:43:26Z
[ "python", "django", "django-templates" ]
<http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup> I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.
Combine [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) with [`operator.itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter) to get a pretty nice solution: ``` from operator import itemgetter from itertools import groupby key = itemgetter('gender') iter...
Python and os.chroot
478,359
2
2009-01-25T21:39:22Z
478,396
7
2009-01-25T22:02:05Z
[ "python", "linux", "chroot" ]
I'm writing a web-server in Python as a hobby project. The code is targeted at \*NIX machines. I'm new to developing on Linux and even newer to Python itself. I am worried about people breaking out of the folder that I'm using to serve up the web-site. The most obvious way to do this is to filter requests for document...
Yes there are pitfalls. Security wise: 1. If you run as root, there are always ways to break out. So first chroot(), then PERMANENTLY drop privileges to an other user. 2. Put nothing which isn't absolutely required into the chroot tree. Especially no suid/sgid files, named pipes, unix domain sockets and device nodes. ...
How to send multiple input field values with same name?
478,382
12
2009-01-25T21:55:12Z
478,406
20
2009-01-25T22:11:21Z
[ "python", "django", "django-forms" ]
I have m2m field, lets say it have name 'relations', so i want to allow user to send as many relations as he wants. I add new input to html with javascript with same name, like so ``` <input type='text' name='relations' value='a' /> <input type='text' name='relations' value='b' /> ``` in cleaned\_data i receive only ...
I don't know how to do that with Forms, but if you want to grab the values in the raw way, here's how I'd do: ``` relations = request.POST.getlist('relations') ```
Python regular expressions with more than 100 groups?
478,458
13
2009-01-25T22:48:56Z
478,470
11
2009-01-25T22:54:05Z
[ "python", "regex" ]
Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.
There is a limit because it would take too much memory to store the complete state machine efficiently. I'd say that if you have more than 100 groups in your re, something is wrong either in the re itself or in the way you are using them. Maybe you need to split the input and work on smaller chunks or something.
How do I simulate biased die in python?
479,236
3
2009-01-26T09:37:47Z
479,299
17
2009-01-26T10:09:03Z
[ "python", "probability" ]
I want to simulate N-sided biased die? ``` def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result >> N=6 >> bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) >> roll(N,bias) 2 ```
A little bit of math here. A regular die will give each number 1-6 with equal probability, namely `1/6`. This is referred to as [uniform distribution](http://en.wikipedia.org/wiki/Uniform_distribution) (the discrete version of it, as opposed to the continuous version). Meaning that if `X` is a random variable describi...
All nodeValue fields are None when parsing XML
479,751
7
2009-01-26T13:15:03Z
479,766
16
2009-01-26T13:21:44Z
[ "python", "xml", "rss", "minidom" ]
I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line. ``` >>> from xml.dom import minidom >>> import urllib2 >>> url ='http://www.digg.com/rss/index.xml' >>> xmldoc = minidom.parse(urllib2.urlopen(url)) >>> channeln...
For RSS feeds you should try the [Universal Feed Parser](http://code.google.com/p/feedparser/) library. It simplifies the handling of RSS feeds immensly. ``` import feedparser d = feedparser.parse('http://www.digg.com/rss/index.xml') title = d.channel.title ```
All nodeValue fields are None when parsing XML
479,751
7
2009-01-26T13:15:03Z
479,780
10
2009-01-26T13:26:05Z
[ "python", "xml", "rss", "minidom" ]
I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line. ``` >>> from xml.dom import minidom >>> import urllib2 >>> url ='http://www.digg.com/rss/index.xml' >>> xmldoc = minidom.parse(urllib2.urlopen(url)) >>> channeln...
This is the syntax you are looking for: ``` >>> print titlenode[0].firstChild.nodeValue digg.com: Stories / Popular ``` Note that the node value is a logical descendant of the node itself.
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
480,227
465
2009-01-26T15:47:01Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
Here you have some alternatives: <http://www.peterbe.com/plog/uniqifiers-benchmark> Fastest one: ``` def f7(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] ``` Why assign `seen.add` to `seen_add` instead of just calling `seen.add`? Python is a dynamic lang...
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
480,229
18
2009-01-26T15:47:14Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
``` from itertools import groupby [ key for key,_ in groupby(sortedList)] ``` The list doesn't even have to be *sorted*, the sufficient condition is that equal values are grouped together. **Edit: I assumed that "preserving order" implies that the list is actually ordered. If this is not the case, then the solution f...
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
15,990,766
28
2013-04-13T17:32:19Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
``` sequence = ['1', '2', '3', '3', '6', '4', '5', '6'] unique = [] [unique.append(item) for item in sequence if item not in unique] ``` unique → `['1', '2', '3', '6', '4', '5']`
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
16,780,848
14
2013-05-27T21:37:23Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
I think if you wanna maintain the order, ## you can try this: ``` list1 = ['b','c','d','b','c','a','a'] list2 = list(set(list1)) list2.sort(key=list1.index) print list2 ``` ## OR similarly you can do this: ``` list1 = ['b','c','d','b','c','a','a'] list2 = sorted(set(list1),key=list1.index) print lis...
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
17,016,257
224
2013-06-10T02:47:13Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
**Important Edit 2015** As [@abarnert](http://stackoverflow.com/a/19279812/1219006) notes, the [`more_itertools`](https://pythonhosted.org/more-itertools/api.html) library (`pip install more_itertools`) contains a [`unique_everseen`](https://pythonhosted.org/more-itertools/api.html#more_itertools.unique_everseen) func...
How do you remove duplicates from a list in whilst preserving order?
480,214
414
2009-01-26T15:43:58Z
19,279,812
7
2013-10-09T18:27:09Z
[ "python", "list", "duplicates", "unique" ]
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: ``` def uniq(input): output = [] for x in input: if x not in output: output.appen...
For another very late answer to another very old question: The [`itertools` recipes](http://docs.python.org/3/library/itertools.html#itertools-recipes) have a function that does this, using the `seen` set technique, but: * Handles a standard `key` function. * Uses no unseemly hacks. * Optimizes the loop by pre-bindin...
Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?
481,266
3
2009-01-26T20:43:24Z
481,280
9
2009-01-26T20:49:24Z
[ "python", "regex", "list" ]
i have a list of regex patterns (stored in a list type) that I would like to apply to a string. Does anyone know a good way to: 1. Apply every regex pattern in the list to the string and 2. Call a different function that is associated with that pattern in the list if it matches. I would like to do this in python ...
``` import re def func1(s): print s, "is a nice string" def func2(s): print s, "is a bad string" funcs = { r".*pat1.*": func1, r".*pat2.*": func2 } s = "Some string with both pat1 and pat2" for pat, func in funcs.items(): if re.search(pat, s): func(s) ``` The above code will call both f...
Can a lambda function call itself recursively in Python?
481,692
49
2009-01-26T22:42:42Z
481,755
48
2009-01-26T23:04:03Z
[ "python", "recursion", "lambda", "y-combinator" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
The only way I can think of to do this amounts to giving the function a name: ``` fact = lambda x: 1 if x == 0 else x * fact(x-1) ``` or alternately, for earlier versions of python: ``` fact = lambda x: x == 0 and 1 or x * fact(x-1) ``` **Update**: using the ideas from the other answers, I was able to wedge the fac...
Can a lambda function call itself recursively in Python?
481,692
49
2009-01-26T22:42:42Z
481,790
21
2009-01-26T23:16:29Z
[ "python", "recursion", "lambda", "y-combinator" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
You can't directly do it, because it has no name. But with a helper function like the Y-combinator Lemmy pointed to, you can create recursion by passing the function as a parameter to itself (as strange as that sounds): ``` # helper function def recursive(f, *p, **kw): return f(f, *p, **kw) def fib(n): # The re...
Can a lambda function call itself recursively in Python?
481,692
49
2009-01-26T22:42:42Z
482,200
9
2009-01-27T02:52:33Z
[ "python", "recursion", "lambda", "y-combinator" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
Yes. I have two ways to do it, and one was already covered. This is my preferred way. ``` (lambda v: (lambda n: n * __import__('types').FunctionType( __import__('inspect').stack()[0][0].f_code, dict(__import__=__import__, dict=dict) )(n - 1) if n > 1 else 1)(v))(5) ```
Can a lambda function call itself recursively in Python?
481,692
49
2009-01-26T22:42:42Z
8,703,135
35
2012-01-02T16:34:15Z
[ "python", "recursion", "lambda", "y-combinator" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
without reduce, map, named lambdas or python internals: ``` (lambda a:lambda v:a(a,v))(lambda s,x:1 if x==0 else x*s(s,x-1))(10) ```
Can a lambda function call itself recursively in Python?
481,692
49
2009-01-26T22:42:42Z
10,144,992
16
2012-04-13T16:50:05Z
[ "python", "recursion", "lambda", "y-combinator" ]
A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?
Contrary to what sth said, you CAN directly do this. ``` (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(lambda f: (lambda i: 1 if (i == 0) else i * f(i - 1)))(n) ``` The first part is the [fixed-point combinator](http://en.wikipedia.org/wiki/Fixed-point_combinator#Example_in_Python) *Y* ...
How would you do the equivalent of preprocessor directives in Python?
482,014
36
2009-01-27T01:10:43Z
482,022
21
2009-01-27T01:14:24Z
[ "python", "preprocessor", "equivalent", "directive" ]
Is there a way to do the following preprocessor directives in Python? ``` #if DEBUG < do some code > #else < do some other code > #endif ```
I suspect you're gonna hate this answer. The way you do that in Python is ``` # code here if DEBUG: #debugging code goes here else: # other code here. ``` Since python is an interpreter, there's no preprocessing step to be applied, and no particular advantage to having a special syntax.
How would you do the equivalent of preprocessor directives in Python?
482,014
36
2009-01-27T01:10:43Z
482,027
9
2009-01-27T01:16:14Z
[ "python", "preprocessor", "equivalent", "directive" ]
Is there a way to do the following preprocessor directives in Python? ``` #if DEBUG < do some code > #else < do some other code > #endif ```
You can use the preprocessor in Python. Just run your scripts through the cpp (C-Preprocessor) in your bin directory. However I've done this with Lua and the benefits of easy interpretation have outweighed the more complex compilation IMHO.
How would you do the equivalent of preprocessor directives in Python?
482,014
36
2009-01-27T01:10:43Z
482,244
79
2009-01-27T03:25:06Z
[ "python", "preprocessor", "equivalent", "directive" ]
Is there a way to do the following preprocessor directives in Python? ``` #if DEBUG < do some code > #else < do some other code > #endif ```
There's `__debug__`, which is a special value that the compiler does preprocess. ``` if __debug__: print "If this prints, you're not running python -O." else: print "If this prints, you are running python -O!" ``` `__debug__` will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove a...
How would you do the equivalent of preprocessor directives in Python?
482,014
36
2009-01-27T01:10:43Z
2,987,538
19
2010-06-07T06:46:27Z
[ "python", "preprocessor", "equivalent", "directive" ]
Is there a way to do the following preprocessor directives in Python? ``` #if DEBUG < do some code > #else < do some other code > #endif ```
I wrote a python preprocessor called pypreprocessor that does exactly what you're describing. [The source and documentation is available on Google Code](http://code.google.com/p/pypreprocessor/). [The package can also be downloaded/installed through the PYPI](http://pypi.python.org/pypi/pypreprocessor/). Here's an e...
Replace Nested For Loops... or not
482,146
5
2009-01-27T02:27:28Z
482,192
14
2009-01-27T02:46:03Z
[ "python", "loops", "for-loop", "nested-loops" ]
I have a script that loops through a series of four (or less) characters strings. For example: ``` aaaa aaab aaac aaad ``` If have been able to implement it with nested for loops like so: ``` chars = string.digits + string.uppercase + string.lowercase for a in chars: print '%s' % a for b in chars: ...
``` import string import itertools chars = string.digits + string.letters MAX_CHARS = 4 for nletters in range(MAX_CHARS): for word in itertools.product(chars, repeat=nletters + 1): print (''.join(word)) ``` That'll print all **`15018570`** words you're looking for. If you want more/less words just change ...
Beginner-level Python threading problems
482,263
7
2009-01-27T03:38:45Z
487,110
9
2009-01-28T10:13:37Z
[ "python", "multithreading", "pygtk" ]
As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI r...
Threading with PyGTK is bit tricky if you want to do it right. Basically, you should not update GUI from within any other thread than main thread (common limitation in GUI libs). Usually this is done in PyGTK using mechanism of queued messages (for communication between workers and GUI) which are read periodically usin...
How do I convert a string to a double in Python?
482,410
89
2009-01-27T05:40:38Z
482,423
144
2009-01-27T05:49:18Z
[ "python" ]
I would like to know how to convert a string containing digits to a double.
``` >>> x = "2342.34" >>> float(x) 2342.3400000000001 ``` There you go. Use float (which is almost always a C double).
How do I convert a string to a double in Python?
482,410
89
2009-01-27T05:40:38Z
6,385,389
25
2011-06-17T11:56:28Z
[ "python" ]
I would like to know how to convert a string containing digits to a double.
The decimal operator might be more in line with what you are looking for: ``` >>> from decimal import Decimal >>> x = "234243.434" >>> print Decimal(x) 234243.434 ```
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
483,680
18
2009-01-27T14:49:46Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
Try this: ``` inv_map = dict(zip(my_map.values(), my_map.keys())) ``` (Note that [the Python docs on dictionary views](https://docs.python.org/library/stdtypes.html#dictionary-view-objects) explicitly guarantee that `.keys()` and `.values()` have their elements in the same order, which allows the approach above to wo...
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
483,685
144
2009-01-27T14:50:22Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
Assuming that the values in the dict are unique: ``` dict((v, k) for k, v in my_map.iteritems()) ```
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
483,833
352
2009-01-27T15:24:56Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
For Python 2.7.x ``` inv_map = {v: k for k, v in my_map.iteritems()} ``` For Python 3+: ``` inv_map = {v: k for k, v in my_map.items()} ```
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
485,368
67
2009-01-27T21:33:26Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
If the values in `my_map` aren't unique: ``` inv_map = {} for k, v in my_map.iteritems(): inv_map[v] = inv_map.get(v, []) inv_map[v].append(k) ```
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
1,679,702
18
2009-11-05T10:41:30Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
``` def inverse_mapping(f): return f.__class__(map(reversed, f.items())) ```
Python reverse / invert a mapping
483,666
269
2009-01-27T14:46:09Z
22,047,530
9
2014-02-26T16:35:03Z
[ "python", "dictionary", "mapping", "inverse" ]
Given a dictionary like so: ``` my_map = { 'a': 1, 'b':2 } ``` How can one invert this map to get: ``` inv_map = { 1: 'a', 2: 'b' } ``` **EDITOR NOTE: `map` changed to `my_map` to avoid conflicts with the built-in function, `map`. Some comments may be affected below.**
Another, more functional, way: ``` my_map = { 'a': 1, 'b':2 } dict(map(reversed, my_map.iteritems())) ```
Problem with encoding in Django templates
484,338
5
2009-01-27T17:23:20Z
484,358
8
2009-01-27T17:29:17Z
[ "python", "django", "unicode", "internationalization", "django-templates" ]
I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the rest of application in both the data, templates ...
Sometimes there's nothing like describing a problem to someone else to help you solve it. :) I should have marked the Python strings as Unicode like this and everything works now: ``` def test(request): return render_to_response("test.html", { "s1": u"dados", ...
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
485,789
33
2009-01-27T23:11:02Z
485,808
36
2009-01-27T23:19:00Z
[ "python" ]
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount). I run into this error. Anyone know what could be wrong or have any suggestions? ``` salesAmount = raw_input (["Insert sale amount here \n"]) ['Insert sale a...
`raw_input` returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: `"AB" * 3` is `"ABABAB"`; how much is `"L" * 3.14` ? Please do not reply `"LLL|"`). You need to parse the string to a numerical value. ...
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
485,789
33
2009-01-27T23:11:02Z
27,488,582
7
2014-12-15T16:28:02Z
[ "python" ]
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount). I run into this error. Anyone know what could be wrong or have any suggestions? ``` salesAmount = raw_input (["Insert sale amount here \n"]) ['Insert sale a...
Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the \* operator on a list. For example...
Python shelve module question
486,490
6
2009-01-28T04:32:14Z
486,676
7
2009-01-28T06:38:26Z
[ "python", "shelve" ]
Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?
The shelve module uses an underlying database package (such as dbm, [gdbm](http://docs.python.org/library/gdbm.html#module-gdbm) or bsddb) . The [*restrictions* pragraph](http://docs.python.org/library/shelve.html#restrictions) says (my emphasis): > The shelve module **does not support concurrent read/write access to...
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
487,045
15
2009-01-28T09:49:35Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
I think you'll like [sandbox](http://github.com/nkryptic/sandbox/tree/master).
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
3,801,789
63
2010-09-27T07:20:31Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
[RVM](http://rvm.io/) works closer to how virtualenv works since it lets you sandbox different ruby versions and their gems, etc.
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
12,663,154
14
2012-09-30T16:58:20Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
No one seems to have mentioned [rbenv](http://rbenv.org/).
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
12,663,612
34
2012-09-30T17:57:19Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
Neither sandbox, RVM, nor rbenv manage the versions of your app's gem dependencies. The tool for that is [bundler](http://gembundler.com/v1.2/rationale.html). * use a [Gemfile](http://gembundler.com/v0.9/gemfile.html) as your application's dependency declaration * use `bundle install` to install explicit versions of t...
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
13,307,346
8
2012-11-09T11:33:15Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
I'll mention the way I do this with Bundler (which I use with RVM - RVM to manage the rubies and a default set of global gems, Bundler to handle project specific gems) ``` bundler install --binstubs --path vendor ``` Running this command in the root of a project will install the gems listed from your Gemfile, put the...
Ruby equivalent of virtualenv?
486,995
126
2009-01-28T09:24:14Z
17,413,767
12
2013-07-01T21:10:18Z
[ "python", "ruby", "virtualenv" ]
Is there something similar to the Python utility [virtualenv](http://pypi.python.org/pypi/virtualenv)? Basically it allows you to install Python packages into a sandboxed environment, so `easy_install django` doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For ...
If you only need to install gems as non-root, try setting the `GEM_HOME` environment variable. Then just run `gem`. For example: ``` $ export GEM_HOME=$HOME/local/gems $ gem install rhc ```
How do I specify input and output data types in python comments?
487,184
11
2009-01-28T10:40:31Z
487,203
13
2009-01-28T10:44:32Z
[ "python", "documentation", "comments", "types" ]
I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice? Is the new functionality in <http://www.python.org/dev/peps/pep-3107/> something I should start using for this?
Function annotations are not for a specific use, they can be used for anything. Tools can be written to extract information from the annotations and do anything you want, including checking types or generating documentation. But python itself does not do anything with the information. You could use to a completely dif...
How do I specify input and output data types in python comments?
487,184
11
2009-01-28T10:40:31Z
487,306
7
2009-01-28T11:30:54Z
[ "python", "documentation", "comments", "types" ]
I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice? Is the new functionality in <http://www.python.org/dev/peps/pep-3107/> something I should start using for this?
If you use [epydoc](http://epydoc.sourceforge.net/) to produce API documentation, you have three choices. * Epytext. * ReStructuredText, RST. * JavaDoc notation, which looks a bit like epytext. I recommend RST because it works well with [sphinx](http://sphinx.pocoo.org/) for generating overall documentation suite tha...
Reducing Django Memory Usage. Low hanging fruit?
487,224
127
2009-01-28T10:52:19Z
487,261
44
2009-01-28T11:11:14Z
[ "python", "django", "profiling", "memory-management", "mod-python" ]
My memory usage increases over time and restarting Django is not kind to users. I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful. I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvio...
Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory. Don't use `mod_python`. It loads an interpreter inside apache. If you need to use apache, use [`mod_wsgi`](http://code.google.com/p/modwsgi/) instead. It is not tricky to switch. It is very ea...
Reducing Django Memory Usage. Low hanging fruit?
487,224
127
2009-01-28T10:52:19Z
501,501
25
2009-02-01T20:18:57Z
[ "python", "django", "profiling", "memory-management", "mod-python" ]
My memory usage increases over time and restarting Django is not kind to users. I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful. I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvio...
If you are running under mod\_wsgi, and presumably spawning since it is WSGI compliant, you can use [Dozer](http://pypi.python.org/pypi/Dozer) to look at your memory usage. Under mod\_wsgi just add this at the bottom of your WSGI script: ``` from dozer import Dozer application = Dozer(application) ``` Then point you...
Reducing Django Memory Usage. Low hanging fruit?
487,224
127
2009-01-28T10:52:19Z
521,918
14
2009-02-06T19:55:59Z
[ "python", "django", "profiling", "memory-management", "mod-python" ]
My memory usage increases over time and restarting Django is not kind to users. I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful. I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvio...
These are the Python memory profiler solutions I'm aware of (not Django related): * [Heapy](http://guppy-pe.sourceforge.net/#Heapy) * [pysizer](http://pysizer.8325.org/) (discontinued) * [Python Memory Validator](http://www.softwareverify.com/python/memory/index.html) (commercial) * [Pympler](http://pypi.python.org/py...
Client Server programming in python?
487,229
8
2009-01-28T10:55:51Z
487,281
18
2009-01-28T11:19:49Z
[ "python", "multithreading", "client", "sockets" ]
Here is source code for multithreaed server and client in python. In the code client and server closes connection after the job is finished. I want to keep the connections alive and send more data over the same connections to **avoid overhead of closing and opening sockets every time**. Following code is from : <http...
Spawning a new thread for every connection is a **really bad** design choice. What happens if you get hit by a lot of connections? In fact, using threads to wait for network IO is not worth it. Your program gets really complex and you get absolutely **no benefit** since waiting for network in threads won't make you **...
Is there a standard way to list names of Python modules in a package?
487,971
57
2009-01-28T15:11:32Z
489,489
11
2009-01-28T21:35:25Z
[ "python", "module", "package" ]
Is there a straightforward way to list the names of all modules in a package, without using `__all__`? For example, given this package: ``` /testpkg /testpkg/__init__.py /testpkg/modulea.py /testpkg/moduleb.py ``` I'm wondering if there is a standard or built-in way to do something like this: ``` >>> package_conten...
``` import module help(module) ```
Is there a standard way to list names of Python modules in a package?
487,971
57
2009-01-28T15:11:32Z
489,649
14
2009-01-28T22:14:44Z
[ "python", "module", "package" ]
Is there a straightforward way to list the names of all modules in a package, without using `__all__`? For example, given this package: ``` /testpkg /testpkg/__init__.py /testpkg/modulea.py /testpkg/moduleb.py ``` I'm wondering if there is a standard or built-in way to do something like this: ``` >>> package_conten...
Maybe this will do what you're looking for? ``` import imp import os MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo') def package_contents(package_name): file, pathname, description = imp.find_module(package_name) if file: raise ImportError('Not a package: %r', package_name) # Use a set because some ma...
Is there a standard way to list names of Python modules in a package?
487,971
57
2009-01-28T15:11:32Z
1,310,912
124
2009-08-21T09:21:02Z
[ "python", "module", "package" ]
Is there a straightforward way to list the names of all modules in a package, without using `__all__`? For example, given this package: ``` /testpkg /testpkg/__init__.py /testpkg/modulea.py /testpkg/moduleb.py ``` I'm wondering if there is a standard or built-in way to do something like this: ``` >>> package_conten...
Using [python2.3 and above](http://docs.python.org/library/pkgutil.html), you could also use the `pkgutil` module: ``` >>> import pkgutil >>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])] ['modulea', 'moduleb'] ``` **EDIT:** Note that the parameter is not a list of modules, but a list of paths, so you mi...
Django: ModelMultipleChoiceField doesn't select initial choices
488,036
18
2009-01-28T15:30:02Z
488,113
8
2009-01-28T15:45:06Z
[ "python", "django", "django-models", "django-forms" ]
ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example: <http://code.djangoproject.com/ticket/5247#comment:6> My models and form: ``` class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): ...
You will need to add an `__init__` method to `Action_Form` to set your initial values, remembering to call `__init__` on the base `ModelForm` class via **super**. ``` class Action_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(Action_Form, self).__init__(*args, **kwargs) self.fie...
Django: ModelMultipleChoiceField doesn't select initial choices
488,036
18
2009-01-28T15:30:02Z
1,530,632
18
2009-10-07T10:01:37Z
[ "python", "django", "django-models", "django-forms" ]
ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example: <http://code.djangoproject.com/ticket/5247#comment:6> My models and form: ``` class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): ...
I'm replying for 1) > 1. How can I make ModelMultipleChoiceField take those "initial" values? This could be done in your `Action_Form` `__init__` method using ModelMultipleChoiceField `initial` attribute. As it says in the Django source code (*db/models/fields/related.py*) in `def formfield(self, **kwargs)`: ``` ...
Django: ModelMultipleChoiceField doesn't select initial choices
488,036
18
2009-01-28T15:30:02Z
3,915,048
8
2010-10-12T13:13:25Z
[ "python", "django", "django-models", "django-forms" ]
ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example: <http://code.djangoproject.com/ticket/5247#comment:6> My models and form: ``` class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): ...
If previous answer wasn't straight-forward enough, I try to answer 1) again: > 1. How can I make ModelMultipleChoiceField take those "initial" values? You can leave `Action_Form` as it was in the original question, and just use this to render exactly what you want: ``` >>> form4 = Action_Form(initial={'from_company'...
How do I make environment variable changes stick in Python?
488,366
10
2009-01-28T16:36:47Z
488,713
7
2009-01-28T18:16:58Z
[ "python", "environment-variables" ]
From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system? The reason I need to do this is because at the studio where I work, tools like May...
> make them stick by committing them to > the system? I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates. If you really do th...