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
What's the difference of ContentType and MimeType
3,452,381
62
2010-08-10T18:54:58Z
17,949,292
16
2013-07-30T14:06:21Z
[ "python", "django", "content-type", "mime-types" ]
As far as I know, they are absolute equal. However, browsing some django docs, I've found this piece of code: `HttpResponse.__init__(content='', mimetype=None, status=200, content_type='text/html')` which surprise me the two getting along each other. The official docs was able to solve the issue in a pratical manner:...
I've always viewed contentType to be a superset of mimeType. The only difference being the optional character set encoding. If the contentType does not include an optional character set encoding then it is identical to a mimeType. Otherwise, the mimeType is the data prior to the character set encoding sequence. E.G. `...
wxPython: How do I find out which widget has the focus?
3,452,489
7
2010-08-10T19:06:15Z
3,452,599
8
2010-08-10T19:20:05Z
[ "python", "wxpython", "focus", "wxwidgets" ]
How do I find out which widget in my `wx.Frame` has the focus?
You should be able to use the Window class's static `FindFocus()` method to return the object that has focus. api: <http://www.wxpython.org/docs/api/wx.Window-class.html#FindFocus> examples: <http://nullege.com/codes/search/wx.Window.FindFocus/all/page:2>
Remove duplicate rows from a large file in Python
3,452,832
8
2010-08-10T19:50:07Z
3,453,383
10
2010-08-10T21:00:09Z
[ "python", "duplicates" ]
I've a csv file that I want to remove duplicate rows from, but it's too large to fit into memory. I found a way to get it done, but my guess is that it's not the best way. Each row contains 15 fields and several hundred characters, and all fields are needed to determine uniqueness. Instead of comparing the entire row ...
If you want a really simple way to do this, just create a sqlite database: ``` import sqlite3 conn = sqlite3.connect('single.db') cur = conn.cursor() cur.execute("""create table test( f1 text, f2 text, f3 text, f4 text, f5 text, f6 text, f7 text, f8 text, f9 text, f10 text, f11 text, f12 text, f13 text, f14 text, f15 ...
What is :: (double colon) in Python when subscripting sequences?
3,453,085
99
2010-08-10T20:21:53Z
3,453,101
8
2010-08-10T20:24:08Z
[ "python", "syntax", "slice" ]
I know I can use something like string[3:4] to get a substring in Python, but what does the 3 mean in somesequence[::3]?
When slicing in Python the third parameter is the step. As others mentioned, see [Extended Slices](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) for a nice overview. With this knowledge, `[::3]` just means that you have not specified any start or end indices for your slice. Since you have specifie...
What is :: (double colon) in Python when subscripting sequences?
3,453,085
99
2010-08-10T20:21:53Z
3,453,102
72
2010-08-10T20:24:08Z
[ "python", "syntax", "slice" ]
I know I can use something like string[3:4] to get a substring in Python, but what does the 3 mean in somesequence[::3]?
Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. `a[::3]` is every third element of the sequence.
What is :: (double colon) in Python when subscripting sequences?
3,453,085
99
2010-08-10T20:21:53Z
3,453,103
86
2010-08-10T20:24:20Z
[ "python", "syntax", "slice" ]
I know I can use something like string[3:4] to get a substring in Python, but what does the 3 mean in somesequence[::3]?
it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. [Extended slices](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) is what you want. New in Python 2.3
What is :: (double colon) in Python when subscripting sequences?
3,453,085
99
2010-08-10T20:21:53Z
3,453,104
37
2010-08-10T20:24:22Z
[ "python", "syntax", "slice" ]
I know I can use something like string[3:4] to get a substring in Python, but what does the 3 mean in somesequence[::3]?
`seq[::n]` is a sequence of each `n`-th item in the entire sequence. Example: ``` >>> range(10)[::2] [0, 2, 4, 6, 8] ``` The syntax is: ``` seq[start:end:step] ``` So you can do: ``` >>> range(100)[5:18:2] [5, 7, 9, 11, 13, 15, 17] ```
What is :: (double colon) in Python when subscripting sequences?
3,453,085
99
2010-08-10T20:21:53Z
3,453,174
28
2010-08-10T20:33:02Z
[ "python", "syntax", "slice" ]
I know I can use something like string[3:4] to get a substring in Python, but what does the 3 mean in somesequence[::3]?
## Explanation `s[i:j:k]` is, [according to the documentation](http://docs.python.org/library/stdtypes.html#typesseq), "slice of s from i to j with step k". When `i` and `j` are absent, the whole sequence is assumed and thus `s[::k]` means "every k-th item". ## Examples First, let's initialize a list: ``` >>> s = r...
Convert Python datetime to rfc 2822
3,453,177
21
2010-08-10T20:33:24Z
3,453,266
19
2010-08-10T20:43:44Z
[ "python", "datetime", "rfc2822" ]
I want to convert a Python datetime to a an RFC 2822 datetime. I've tried these methods to no avail: ``` >>> from email.Utils import formatdate >>> import datetime >>> formatdate(datetime.datetime.now()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python....
If you indeed want the current time, just call `formatdate` with no arguments: ``` >>> from email.Utils import formatdate >>> formatdate() 'Tue, 10 Aug 2010 20:40:23 -0000' ``` But, if you must pass it an argument, you want the output of `time.time` (a number of seconds since 01/01/1970): ``` >>> import time >>> for...
Convert Python datetime to rfc 2822
3,453,177
21
2010-08-10T20:33:24Z
3,453,277
28
2010-08-10T20:45:28Z
[ "python", "datetime", "rfc2822" ]
I want to convert a Python datetime to a an RFC 2822 datetime. I've tried these methods to no avail: ``` >>> from email.Utils import formatdate >>> import datetime >>> formatdate(datetime.datetime.now()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python....
Here's some working code, broken down into simple pieces just for clarity: ``` >>> import datetime >>> import time >>> from email import utils >>> nowdt = datetime.datetime.now() >>> nowtuple = nowdt.timetuple() >>> nowtimestamp = time.mktime(nowtuple) >>> utils.formatdate(nowtimestamp) 'Tue, 10 Aug 2010 20:43:53 -000...
Matplotlib: display plot on a remote machine
3,453,188
20
2010-08-10T20:34:59Z
3,453,318
13
2010-08-10T20:51:52Z
[ "python", "ssh", "matplotlib" ]
I have a python code doing some calculation on a remote machine, named A. I connect on A via `ssh` from a machine named B. Is there a way to display the figure on machine B?
Sure, you can enable X11 forwarding. Usually this is done by passing the `-X` or `-Y` option to `ssh` when you connect to the remote computer ``` ssh -X computerA ``` Note that the SSH daemon on computer A will also have to be configured to enable X11 forwarding. This is done by putting ``` X11Forwarding yes ``` in...
Matplotlib: display plot on a remote machine
3,453,188
20
2010-08-10T20:34:59Z
3,453,527
17
2010-08-10T21:17:58Z
[ "python", "ssh", "matplotlib" ]
I have a python code doing some calculation on a remote machine, named A. I connect on A via `ssh` from a machine named B. Is there a way to display the figure on machine B?
If you use matplotlib on Mac OS X, you must first make sure that you use one of the X11-based display back-ends, since the native Mac OS X back-end cannot export its plots. Selecting a back-end can be achieved with ``` import matplotlib matplotlib.use('GTK') # Or any other X11 back-end ``` The list of supported back...
twisted: catch keyboardinterrupt and shutdown properly
3,453,451
15
2010-08-10T21:09:41Z
3,453,986
29
2010-08-10T22:29:59Z
[ "python", "twisted", "shutdown" ]
UPDATE: For ease of reading, here is how to add a callback before the reactor gets shutdown: ``` reactor.addSystemEventTrigger('before', 'shutdown', callable) ``` Original question follows. --- If I have a client connected to a server, and it's chilling in the reactor main loop waiting for events, when I hit CTRL-C...
If you really, really want to catch C-c specifically, then you can do this in the usual way for a Python application - use `signal.signal` to install a handler for `SIGINT` that does whatever you want to do. If you invoke any Twisted APIs from the handler, make sure you use `reactor.callFromThread` since almost all oth...
in python, how do i split a number by the decimal point
3,454,085
13
2010-08-10T22:48:14Z
3,454,107
8
2010-08-10T22:52:37Z
[ "python", "floating-point", "split", "decimal" ]
So if I run: ``` a = b / c ``` and get the result `1.2234` How do i separate it so that I have: ``` a = 1 b = 0.2234 ```
``` a,b = divmod(a, 1) ```
in python, how do i split a number by the decimal point
3,454,085
13
2010-08-10T22:48:14Z
3,454,431
14
2010-08-11T00:14:02Z
[ "python", "floating-point", "split", "decimal" ]
So if I run: ``` a = b / c ``` and get the result `1.2234` How do i separate it so that I have: ``` a = 1 b = 0.2234 ```
``` >>> from math import modf >>> b,a = modf(1.2234) >>> print ('a = %f and b = %f'%(a,b)) a = 1.000000 and b = 0.223400 >>> b,a = modf(-1.2234) >>> print ('a = %f and b = %f'%(a,b)) a = -1.000000 and b = -0.223400 ```
Using the argparse output to call functions
3,454,934
9
2010-08-11T02:51:11Z
3,455,109
10
2010-08-11T03:36:46Z
[ "python", "command-line", "parameters", "arguments", "argparse" ]
Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to 'best practices'? I haven't seen code actually using the output of `argparse`, only how to set it up. ``` def useArguments(): x = 0 while x <= 5: if x == 0: ...
You could supply a custom [action](http://docs.python.org/library/argparse.html#action) for an argument by, and I quote: > passing an object that implements the > Action API. The easiest way to do this > is to extend argparse.Action, > supplying an appropriate `__call__` > method. The `__call__` method should > accept...
Wikipedia with Python
3,455,104
2
2010-08-11T03:35:49Z
3,455,130
9
2010-08-11T03:43:45Z
[ "python", "xml", "wikipedia" ]
I have this very simple python code to read xml for the wikipedia api: ``` import urllib from xml.dom import minidom usock = urllib.urlopen("http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500") xmldoc=minidom.parse(usock) usock.close() print xmldoc.toxml() ``` But this code returns ...
The URL you're requesting is an HTML representation of the XML that would be returned: ``` http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500 ``` So the XML parser fails. You can see this by pasting the above in a browser. Try adding a `format=xml` at the end: ``` http://en.wikipedi...
GPGPU programming in Python
3,455,608
4
2010-08-11T05:55:30Z
4,869,923
11
2011-02-02T01:32:17Z
[ "python", "opencl" ]
I want to start [GPGPU](https://en.wikipedia.org/wiki/General-purpose_computing_on_graphics_processing_units) programming in Python. Should I start with pyopencl or clyther? What's the difference?
OpenCL consists of two parts. There is a host-side which is typically written in C, and a device-side which is written in a derivative of C defined by OpenCL. This code is compiled to the device (typically a GPU) at run-time. CLyther attempts to abstract everything out. You write the host-side code in Python. You writ...
Difference between simple Python function call and wrapping it in cProfile.run()
3,457,129
3
2010-08-11T09:45:33Z
3,457,216
9
2010-08-11T09:57:57Z
[ "python", "profiler", "python-2.6" ]
I have a rather simple Python script that contains a function call like `f(var, other_var)` i.e. a function that gets several parameters. All those parameters can be accessed within f and have values. When I instead call `cProfile.run('f(var, other_var)')` it fails with the error message: `NameError: "name 'var' ...
This is because cProfile attempts to `exec` the code you pass it as a string, and fails because, well, `var` is not defined in that piece of code! It is using the variables in the scope of the call to `run()`, but since you haven't told cProfile about them it doesn't know to use them. Use [`runctx`](http://docs.python....
Elegant way to create a dictionary of pairs, from a list of tuples?
3,457,673
7
2010-08-11T11:15:35Z
3,457,803
10
2010-08-11T11:33:25Z
[ "python" ]
I have defined a tuple thus: (slot, gameid, bitrate) and created a list of them called `myListOfTuples`. In this list might be tuples containing the same `gameid`. E.g. the list can look like: ``` [ (1, "Solitaire", 1000 ), (2, "Diner Dash", 22322 ), (3, "Solitaire", 0 ), (4, "Super Mario Kart", 854564 )...
For python2.6 ``` dict(x[1:] for x in reversed(myListOfTuples)) ``` If you have Python2.7 or 3.1, you can use katrielalex's answer
Create List of Single Item Repeated n Times in Python
3,459,098
189
2010-08-11T14:01:33Z
3,459,112
15
2010-08-11T14:02:50Z
[ "python", "operator-overloading", "list-comprehension", "multiplication" ]
I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach. I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing ``` [...
Itertools has a function just for that: ``` import itertools it = itertools.repeat(e,n) ``` Of course `itertools` gives you a iterator instead of a list. `[e] * n` gives you a list, but, depending on what you will do with those sequences, the `itertools` variant can be much more efficient.
Create List of Single Item Repeated n Times in Python
3,459,098
189
2010-08-11T14:01:33Z
3,459,131
291
2010-08-11T14:04:53Z
[ "python", "operator-overloading", "list-comprehension", "multiplication" ]
I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach. I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing ``` [...
You can also write: ``` [e] * n ``` You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists. **Performance testing** At first glance it *seems* that repeat is the fastest way to create a list with n identical elements: ``` >>> timeit.t...
Create List of Single Item Repeated n Times in Python
3,459,098
189
2010-08-11T14:01:33Z
3,459,140
60
2010-08-11T14:05:41Z
[ "python", "operator-overloading", "list-comprehension", "multiplication" ]
I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach. I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing ``` [...
``` >>> [5] * 4 [5, 5, 5, 5] ``` Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list! ``` >>> x=[5] >>> y=[x] * 4 >>> y [[5], [5], [5], [5]] >>> y[0][0] = 6 >>> y [[6], [6], [6], [6]] ```
Create List of Single Item Repeated n Times in Python
3,459,098
189
2010-08-11T14:01:33Z
24,557,558
23
2014-07-03T15:18:21Z
[ "python", "operator-overloading", "list-comprehension", "multiplication" ]
I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach. I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing ``` [...
> # Create List of Single Item Repeated n Times in Python ## Immutable items For immutable items, like None, strings, tuples, or frozensets, you can do it like this: ``` [e] * 4 ``` Note that this is best only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same ...
Create List of Single Item Repeated n Times in Python
3,459,098
189
2010-08-11T14:01:33Z
28,176,867
7
2015-01-27T17:53:32Z
[ "python", "operator-overloading", "list-comprehension", "multiplication" ]
I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach. I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without doing ``` [...
As others have pointed out, using the \* operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never us...
I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?
3,459,423
4
2010-08-11T14:32:50Z
3,459,578
11
2010-08-11T14:46:31Z
[ "python", "conventions", "code-formatting" ]
I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is *how* exactly the overflowing text should be formatted. Do I push it a...
> Supposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct? Yes, that's how PEP 8 shows it in examples: ``` class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if width == 0 and...
Converting (part of) a numpy recarray into a 2d array?
3,459,611
3
2010-08-11T14:49:50Z
3,460,221
8
2010-08-11T15:46:57Z
[ "python", "numpy", "recarray" ]
We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values. Several of these: ``` ts a b c 2010-08-06 08:00, 1.2, 3.4, 5.6 2010-08-06 08:05, 1.2, 3.4, 5.6 2010-08-06 08:10, 1.2, 3.4, 5.6 2010-08-06 08:15, 2.2, 3.3, 5.6 2010-08-06 08:20, ...
There are several ways to do this. One way is to select multiple columns of the recarray and cast them as floats, then reshape back into a 2D array: ``` new_data = data[['a','b','c']].astype(np.float).reshape((data.size, 3)) ``` Alternatively, you might consider something like this (negligibly slower, but more readab...
Is it possible to make Python functions behave like instances?
3,459,758
2
2010-08-11T15:02:34Z
3,459,803
7
2010-08-11T15:05:58Z
[ "python", "function", "attributes" ]
I understand that functions can have attributes. So I can do the following: ``` def myfunc(): myfunc.attribute += 1 print(myfunc.attribute) myfunc.attribute = 1 ``` Is it possible by any means to make such a function behave as if it were an instance? For example, I'd like to be able to do something like this...
You can make a class with a `__call__` method which would achieve a similar thing. **Edit for clarity:** Instead of making `myfunc` a function, make it a callable class. It walks like a function and it quacks like a function, but it can have members like a class.
subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution
3,460,130
6
2010-08-11T15:37:26Z
3,478,415
14
2010-08-13T15:35:49Z
[ "python", "eclipse", "subprocess", "popen", "pycharm" ]
The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX. Here's a simple example script: ``` import subprocess args = ["/usr/bin/which", "git"] print "Will execute %s" % " ".join(args) try: p = subprocess...
Ok, found the problem, and it's an important thing to keep in mind when using an IDE in a Unix-type environment. IDE's operate under a different environment context than the terminal user (duh, right?!). I was not considering that the subprocess was using a different environment than the context that I have for my term...
Remove adjacent duplicate elements from a list
3,460,161
10
2010-08-11T15:40:37Z
3,463,582
13
2010-08-11T23:15:34Z
[ "python" ]
Google Python Class | List Exercise - > Given a list of numbers, return a list where > all adjacent == elements have been reduced to a single element, > so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or > modify the passed in list. My solution using a new list is - ``` def remove_adjacent(nums): a = ...
Here's the traditional way, deleting adjacent duplicates in situ, while traversing the list backwards: ``` Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> def dedupe_adjacent(alist): ... for i in xrange(len(alist) - 1, 0, -1):...
Asking "is hashable" about a Python value
3,460,650
27
2010-08-11T16:35:07Z
3,460,725
14
2010-08-11T16:45:24Z
[ "python" ]
I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way. One mutation I would like to do is swap keys and value. Unfortunately, some values are dicts in their own right. However, this generates a "unhashable type: 'dict'" error. I don't really mind just stringifying the va...
``` def hashable(v): """Determine whether `v` can be hashed.""" try: hash(v) except TypeError: return False return True ```
Asking "is hashable" about a Python value
3,460,650
27
2010-08-11T16:35:07Z
3,460,747
32
2010-08-11T16:47:35Z
[ "python" ]
I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way. One mutation I would like to do is swap keys and value. Unfortunately, some values are dicts in their own right. However, this generates a "unhashable type: 'dict'" error. I don't really mind just stringifying the va...
Since Python 2.6 you can use the abstract base class [`collections.Hashable`](http://docs.python.org/library/collections.html#abcs-abstract-base-classes): ``` import collections >>> isinstance({}, collections.Hashable) False >> isinstance(0, collections.Hashable) True ``` This approach is also mentioned briefly in th...
Parse this date in Python: 5th November 2010
3,461,435
3
2010-08-11T18:05:15Z
3,461,462
17
2010-08-11T18:09:12Z
[ "python", "date-formatting", "python-datetime" ]
I'm having a bad time with date parsing and formatting today. Points for somebody who can parse this date format into a `datetime.date` or `datetime.datetime` (I'm not too fussy but I'd prefer `.date`): `5th November 2010`
Using [dateutil](http://labix.org/python-dateutil): ``` In [2]: import dateutil.parser as dparser In [3]: date = dparser.parse('5th November 2010') In [4]: date Out[4]: datetime.datetime(2010, 11, 5, 0, 0) ```
Parse this date in Python: 5th November 2010
3,461,435
3
2010-08-11T18:05:15Z
3,461,568
9
2010-08-11T18:23:24Z
[ "python", "date-formatting", "python-datetime" ]
I'm having a bad time with date parsing and formatting today. Points for somebody who can parse this date format into a `datetime.date` or `datetime.datetime` (I'm not too fussy but I'd prefer `.date`): `5th November 2010`
Unfortunately, `strptime` has no format characters for "skip an ordinal suffix" -- so, I'd do the skipping first, with a little RE, and then parse the resulting "clear" string. I.e.: ``` >>> import re >>> import datetime >>> ordn = re.compile(r'(?<=\d)(st|nd|rd|th)\b') >>> def parse(s): ... cleans = ordn.sub('', s) ...
What are the use cases of Node.js vs Twisted?
3,461,549
58
2010-08-11T18:21:05Z
3,461,640
71
2010-08-11T18:32:24Z
[ "javascript", "python", "twisted", "node.js" ]
Assuming a team of developers are equally comfortable with writing Javascript on the server side as they are with Python & Twisted, when is Node.js going to be more appropriate than Twisted (and vice versa)?
Twisted is more mature -- it's been around for a long, long time, and has so many bells and whistles as to make your head spin (implementations of the fanciest protocols, integration of the reactor with a large variety of other event loops, and so forth). Node.js is said to be faster (I have not measured it myself) an...
What are the use cases of Node.js vs Twisted?
3,461,549
58
2010-08-11T18:21:05Z
11,686,658
8
2012-07-27T11:14:23Z
[ "javascript", "python", "twisted", "node.js" ]
Assuming a team of developers are equally comfortable with writing Javascript on the server side as they are with Python & Twisted, when is Node.js going to be more appropriate than Twisted (and vice versa)?
As of 2012, Node.js has proved to be a fast, scalable, mature, and widely used platform. Ryan Dahl, creator of Node.js quotes: > These days, Node is being used by a large number of startups and established companies > around the world, from Voxer and Uber to Walmart and Microsoft. It’s safe to say that > billions of...
Multithreaded Python script taking longer than non-threaded script
3,461,899
3
2010-08-11T19:09:51Z
3,461,914
8
2010-08-11T19:12:05Z
[ "python", "multithreading" ]
Disclaimer: I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong. I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up. Multithreading seemed like an option, so I decided to try it out. However, while the original script took ~85 seco...
I suspect the Python Global Interpreter Lock is preventing your code from running in two threads at once. <http://stackoverflow.com/questions/1294382/what-is-a-global-interpreter-lock-gil> Clearly you want to take advantage of multiple CPUs. Can you split the ray tracing across processes instead of threads? The mult...
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
3,462,160
392
2010-08-11T19:40:00Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
``` In [5]: list(set(temp1) - set(temp2)) Out[5]: ['Four', 'Three'] ```
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
3,462,164
23
2010-08-11T19:40:27Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
``` temp3 = [item for item in temp1 if item not in temp2] ```
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
3,462,181
11
2010-08-11T19:42:06Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
i'll toss in since none of the present solutions yield a tuple: ``` temp3 = tuple(set(temp1) - set(temp2)) ``` alternatively: ``` #edited using @Mark Byers idea. If you accept this one as answer, just accept his instead. temp3 = tuple(x for x in temp1 if x not in set(temp2)) ``` Like the other non-tuple yielding an...
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
3,462,202
252
2010-08-11T19:44:47Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
The existing solutions all offer either one or the other of: * Faster than O(n\*m) performance. * Preserve order of input list. But so far no solution has both. If you want both, try this: ``` s = set(temp2) temp3 = [x for x in temp1 if x not in s] ``` **Performance test** ``` import timeit init = 'temp1 = list(ra...
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
12,005,040
11
2012-08-17T11:38:00Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
The difference between two lists (say list1 and list2) can be found using the following simple function. ``` def diff(list1, list2): c = set(list1).union(set(list2)) d = set(list1).intersection(set(list2)) return list(c - d) ``` By Using the above function, the difference can be found using `diff(temp2, t...
Get difference between two lists
3,462,143
262
2010-08-11T19:38:10Z
26,079,411
10
2014-09-27T21:30:22Z
[ "python", "list", "set", "set-difference" ]
I have two lists in Python, like these: ``` temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] ``` I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: ``` temp3 = ['Three', 'Four'] ``` Are there any fast ways without cycles...
In case you want the difference recursively, I have written a package for python: <https://github.com/seperman/deepdiff> ## Installation Install from PyPi: ``` pip install deepdiff ``` ## Example usage Importing ``` >>> from deepdiff import DeepDiff >>> from pprint import pprint >>> from __future__ import print_f...
check if a string matches an IP address pattern in python?
3,462,784
20
2010-08-11T20:59:17Z
3,462,840
43
2010-08-11T21:06:31Z
[ "python" ]
What is the fastest way to check if a string matches a certain pattern? Is regex the best way? For example, I have a bunch of strings and want to check each one to see if they are a valid IP address (valid in this case meaning correct format), is the fastest way to do this using regex? Or is there something faster wit...
It looks like you are trying to [validate IP addresses](http://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python). A regular expression is probably not the best tool for this. If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) the...
check if a string matches an IP address pattern in python?
3,462,784
20
2010-08-11T20:59:17Z
3,462,915
10
2010-08-11T21:16:30Z
[ "python" ]
What is the fastest way to check if a string matches a certain pattern? Is regex the best way? For example, I have a bunch of strings and want to check each one to see if they are a valid IP address (valid in this case meaning correct format), is the fastest way to do this using regex? Or is there something faster wit...
I'm normally the one of the very few Python experts who steadfastly defends regular expressions (they have quite a bad reputation in the Python community), but this is not one of those cases -- accepting (say) `'333.444.555.666'` as an "IP address" is **really** bad, and if you need to do more checks after matching the...
Check if OneToOneField is None in Django
3,463,240
52
2010-08-11T22:08:28Z
4,901,736
7
2011-02-04T18:44:10Z
[ "python", "django-models", "one-to-one" ]
I have two models like this: ``` class Type1Profile(models.Model): user = models.OneToOneField(User, unique=True) ... class Type2Profile(models.Model): user = models.OneToOneField(User, unique=True) ... ``` I need to do something if the user has Type1 or Type2 profile: ``` if request.user.type1prof...
How about using try/except blocks? ``` def get_profile_or_none(user, profile_cls): try: profile = getattr(user, profile_cls.__name__.lower()) except profile_cls.DoesNotExist: profile = None return profile ``` Then, use like this! ``` u = request.user if get_profile_or_none(u, Type1Profi...
Check if OneToOneField is None in Django
3,463,240
52
2010-08-11T22:08:28Z
9,016,298
49
2012-01-26T09:50:22Z
[ "python", "django-models", "one-to-one" ]
I have two models like this: ``` class Type1Profile(models.Model): user = models.OneToOneField(User, unique=True) ... class Type2Profile(models.Model): user = models.OneToOneField(User, unique=True) ... ``` I need to do something if the user has Type1 or Type2 profile: ``` if request.user.type1prof...
To check if the (OneToOne) relation exists or not, you can use the `hasattr` function: ``` if hasattr(request.user, 'type1profile'): # do something elif hasattr(request.user, 'type2profile'): # do something else else: # do something else ```
Check if OneToOneField is None in Django
3,463,240
52
2010-08-11T22:08:28Z
22,240,021
22
2014-03-07T01:59:24Z
[ "python", "django-models", "one-to-one" ]
I have two models like this: ``` class Type1Profile(models.Model): user = models.OneToOneField(User, unique=True) ... class Type2Profile(models.Model): user = models.OneToOneField(User, unique=True) ... ``` I need to do something if the user has Type1 or Type2 profile: ``` if request.user.type1prof...
It's possible to see if a nullable one-to-one relationship is null for a particular model simply by testing the corresponding field on the model for `None`ness, but *only* if you test on the model where the one-to-one relationship originates. For example, given these two classes… ``` class Place(models.Model): n...
Parsing a Wikipedia dump
3,463,447
10
2010-08-11T22:44:34Z
3,464,095
10
2010-08-12T01:26:44Z
[ "python", "mediawiki", "wikipedia-api", "mediawiki-api", "wikimedia-dumps" ]
For example using this Wikipedia dump: <http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=lebron%20james&rvprop=content&redirects=true&format=xmlfm> Is there an existing library for Python that I can use to create an array with the mapping of subjects and values? For example: ``` {height_ft,6},{n...
It looks like you really want to be able to parse MediaWiki markup. There is a python library designed for this purpose called [mwlib](http://code.pediapress.com/wiki/wiki/mwlib). You can use python's built-in XML packages to extract the page content from the API's response, then pass that content into mwlib's parser t...
Python: coerce new-style class
3,463,530
8
2010-08-11T23:02:50Z
3,463,578
9
2010-08-11T23:14:26Z
[ "python", "oop", "class", "coerce" ]
I want this code to "just work": ``` def main(): c = Castable() print c/3 print 2-c print c%7 print c**2 print "%s" % c print "%i" % c print "%f" % c ``` Of course, the easy way out is to write `int(c)/3`, but I'd like to enable a simpler perl-ish syntax for a configuration mini-langua...
You need to define `__div__` if you want `c/3` to work. Python won't convert your object to a number first for you.
django combobox
3,463,700
6
2010-08-11T23:41:50Z
3,464,260
10
2010-08-12T02:04:37Z
[ "python", "django", "forms", "combobox" ]
ok so i`m makeing an app that has a file name field upload file field and a combobox, lets say I have smth like this for the combobox ``` <select name="menu"> <option value="0" selected> select imp </option> <option value="1"> imp 1 </option> <option value="2"> imp 2 </option> <option value="3"> imp 3 </op...
You need to use a [ChoiceField](http://docs.djangoproject.com/en/1.2/ref/forms/fields/#choicefield): ``` IMP_CHOICES = ( ('1', 'imp 1'), ('2', 'imp 2'), ('3', 'imp 3'), ('4', 'imp 4'), ) class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(widget=for...
'in-place' string modifications in Python
3,463,746
10
2010-08-11T23:52:57Z
3,463,789
12
2010-08-12T00:02:39Z
[ "python", "string" ]
In Python, strings are immutable. What is the standard idiom to walk through a string character-by-character and modify it? The only methods I can think of are some genuinely stanky hacks related to joining against a result string. -- In C: ``` for(int i = 0; i < strlen(s); i++) { s[i] = F(s[i]); } ``` This is...
Don't use a string, use something mutable like bytearray: ``` #!/usr/bin/python s = bytearray("my dog has fleas") for n in xrange(len(s)): s[n] = chr(s[n]).upper() print s ``` Results in: ``` MY DOG HAS FLEAS ``` Edit: Since this is a `bytearray`, you aren't (necessarily) working with *characters*. You're wor...
'in-place' string modifications in Python
3,463,746
10
2010-08-11T23:52:57Z
3,463,847
9
2010-08-12T00:18:24Z
[ "python", "string" ]
In Python, strings are immutable. What is the standard idiom to walk through a string character-by-character and modify it? The only methods I can think of are some genuinely stanky hacks related to joining against a result string. -- In C: ``` for(int i = 0; i < strlen(s); i++) { s[i] = F(s[i]); } ``` This is...
you can use the UserString module: ``` >>> import UserString ... s = UserString.MutableString('Python') ... print s Python >>> s[0] = 'c' >>> print s cython ```
'in-place' string modifications in Python
3,463,746
10
2010-08-11T23:52:57Z
3,463,868
14
2010-08-12T00:25:54Z
[ "python", "string" ]
In Python, strings are immutable. What is the standard idiom to walk through a string character-by-character and modify it? The only methods I can think of are some genuinely stanky hacks related to joining against a result string. -- In C: ``` for(int i = 0; i < strlen(s); i++) { s[i] = F(s[i]); } ``` This is...
The Python analog of your C: ``` for(int i = 0; i < strlen(s); i++) { s[i] = F(s[i]); } ``` would be: ``` s = "".join(F(c) for c in s) ``` which is also very expressive. It says exactly what is happening, but in a functional style rather than a procedural style.
'in-place' string modifications in Python
3,463,746
10
2010-08-11T23:52:57Z
3,464,238
7
2010-08-12T02:00:24Z
[ "python", "string" ]
In Python, strings are immutable. What is the standard idiom to walk through a string character-by-character and modify it? The only methods I can think of are some genuinely stanky hacks related to joining against a result string. -- In C: ``` for(int i = 0; i < strlen(s); i++) { s[i] = F(s[i]); } ``` This is...
I'd say the most Pythonic way is to use [`map()`](http://docs.python.org/library/functions.html#map): ``` s = map(func, s) # func has been applied to every character in s ``` This is the equivalent of writing: ``` s = "".join(func(c) for c in s) ```
How to round the minute of a datetime object python
3,463,930
48
2010-08-12T00:45:21Z
3,464,000
76
2010-08-12T01:04:05Z
[ "python" ]
I have a datetime object produced using strptime(). ``` >>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) ``` What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it. ``` min = round(tm.minute, -1) ``` However, as w...
This will get the 'floor' of a `datetime` object stored in tm rounded to the 10 minute mark before `tm`. ``` tm = tm - datetime.timedelta(minutes=tm.minute % 10, seconds=tm.second, microseconds=tm.microsecond) ``` If you want classic rounding to the nearest 10...
How to round the minute of a datetime object python
3,463,930
48
2010-08-12T00:45:21Z
10,854,034
50
2012-06-01T16:25:32Z
[ "python" ]
I have a datetime object produced using strptime(). ``` >>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) ``` What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it. ``` min = round(tm.minute, -1) ``` However, as w...
General function to round a datetime at any time laps in seconds: ``` def roundTime(dt=None, roundTo=60): """Round a datetime object to any time laps in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 1 minute. Author: Thierry Husson 2012 - Use i...
How to round the minute of a datetime object python
3,463,930
48
2010-08-12T00:45:21Z
31,005,978
8
2015-06-23T14:43:13Z
[ "python" ]
I have a datetime object produced using strptime(). ``` >>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) ``` What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it. ``` min = round(tm.minute, -1) ``` However, as w...
From the best answer I modified to an adapted version using only datetime objects, this avoids having to do the conversion to seconds and makes the calling code more readable: ``` def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)): """Round a datetime object to a multiple of a timedelta dt : datet...
Cast base class to derived class python (or more pythonic way of extending classes)
3,464,061
17
2010-08-12T01:20:12Z
3,464,154
28
2010-08-12T01:39:13Z
[ "python", "inheritance", "derived-class", "base-class" ]
I need to extend the Networkx python package and add a few methods to the `Graph` class for my particular need The way I thought about doing this is simplying deriving a new class say `NewGraph`, and adding the required methods. However there are several other functions in networkx which create and return `Graph` obj...
If you are just adding behavior, and not depending on additional instance values, you can assign to the object's `__class__`: ``` from math import pi class Circle(object): def __init__(self, radius): self.radius = radius def area(self): return pi * self.radius**2 class CirclePlus(Circle): ...
Cast base class to derived class python (or more pythonic way of extending classes)
3,464,061
17
2010-08-12T01:20:12Z
4,714,744
10
2011-01-17T15:19:12Z
[ "python", "inheritance", "derived-class", "base-class" ]
I need to extend the Networkx python package and add a few methods to the `Graph` class for my particular need The way I thought about doing this is simplying deriving a new class say `NewGraph`, and adding the required methods. However there are several other functions in networkx which create and return `Graph` obj...
Here's how to "magically" replace a class in a module with a custom-made subclass without touching the module. It's only a few extra lines from a normal subclassing procedure, and therefore gives you (almost) all the power and flexibility of subclassing as a bonus. For instance this allows you to add new attributes, if...
Is it possible to wrap the text of xticks in matplotlib in python?
3,464,359
5
2010-08-12T02:29:40Z
3,464,416
9
2010-08-12T02:50:25Z
[ "python", "django", "matlab", "matplotlib" ]
Anyone know if it is possible to wrap the xtick labels in matplotlib? Right now I've got the following code (kind of messy -- been hacking at it for a while): ``` def plotResults(request, question_id): responses = ResponseOption.objects.filter(question__id=question_id).order_by('order').annotate(response_num=Count('r...
Perhaps try: ``` ax.set_xticklabels(labels, rotation=45) ``` Thanks to Amro for pointing out that [`rotation` can be any degree](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks).
sqlalchemy: one-to-one relationship with declarative
3,464,443
24
2010-08-12T02:59:01Z
4,324,826
16
2010-12-01T13:30:54Z
[ "python", "sqlalchemy" ]
What is the best way to create a one-to-one relationship in SQLAlchemy using declarative? I have two tables, `foo` and `bar`, and I want `foo.bar_id` to link to `bar`. The catch is that this is a one-way one-to-one relationship. `bar` must not know anything about `foo`. For every foo, there will be one and only one `b...
If you want a true one-to-one relationship, you also have to use the "uselist=False" in your relationship definition. ``` bar_id = Column(Integer, ForeignKey(Bar.id)) bar = relationship(Bar, uselist=False) ```
sqlalchemy: one-to-one relationship with declarative
3,464,443
24
2010-08-12T02:59:01Z
9,611,874
51
2012-03-08T01:50:31Z
[ "python", "sqlalchemy" ]
What is the best way to create a one-to-one relationship in SQLAlchemy using declarative? I have two tables, `foo` and `bar`, and I want `foo.bar_id` to link to `bar`. The catch is that this is a one-way one-to-one relationship. `bar` must not know anything about `foo`. For every foo, there will be one and only one `b...
The documentation for 0.7 [explains this nicely](http://docs.sqlalchemy.org/en/latest/orm/relationships.html#one-to-one): ``` class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child = relationship("Child", uselist=False, backref="parent") class Child(Base): __tablenam...
What's the best layout for a python command line application?
3,465,045
9
2010-08-12T05:49:36Z
3,466,342
7
2010-08-12T09:35:34Z
[ "python", "packaging", "setuptools", "distribute" ]
What is the right way (or I'll settle for a *good* way) to lay out a command line python application of moderate complexity? I've created a python project skeleton using paster, which gave me a few files to start with: ``` myproj/__init__.py MyProj.egg-info/ dependency_links.txt entry_points.txt PKG-INFO SOURCES.t...
You don't need to create all that, the `.egg-info` directory is generated by setuptools. You mention the command line, so I assumed you have a 'top level' script somewhere, let's say `myproj-bin`. Then this would work: ``` ./setup.py ./myproj ./myproj/__init__.py ./scripts ./scripts/myproj-bin ``` And then put someth...
Python urllib2 URLError HTTP status code.
3,465,704
25
2010-08-12T07:51:04Z
3,465,796
50
2010-08-12T08:07:02Z
[ "python", "exception", "urllib2" ]
I want to grab the HTTP status code once it raises a URLError exception: I tried this but didn't help: ``` except URLError, e: logger.warning( 'It seems like the server is down. Code:' + str(e.code) ) ```
You shouldn't check for a status code after catching `URLError`, since that exception can be raised in situations where there's no HTTP status code available, for example when you're getting connection refused errors. Use `HTTPError` to check for HTTP specific errors, and then use `URLError` to check for other problem...
Attaching a decorator to all functions within a class
3,467,526
27
2010-08-12T12:16:41Z
3,467,879
17
2010-08-12T12:59:54Z
[ "python", "decorator" ]
I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function. I suppose it then becomes a kind of aspect, rather than a decorator and it does feel a bit odd, but was thinking for something li...
The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass. Alternatively, just apply your decorator at the end of the class definition: ``` class Something: def foo(self): pass for name, fn in inspect.getmembers(Something): if isinstance(fn, types.UnboundMethodT...
Attaching a decorator to all functions within a class
3,467,526
27
2010-08-12T12:16:41Z
3,468,410
18
2010-08-12T13:54:47Z
[ "python", "decorator" ]
I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function. I suppose it then becomes a kind of aspect, rather than a decorator and it does feel a bit odd, but was thinking for something li...
Everytime you think of changing class definition, you can either use the class decorator or metaclass. e.g. using metaclass ``` import types class DecoMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.iteritems(): if isinstance(attr_value, types.FunctionType): ...
How can Python lists within objects be freed?
3,467,704
2
2010-08-12T12:40:05Z
3,467,727
9
2010-08-12T12:43:04Z
[ "python", "list" ]
I have a Python class containing a list, to which I `append()` values. If I delete an object of this class then create a second object later on in the same script, the second object's list is the same as the first's was at the time of deletion. For example: ``` class myObj: a = [] b = False o = myObj() o.a....
When you create a variable inside a class declaration, it's a class attribute, not an instance attribute. To create instance attributes you have to do `self.a` inside a method, e.g. `__init__`. Change it to: ``` class myObj: def __init__(self): self.a = [] self.b = False ```
Java or any other language: Which method/class invoked mine?
3,468,101
11
2010-08-12T13:25:34Z
3,468,188
18
2010-08-12T13:33:17Z
[ "java", "javascript", "python", "programming-languages", "classloader" ]
I would like to write a code internal to my method that print which method/class has invoked it. (My assumption is that I can't change anything but my method..) How about other programming languages? **EDIT:** Thanks guys, how about JavaScript? python? C++?
This is specific to Java. You can use `Thread.currentThread().`[`getStackTrace()`](http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace%28%29). This will return an array of [`StackTraceElements`](http://download.oracle.com/javase/6/docs/api/java/lang/StackTraceElement.html). The 2nd elemen...
Detect "overall average" color of the picture
3,468,500
41
2010-08-12T14:02:52Z
3,468,588
63
2010-08-12T14:12:00Z
[ "php", "javascript", "python", "image-processing" ]
I have a jpg image. I need to know "overall average" the color of the image. At first glance there can use the histogram of the image (channel RGB). At work I use mostly JavaScript and PHP (a little Python) therefore welcomed the decision in these languages. Maybe ther are library for working with images that address...
You can use **PHP** to get an array of the color palette like so: ``` <?php function colorPalette($imageFile, $numColors, $granularity = 5) { $granularity = max(1, abs((int)$granularity)); $colors = array(); $size = @getimagesize($imageFile); if($size === false) { user_error("Unable to get...
Understanding Python daemon threads
3,470,235
8
2010-08-12T17:11:09Z
3,470,359
12
2010-08-12T17:27:19Z
[ "python" ]
I've obviously misunderstood something fundamental about a Python Thread object's daemon attribute. Consider the following: ``` daemonic.py import sys, threading, time class TestThread(threading.Thread): def __init__(self, daemon): threading.Thread.__init__(self) self.daemon = daemon def ru...
Your understanding about what daemon threads *should* do is correct. As to why this isn't happening, I am guessing you are using an older version of Python. The Python 2.5.4 docs include a `setDaemon(daemonic)` function, as well as `isDaemon()` to check if a thread is a daemon thread. The 2.6 docs replace these with a...
List of integers into string (byte array) - python
3,470,398
16
2010-08-12T17:32:53Z
3,470,466
7
2010-08-12T17:40:53Z
[ "python" ]
I have a list of integer ascii values that I need to transform into a string (binary) to use as the key for a crypto operation. (I am re-implementing java crypto code in python) This works (assuming an 8-byte key): ``` key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76) ``` However, I would prefer to not ...
``` struct.pack('B' * len(integers), *integers) ``` `*sequence` means "unpack sequence" - or rather, "when calling `f(..., *args ,...)`, let `args = sequence`".
List of integers into string (byte array) - python
3,470,398
16
2010-08-12T17:32:53Z
3,470,652
26
2010-08-12T18:07:47Z
[ "python" ]
I have a list of integer ascii values that I need to transform into a string (binary) to use as the key for a crypto operation. (I am re-implementing java crypto code in python) This works (assuming an 8-byte key): ``` key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76) ``` However, I would prefer to not ...
I much prefer the [`array`](http://docs.python.org/library/array.html) module to the `struct` module for this kind of tasks (ones involving sequences of *homogeneous* values): ``` >>> import array >>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring() '\x11\x18y\x01\x0c\xde"L' ``` no `len` call, no string...
List of integers into string (byte array) - python
3,470,398
16
2010-08-12T17:32:53Z
3,646,405
34
2010-09-05T14:30:52Z
[ "python" ]
I have a list of integer ascii values that I need to transform into a string (binary) to use as the key for a crypto operation. (I am re-implementing java crypto code in python) This works (assuming an 8-byte key): ``` key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76) ``` However, I would prefer to not ...
For Python 2.6 and later if you are dealing with bytes then a `bytearray` is the most obvious choice: ``` >>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76])) '\x11\x18y\x01\x0c\xde"L' ``` To me this is even more direct than Alex Martelli's answer - still no string manipulation or `len` call but now you don't even n...
Python base64 data decode
3,470,546
47
2010-08-12T17:52:52Z
3,470,583
67
2010-08-12T17:58:08Z
[ "python", "base64", "decode" ]
I have the following piece of base64 encoded data, and I want to use python base64 module to extract information from it. It seems that module does not work. Can anyone tell me how? ``` Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH...
``` import base64 coded_string = '''Q5YACgA...''' base64.b64decode(coded_string) ``` worked for me. At the risk of pasting an offensively-long result, I got: ``` >>> base64.b64decode(coded_string) 2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07...
Python base64 data decode
3,470,546
47
2010-08-12T17:52:52Z
12,984,159
10
2012-10-20T00:29:35Z
[ "python", "base64", "decode" ]
I have the following piece of base64 encoded data, and I want to use python base64 module to extract information from it. It seems that module does not work. Can anyone tell me how? ``` Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH...
(I know this is old but I wanted to post this for people like me who stumble upon it in the future) I personally just use this python code to decode base64 strings: ``` print open("FILE-WITH-STRING", "rb").read().decode("base64") ``` So you can run it in a bash script like this: ``` python -c 'print open("FILE-WITH-...
Python base64 data decode
3,470,546
47
2010-08-12T17:52:52Z
25,487,483
48
2014-08-25T13:52:41Z
[ "python", "base64", "decode" ]
I have the following piece of base64 encoded data, and I want to use python base64 module to extract information from it. It seems that module does not work. Can anyone tell me how? ``` Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH...
A quick way to decode it without importing anything: ``` >>> a = 'eW91ciB0ZXh0' >>> a.decode('base64') 'your text' ``` or just ``` 'eW91ciB0ZXh0'.decode('base64') ``` This doesnt work in Python 3.
Be my human compiler: What is wrong with this Python 2.5 code?
3,471,295
5
2010-08-12T19:30:50Z
3,471,391
17
2010-08-12T19:41:55Z
[ "python", "django", "syntax" ]
My framework is raising a syntax error when I try to execute this code: ``` from django.template import Template, TemplateSyntaxError try: Template(value) except TemplateSyntaxError as error: raise forms.ValidationError(error) return value ``` And here's the error: ``` from templa...
The alternate syntax `except SomeException as err` [is new in 2.6](http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes). You should use `except SomeException, err` in 2.5.
memory size of Python data structure
3,471,559
12
2010-08-12T19:59:51Z
3,471,594
14
2010-08-12T20:05:19Z
[ "python", "memory", "data-structures", "memory-management" ]
How do I find out the memory size of a Python data structure? I'm looking for something like: ``` sizeof({1:'hello', 2:'world'}) ``` It is great if it counts every thing recursively. But even a basic non-recursive result helps. Basically I want to get a sense of various implementation options like tuple v.s. list v.s...
Have a look at the [`sys.getsizeof`](http://docs.python.org/library/sys.html#sys.getsizeof) function. According to the documentation, it returns the size of an object in bytes, as given by the object's `__sizeof__` method. As [Daniel](https://stackoverflow.com/users/219162/daniel-stutzbach) pointed out in a comment, i...
How do I merge two lists into a single list?
3,471,999
14
2010-08-12T21:01:45Z
3,472,009
17
2010-08-12T21:02:51Z
[ "python" ]
I have ``` a = [1, 2] b = ['a', 'b'] ``` I want ``` c = [1, 'a', 2, 'b'] ```
If the order of the elements much match the order in your example then you can use a combination of [zip](http://docs.python.org/library/functions.html#zip) and [chain](http://docs.python.org/library/itertools.html#chain): ``` from itertools import chain c = list(chain(*zip(a,b))) ``` If you don't care about the orde...
How do I merge two lists into a single list?
3,471,999
14
2010-08-12T21:01:45Z
3,472,069
31
2010-08-12T21:09:10Z
[ "python" ]
I have ``` a = [1, 2] b = ['a', 'b'] ``` I want ``` c = [1, 'a', 2, 'b'] ```
``` [j for i in zip(a,b) for j in i] ```
How do I merge two lists into a single list?
3,471,999
14
2010-08-12T21:01:45Z
3,472,379
16
2010-08-12T21:59:37Z
[ "python" ]
I have ``` a = [1, 2] b = ['a', 'b'] ``` I want ``` c = [1, 'a', 2, 'b'] ```
Parsing ``` [j for i in zip(a,b) for j in i] ``` in your head is easy enough if you recall that the `for` and `if` clauses are done in order, followed a final append of the result: ``` temp = [] for i in zip(a, b): for j in i: temp.append(j) ``` and would be easier had it have been written with more mea...
How can I make setuptools install a package that's not on PyPI?
3,472,430
89
2010-08-12T22:10:05Z
3,481,388
118
2010-08-14T00:03:48Z
[ "python", "setuptools", "distutils", "pypi" ]
I've just started working with setuptools and virtualenv. My package requires the latest python-gearman that is only available from GitHub. The python-gearman version that's on PyPI is an old one. The Github source is setuptools-compatible, i.e. has setup.py, etc. Is there a way to make setuptools download and install ...
The key is to tell easy\_install where the package can be downloaded. In this particular case, it can be found at the url <http://github.com/mtai/python-gearman/tarball/master>. However, that link by itself won't work, because easy\_install can't tell just by looking at the URL what it's going to get. By changing it t...
How can I make setuptools install a package that's not on PyPI?
3,472,430
89
2010-08-12T22:10:05Z
23,865,528
29
2014-05-26T08:06:26Z
[ "python", "setuptools", "distutils", "pypi" ]
I've just started working with setuptools and virtualenv. My package requires the latest python-gearman that is only available from GitHub. The python-gearman version that's on PyPI is an old one. The Github source is setuptools-compatible, i.e. has setup.py, etc. Is there a way to make setuptools download and install ...
You can use the `pip install protocol+location[@tag][#egg=Dependency]` format to install directly from source using pip. ## Git ``` pip install git+https://github.com/username/repo.git pip install git+https://github.com/username/repo.git@MyTag pip install git+https://github.com/username/repo.git@MyTag#egg=ProjectName...
About pyjamas maturity vs GWT maturity (with short dead lines) for a web application
3,472,493
6
2010-08-12T22:23:07Z
3,473,114
7
2010-08-13T00:44:55Z
[ "java", "python", "gwt", "pyjamas" ]
I love both, python and Java and I have this first '*serious*' web application project that I would like to carry out. I find it hard to choose between **pyjamas** + **django** and **GWT** + **Hibernate**. In fact, from my beginner point of view, it seems like the python world is more suitable for a quickly-developed...
> In fact, from my beginner point of > view, it seems like the python world > is more suitable for a > quickly-developed and fun web > application. And, on the other hand, > the java world is useful for > performance-oriented, scalable > solutions and for 'serious' projects > with big money involved... Naah. For examp...
Python urllib2.urlopen() is slow, need a better way to read several urls
3,472,515
8
2010-08-12T22:26:18Z
3,472,533
7
2010-08-12T22:30:36Z
[ "python", "http", "concurrency", "urllib2" ]
As the title suggests, I'm working on a site written in python and it makes several calls to the urllib2 module to read websites. I then parse them with BeautifulSoup. As I have to read 5-10 sites, the page takes a while to load. I'm just wondering if there's a way to read the sites all at once? Or anytricks to make ...
**Edit:** Please take a look at Wai's post for a better version of this code. Note that there is nothing wrong with this code and it **will work properly**, despite the comments below. The speed of reading web pages is probably bounded by your Internet connection, not Python. You could use threads to load them all at...
Python urllib2.urlopen() is slow, need a better way to read several urls
3,472,515
8
2010-08-12T22:26:18Z
3,472,905
11
2010-08-12T23:49:16Z
[ "python", "http", "concurrency", "urllib2" ]
As the title suggests, I'm working on a site written in python and it makes several calls to the urllib2 module to read websites. I then parse them with BeautifulSoup. As I have to read 5-10 sites, the page takes a while to load. I'm just wondering if there's a way to read the sites all at once? Or anytricks to make ...
I'm rewriting Dumb Guy's code below using modern Python modules like `threading` and `Queue`. ``` import threading, urllib2 import Queue urls_to_load = [ 'http://stackoverflow.com/', 'http://slashdot.org/', 'http://www.archive.org/', 'http://www.yahoo.co.jp/', ] def read_url(url, queue): data = urllib2.urlopen(u...
python: httplib error: can not send headers
3,473,583
3
2010-08-13T02:58:38Z
3,473,627
7
2010-08-13T03:11:02Z
[ "python", "http-headers", "httprequest", "httplib" ]
``` conn = httplib.HTTPConnection('thesite') conn.request("GET","myurl") conn.putheader('Connection','Keep-Alive') #conn.putheader('User-Agent','Mozilla/5.0(Windows; u; windows NT 6.1;en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome//5.0.375.126 Safari//5.33.4') #conn.putheader('Accept-Encoding','gzip,deflate,sdch')...
Use `putrequest` instead of `request`. Since `request` also can send headers, it will send a blank line to the server to indicate end of headers, so sending headers afterward will create an error. Alternatively, you could do as is done [here](http://docs.python.org/library/httplib.html): ``` import httplib, urllib pa...
exception for notifying that subclass should implement a method in python
3,473,667
8
2010-08-13T03:20:50Z
3,473,796
11
2010-08-13T03:58:50Z
[ "python", "design-patterns", "exception", "coding-style" ]
suppose I want to create an abstract class in python with some methods to be implemented by subclasses. (in Python) for example: ``` class Base(): def f(self): print "Hello." self.g() print "Bye!" class A(Base): def g(self): print "I am A" class B(Base): def g(self): ...
In Python 2.6 and better, you can use the [abc](http://docs.python.org/library/abc.html) module to make `Base` an "actually" abstract base class: ``` import abc class Base: __metaclass__ = abc.ABCMeta @abc.abstractmethod def g(self): pass def f(self): # &c ``` this guarantees that `Base` cann...
Modifying a namedtuple's constructor arguments via subclassing?
3,474,118
13
2010-08-13T05:22:48Z
3,474,156
10
2010-08-13T05:31:31Z
[ "python", "new-operator", "super", "namedtuple" ]
I want to create a `namedtuple` which represents the individual flags in a short bitfield. I'm trying to subclass it so that I can unpack the bitfield before the tuple is created. However, my current attempt isn't working: ``` class Status(collections.namedtuple("Status", "started checking start_after_check checked er...
I'd avoid `super` unless you're explicitly catering to multiple inheritance (hopefully not the case here;-). Just do something like...: ``` def __new__(cls, status): return cls.__bases__[0].__new__(cls, status & 1, status & 2, status & 4, stat...
Modifying a namedtuple's constructor arguments via subclassing?
3,474,118
13
2010-08-13T05:22:48Z
8,322,450
12
2011-11-30T07:23:50Z
[ "python", "new-operator", "super", "namedtuple" ]
I want to create a `namedtuple` which represents the individual flags in a short bitfield. I'm trying to subclass it so that I can unpack the bitfield before the tuple is created. However, my current attempt isn't working: ``` class Status(collections.namedtuple("Status", "started checking start_after_check checked er...
You almost had it :-) There are just two little corrections: 1. The *new* method needs a *return* statement 2. The *super* call should have two arguments, *cls* and *Status* The resulting code looks like this: ``` import collections class Status(collections.namedtuple("Status", "started checking start_after_check c...
How do I run two python loops concurrently?
3,474,382
10
2010-08-13T06:23:49Z
3,474,430
13
2010-08-13T06:31:10Z
[ "python", "concurrency" ]
Suppose I have the following in Python ``` # A loop for i in range(10000): Do Task A # B loop for i in range(10000): Do Task B ``` How do I run these loops simultaneously in Python?
Why do you want to run the two processes at the same time? Is it because you think they will go faster (there is a good chance that they wont). Why not run the tasks in the same loop, e.g. ``` for i in range(10000): doTaskA() doTaskB() ``` The obvious answer to your question is to use threads - see the python...
How do I run two python loops concurrently?
3,474,382
10
2010-08-13T06:23:49Z
3,475,576
16
2010-08-13T09:30:11Z
[ "python", "concurrency" ]
Suppose I have the following in Python ``` # A loop for i in range(10000): Do Task A # B loop for i in range(10000): Do Task B ``` How do I run these loops simultaneously in Python?
If you want concurrency, here's a very simple example: ``` from multiprocessing import Process def loop_a(): while 1: print("a") def loop_b(): while 1: print("b") if __name__ == '__main__': Process(target=loop_a).start() Process(target=loop_b).start() ``` This is just the *most basi...
Split a string by a delimiter in python
3,475,251
50
2010-08-13T08:46:07Z
3,475,270
82
2010-08-13T08:48:55Z
[ "python" ]
How to split this string where $$TEXT$$ is the delimiter. ``` 1.MATCHES$$TEXT$$STRING 2.MATCHES $$TEXT$$ STRING ```
`string.split('$$TEXT$$')` ? ``` >>> a="1.MATCHES$$TEXT$$STRING" >>> a.split("$$TEXT$$") ['1.MATCHES', 'STRING'] >>> a="2.MATCHES $$TEXT$$ STRING" >>> a.split("$$TEXT$$") ['2.MATCHES ', ' STRING'] ``` and: ``` >>> [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")] ['2.MATCHES', 'STRING'] ```
Static variable inheritance in Python
3,475,488
9
2010-08-13T09:20:17Z
3,475,678
15
2010-08-13T09:44:22Z
[ "python", "inheritance", "syntax", "static", "blender" ]
I'm writing Python scripts for Blender for a project, but I'm pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of code I am currently working on: ``` class panelToggle(bpy.types.Operator): active = False def invoke(self, context, event): sel...
use `type(self)` for access to class attributes ``` >>> class A(object): var = 2 def write(self): print type(self).var >>> class B(A): pass >>> B().write() 2 >>> B.var = 3 >>> B().write() 3 >>> A().write() 2 ```
How to loop backwards in python?
3,476,732
68
2010-08-13T12:25:08Z
3,476,753
51
2010-08-13T12:27:14Z
[ "python", "iteration", "range" ]
I'm talking about doing something like: ``` for(i=n; i>=1; --i) { //do something with i } ``` I can think of some ways to do so in python (creating a list of `range(1,n+1)` and reverse it, using `while` and `--i`, ...) but I wondered if there's a more elegant way to do it. Is there? EDIT: Some suggested I use xra...
``` for x in reversed(whatever): do_something() ``` This works on basically everything that has a defined order, including `xrange` objects and lists.
How to loop backwards in python?
3,476,732
68
2010-08-13T12:25:08Z
3,476,768
104
2010-08-13T12:28:58Z
[ "python", "iteration", "range" ]
I'm talking about doing something like: ``` for(i=n; i>=1; --i) { //do something with i } ``` I can think of some ways to do so in python (creating a list of `range(1,n+1)` and reverse it, using `while` and `--i`, ...) but I wondered if there's a more elegant way to do it. Is there? EDIT: Some suggested I use xra...
`range()` and `xrange()` take a third parameter that specifies a step. So you can do the following. ``` range(10, 0, -1) ``` Which gives ``` [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] ``` But for iteration, you should really be using `xrange` instead. So, ``` xrange(10, 0, -1) ```
What is the maximum float in Python?
3,477,283
77
2010-08-13T13:34:15Z
3,477,332
123
2010-08-13T13:38:46Z
[ "python", "int", "long-integer", "max" ]
I think the maximum integer in python is available by calling `sys.maxint`. What is the maximum `float` or `long` in Python?
For `float` have a look at [`sys.float_info`](http://docs.python.org/library/sys.html#sys.float_info): ``` >>> import sys >>> sys.float_info sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2 250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil on=2.22044604925...
What is the maximum float in Python?
3,477,283
77
2010-08-13T13:34:15Z
3,477,336
10
2010-08-13T13:39:09Z
[ "python", "int", "long-integer", "max" ]
I think the maximum integer in python is available by calling `sys.maxint`. What is the maximum `float` or `long` in Python?
sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.
"pythonic" method to parse a string of comma-separated integers into a list of integers?
3,477,502
5
2010-08-13T13:56:24Z
3,477,515
16
2010-08-13T13:57:49Z
[ "python" ]
I am reading in a string of integers such as `"3 ,2 ,6 "` and want them in the list `[3,2,6]` as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
``` mylist = [int(x) for x in '3 ,2 ,6 '.split(',')] ``` And if you're not sure you'll only have digits (or want to discard the others): ``` mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()] ```