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
Can I use a multiprocessing Queue in a function called by Pool.imap?
3,827,065
21
2010-09-30T01:22:27Z
3,843,313
37
2010-10-01T21:57:55Z
[ "python", "queue", "multiprocessing", "pool" ]
I'm using python 2.7, and trying to run some CPU heavy tasks in their own processes. I would like to be able to send messages back to the parent process to keep it informed of the current status of the process. The multiprocessing Queue seems perfect for this but I can't figure out how to get it work. So, this is my b...
The trick is to pass the Queue as an argument to the initializer. Appears to work with all the Pool dispatch methods. ``` import multiprocessing as mp def f(x): f.q.put('Doing: ' + str(x)) return x*x def f_init(q): f.q = q def main(): jobs = range(1,6) q = mp.Queue() p = mp.Pool(None, f_ini...
strange python behaviour with mixing globals/parameters and function named 'top'
3,828,611
19
2010-09-30T07:23:51Z
3,828,869
13
2010-09-30T08:12:02Z
[ "python", "python-3.x" ]
The following code (not directly in an interpreter, but execute as file) ``` def top(deck): pass def b(): global deck ``` produces the error ``` SyntaxError: name 'deck' is local and global ``` on python2.6.4 and ``` SyntaxError: name 'deck' is parameter and global ``` on python 3.1 python2.4 seems to a...
It looks like it is a bug in the symbol table handling. Python/symtable.c has some code that (although somewhat obfuscated) does indeed treat 'top' as a special identifier: ``` if (!GET_IDENTIFIER(top) || !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { PySymtable_Free(st); return NULL; } ```...
Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?
3,828,723
84
2010-09-30T07:46:08Z
3,828,742
83
2010-09-30T07:48:37Z
[ "python", "encoding", "utf-8", "sys" ]
I have seen few py scripts which use this at the top of the script. In what cases one should use it? ``` import sys reload(sys) sys.setdefaultencoding("utf-8") ```
As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode. This function is only available at Python start-up time, when Python scans the environment. It has to be called in a syste...
Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?
3,828,723
84
2010-09-30T07:46:08Z
6,742,053
12
2011-07-19T03:40:25Z
[ "python", "encoding", "utf-8", "sys" ]
I have seen few py scripts which use this at the top of the script. In what cases one should use it? ``` import sys reload(sys) sys.setdefaultencoding("utf-8") ```
``` #!/usr/bin/env python #-*- coding: utf-8 -*- u = u'moçambique' print u.encode("utf-8") print u chmod +x test.py ./test.py moçambique moçambique ./test.py > output.txt Traceback (most recent call last): File "./test.py", line 5, in <module> print u UnicodeEncodeError: 'ascii' codec can't encode character ...
Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?
3,828,723
84
2010-09-30T07:46:08Z
34,378,962
11
2015-12-20T07:49:25Z
[ "python", "encoding", "utf-8", "sys" ]
I have seen few py scripts which use this at the top of the script. In what cases one should use it? ``` import sys reload(sys) sys.setdefaultencoding("utf-8") ```
## tl;dr The answer is **NEVER**! (unless you really know what you're doing) 9/10 times the solution can be resolved with a proper understanding of encoding/decoding. 1/10 people have an incorrectly defined locale or environment and need to set: ``` PYTHONIOENCODING="UTF-8" ``` in their environment to fix console ...
Generate XML file from model data
3,829,442
10
2010-09-30T09:44:35Z
3,830,144
19
2010-09-30T11:35:41Z
[ "python", "xml", "django", "serialization" ]
I need to write model data (`CharField`s only) to an XML file to contain the data for a flash file. I am new to this, and the process is a little unclear to me for doing this in django. I am creating an xml file, and then writing the text data to the file (as is done with the csv module, but to xml). A very simplified ...
You have two possible solutions here: **1.** You can extend base django xml serializer(`django.core.serializers.xml_serializer.Serializer`) and modify it so it will return data in your structure. You could then run ex. ``` YourSerializer('xml', myModel.objects.filter(instanceIwantTowrite), fields=('fieldName')) ``` ...
Generating all 5 card poker hands
3,829,457
36
2010-09-30T09:46:48Z
3,831,682
17
2010-09-30T14:41:28Z
[ "python", "algorithm", "permutation", "combinatorics", "poker" ]
This problem sounds simple at first glance, but turns out to be a lot more complicated than it seems. It's got me stumped for the moment. There are 52c5 = 2,598,960 ways to choose 5 cards from a 52 card deck. However, since suits are interchangeable in poker, many of these are equivalent - the hand 2H 2C 3H 3S 4D is e...
Your overall approach is sound. I'm pretty sure the problem lies with your `make_canonical` function. You can try printing out the hands with num\_cards set to 3 or 4 and look for equivalencies that you've missed. I found one, but there may be more: ``` # The inputs are equivalent and should return the same value pri...
Assert that a method was called in a Python unit test
3,829,742
27
2010-09-30T10:32:55Z
3,829,849
8
2010-09-30T10:49:13Z
[ "python", "unit-testing" ]
Suppose I have the following code in a Python unit test: ``` aw = aps.Request("nv1") aw2 = aps.Request("nv2", aw) ``` Is there an easy way to assert that a particular method (in my case `aw.Clear()`) was called during the second line of the test? e.g. is there something like this: ``` #pseudocode: assertMethodIsCall...
I'm not aware of anything built-in. It's pretty simple to implement: ``` class assertMethodIsCalled(object): def __init__(self, obj, method): self.obj = obj self.method = method def called(self, *args, **kwargs): self.method_called = True self.orig_method(*args, **kwargs) ...
Assert that a method was called in a Python unit test
3,829,742
27
2010-09-30T10:32:55Z
4,734,439
46
2011-01-19T10:59:22Z
[ "python", "unit-testing" ]
Suppose I have the following code in a Python unit test: ``` aw = aps.Request("nv1") aw2 = aps.Request("nv2", aw) ``` Is there an easy way to assert that a particular method (in my case `aw.Clear()`) was called during the second line of the test? e.g. is there something like this: ``` #pseudocode: assertMethodIsCall...
I use [Mock](http://pypi.python.org/pypi/mock/) for this: ``` from mock import patch from PyQt4 import Qt @patch.object(Qt.QMessageBox, 'aboutQt') def testShowAboutQt(self, mock): self.win.actionAboutQt.trigger() self.assertTrue(mock.called) ``` For your case, it could look like this: ``` import mock def t...
Python, using os.system - Is there a way for Python script to move past this without waiting for call to finish?
3,830,036
5
2010-09-30T11:18:11Z
3,830,083
9
2010-09-30T11:25:16Z
[ "python", "django", "command-line", "os.system" ]
I am trying to use Python (through Django framework) to make a Linux command line call and have tried both os.system and os.open but for both of these it seems that the Python script hangs after making the command line call as the call is for instantiating a server (so it never "finishes" as its meant to be long-runnin...
I'm not sure, but I think [the subprocess module](http://docs.python.org/library/subprocess.html) with its Popen is much more flexible than os.popen. If I recall correctly it includes asynchronous process spawning, which I think is what you're looking for. **Edit:** It's been a while since I used the subprocess module...
Check memory usage of subprocess in Python
3,830,658
6
2010-09-30T12:56:15Z
3,830,958
9
2010-09-30T13:28:25Z
[ "python", "subprocess" ]
I'm developing an application in Python on Ubuntu and I'm running external binaries from within python using subprocess. Since these binaries are generated at run time and can go rogue, I need to keep a strict tab on the amount of memory footprint and runtime of these binaries. Is there someway I can limit or monitor t...
You can use Python's [resource](http://docs.python.org/library/resource.html) module to set limits before spawning your subprocess. For monitoring, resource.getrusage() will give you summarized information over all your subprocesses; if you want to see per-subprocess information, you can do the /proc trick in that oth...
matplotlib pyplot colorbar question
3,831,569
3
2010-09-30T14:30:57Z
3,831,793
11
2010-09-30T14:53:47Z
[ "python", "matplotlib" ]
Dear all, I'm trying to perform a scatter plot with color with an associated color bar. I would like the colorbar to have string values rather than numerical values, as I'm comparing two different data sets each one with different colorvalues (but in any case between a maximum and minimum values). Here the code I'm usi...
``` cbar.ax.set_yticklabels(['Low','High']) ``` For example, ``` import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt data = np.random.random((10, 4)) data2 = np.random.random((10, 4)) plt.subplots_adjust(bottom = 0.1) plt.xlabel(r'$\partial \Delta/\partial\Phi[$mm$/^{\circ}]$', fontsize = 1...
Printing negative values as hex in python
3,831,833
7
2010-09-30T14:57:33Z
3,831,853
15
2010-09-30T15:00:42Z
[ "python", "number-formatting" ]
I have the following code snippet in C++: ``` for (int x = -4; x < 5; ++x) printf("hex x %d 0x%08X\n", x, x); ``` And its output is ``` hex x -4 0xFFFFFFFC hex x -3 0xFFFFFFFD hex x -2 0xFFFFFFFE hex x -1 0xFFFFFFFF hex x 0 0x00000000 hex x 1 0x00000001 hex x 2 0x00000002 hex x 3 0x00000003 hex x 4 0x00000004...
You need to explicitly restrict the integer to 32-bits: ``` for x in range(-4,5): print "hex x %d 0x%08X" % (x, x & 0xffffffff) ```
how to change the color of a single bar if condition is True matplotlib
3,832,809
5
2010-09-30T16:39:28Z
3,833,007
13
2010-09-30T17:04:03Z
[ "python", "matplotlib" ]
I've been googleing to find if it's possible to change only the color of a bar in a graph made by matplotlib. Imagine this graph: ![alt text](http://i.stack.imgur.com/HmFtg.png) let's say I've evaluation 1 to 10 and for each one I've a graph generate when the user choice the evaluation. For each evaluation one of thi...
You need to use `color` instead of `facecolor`. You can also specify color as a list instead of a scalar value. So for your example, you could have `color=['r','b','b','b','b']` For example, ``` import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) N = 5 ind = np.arange(N) ...
Install particular version with easy_install
3,833,011
63
2010-09-30T17:05:03Z
3,833,035
110
2010-09-30T17:08:24Z
[ "python", "version", "easy-install" ]
I'm trying to install `lxml`. I've had a look at the website, and version 2.2.8 looked reasonable to me but when I did `easy_install lxml`, it installed version 2.3.beta1 which is not really what I want I presume. What is the best way to fix this and how can I force easy\_install to install a particular version? (Mac...
I believe the way to specify a version would be like this: ``` easy_install lxml==2.2.8 ``` I (and most other Python users I suspect) stopped using `easy_install` and started using `pip` some time ago, so a solution in those terms is: ``` easy_install pip pip install lxml==2.2.8 ``` (`pip` has several benefits, inc...
Install particular version with easy_install
3,833,011
63
2010-09-30T17:05:03Z
3,833,042
18
2010-09-30T17:09:24Z
[ "python", "version", "easy-install" ]
I'm trying to install `lxml`. I've had a look at the website, and version 2.2.8 looked reasonable to me but when I did `easy_install lxml`, it installed version 2.3.beta1 which is not really what I want I presume. What is the best way to fix this and how can I force easy\_install to install a particular version? (Mac...
From the easy\_install [documentation](http://peak.telecommunity.com/DevCenter/EasyInstall#changing-the-active-version): `easy_install PackageName==1.2.3`
Python equivalent of Ruby's each_slice(count)
3,833,589
4
2010-09-30T18:19:19Z
3,833,630
7
2010-09-30T18:24:46Z
[ "python", "ruby" ]
What is pythons equivalent of Ruby's `each_slice(count)`? I want to take 2 elements from list for each iteration. Like for `[1,2,3,4,5,6]` I want to handle `1,2` in first iteration then `3,4` then `5,6`. Ofcourse there is a roundabout way using index values. But is there a direct function or someway to do this di...
There is a [recipe](http://docs.python.org/library/itertools.html#recipes) for this in the [itertools documentation](http://docs.python.org/library/itertools.html) called grouper: ``` from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args ...
testing for numeric equality when variable is modified inside loop
3,834,253
4
2010-09-30T19:46:31Z
3,834,261
7
2010-09-30T19:48:28Z
[ "python", "floating-point" ]
I am new to python and I was writing something like: ``` t = 0. while t<4.9: t = t + 0.1 if t == 1.: ... do something ... ``` I noticed that the if statement was never being executed. So I modified the code to look like this: ``` ''' Case a''' t = 0. while t<4.9: t = t + 0.1 print(t) ...
The problem is that binary floating point arithmetic is not precise so you will get small errors in the calculations. In particular the number 0.1 has no exact binary representation. When you calculate using floating point numbers the very small errors cause the result to be slightly incorrect from what you might expec...
Flatten a dictionary of dictionaries (2 levels deep) of lists in Python
3,835,192
5
2010-09-30T22:11:28Z
3,835,227
15
2010-09-30T22:18:13Z
[ "python", "data-structures", "mapreduce", "dictionary" ]
I'm trying to wrap my brain around this but it's not flexible enough. In my Python script I have a dictionary of dictionaries of lists. (Actually it gets a little deeper but that level is not involved in this question.) I want to flatten all this into one long list, throwing away all the dictionary keys. Thus I want ...
I hope you realize that any order you see in a dict is accidental -- it's there only because, when shown on screen, **some** order has to be picked, but there's absolutely no guarantee. Net of ordering issues among the various sublists getting catenated, ``` [x for d in thedict.itervalues() for alist in d.itervalu...
Python, using subprocess.Popen to make linux command line call? I'm getting "[Errno 2] No such file or directory"
3,835,400
4
2010-09-30T22:56:35Z
3,835,414
11
2010-09-30T23:00:56Z
[ "python", "command-line", "subprocess", "popen" ]
I'm trying to follow the info I can find about subprocess.Popen as I want to make a linux command line call.. I am trying as below but am getting the error "[Errno 2] No such file or directory". I'm not trying to open a file so I don't understand this error, and it works fine (although with other issues relating to wai...
``` import subprocess proc=subprocess.Popen(['ls','-l']) # <-- Change the command here proc.communicate() ``` `Popen` expects a list of strings. The first string is typically the program to be run, followed by its arguments. Sometimes when the command is complicated, it's convenient to use `shlex.split` to compos...
How do I specify a range of unicode characters
3,835,917
12
2010-10-01T01:18:32Z
3,836,052
16
2010-10-01T01:59:37Z
[ "python", "regex", "unicode" ]
How do I specify a range of unicode characters from `' '` (space) to `\u00D7FF`? I have a regular expression like `r'[\u0020-\u00D7FF]'` and it won't compile saying that it's a bad range. I am new to Unicode regular expressions so I haven't had this problem before. Is there a way to make this compile or a regular exp...
The syntax of your unicode range will not do what you expect. 1. The raw `r''` string prevents `\u` escapes from being parsed, and the regex engine will not do this. The only range in this set is `[0-\]`: ``` >>> re.compile(r'[\u0020-\u00d7ff]', re.DEBUG) in literal 117 literal 48 literal 48 ...
How to parse the "request body" using python CGI?
3,836,828
7
2010-10-01T05:49:08Z
3,837,018
14
2010-10-01T06:40:55Z
[ "python", "parsing", "cgi", "request" ]
I just need to write a simple python CGI script to parse the contents of a POST request containing JSON. This is only test code so that I can test a client application until the actual server is ready (written by someone else). I can read the cgi.FieldStorage() and dump the keys() but the request body containing the J...
If you're using CGI, just read data from `stdin`: ``` import sys data = sys.stdin.read() ```
How to get Network Interface Card names in Python?
3,837,069
11
2010-10-01T06:55:31Z
3,837,540
8
2010-10-01T08:22:54Z
[ "python", "networking" ]
I am totally new to python programming so please be patient with me. Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo? If so how do you do it? I have researched but so far I have only found codes to get IP addresses and MAC addresses only such as ``` import socket socket.gethostbyname(s...
I don't think there's anything in the standard library to query these names. If I needed these names on a Linux system I would parse the output of `ifconfig` or the contents of `/proc/net/dev`. Look at this [blog entry](http://coreygoldberg.blogspot.com/2010/09/python-linux-parse-network-stats-from.html) for a similar...
How to get Network Interface Card names in Python?
3,837,069
11
2010-10-01T06:55:31Z
12,261,059
7
2012-09-04T10:00:58Z
[ "python", "networking" ]
I am totally new to python programming so please be patient with me. Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo? If so how do you do it? I have researched but so far I have only found codes to get IP addresses and MAC addresses only such as ``` import socket socket.gethostbyname(s...
Since this answer pops up in Google when I search for this information, I thought I should add my technique for getting the available interfaces (as well as IP addresses). The very nice module [netifaces](http://alastairs-place.net/projects/netifaces/) takes care of that, in a portable manner.
How to get Network Interface Card names in Python?
3,837,069
11
2010-10-01T06:55:31Z
30,335,064
13
2015-05-19T20:01:09Z
[ "python", "networking" ]
I am totally new to python programming so please be patient with me. Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo? If so how do you do it? I have researched but so far I have only found codes to get IP addresses and MAC addresses only such as ``` import socket socket.gethostbyname(s...
On Linux, you can just list the links in */sys/class/net/* by ``` os.listdir('/sys/class/net/') ``` Not sure if this works on all distributions.
Python set intersection question
3,837,426
7
2010-10-01T08:05:59Z
3,837,594
13
2010-10-01T08:32:24Z
[ "python", "set" ]
I have three sets: ``` s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false ``` I want a function that will return True if every set in the list intersects with at least one other set in the list. Is there a built-in for this o...
``` all(any(a & b for a in s if a is not b) for b in s) ```
How to create a simple Gradient Descent algorithm
3,837,692
7
2010-10-01T08:49:48Z
3,838,390
8
2010-10-01T10:35:36Z
[ "python", "machine-learning" ]
I'm studying simple machine learning algorithms, beginning with a simple gradient descent, but I've got some trouble trying to implement it in python. Here is the example I'm trying to reproduce, I've got data about houses with the (living area (in feet2), and number of bedrooms) with the resulting price : Living are...
First issue is that running this with only one piece of data gives you an underdetermined system... this means it may have an infinite number of solutions. With three variables, you'd expect to have at least 3 data points, preferably much higher. Secondly using gradient descent where the step size is a scaled version ...
How to resolve DNS in Python?
3,837,744
9
2010-10-01T08:57:59Z
3,837,782
17
2010-10-01T09:06:20Z
[ "python", "reverse-dns" ]
I have a DNS script which allow users to resolve DNS names by typing website names on a Windows command prompt. I have looked through several guides on the DNS resolve but my script can't still seem to resolve the names (www.google.com) or (google.com) to IP address. The script outputs an error of ``` Traceback (mos...
input() is the wrong function to use here. It actually evaluates the string that the user entered. Also gethostbyname\_ex returns more than just a string. So your print statement would also have failed. In your case this code should work: ``` import socket x = raw_input ("\nPlease enter a domain name that you wish ...
How can I check if a point is below a line or not?
3,838,319
6
2010-10-01T10:23:21Z
3,838,398
7
2010-10-01T10:36:30Z
[ "python", "math" ]
How can I check if a point is below a line or not ? I've the following data: ``` Line [ {x1,y1}, {x2,y2} ] Points {xA,yA}, {xB,yB} ... ``` I need to write a small algorithm in python to detect points on one side and the other side of the line. thanks
You could try using a cross product -- <http://en.wikipedia.org/wiki/Cross_product>. ``` v1 = {x2-x1, y2-y1} # Vector 1 v2 = {x2-xA, y2-yA} # Vector 1 xp = v1.x*v2.y - v1.y*v2.x # Cross product if xp > 0: print 'on one side' elif xp < 0: print 'on the other' else: print 'on the same line!' ``` You'd ...
How can I check if two segments intersect?
3,838,329
35
2010-10-01T10:24:41Z
3,838,357
27
2010-10-01T10:29:06Z
[ "python", "math" ]
How can I check if 2 segments intersect? I've the following data: ``` Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] ``` I need to write a small algorithm in python to detect if the 2 lines are intersecting. Update: ![alt text](http://i.stack.imgur.com/AlB0e.png)
The equation of a line is: ``` f(x) = A*x + b = y ``` For a segment, it is exactly the same, except that x is included into an interval I. If you have two segments, defined as follow: ``` Segment1 = {(X1, Y1), (X2, Y2)} Segment2 = {(X3, Y3), (X4, Y4)} ``` The abcisse Xa of the potential point of intersection (Xa,Y...
How can I check if two segments intersect?
3,838,329
35
2010-10-01T10:24:41Z
3,842,157
11
2010-10-01T18:47:58Z
[ "python", "math" ]
How can I check if 2 segments intersect? I've the following data: ``` Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] ``` I need to write a small algorithm in python to detect if the 2 lines are intersecting. Update: ![alt text](http://i.stack.imgur.com/AlB0e.png)
Suppose the two segments have endpoints A,B and C,D. The numerically robust way to determine intersection is to check the sign of the four determinants: ``` | Ax-Cx Bx-Cx | | Ax-Dx Bx-Dx | | Ay-Cy By-Cy | | Ay-Dy By-Dy | | Cx-Ax Dx-Ax | | Cx-Bx Dx-Bx | | Cy-Ay Dy-Ay | | Cy-By Dy-By | ``` For inte...
How can I check if two segments intersect?
3,838,329
35
2010-10-01T10:24:41Z
3,842,240
16
2010-10-01T19:00:36Z
[ "python", "math" ]
How can I check if 2 segments intersect? I've the following data: ``` Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] ``` I need to write a small algorithm in python to detect if the 2 lines are intersecting. Update: ![alt text](http://i.stack.imgur.com/AlB0e.png)
You don't have to compute exactly **where** does the segments intersect, but only understand **whether** they intersect at all. This will simplify the solution. The idea is to treat one segment as the "anchor" and separate the second segment into 2 points. Now, you will have to find the relative position of each poi...
How can I check if two segments intersect?
3,838,329
35
2010-10-01T10:24:41Z
9,997,374
28
2012-04-03T16:19:22Z
[ "python", "math" ]
How can I check if 2 segments intersect? I've the following data: ``` Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] ``` I need to write a small algorithm in python to detect if the 2 lines are intersecting. Update: ![alt text](http://i.stack.imgur.com/AlB0e.png)
User @i\_4\_got points to [this page](http://www.bryceboe.com/2006/10/23/line-segment-intersection-algorithm/) with a very efficent solution in Python. I reproduce it here for convenience (since it would have made me happy to have it here): ``` def ccw(A,B,C): return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x) ...
compress a string in python 3?
3,839,323
3
2010-10-01T12:55:33Z
3,839,379
8
2010-10-01T13:01:48Z
[ "python", "string", "python-3.x", "zlib", "compression" ]
I don't understand in 2.X it worked : ``` import zlib zlib.compress('Hello, world') ``` now i have a : ``` zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str ``` How can i compress my string ? Regards Bussiere
This is meant to enforce that you actually have a defined encoding. ``` zlib.compress("Hello, world".encode("utf-8")) b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' zlib.compress("Hello, world".encode("ascii")) b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' ``` The same string could de...
compress a string in python 3?
3,839,323
3
2010-10-01T12:55:33Z
3,839,654
8
2010-10-01T13:33:49Z
[ "python", "string", "python-3.x", "zlib", "compression" ]
I don't understand in 2.X it worked : ``` import zlib zlib.compress('Hello, world') ``` now i have a : ``` zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str ``` How can i compress my string ? Regards Bussiere
In python 2.x strings are bytes string by default. In python 3.x they are unicode strings. Compressing needs a byte string.
Python optparse and spaces in an argument
3,839,791
6
2010-10-01T13:50:46Z
3,839,820
11
2010-10-01T13:54:45Z
[ "python", "optparse" ]
When using optparse i want to get the whole string after an option, but I only get part of it up to the first space. e.g.: ``` python myprog.py --executable python someOtherProg.py ``` What I get in 'executable' is just 'python'. Is it possible to parse such lines using optparse or do you have to use argparse to do...
You can enclose them in quotes to make them work with the existing code. ``` python myprog.py --executable "python someOtherProg.py" ``` > Is it possible to parse such lines using optparse or do you have to use argparse to do it? I don't know if/how you can do it with `optparse` as I haven't really worked with `optp...
Appending turns my list to NoneType
3,840,784
7
2010-10-01T15:45:13Z
3,840,802
15
2010-10-01T15:46:53Z
[ "python", "mutators" ]
In Python Shell, I entered: ``` aList = ['a', 'b', 'c', 'd'] for i in aList: print(i) ``` and got ``` a b c d ``` but when I tried: ``` aList = ['a', 'b', 'c', 'd'] aList = aList.append('e') for i in aList: print(i) ``` and got ``` Traceback (most recent call last): File "<pyshell#22>...
`list.append` is a method that modifies the existing list. It doesn't return a new list -- it returns `None`, like most methods that modify the list. Simply do `aList.append('e')` and your list will get the element appended.
How to downcase the first character of a string in Python?
3,840,843
28
2010-10-01T15:52:28Z
3,840,854
15
2010-10-01T15:53:31Z
[ "python", "string" ]
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase. How can I do that in Python ?
``` def first_lower(s): if len(s) == 0: return s else: return s[0].lower() + s[1:] print first_lower("HELLO") # Prints "hELLO" print first_lower("") # Doesn't crash :-) ```
How to downcase the first character of a string in Python?
3,840,843
28
2010-10-01T15:52:28Z
3,840,867
12
2010-10-01T15:54:42Z
[ "python", "string" ]
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase. How can I do that in Python ?
``` s = "Bobby tables" s = s[0].lower() + s[1:] ```
How to downcase the first character of a string in Python?
3,840,843
28
2010-10-01T15:52:28Z
3,847,369
31
2010-10-02T20:16:10Z
[ "python", "string" ]
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase. How can I do that in Python ?
One-liner which handles empty strings and `None`: ``` func = lambda s: s[:1].lower() + s[1:] if s else '' >>> func(None) >>> '' >>> func('') >>> '' >>> func('MARTINEAU') >>> 'mARTINEAU' ```
Is there a way to make the Tkinter text widget read only?
3,842,155
19
2010-10-01T18:47:34Z
3,842,234
27
2010-10-01T18:59:32Z
[ "python", "text", "tkinter" ]
It doesn't look like it has that attribute, but it'd be really useful to me.
You have to change [the state](http://effbot.org/tkinterbook/text.htm#patterns) of the `Text` widget from `NORMAL` to `DISABLED`: ``` text.config(state=DISABLED) ```
Is there a way to make the Tkinter text widget read only?
3,842,155
19
2010-10-01T18:47:34Z
11,612,656
10
2012-07-23T12:34:52Z
[ "python", "text", "tkinter" ]
It doesn't look like it has that attribute, but it'd be really useful to me.
The [tcl wiki](http://wiki.tcl.tk/1152) describes this problem in detail, and lists three possible solutions: 1. The Disable/Enable trick described in other answers 2. Replace the bindings for the insert/delete events 3. Same as (2), but wrap it up in a separate widget. (2) or (3) would be preferable, however, the so...
Is there a way to make the Tkinter text widget read only?
3,842,155
19
2010-10-01T18:47:34Z
24,965,264
9
2014-07-25T22:12:02Z
[ "python", "text", "tkinter" ]
It doesn't look like it has that attribute, but it'd be really useful to me.
``` text = Text(app, state='disabled', width=44, height=5) ``` Before and after inserting, change the state, otherwise it won't update ``` text.configure(state='normal') text.insert('end', 'Some Text') text.configure(state='disabled') ```
Make Tkinter widget take focus
3,842,220
8
2010-10-01T18:57:17Z
3,842,244
11
2010-10-01T19:01:44Z
[ "python", "user-interface", "tkinter" ]
I have a script that uses Tkinter to pop up a window with a message. How do I make sure it takes focus so the user doesn't miss it and explicitly has to dismiss the window. the code is : ``` root = Tk() to_read = "Stuff" w = Label(root, text=to_read) w.pack() root.mainloop() ```
You can use `focus_force` method. See the following: * [Universal widget methods](http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html) But note the the documentation: > w.focus\_force() > > Force the input focus to the widget. This is impolite. It's better to wait for the window manager to give you the focu...
Parallel Processing in python
3,842,237
34
2010-10-01T18:59:55Z
3,842,660
8
2010-10-01T20:03:53Z
[ "python", "parallel-processing" ]
Whats a simple code that does parallel processing in python 2.7? All the examples Ive found online are convoluted and include unnecessary codes. how would i do a simple brute force integer factoring program where I can factor 1 integer on each core (4)? my real program probably only needs 2 cores, and need to share in...
[`mincemeat`](http://remembersaurus.com/mincemeatpy/) is the simplest map/reduce implementation that I've found. Also, it's very light on dependencies - it's a single file and does everything with standard library.
Parallel Processing in python
3,842,237
34
2010-10-01T18:59:55Z
3,846,686
29
2010-10-02T17:02:33Z
[ "python", "parallel-processing" ]
Whats a simple code that does parallel processing in python 2.7? All the examples Ive found online are convoluted and include unnecessary codes. how would i do a simple brute force integer factoring program where I can factor 1 integer on each core (4)? my real program probably only needs 2 cores, and need to share in...
A good simple way to start with parallel processing in python is just the pool mapping in mutiprocessing -- its like the usual python maps but individual function calls are spread out over the different number of processes. Factoring is a nice example of this - you can brute-force check all the divisions spreading out...
How do I get a size of an UTF-8 string in Bytes with Python
3,842,487
8
2010-10-01T19:39:22Z
3,842,583
7
2010-10-01T19:53:32Z
[ "python" ]
Having an UTF-8 string like this: ``` mystring = "işğüı" ``` is it possible to get its (in memory) size in Bytes with Python (2.5)?
Assuming you mean the number of UTF-8 bytes (and not the extra bytes that Python requires to store the object), it’s the same as for the length of any other string. A string literal in Python 2.x is a string of encoded bytes, not Unicode characters. Byte strings: ``` >>> mystring = "işğüı" >>> print "length of ...
Organizing Python classes in modules and/or packages
3,842,616
44
2010-10-01T19:58:31Z
3,842,687
44
2010-10-01T20:07:07Z
[ "python", "class", "module", "package" ]
I like the Java convention of having one public class per file, even if there are sometimes good reasons to put more than one public class into a single file. In my case I have alternative implementations of the same interface. But if I would place them into separate files, I'd have redundant names in the import statem...
A lot of it is personal preference. Using python modules, you do have the option to keep each class in a separate file and still allow for `import converters.SomeConverter` (or `from converters import SomeConverter`) Your file structure could look something like this: ``` * converters - __init__.py - baseco...
Organizing Python classes in modules and/or packages
3,842,616
44
2010-10-01T19:58:31Z
13,258,827
28
2012-11-06T20:25:56Z
[ "python", "class", "module", "package" ]
I like the Java convention of having one public class per file, even if there are sometimes good reasons to put more than one public class into a single file. In my case I have alternative implementations of the same interface. But if I would place them into separate files, I'd have redundant names in the import statem...
Zach's solution breaks on Python 3. Here is a fixed solution. A lot of it is personal preference. Using python modules, you do have the option to keep each class in a separate file and still allow for `import converters.SomeConverter` (or `from converters import SomeConverter`) Your file structure could look somethin...
Efficiently detect sign-changes in python
3,843,017
13
2010-10-01T20:59:36Z
3,843,124
44
2010-10-01T21:22:00Z
[ "python", "math", "performance", "numpy" ]
I want to do exactly what this guy did: [Python - count sign changes](http://stackoverflow.com/questions/2936834/python-counting-sign-changes) However I need to optimize it to run super fast. In brief I want to take a time series and tell every time it crosses crosses zero (changes sign). I want to record the time in...
What about: ``` import numpy a = [1, 2, 1, 1, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10] zero_crossings = numpy.where(numpy.diff(numpy.sign(a)))[0] ``` Output: ``` > zero_crossings array([ 3, 5, 9, 10, 11, 12, 15]) ``` i.e. zero\_crossings will contain the indices of elements *after* which a zero crossing occu...
Efficiently detect sign-changes in python
3,843,017
13
2010-10-01T20:59:36Z
29,674,950
12
2015-04-16T12:37:34Z
[ "python", "math", "performance", "numpy" ]
I want to do exactly what this guy did: [Python - count sign changes](http://stackoverflow.com/questions/2936834/python-counting-sign-changes) However I need to optimize it to run super fast. In brief I want to take a time series and tell every time it crosses crosses zero (changes sign). I want to record the time in...
As remarked by Jay Borseth the accepted answer does not handle arrays containing 0 correctly. I propose using: ``` import numpy as np a = np.array([-2, -1, 0, 1, 2]) zero_crossings = np.where(np.diff(np.signbit(a)))[0] print zero_crossings # output: [1] ``` Since a) using numpy.signbit() is a little bit quicker than...
Does this function have to use reduce() or is there a more pythonic way?
3,843,188
4
2010-10-01T21:33:27Z
3,843,203
8
2010-10-01T21:37:31Z
[ "python", "list-comprehension", "reduce" ]
If I have a value, and a list of additional terms I want multiplied to the value: ``` n = 10 terms = [1,2,3,4] ``` Is it possible to use a list comprehension to do something like this: ``` n *= (term for term in terms) #not working... ``` Or is the only way: ``` n *= reduce(lambda x,y: x*y, terms) ``` This is on ...
`reduce` is the best way to do this IMO, but you don't have to use a lambda; instead, you can use the `*` operator directly: ``` import operator n *= reduce(operator.mul, terms) ``` `n` is now 240. See the docs for the [operator module](http://docs.python.org/library/operator.html) for more info.
How come I can not activate my Virtual Python Environment with 'source env/bin/activate' command?
3,843,981
6
2010-10-02T01:30:55Z
3,844,055
8
2010-10-02T02:03:58Z
[ "python", "pylons" ]
I am trying to activate my Virtual Python Environment to use with Pylons but I think I am executing the commands wrong. ``` jem@jem-laptop:~$ source env/bin/activate bash: env/bin/activate: No such file or directory ``` What am I doing wrong? How should I do it right?
I realize I had to do ``` jem@jem-laptop:~$ ls Desktop examples.desktop Public shortener.rb Documents Mac4Lin_v1.0 ruby-1.9.1-p378 Templates Downloads Music rubygems-1.3.7 Videos Dropbox Pictures setcolors.vim virtualenv.py ``` And here we see virtualenv.py. From her...
Static or constant or what are they?
3,844,158
2
2010-10-02T02:49:15Z
3,844,175
8
2010-10-02T02:58:02Z
[ "python", "oop" ]
I just want to know how I can call certian classes in design pattern here, like which type are they classified in OO design (1) I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. (2) I use a class with full of static m...
> What are these kinda classes classified under OOdesign? Can I do it in a more elegant way? You do have better alternatives, IMHO. > I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. For e.g. in this case you don't ...
Best way to generate xml?
3,844,360
48
2010-10-02T04:14:10Z
3,844,432
59
2010-10-02T04:49:51Z
[ "python", "xml", "api" ]
I'm creating an web api and need a good way to very quickly generate some well formatted xml. I cannot find any good way of doing this in python. Note: Some libraries look promising but either lack documentation or only output to files.
Using [lxml](http://lxml.de/): ``` from lxml import etree # create XML root = etree.Element('root') root.append(etree.Element('child')) # another child with text child = etree.Element('child') child.text = 'some text' root.append(child) # pretty string s = etree.tostring(root, pretty_print=True) print s ``` Output...
Best way to generate xml?
3,844,360
48
2010-10-02T04:14:10Z
3,844,456
67
2010-10-02T05:03:51Z
[ "python", "xml", "api" ]
I'm creating an web api and need a good way to very quickly generate some well formatted xml. I cannot find any good way of doing this in python. Note: Some libraries look promising but either lack documentation or only output to files.
[ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) is a good module for reading xml and writing too e.g. ``` from xml.etree.ElementTree import Element, SubElement, tostring root = Element('root') child = SubElement(root, "child") child.text = "I am a child" print tostring(root) ``` Output: ``...
Best way to generate xml?
3,844,360
48
2010-10-02T04:14:10Z
10,412,758
9
2012-05-02T11:24:29Z
[ "python", "xml", "api" ]
I'm creating an web api and need a good way to very quickly generate some well formatted xml. I cannot find any good way of doing this in python. Note: Some libraries look promising but either lack documentation or only output to files.
Use lxml.builder class, from: <http://lxml.de/tutorial.html#the-e-factory> ``` import lxml.builder as lb from lxml import etree nstext = "new story" story = lb.E.Asset( lb.E.Attribute(nstext, name="Name", act="set"), lb.E.Relation(lb.E.Asset(idref="Scope:767"), name="Scope", act="set") ) print 'sto...
Best way to generate xml?
3,844,360
48
2010-10-02T04:14:10Z
22,893,831
10
2014-04-06T12:10:29Z
[ "python", "xml", "api" ]
I'm creating an web api and need a good way to very quickly generate some well formatted xml. I cannot find any good way of doing this in python. Note: Some libraries look promising but either lack documentation or only output to files.
I would use the [yattag](http://www.yattag.org) library. I think it's the most pythonic way: ``` from yattag import Doc doc, tag, text = Doc().tagtext() with tag('food'): with tag('name'): text('French Breakfast') with tag('price', currency='USD'): text('6.95') with tag('ingredients'): ...
How to get the duration of a video in Python?
3,844,430
10
2010-10-02T04:49:15Z
3,844,467
25
2010-10-02T05:06:29Z
[ "python", "django", "video", "video-streaming" ]
I need to get the video duration in Python. The video formats that I need to get are [MP4](http://en.wikipedia.org/wiki/MPEG-4_Part_14), Flash video, [AVI](http://en.wikipedia.org/wiki/Audio_Video_Interleave), and MOV... I have a shared hosting solution, so I have no [FFmpeg](http://en.wikipedia.org/wiki/FFmpeg) suppor...
You'll probably need to invoke an external program. [`ffprobe`](http://ffmpeg.org/ffprobe.html) can provide you with that information: ``` import subprocess def getLength(filename): result = subprocess.Popen(["ffprobe", filename], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) return [x for x in result...
check if all elements in a list are identical
3,844,801
156
2010-10-02T07:31:11Z
3,844,832
197
2010-10-02T07:43:37Z
[ "python", "algorithm", "comparison" ]
I need the following function: **Input**: a `list` **Output**: * `True` if all elements in the input list evaluate as equal to each other using the standard equality operator; * `False` otherwise. **Performance**: of course, I prefer not to incur any unnecessary overhead. I feel it would be best to: * iterate thr...
General method: ``` def checkEqual1(iterator): iterator = iter(iterator) try: first = next(iterator) except StopIteration: return True return all(first == rest for rest in iterator) ``` One-liner: ``` def checkEqual2(iterator): return len(set(iterator)) <= 1 ``` Also one-liner: `...
check if all elements in a list are identical
3,844,801
156
2010-10-02T07:31:11Z
3,844,833
17
2010-10-02T07:43:41Z
[ "python", "algorithm", "comparison" ]
I need the following function: **Input**: a `list` **Output**: * `True` if all elements in the input list evaluate as equal to each other using the standard equality operator; * `False` otherwise. **Performance**: of course, I prefer not to incur any unnecessary overhead. I feel it would be best to: * iterate thr...
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. ``` if len(sets.Set(input_list)) == 1 // input_list has all identical elements. ```
check if all elements in a list are identical
3,844,801
156
2010-10-02T07:31:11Z
3,844,948
150
2010-10-02T08:25:21Z
[ "python", "algorithm", "comparison" ]
I need the following function: **Input**: a `list` **Output**: * `True` if all elements in the input list evaluate as equal to each other using the standard equality operator; * `False` otherwise. **Performance**: of course, I prefer not to incur any unnecessary overhead. I feel it would be best to: * iterate thr...
A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list) ``` x.count(x[0]) == len(x) ``` some simple benchmarks: ``` >>> timeit.tim...
check if all elements in a list are identical
3,844,801
156
2010-10-02T07:31:11Z
10,285,205
44
2012-04-23T17:23:42Z
[ "python", "algorithm", "comparison" ]
I need the following function: **Input**: a `list` **Output**: * `True` if all elements in the input list evaluate as equal to each other using the standard equality operator; * `False` otherwise. **Performance**: of course, I prefer not to incur any unnecessary overhead. I feel it would be best to: * iterate thr...
The simplest and most elegant way is as follows: ``` all(x==myList[0] for x in myList) ``` (Yes, this even works with the null list! This is because this is one of the few cases where python has lazy semantics.) Regarding performance, this will fail at the earliest possible time, so it is asymptotically optimal.
Mercurial for Windows - Python version?
3,844,859
4
2010-10-02T07:52:28Z
3,844,940
10
2010-10-02T08:24:24Z
[ "python", "windows", "mercurial", "version" ]
What version of Python is needed to run Mercurial? I see that the website says it requires 2.4. Does that mean 2.4, or 2.x? or something higher than 2.4, i.e., could I install 3.x? I've installed Mercurial without reading the requirements and I installed it anyway and `hg.exe` executes fine. Looking in the directory t...
Yes, it comes bundled. If you install Mercurial using the Windows installer, then you don't need to worry about which version of Python you are using. Mercurial uses [py2exe](http://www.py2exe.org/) to create an executable that runs without a Python installation.
Python: Boolean operators vs Bitwise operators
3,845,018
26
2010-10-02T08:52:03Z
3,845,032
25
2010-10-02T08:56:33Z
[ "python" ]
I am confused as to when I should use a Boolean vs Bitwise operators ``` and vs &, or vs | ``` Could someone enlighten me as to when do i use each and when will using one over the other affect my results?
Here are a couple of guidelines: * Boolean operators are usually used on *boolean* values but bitwise operators are usually used on *integer* values. * Boolean operators are *short-circuiting* but bitwise operators are *not* short-circuiting. The short-circuiting behaviour is useful in expressions like this: ``` if ...
Python: Boolean operators vs Bitwise operators
3,845,018
26
2010-10-02T08:52:03Z
3,845,096
14
2010-10-02T09:16:23Z
[ "python" ]
I am confused as to when I should use a Boolean vs Bitwise operators ``` and vs &, or vs | ``` Could someone enlighten me as to when do i use each and when will using one over the other affect my results?
In theory, `and` and `or` come straight from boolean logic (and therefore operate on two booleans to produce a boolean), while `&` and `|` apply the boolean and/or to the individual bits of integers. There are a lot lot of questions here on how the latter work exactly. Here are practical differences that potentially a...
Running matplotlib in tkinter
3,845,407
17
2010-10-02T11:16:15Z
3,851,087
18
2010-10-03T18:46:58Z
[ "python", "matplotlib", "tkinter" ]
I have this beautiful sphere I made in matplotlib. How would I go about putting it in a tkinter frame widget? It'd be nice to be able to integrate it into an existing tkinter GUI. Also is it possible to rid of the menu bar below the display? I have no need to save the output or zoom, so it's useless to me. ``` from mp...
Have a look at the examples for embedding plots in a tk GUI, it should be enough to get you started in the right direction. [user\_interfaces example code: embedding\_in\_tk.py](http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html) [user\_interfaces example code: embedding\_in\_tk2.py](http...
Remove empty strings from a list of strings
3,845,423
325
2010-10-02T11:21:10Z
3,845,449
100
2010-10-02T11:27:27Z
[ "python", "string", "list" ]
I want to remove all empty strings from a list of strings in python. My idea looks like this: ``` while '' in str_list: str_list.remove('') ``` Is there any more pythonic way to do this?
[List comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) ``` strings = ["first", "", "second"] [x for x in strings if x] ``` Output: `['first', 'second']` Edit: Shortened as suggested
Remove empty strings from a list of strings
3,845,423
325
2010-10-02T11:21:10Z
3,845,453
520
2010-10-02T11:28:50Z
[ "python", "string", "list" ]
I want to remove all empty strings from a list of strings in python. My idea looks like this: ``` while '' in str_list: str_list.remove('') ``` Is there any more pythonic way to do this?
I would use [`filter`](http://docs.python.org/library/functions.html#filter): ``` str_list = filter(None, str_list) # fastest str_list = filter(bool, str_list) # fastest str_list = filter(len, str_list) # a bit of slower str_list = filter(lambda item: item, str_list) # slower than list comprehension ``` Python 3 ret...
Remove empty strings from a list of strings
3,845,423
325
2010-10-02T11:21:10Z
3,845,584
49
2010-10-02T12:04:30Z
[ "python", "string", "list" ]
I want to remove all empty strings from a list of strings in python. My idea looks like this: ``` while '' in str_list: str_list.remove('') ``` Is there any more pythonic way to do this?
filter actually has a special option for this: ``` filter(None, sequence) ``` It will filter out all elements that evaluate to False. No need to use an actual callable here such as bool, len and so on. It's equally fast as map(bool, ...)
Remove empty strings from a list of strings
3,845,423
325
2010-10-02T11:21:10Z
19,251,026
7
2013-10-08T14:49:28Z
[ "python", "string", "list" ]
I want to remove all empty strings from a list of strings in python. My idea looks like this: ``` while '' in str_list: str_list.remove('') ``` Is there any more pythonic way to do this?
Instead of if x, I would use if X != '' in order to just eliminate empty strings. Like this: ``` str_list = [x for x in str_list if x != ''] ``` This will preserve None data type within your list. Also, in case your list has integers and 0 is one among them, it will also be preserved. For example, ``` str_list = [N...
Remove empty strings from a list of strings
3,845,423
325
2010-10-02T11:21:10Z
33,343,035
9
2015-10-26T10:06:54Z
[ "python", "string", "list" ]
I want to remove all empty strings from a list of strings in python. My idea looks like this: ``` while '' in str_list: str_list.remove('') ``` Is there any more pythonic way to do this?
``` >>> lstr = ['hello', '', ' ', 'world', ' '] >>> lstr ['hello', '', ' ', 'world', ' '] >>> ' '.join(lstr).split() ['hello', 'world'] >>> filter(None, lstr) ['hello', ' ', 'world', ' '] ``` Compare time ``` >>> from timeit import timeit >>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']",...
Django: request.GET and KeyError
3,845,582
13
2010-10-02T12:03:42Z
3,845,608
23
2010-10-02T12:11:02Z
[ "python", "django", "django-urls" ]
Code: ``` # it's an ajax request, so parameters are passed via GET method def my_view(request): my_param = request.GET['param'] // should I check for KeyError exception? ``` In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted para...
Your server should never produce a 500 error page. You can avoid the error by using: ``` my_param = request.GET.get('param', default_value) ``` or: ``` my_param = request.GET.get('param') if my_param is None: return HttpResponseBadRequest() ```
Precompose Unicode Character Sequences in Python
3,845,793
4
2010-10-02T12:57:12Z
3,845,857
8
2010-10-02T13:10:50Z
[ "python", "osx", "unicode" ]
How can I convert decomposed unicode character sequences like "LATIN SMALL LETTER E" + "COMBINING ACUTE ACCENT" (or U+0075 + U+0301) so they become the precomposed form: "LATIN SMALL LETTER E WITH ACUTE" (or U+00E9) using native Python 2.5+ functions? If it matters, I am on Mac OS X (10.6.4) and I have seen the questi...
``` import unicodedata as ud astr=u"\N{LATIN SMALL LETTER E}" + u"\N{COMBINING ACUTE ACCENT}" combined_astr=ud.normalize('NFC',astr) ``` 'NFC' tells [ud.normalize](http://docs.python.org/library/unicodedata.html#unicodedata.normalize) to apply the canonical decomposition ('NFD'), then compose pre-combined characters:...
Django: TEMPLATE_DIRS vs INSTALLED_APPS
3,846,128
3
2010-10-02T14:22:06Z
3,846,276
7
2010-10-02T15:03:39Z
[ "python", "django" ]
I am currently just add app to INSTALLED\_APPS to be able to use templates from that app, but there is also TEMPLATE\_DIRS setting. When have I to prefer TEMPLATE\_DIRS over INSTALLED\_APPS?
You can use templates in TEMPLATE\_DIRS to either override templates coming from apps (by giving them the same name) or for templates that are relevant for more than one app (base.html comes to mind). This works because of the order in which template loaders are set in TEMPLATE\_LOADERS (filesystem before app\_directo...
C++ vs Python precision
3,846,631
5
2010-10-02T16:45:38Z
3,846,750
8
2010-10-02T17:19:55Z
[ "c++", "python", "floating-point", "precision", "floating-accuracy" ]
Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python C++ ``` long double intpart,num,f_digit,k; cin>>num>>k; f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1); cout<<f_digit; ``` Python ``` (a,b) = modf(num*log10(num)) f_digits = pow(10,b+k-1) print f_digits ...
`Decimal` is a built in python class that handles floating points correctly (as base 10, not as IEEE 7somethingsomething standard). I don't know if it supports logarithms and all that though. Edit: It does indeed [support logarithms "and all that".](http://docs.python.org/library/decimal.html#decimal-objects) You can...
Print variable in python without space or newline
3,846,801
5
2010-10-02T17:32:52Z
3,846,817
10
2010-10-02T17:36:01Z
[ "python", "formatting", "printing" ]
print a variable without newline or space python3 does it by print (x,end='') how to do it in python 2.5
`sys.stdout.write` writes (only) strings without newlines unless specified. ``` >>> x = 4 >>> print x 4 >>> import sys >>> sys.stdout.write(str(x)) # you have to str() your variables 4>>> # <- no newline ```
Learning Twisted
3,846,875
17
2010-10-02T17:50:17Z
3,846,951
18
2010-10-02T18:12:10Z
[ "python", "twisted" ]
How do I begin learning Twisted? What books, documentation or tutorial do you guys recommend? The reason I asked this question is that I think learning Twisted would help me otherwise also in learning concepts related to network programming (terminologies and how it works and stuff) I have heard that the documentation...
I'm finding [this tutorial](http://krondo.com/?page_id=1327), linked to from the [third party documentation](http://twistedmatrix.com/trac/wiki/Documentation#ThirdPartyDocumentation) section of the main twisted documentation page, to be well-written and instructive. The tutorial consists of numerous iterations of the ...
Testing if a list contains another list with Python
3,847,386
18
2010-10-02T20:20:32Z
3,847,585
11
2010-10-02T21:23:54Z
[ "python", "list", "contains", "list-comparison" ]
How can I test if a list contains another list (ie. it's a subsequence). Say there was a function called contains: ``` contains([1,2], [-1, 0, 1, 2]) # Returns [2, 3] (contains returns [start, end]) contains([1,3], [-1, 0, 1, 2]) # Returns False contains([1, 2], [[1, 2], 3) # Returns False contains([[1, 2]], [[1, 2], ...
Here is my version: ``` def contains(small, big): for i in xrange(len(big)-len(small)+1): for j in xrange(len(small)): if big[i+j] != small[j]: break else: return i, i+len(small) return False ``` It returns a tuple of (start, end+1) since I think that is...
convert a json string to python object
3,847,399
24
2010-10-02T20:25:47Z
3,847,417
55
2010-10-02T20:31:10Z
[ "python", "json" ]
Is it possible to convert a json string (for e.g. the one returned from the twitter search json service) to simple string objects. Here is a small representation of data returned from the json service: ``` { results:[...], "max_id":1346534, "since_id":0, "refresh_url":"?since_id=26202877001&q=twitter", . . . } ``` Le...
> I've tried using `simplejson.load()` and `json.load()` but it gave me an error saying `'str' object has no attribute 'read'` To load from a string, use `json.loads()` (note the 's'). More efficiently, skip the step of reading the response into a string, and just pass the response to `json.load()`.
get index of character in python list
3,847,472
5
2010-10-02T20:48:15Z
3,847,494
8
2010-10-02T20:54:07Z
[ "python", "indexing", "character" ]
What would be the best way to find the index of a specified character in a list containing multiple characters?
``` >>> ['a', 'b'].index('b') 1 ``` If the list is already sorted, you can of course do better than linear search.
Wrapping exceptions in Python
3,847,503
24
2010-10-02T20:55:50Z
3,847,530
24
2010-10-02T21:06:31Z
[ "python", "exception" ]
I'm working on a mail-sending library, and I want to be able to catch exceptions produced by the senders (SMTP, Google AppEngine, etc.) and wrap them in easily catchable exceptions specific to my library (ConnectionError, MessageSendError, etc.), with the original traceback intact so it can be debugged. What is the bes...
The simplest way would be to reraise with the old trace object. The following example shows this: ``` import sys def a(): def b(): raise AssertionError("1") b() try: a() except AssertionError: # some specific exception you want to wrap trace = sys.exc_info()[2] raise Exception("error desc...
Is Celery appropriate for use with many small, distributed systems?
3,848,024
6
2010-10-03T00:13:02Z
3,849,556
11
2010-10-03T11:30:15Z
[ "python", "celery" ]
I'm writing some software which will manage a few hundred [small systems](http://beagleboard.org/) in “the field” over an intermittent [3G](http://en.wikipedia.org/wiki/3G) (or similar) connection. Home base will need to send jobs to the systems in the field (eg, “report on your status”, “update your softwar...
> The majority of tasks will be directed > to an individual worker (eg, “send the > ‘get\_status’ job to ‘system51’”) — > will this be a problem? Not at all. Just create a queue for each worker, e.g. say each node listens to a round robin queue called `default` and each node has its own queue named after...
Python set iteration order varies from run to run
3,848,091
14
2010-10-03T00:41:58Z
3,848,111
9
2010-10-03T00:52:43Z
[ "python", "set", "iteration" ]
Why does the iteration order of a Python set (with the same contents) vary from run to run, and what are my options for making it consistent from run to run? I understand that the iteration order for a Python set is arbitrary. If I put 'a', 'b', and 'c' into a set and then iterate them, they may come back out in any o...
What you want isn't possible. Arbitrary means arbitrary. My solution would be the same as yours, you have to sort the set if you want to be able to compare it to another one.
Python set iteration order varies from run to run
3,848,091
14
2010-10-03T00:41:58Z
3,850,585
10
2010-10-03T16:30:12Z
[ "python", "set", "iteration" ]
Why does the iteration order of a Python set (with the same contents) vary from run to run, and what are my options for making it consistent from run to run? I understand that the iteration order for a Python set is arbitrary. If I put 'a', 'b', and 'c' into a set and then iterate them, they may come back out in any o...
Use the symmetric\_difference (^) operator on your two sets to see if there are any differences: ``` In [1]: s1 = set([5,7,8,2,1,9,0]) In [2]: s2 = set([9,0,5,1,8,2,7]) In [3]: s1 Out[3]: set([0, 1, 2, 5, 7, 8, 9]) In [4]: s2 Out[4]: set([0, 1, 2, 5, 7, 8, 9]) In [5]: s1 ^ s2 Out[5]: set() ```
How to map a tuple of data to a tuple of functions?
3,848,829
2
2010-10-03T06:26:29Z
3,848,834
8
2010-10-03T06:28:44Z
[ "python", "function", "mapping", "arguments", "tuples" ]
I have the following Python code: ``` data = ['1', '4.6', 'txt'] funcs = [int, float, str] ``` How to call every function with data in corresponding index as an argument to the function? Now I'm using the code: ``` result = [] for i, func in enumerate(funcs): result.append(func(data[i])) ``` **map(funcs, data)...
You could [use `zip`](http://docs.python.org/library/functions.html#zip)\* to combine many sequences together: ``` zip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...] ``` then you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them int...
Python: Why Lists do not have a find method?
3,848,954
7
2010-10-03T07:25:30Z
3,848,964
7
2010-10-03T07:28:53Z
[ "python", "string", "list", "methods" ]
I was trying to write an answer to this [question](http://stackoverflow.com/questions/3847386/testing-if-a-list-contains-another-list-with-python/3848928#3848928) and was quite surprised to find out that there is no find method for lists, lists have only the index method (strings have find and index). Can anyone tell ...
I don't know why or maybe is buried in some PEP somewhere, but i do know 2 very basic "find" method for lists, and they are `array.index()` and the `in` operator. You can always make use of these 2 to find your items. (Also, re module, etc)
sum of products for multiple lists in python
3,849,251
6
2010-10-03T09:34:21Z
3,849,258
15
2010-10-03T09:36:15Z
[ "python", "algorithm" ]
Trying to imitate Excel's SUMPRODUCT function: ``` SUMPRODUCT(v1, v2, ..., vN) = v1[0]*v2[0]*...*vN[0] + v1[1]*v2[1]*...*vN[1] + ... + v1[n]*v2[n]*...*vN[n] ``` where n is the number of elements in each vector. This is similar to dot product, but for multiple vectors. I read [the very detailed discussion](http:/...
``` import operator def sumproduct(*lists): return sum(reduce(operator.mul, data) for data in zip(*lists)) ``` for python 3 ``` import operator import functools def sumproduct(*lists): return sum(functools.reduce(operator.mul, data) for data in zip(*lists)) ```
How to remove \n from a list element?
3,849,509
35
2010-10-03T11:12:25Z
3,849,519
84
2010-10-03T11:16:38Z
[ "python", "list", "newline" ]
I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used `split("\t")` to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list. The problem...
If you want to remove `\n` from the last element only, use this: ``` t[-1] = t[-1].strip() ``` If you want to remove `\n` from all the elements, use this: ``` t = map(lambda s: s.strip(), t) ``` You might also consider removing `\n` **before** splitting the line: ``` line = line.strip() # split line... ```
How to remove \n from a list element?
3,849,509
35
2010-10-03T11:12:25Z
3,849,699
9
2010-10-03T12:27:37Z
[ "python", "list", "newline" ]
I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used `split("\t")` to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list. The problem...
It sounds like you want something like the Perl `chomp()` function. That's trivial to do in Python: ``` def chomp(s): return s[:-1] if s.endswith('\n') else s ``` ... assuming you're using Python 2.6 or later. Otherwise just use the slightly more verbose: ``` def chomp(s): if s.endwith('\n'): return...
How to remove \n from a list element?
3,849,509
35
2010-10-03T11:12:25Z
30,881,893
13
2015-06-17T03:35:09Z
[ "python", "list", "newline" ]
I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used `split("\t")` to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list. The problem...
## ***From Python3 onwards*** `map` no longer returns a `list` but a `mapObject`, thus the answer will look something like ``` >>> map(lambda x:x.strip(),l) <map object at 0x7f00b1839fd0> ``` You can read more about it on [What’s New In Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-...
pairwise traversal of a list or tuple
3,849,625
8
2010-10-03T11:57:48Z
3,849,636
14
2010-10-03T12:01:47Z
[ "python", "iteration" ]
``` a = [5, 66, 7, 8, 9, ...] ``` Is it possible to make an iteration instead of writing like this? ``` a[1] - a[0] a[2] - a[1] a[3] - a[2] a[4] - a[3] ``` ... Thank you!
for a small list in python 2 or any list in python 3, you can use ``` [x - y for x, y in zip(a[1:], a)] ``` for a larger list, you probably want ``` import itertools as it [x - y for x, y in it.izip(a[1:], a)] ``` if you are using python 2 And I would consider writing it as a generator expression instead ``` (x ...
pairwise traversal of a list or tuple
3,849,625
8
2010-10-03T11:57:48Z
3,849,706
37
2010-10-03T12:29:45Z
[ "python", "iteration" ]
``` a = [5, 66, 7, 8, 9, ...] ``` Is it possible to make an iteration instead of writing like this? ``` a[1] - a[0] a[2] - a[1] a[3] - a[2] a[4] - a[3] ``` ... Thank you!
Using `range` is perfectly fine. However, programming (like maths) is about building on abstractions. Consecutive pairs *[(x0, x1), (x1, x2), ..., (xn-2, xn-1)]*, are called *pairwise combinations*, see for example a [recipe in the itertools docs](http://docs.python.org/library/itertools.html#recipes). Once you have th...
itertools or hand-written generator - what is preferable?
3,849,702
7
2010-10-03T12:28:43Z
3,849,780
7
2010-10-03T12:44:54Z
[ "python", "iterator", "generator" ]
I have a number of Python generators, which I want to combine into a new generator. I can easily do this by a hand-written generator using a bunch of `yield` statements. On the other hand, the `itertools` module is made for things like this and to me it seems as if the pythonic way to create the generator I need is to...
I did some profiling and the regular generator function is way faster than either your second generator or my implementation. ``` $ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator1(a, b))' 10 loops, best of 3: 169 msec per loop $ python -mtimeit -s'import gen; a, b = gen.make_test_case...
Python 3, easy_install, pip and pypi
3,849,762
29
2010-10-03T12:40:49Z
3,850,088
26
2010-10-03T14:11:20Z
[ "python", "python-3.x" ]
What is the current status of easy\_install, pip and the repository (pypi.python.org) with regards to Python 3.x? Are there versions of easy\_install and/or pip that can install the right versions of packages from there? Else, are they expected soon?
PyPi itself supports Python 3. The [setuptools](https://pypi.python.org/pypi/setuptools/1.1.6#unix-based-systems-including-mac-os-x) package provides a version of easy\_install that works with Python 3. According to [the pip page](http://pypi.python.org/pypi/pip), pip support Python 3 since v 1.0.
How to load existing db file to memory in Python sqlite3?
3,850,022
25
2010-10-03T13:55:00Z
3,850,259
11
2010-10-03T15:02:19Z
[ "python", "performance", "sqlite", "sqlite3" ]
I have an existing `sqlite3` db file, on which I need to make some extensive calculations. Doing the calculations from the file is painfully slow, and as the file is not large (~`10 MB`), so there should be no problem to load it into memory. Is there a Pythonic way to load the existing file into memory in order to spe...
[`sqlite3.Connection.iterdump`](http://docs.python.org/library/sqlite3.html#sqlite3.Connection.iterdump) "[r]eturns an iterator to dump the database in an SQL text format. Useful when saving an in-memory database for later restoration. This function provides the same capabilities as the `.dump` command in the sqlite3 s...
How to load existing db file to memory in Python sqlite3?
3,850,022
25
2010-10-03T13:55:00Z
10,856,450
66
2012-06-01T19:46:07Z
[ "python", "performance", "sqlite", "sqlite3" ]
I have an existing `sqlite3` db file, on which I need to make some extensive calculations. Doing the calculations from the file is painfully slow, and as the file is not large (~`10 MB`), so there should be no problem to load it into memory. Is there a Pythonic way to load the existing file into memory in order to spe...
Here is the snippet that I wrote for my flask application: ``` import sqlite3 from StringIO import StringIO def init_sqlite_db(app): # Read database to tempfile con = sqlite3.connect(app.config['SQLITE_DATABASE']) tempfile = StringIO() for line in con.iterdump(): tempfile.write('%s\n' % line) ...
Doing something before program exit
3,850,261
27
2010-10-03T15:02:30Z
3,850,271
40
2010-10-03T15:04:35Z
[ "python", "function", "exit" ]
How can you have a function or something that will be executed before your program quits? I have a script that will be constantly running in the background, and I need it to save some data to a file before it exits. Is there a standard way of doing this?
Check out the `atexit` module: <http://docs.python.org/library/atexit.html> For example, if I wanted to print a message when my application was terminating: ``` import atexit def exit_handler(): print 'My application is ending!' atexit.register(exit_handler) ``` Just be aware that this works great for normal ...
Doing something before program exit
3,850,261
27
2010-10-03T15:02:30Z
3,850,621
7
2010-10-03T16:38:47Z
[ "python", "function", "exit" ]
How can you have a function or something that will be executed before your program quits? I have a script that will be constantly running in the background, and I need it to save some data to a file before it exits. Is there a standard way of doing this?
If you want something to always run, even on errors, use try: finally: like this - ``` def main(): try: execute_app() finally: handle_cleanup() if __name__=='__main__': main() ``` If you want to also handle exceptions you can insert an except: before the finally:
Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models?
3,850,742
13
2010-10-03T17:16:27Z
3,859,771
22
2010-10-04T23:00:20Z
[ "python", "forms", "flask", "sqlalchemy" ]
I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have: ``` # the model - assumes Flask-SQLAlchemy from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Person(db.Model): id = db.Colu...
Please refer to the wtforms documentation: <http://wtforms.simplecodes.com/docs/0.6/forms.html#wtforms.form.Form> You pass in the "obj" as argument. This will bind the model properties to the form fields to provide the default values: ``` @app.route('/person/edit/<id>/', methods=['GET', 'POST']) def edit_person(id):...