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
List of unicode strings
9,097,441
5
2012-02-01T14:24:46Z
9,097,748
14
2012-02-01T14:43:45Z
[ "python", "unicode" ]
If I have a list of unicode strings ``` lst = [ u"aaa", u"bbb", u"foo", u"bar", ... u"baz", u"zzz" ] ``` is it necessary to write a prefix `u` before every string? Can I make a construction that says that every element of lst will be unicode string and then write it without `u` prefix?
In Python 2.7 (also Python 2.6) you can make unicode literals the default for a module: ``` from __future__ import unicode_literals ``` You must include the import at the top of the file, and it then applies to all string literals in the file. Use a `b` prefix to force byte strings: ``` >>> from __future__ import un...
Why assert is not largely used?
9,097,706
38
2012-02-01T14:41:15Z
9,100,717
11
2012-02-01T17:53:46Z
[ "python", "debugging", "assert" ]
I found that [Python's assert statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-assert_stmt) is a good way to catch situations that [*should never happen*](http://stackoverflow.com/questions/944592/best-practice-for-python-assert). And it can be removed by Python optimization when the code is ...
I'm not an author of any of those projects, so this is just a guess based on my own experiences. Without directly asking people in those projects you won't get a concrete answer. Assert is great when you're trying to do debugging, etc in your own application. As stated in the link you provided, however, using a condit...
Why assert is not largely used?
9,097,706
38
2012-02-01T14:41:15Z
9,132,116
38
2012-02-03T16:39:47Z
[ "python", "debugging", "assert" ]
I found that [Python's assert statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-assert_stmt) is a good way to catch situations that [*should never happen*](http://stackoverflow.com/questions/944592/best-practice-for-python-assert). And it can be removed by Python optimization when the code is ...
I guess the main reason for `assert` not being used more often is that **nobody uses Python's "optimized" mode**. Asserts are a great tool to detect programming mistakes, to guard yourself from unexpected situations, but all this error checking comes with a cost. In compiled languages such as C/C++, this does not real...
Why assert is not largely used?
9,097,706
38
2012-02-01T14:41:15Z
12,872,502
27
2012-10-13T11:07:06Z
[ "python", "debugging", "assert" ]
I found that [Python's assert statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-assert_stmt) is a good way to catch situations that [*should never happen*](http://stackoverflow.com/questions/944592/best-practice-for-python-assert). And it can be removed by Python optimization when the code is ...
Several reasons come to mind... **It is not a primary function** Many programmers, lets not get bogged down by the rationale, disrespect anything which is not a direct participant in the program's penultimate functionality. The assert statement is intended for debugging and testing, and so, a luxury they can ill-affo...
Aren't Python strings immutable?
9,097,994
32
2012-02-01T14:56:56Z
9,098,025
32
2012-02-01T14:59:14Z
[ "python" ]
My understanding was that Python strings are immutable. I tried the following code: ``` a = "Dog" b = "eats" c = "treats" print a, b, c # Dog eats treats print a + " " + b + " " + c # Dog eats treats print a # Dog a = a + " " + b + " " + c print a # Dog eats treats # !!! ``` Shouldn't Python have prevented the a...
The string objects themselves are immutable. The variable, `a`, which points to the string, is mutable. Consider: ``` a = "Foo" # a now points to "Foo" b = a # b points to the same "Foo" that a points to a = a + a # a points to the new string "FooFoo", but b still points to the old "Foo" print a print b # Outputs: ...
Aren't Python strings immutable?
9,097,994
32
2012-02-01T14:56:56Z
9,098,026
9
2012-02-01T14:59:17Z
[ "python" ]
My understanding was that Python strings are immutable. I tried the following code: ``` a = "Dog" b = "eats" c = "treats" print a, b, c # Dog eats treats print a + " " + b + " " + c # Dog eats treats print a # Dog a = a + " " + b + " " + c print a # Dog eats treats # !!! ``` Shouldn't Python have prevented the a...
A variable is just a label pointing to an object. The object is immutable, but you can make the label point to a completely different object if you want to.
Aren't Python strings immutable?
9,097,994
32
2012-02-01T14:56:56Z
9,098,038
69
2012-02-01T15:00:03Z
[ "python" ]
My understanding was that Python strings are immutable. I tried the following code: ``` a = "Dog" b = "eats" c = "treats" print a, b, c # Dog eats treats print a + " " + b + " " + c # Dog eats treats print a # Dog a = a + " " + b + " " + c print a # Dog eats treats # !!! ``` Shouldn't Python have prevented the a...
First `a` pointed to the string "Dog". Then you changed the variable `a` to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.
Aren't Python strings immutable?
9,097,994
32
2012-02-01T14:56:56Z
9,098,193
9
2012-02-01T15:09:06Z
[ "python" ]
My understanding was that Python strings are immutable. I tried the following code: ``` a = "Dog" b = "eats" c = "treats" print a, b, c # Dog eats treats print a + " " + b + " " + c # Dog eats treats print a # Dog a = a + " " + b + " " + c print a # Dog eats treats # !!! ``` Shouldn't Python have prevented the a...
The variable a is pointing at the object "Dog". It's best to think of the variable in Python as a tag. You can move the tag to different objects which is what you did when you changed `a = "dog"` to `a = "dog eats treats"`. However, immutability refers to the object, not the tag. --- If you tried `a[1] = 'z'` to mak...
Name parts of iterables in itertools.products
9,098,194
3
2012-02-01T15:09:07Z
9,098,295
11
2012-02-01T15:15:42Z
[ "python", "itertools" ]
I've been reading about `itertools`, which seems to be a very powerful module. I am particularly interested in `itertools.product()` which appears to give me all of the combinations of the iterable inputs. However, I would like to know which of the input iterables each of the outputs are coming from. For example, a si...
The output of `itertools.product([1, 2, 3], [1, 2])` is a series of ordered pairs whether the first element comes from `[1,2,3]` and the second element from `[1,2]`. This is guaranteed behavior. If field names are desired, you can cast the result to a [named tuple](http://docs.python.org/library/collections.html#colle...
Tool for pinpointing circular imports in Python/Django?
9,098,787
22
2012-02-01T15:46:55Z
9,219,685
31
2012-02-09T22:16:57Z
[ "python", "django", "import" ]
I have a Django app and somewhere in it is a recursive import that is causing problems. Because of the size of the app I'm having a problem pinpointing the cause of the circular import. I know that the answer is "just don't write circular imports" but the problem is I'm having a hard time figuring out where the circul...
The cause of the import error is easily found, in the backtrace of the ImportError exception. When you look in the backtrace, you'll see that the module has been imported before. One of it's imports imported something else, executed main code, and now imports that first module. Since the first module was not fully ini...
Tool for pinpointing circular imports in Python/Django?
9,098,787
22
2012-02-01T15:46:55Z
9,220,736
9
2012-02-09T23:45:44Z
[ "python", "django", "import" ]
I have a Django app and somewhere in it is a recursive import that is causing problems. Because of the size of the app I'm having a problem pinpointing the cause of the circular import. I know that the answer is "just don't write circular imports" but the problem is I'm having a hard time figuring out where the circul...
One of the common causes of circular imports in Django is using foreign keys in modules that reference each other. Django provides a way to circumvent this by explicitly specifying a model as a string with the full application label: ``` class MyModel(models.Model): myfk = models.ForeignKey( 'myapp.MyAppMo...
swig error: Undefined Symbol
9,098,980
3
2012-02-01T15:58:47Z
9,102,536
10
2012-02-01T20:09:05Z
[ "python", "swig", "undefined-symbol" ]
I'm having trouble with swig and to me it looks like it is saying that one of the data members of my code is an undefined symbol. I have found answers online on how to fix functions but this is puzzling me. My error is: ``` Traceback (most recent call last): File "./test1.py", line 5, in <module> from volumes i...
We can de-mangle the symbol name with `c++filt`: ``` c++filt _ZN13ConstantColorC1ESt10shared_ptrI5ColorE ``` Which gave: ``` ConstantColor::ConstantColor(std::shared_ptr<Color>) ``` i.e. your constructor which takes a `shared_ptr`. Only the first unresolved symbol will be reported though. Notice that here it's *no...
Where are python bytearrays used?
9,099,145
30
2012-02-01T16:09:12Z
9,099,337
34
2012-02-01T16:22:36Z
[ "python", "types" ]
I recently came across the dataType called `bytearray` in python. Could someone provide scenarios where bytearrays are required?
A `bytearray` is very similar to a regular python string (`str` in python2.x, `bytes` in python3) but with an important difference, whereas strings are *immutable*, `bytearray`s are mutable, a bit like a `list` of single character strings. This is useful because some applications use byte sequences in ways that perfor...
Where are python bytearrays used?
9,099,145
30
2012-02-01T16:09:12Z
9,099,768
36
2012-02-01T16:50:27Z
[ "python", "types" ]
I recently came across the dataType called `bytearray` in python. Could someone provide scenarios where bytearrays are required?
This answer has been shameless ripped off from [here](http://dabeaz.blogspot.com/2010/01/few-useful-bytearray-tricks.html) ### Example 1: Assembling a message from fragments Suppose you're writing some network code that is receiving a large message on a socket connection. If you know about sockets, you know that the ...
Send file from client to server using XMLRPC?
9,099,174
11
2012-02-01T16:11:04Z
14,278,300
12
2013-01-11T12:33:31Z
[ "python", "xml-rpc", "sendfile" ]
I want to write Python code to send a file from client to server. server needs to save the file sent from the client. But my code have some bugs which I cannot fix. Below is my server code: ``` # server.py from SimpleXMLRPCServer import SimpleXMLRPCServer import os server = SimpleXMLRPCServer(('localhost', 9000)) de...
**Server side:** ``` def server_receive_file(self,arg): with open("path/to/save/filename", "wb") as handle: handle.write(arg.data) return True ``` **Client side:** ``` with open("path/to/filename", "rb") as handle: binary_data = xmlrpclib.Binary(handle.read()) client.server_receiv...
Using __new__ on classes derived from Django's models does not work
9,100,409
6
2012-02-01T17:31:31Z
9,104,864
10
2012-02-01T23:17:54Z
[ "python", "django", "django-models" ]
This is something which is puzzling me, but I cannot get a definitive answer. Using the `__new__` method (or more accurately, static method) within classes derived from DJango model. This is how `__new__` should be ideally used (since we are using Django, we can assume that version 2.x of python is being used): ``` c...
`__new__` doesn't receive an instance as its first parameter. How could it when (a) it's a static method, as you note, and (b) its job is to create an instance and return it! The first parameter of `__new__` is conventionally called `cls`, as it is the class. Which makes the error message you quote very weird; it is n...
Why does PyLint warn about no __init__?
9,100,616
10
2012-02-01T17:46:36Z
9,100,718
7
2012-02-01T17:53:47Z
[ "python", "pylint" ]
We have numerous python classes that do not seem to need `__init__`, initialising them empty is either perfectly acceptable or even preferable. PyLint seems to think this is a bad thing. Am I missing some insight into why having no `__init__` is a Bad Smell? Or should I just suppress those warnings and get over it?
What are you using these classes for? If they are just a grouping of functions that do not need to maintain any state, there is no need for an `__init__()` but it would make more sense to just move all of those functions into their own module. If they do maintain a state (they have instance variables) then you should...
Randomly Keep X Percent of Dictionary
9,100,896
3
2012-02-01T18:05:48Z
9,100,956
7
2012-02-01T18:10:25Z
[ "python", "django" ]
I'm struggling with this one. I need to randomly keep X percent of a dictionary for some analysis I'm doing. A user would input a percentage of the data they would like to keep. Example values: 10, 50, 70, 100 So when a user enters 30, how would I go about keeping 30 of every 100th element randomly? I tried the b...
If ordering doesn't matter... ``` import random random.sample(votes_selected, int(len(votes_selected) * DATA_PERCENTAGE / 100)) ``` --- P.S. If votes\_selected is actually a dict, then you can do this: ``` dict(random.sample(votes_selected.iteritems(), int(len(votes_selected) * DATA_PERCENTAGE / 100))) ```
Matplotlib bar graph x axis won't plot string values
9,101,497
14
2012-02-01T18:53:14Z
9,114,298
34
2012-02-02T14:46:10Z
[ "python", "matplotlib", "bar-chart" ]
My name is David and I work for an ambulance service in Florida. I am using Python 2.7 and matplotlib. I am attempting to reach into my database of ambulance calls and count up the number of calls that happen on each weekday. I will then use matplotlib to create a bar chart of this information to give the paramedics ...
Your question has nothing to do with an SQL query, it is simply a means to end. What you are really asking is how to change the text labels on a bar chart in pylab. The docs for the [bar chart](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar) are useful for customizing, but to simply [change...
Pretty printers for maps throwing a type error
9,102,967
6
2012-02-01T20:37:30Z
9,108,404
16
2012-02-02T07:10:55Z
[ "c++", "python", "gdb", "pretty-print" ]
I've configured pretty printers using <http://wiki.eclipse.org/CDT/User/FAQ#How_can_I_inspect_the_contents_of_STL_containers.3F>. It successfully works for vector and other containers. However I can't get to inspect maps as in the example below: ``` #include <map> #include <iostream> using namespace std; int main ()...
What compiler (and which version) did you use to build your test source? I am guessing it wasn't a recent version of `g++`. Here is what I get with `g++ 4.4.3-4ubuntu5`: ``` $ gdb -q ./a.out Reading symbols from /tmp/a.out...done. (gdb) b 12 Breakpoint 1 at 0x400de3: file t.cc, line 12. (gdb) r Breakpoint 1, main...
Is Python 'sys.argv' limited in the maximum number of arguments?
9,103,023
3
2012-02-01T20:40:24Z
9,103,163
7
2012-02-01T20:49:57Z
[ "python", "xargs", "argparse", "argv" ]
I have a Python script that needs to process a large number of files. To get around Linux's relatively small limit on the number of arguments that can be passed to a command, I am using `find -print0` with `xargs -0`. I know another option would be to use Python's glob module, but that won't help when I have a more ad...
`xargs` will chunk your arguments by default. Have a look at the `--max-args` and `--max-chars` options of `xargs`. Its man page also explains the limits (under `--max-chars`).
multiple axis in matplotlib with different scales
9,103,166
31
2012-02-01T20:50:14Z
9,103,464
53
2012-02-01T21:14:29Z
[ "python", "matplotlib" ]
How can multiple scales can be implemented in Matplotlib? I am not talking about the primary and secondary axis plotted against the same x-axis, but something like many trends which have different scales plotted in same y-axis and that can be identified by their colors. For example, if I have `trend1 ([0,1,2,3,4])` an...
If I understand the question, you may interested in [this example](http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html) in the Matplotlib gallery. ![enter image description here](http://i.stack.imgur.com/21CM9.png) Yann's comment above provides a similar example. --- Edit - Link above fixed. Correspon...
multiple axis in matplotlib with different scales
9,103,166
31
2012-02-01T20:50:14Z
24,543,018
19
2014-07-03T00:09:08Z
[ "python", "matplotlib" ]
How can multiple scales can be implemented in Matplotlib? I am not talking about the primary and secondary axis plotted against the same x-axis, but something like many trends which have different scales plotted in same y-axis and that can be identified by their colors. For example, if I have `trend1 ([0,1,2,3,4])` an...
if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter `secondary_y=True`, like this: ``` df.A.plot(label="Points", legend=True) df.B.plot(secondary_y=True, label=...
multiple axis in matplotlib with different scales
9,103,166
31
2012-02-01T20:50:14Z
27,965,971
12
2015-01-15T14:45:05Z
[ "python", "matplotlib" ]
How can multiple scales can be implemented in Matplotlib? I am not talking about the primary and secondary axis plotted against the same x-axis, but something like many trends which have different scales plotted in same y-axis and that can be identified by their colors. For example, if I have `trend1 ([0,1,2,3,4])` an...
Bootstrapping *something fast* to chart multiple y-axes sharing an x-axis using [@joe-kington's](http://stackoverflow.com/a/7734614/1085495) answer: ![enter image description here](http://i.stack.imgur.com/BUJzx.png) ``` # d = Pandas Dataframe, # ys = [ [cols in the same y], [cols in the same y], [cols in the same y]...
Resize image maintaining aspect ratio AND making portrait and landscape images exact same size?
9,103,257
10
2012-02-01T20:58:01Z
9,103,783
15
2012-02-01T21:42:29Z
[ "python", "django", "image", "thumbnails", "python-imaging-library" ]
Currently I am using: ``` os.chdir(album.path) images = glob.glob('*.*') # thumbs size size = 80,80 for image in images: #create thumb file, ext = os.path.splitext(image) im = Image.open(os.path.join(album.path,image)) im.thumbnail(size, Image.ANTIALIAS) th...
Here is my take on doing a padded fit for an image: ``` #!/usr/bin/env python from PIL import Image, ImageChops F_IN = "/path/to/image_in.jpg" F_OUT = "/path/to/image_out.jpg" size = (80,80) image = Image.open(F_IN) image.thumbnail(size, Image.ANTIALIAS) image_size = image.size thumb = image.crop( (0, 0, size[0],...
Is there a way to write these ifs nicer?
9,104,770
38
2012-02-01T23:08:53Z
9,104,797
55
2012-02-01T23:11:09Z
[ "python", "control-structure" ]
I need to write these four `if`s in Python. Notice what it does, is changing between four possible states in a loop: `1,0 -> 0,1 -> -1,0 -> 0,-1` and back to first. ``` if [dx, dy] == [1,0]: dx, dy = 0, 1 if [dx, dy] == 0, 1: dx, dy = -1, 0 if [dx, dy] == [-1, 0] dx, dy = 0, -1 if [dx, dy] == [0, -1]: ...
Magnus' suggestion is undeniably the right answer to your question as posed, but *generally speaking,* you want to use a dictionary for problems like this: ``` statemap = {(1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1), (0, -1): (1, 0)} dx, dy = statemap[dx, dy] ``` Even in this case I *could* argue using a dicti...
Is there a way to write these ifs nicer?
9,104,770
38
2012-02-01T23:08:53Z
9,104,807
155
2012-02-01T23:12:25Z
[ "python", "control-structure" ]
I need to write these four `if`s in Python. Notice what it does, is changing between four possible states in a loop: `1,0 -> 0,1 -> -1,0 -> 0,-1` and back to first. ``` if [dx, dy] == [1,0]: dx, dy = 0, 1 if [dx, dy] == 0, 1: dx, dy = -1, 0 if [dx, dy] == [-1, 0] dx, dy = 0, -1 if [dx, dy] == [0, -1]: ...
``` dx, dy = -dy, dx ``` When in doubt, apply maths. ;)
Is there a way to write these ifs nicer?
9,104,770
38
2012-02-01T23:08:53Z
9,105,596
18
2012-02-02T00:42:19Z
[ "python", "control-structure" ]
I need to write these four `if`s in Python. Notice what it does, is changing between four possible states in a loop: `1,0 -> 0,1 -> -1,0 -> 0,-1` and back to first. ``` if [dx, dy] == [1,0]: dx, dy = 0, 1 if [dx, dy] == 0, 1: dx, dy = -1, 0 if [dx, dy] == [-1, 0] dx, dy = 0, -1 if [dx, dy] == [0, -1]: ...
The values you're working with appear to be a unit vector that continuously rotates - in other words, a [phasor](http://en.wikipedia.org/wiki/Phasor). [Complex numbers are coordinates](http://c2.com/cgi/wiki?ComplexNumbersArePoints), so: ``` # at initialization phase = 1 # at the point of modification phase *= 1j dx, ...
Is there a way to write these ifs nicer?
9,104,770
38
2012-02-01T23:08:53Z
9,197,294
30
2012-02-08T16:22:22Z
[ "python", "control-structure" ]
I need to write these four `if`s in Python. Notice what it does, is changing between four possible states in a loop: `1,0 -> 0,1 -> -1,0 -> 0,-1` and back to first. ``` if [dx, dy] == [1,0]: dx, dy = 0, 1 if [dx, dy] == 0, 1: dx, dy = -1, 0 if [dx, dy] == [-1, 0] dx, dy = 0, -1 if [dx, dy] == [0, -1]: ...
Just extending Magnus answer. If you imagine [dx, dy] as a vector, what you're actually doing is a [rotation](http://en.wikipedia.org/wiki/Rotation_%28mathematics%29) of 90 degrees (or PI/2). To calculate this, you can use the following transformation: ![two dimensional rotation](http://i.stack.imgur.com/9i1IS.png) ...
Is there any way to make simplejson less strict?
9,104,930
5
2012-02-01T23:23:32Z
9,105,030
8
2012-02-01T23:33:57Z
[ "python", "json", "simplejson" ]
I'm interested in having `simplejson.loads()` successfully parse the following: ``` {foo:3} ``` It throws JSONDecodeError saying "expecting property name" but in reality it's saying "I require double quotes around my property names". This is annoying for my use case, and I'd prefer a less strict behavior. I've read t...
You can use YAML (>=1.2)as it is a superset of JSON, you can do: ``` >>> import yaml >>> s = '{foo: 8}' >>> yaml.load(s) {'foo': 8} ```
How to beautify JSON in Python or through command line
9,105,031
34
2012-02-01T23:34:14Z
9,105,132
69
2012-02-01T23:45:43Z
[ "python", "json", "osx" ]
Can someone suggest how I can beautify JSON in Python or through the command line (I use OS X)? The only online based JSON beautifier which could do it was: <http://jsonviewer.stack.hu/>. I need to use it from within Python, however. This is my dataset: ``` { "head": {"vars": [ "address" , "description" ,"listprice"...
From the command-line: ``` echo '{"one":1,"two":2}' | python -mjson.tool ``` which outputs: ``` { "one": 1, "two": 2 } ``` Programmtically, the Python manual [describes pretty-printing JSON](http://docs.python.org/library/json.html): ``` >>> import json >>> print json.dumps({'4': 5, '6': 7}, sort_keys=Tru...
How to beautify JSON in Python or through command line
9,105,031
34
2012-02-01T23:34:14Z
9,105,143
9
2012-02-01T23:47:17Z
[ "python", "json", "osx" ]
Can someone suggest how I can beautify JSON in Python or through the command line (I use OS X)? The only online based JSON beautifier which could do it was: <http://jsonviewer.stack.hu/>. I need to use it from within Python, however. This is my dataset: ``` { "head": {"vars": [ "address" , "description" ,"listprice"...
Use the `indent` argument of the `dumps` function in the [json module](http://docs.python.org/library/json.html#json.dumps). From the docs: ``` >>> import json >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) { "4": 5, "6": 7 } ```
How to beautify JSON in Python or through command line
9,105,031
34
2012-02-01T23:34:14Z
10,181,379
14
2012-04-16T20:41:59Z
[ "python", "json", "osx" ]
Can someone suggest how I can beautify JSON in Python or through the command line (I use OS X)? The only online based JSON beautifier which could do it was: <http://jsonviewer.stack.hu/>. I need to use it from within Python, however. This is my dataset: ``` { "head": {"vars": [ "address" , "description" ,"listprice"...
Try [underscore-cli](https://github.com/ddopson/underscore-cli): ``` cat myfile.json | underscore print --color ``` ![](https://raw.github.com/ddopson/underscore-cli/master/doc/example.png) It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, e...
Python List Slicing with Arbitrary Indices
9,106,065
17
2012-02-02T01:52:54Z
9,106,104
8
2012-02-02T01:58:50Z
[ "python", "list", "slice" ]
Is there a better way to extract arbitrary indices from a list in python? The method I currently use is: ``` a = range(100) s = [a[i] for i in [5,13,25]] ``` Where a is the array I want to slice, and [5,13,25] are the elements that I want to get. It seems much more verbose than the Matlab equivalent: ``` a = 0:99; ...
There is no "ready made" way - the way you do it is quite ingenuous, and you could use it. If you have a lot of that trough your code, you might want to use a subclass of list that would use a syntax just like matlabs - it can be done in a few lines code, the major burden is that you'd have to work always use this new ...
Python List Slicing with Arbitrary Indices
9,106,065
17
2012-02-02T01:52:54Z
9,106,174
14
2012-02-02T02:05:53Z
[ "python", "list", "slice" ]
Is there a better way to extract arbitrary indices from a list in python? The method I currently use is: ``` a = range(100) s = [a[i] for i in [5,13,25]] ``` Where a is the array I want to slice, and [5,13,25] are the elements that I want to get. It seems much more verbose than the Matlab equivalent: ``` a = 0:99; ...
If you are a Matlab user, but want to use Python, check out [numpy](http://numpy.scipy.org/): ``` In [37]: import numpy as np In [38]: a = np.arange(100) In [39]: s = a[[5,13,25]] In [40]: s Out[40]: array([ 5, 13, 25]) ``` Here is a [comparison of NumPy and Matlab](http://www.scipy.org/NumPy_for_Matlab_Users), an...
Python List Slicing with Arbitrary Indices
9,106,065
17
2012-02-02T01:52:54Z
9,108,109
21
2012-02-02T06:34:12Z
[ "python", "list", "slice" ]
Is there a better way to extract arbitrary indices from a list in python? The method I currently use is: ``` a = range(100) s = [a[i] for i in [5,13,25]] ``` Where a is the array I want to slice, and [5,13,25] are the elements that I want to get. It seems much more verbose than the Matlab equivalent: ``` a = 0:99; ...
``` >>> from operator import itemgetter >>> a = range(100) >>> itemgetter(5,13,25)(a) (5, 13, 25) ```
regression testing the entire app in Python
9,106,251
4
2012-02-02T02:15:58Z
9,106,324
9
2012-02-02T02:24:44Z
[ "python", "unit-testing", "testing", "python-3.x", "regression-testing" ]
I have a small command-line application (about 6k lines). It has no unit tests because I didn't know how to write them; but I'm retroactively adding some now. I read [this tutorial](http://openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html) but I'm left puzzled about how to test the whole application using this module...
Step 1. Break your app into two pieces. 1. The piece that uses `optparse` (or `argparse`) to parse the command-line options. 2. The piece that does the real work. Your "main" script then does part 1 to get all the options and invokes part 2 to do the real work. This is called "design for testability" and is the more...
Python logging and rotating files
9,106,795
14
2012-02-02T03:32:34Z
9,106,865
13
2012-02-02T03:43:15Z
[ "python", "logging" ]
I have a python program that is writing to a log file that is being rotated by Linux's logrotate command. When this happens I need to signal my program to stop writing to the old file and start writing to the new one. I can handle the signal but how do I tell python to write to the new file? I am opening the file like...
You may want to look at [WatchedFileHandler](http://docs.python.org/library/logging.handlers.html#watchedfilehandler) to implement this, or as an alternative, implement log rotation with [RotatingFileHandler](http://docs.python.org/library/logging.handlers.html#rotatingfilehandler), both of which are in the [logging.ha...
Python logging and rotating files
9,106,795
14
2012-02-02T03:32:34Z
20,755,477
7
2013-12-24T05:42:03Z
[ "python", "logging" ]
I have a python program that is writing to a log file that is being rotated by Linux's logrotate command. When this happens I need to signal my program to stop writing to the old file and start writing to the new one. I can handle the signal but how do I tell python to write to the new file? I am opening the file like...
Since rotation is already being done by `logrotate`, in your signal handler you should just call `logging.basicConfig(...)` again and that should reopen the log file.
Python logging and rotating files
9,106,795
14
2012-02-02T03:32:34Z
28,333,560
7
2015-02-04T23:28:38Z
[ "python", "logging" ]
I have a python program that is writing to a log file that is being rotated by Linux's logrotate command. When this happens I need to signal my program to stop writing to the old file and start writing to the new one. I can handle the signal but how do I tell python to write to the new file? I am opening the file like...
Don't use `logging.basicConfig`, use `WatchedFileHandler`. Here's how to use it. ``` import time import logging import logging.handlers def log_setup(): log_handler = logging.handlers.WatchedFileHandler('my.log') formatter = logging.Formatter( '%(asctime)s program_name [%(process)d]: %(message)s', ...
django-admin.py prints help only
9,107,196
7
2012-02-02T04:31:47Z
12,064,093
7
2012-08-21T22:41:43Z
[ "python", "django" ]
I am using django 1.3.1 I followed the online tutorial and tried to use "django-admin.py startproject mysite". But I always receive this: ``` D:\Code\djtest>django-admin.py startproject mysite Usage: django-admin.py subcommand [options] [args] Options: -v VERBOSITY, --verbosity=VERBOSITY (...) ``` What is goin...
I had exactly the same problem and solved it using this tool: [FileTypesManager](http://www.nirsoft.net/utils/file_types_manager.html) The problem is that django-admin.py is not receiving the correct arguments from the command line. I did a test by hacking a couple of lines into the front of the admin script to displa...
Efficient memoization in Python
9,108,238
13
2012-02-02T06:48:34Z
9,108,504
14
2012-02-02T07:20:54Z
[ "python", "performance", "argument-passing", "static-variables", "memoization" ]
I have some task to solve and the most important part at the moment is to make the script as time-efficient as possible. One of the elements I am trying to optimize is memoization within one of the functions. So my question is: **Which of the following 3-4 methods is the most efficient / fastest method of implementing...
The different styles of variable access have already been timed and compared at: <http://code.activestate.com/recipes/577834-compare-speeds-of-different-kinds-of-access-to-var> Here's a quick summary: local access beats nonlocal (nested scopes) which beat global access (module scope) which beats access to builtins. Yo...
numpy recarray strings of variable length
9,108,837
13
2012-02-02T07:57:16Z
9,109,626
19
2012-02-02T09:08:38Z
[ "python", "numpy", "recarray" ]
Is it possible to initialise a numpy recarray that will hold strings, without knowing the length of the strings beforehand? As a (contrived) example: ``` mydf = np.empty( (numrows,), dtype=[ ('file_name','STRING'), ('file_size_MB',float) ] ) ``` The problem is that I'm constructing my recarray in advance of populati...
Instead of using the `STRING` dtype, one can always use `object` as dtype. That will allow any object to be assigned to an array element, including Python variable length strings. For example: ``` >>> import numpy as np >>> mydf = np.empty( (2,), dtype=[('file_name',object),('file_size_mb',float)] ) >>> mydf['file_nam...
How does reduce function work?
9,108,855
13
2012-02-02T07:59:03Z
9,108,910
9
2012-02-02T08:03:58Z
[ "python", "reduce" ]
As far as I understand, the reduce function takes a list `l` and a function `f`. Then, it calls the function `f` on first two elements of the list and then repeatedly calls the function `f` with the next list element and the previous result. So, I define the following functions: The following function computes the fa...
Your function calls `fact()` on *both arguments*. You are calculating `((1! * 3!)! * 1!)`. The workaround is to only call it on only the second argument, and pass `reduce()` an initial value of 1.
How does reduce function work?
9,108,855
13
2012-02-02T07:59:03Z
9,109,065
17
2012-02-02T08:17:59Z
[ "python", "reduce" ]
As far as I understand, the reduce function takes a list `l` and a function `f`. Then, it calls the function `f` on first two elements of the list and then repeatedly calls the function `f` with the next list element and the previous result. So, I define the following functions: The following function computes the fa...
The easiest way to understand *reduce()* is to look at its pure Python equivalent code: ``` def myreduce(func, iterable, start=None): it = iter(iterable) if start is None: try: start = next(it) except StopIteration: raise TypeError('reduce() of empty sequence with no ini...
How does reduce function work?
9,108,855
13
2012-02-02T07:59:03Z
31,660,532
8
2015-07-27T18:26:08Z
[ "python", "reduce" ]
As far as I understand, the reduce function takes a list `l` and a function `f`. Then, it calls the function `f` on first two elements of the list and then repeatedly calls the function `f` with the next list element and the previous result. So, I define the following functions: The following function computes the fa...
The other answers are great but I'd simply add an illustrated example that I find pretty good to understand `reduce()`: ``` >>> reduce(lambda x,y: x+y, [47,11,42,13]) 113 ``` will be computed as follows: [![enter image description here](http://i.stack.imgur.com/OCsJC.png)](http://i.stack.imgur.com/OCsJC.png) ([Sour...
Is it bad practice to use a built-in function name as an attribute or method identifier?
9,109,333
23
2012-02-02T08:45:23Z
9,109,359
10
2012-02-02T08:47:21Z
[ "python", "namespaces", "python-3.x", "reserved-words", "naming-conventions" ]
I know to never use built-in function names as variable identifiers. But are there any reasons not to use them as attribute or method identifiers? For example, is it safe to write `my_object.id = 5`, or define an instance method `dict` in my own class?
No, that's fine. Since an object reference is required there is no way to have them shadow the built-in.
Is it bad practice to use a built-in function name as an attribute or method identifier?
9,109,333
23
2012-02-02T08:45:23Z
9,109,488
8
2012-02-02T08:59:03Z
[ "python", "namespaces", "python-3.x", "reserved-words", "naming-conventions" ]
I know to never use built-in function names as variable identifiers. But are there any reasons not to use them as attribute or method identifiers? For example, is it safe to write `my_object.id = 5`, or define an instance method `dict` in my own class?
Yes it's bad practice. It might not immediately break anything for you, but it still hurts readability of the code. To selectively quote from PEP20: > Beautiful is better than ugly. > Simple is better than complex. > Readability counts. > If the implementation is hard to explain, it's a bad idea. Seeing a call...
Is it bad practice to use a built-in function name as an attribute or method identifier?
9,109,333
23
2012-02-02T08:45:23Z
9,109,489
22
2012-02-02T08:59:06Z
[ "python", "namespaces", "python-3.x", "reserved-words", "naming-conventions" ]
I know to never use built-in function names as variable identifiers. But are there any reasons not to use them as attribute or method identifiers? For example, is it safe to write `my_object.id = 5`, or define an instance method `dict` in my own class?
It won't confuse the interpreter but it may confuse people reading your code. Unnecessary use of builtin names for attributes and methods should be avoided. Another ill-effect is that shadowing builtins confuses syntax highlighters in most python-aware editors (vi, emacs, pydev, idle, etc.) Also, some of the lint tool...
Python Config parser read comment along with value
9,110,428
6
2012-02-02T10:08:05Z
9,110,539
7
2012-02-02T10:16:05Z
[ "python", "configparser" ]
I have config file, ``` [local] variable1 : val1 ;#comment1 variable2 : val2 ;#comment2 ``` code like this reads only value of the key: ``` class Config(object): def __init__(self): self.config = ConfigParser.ConfigParser() self.config.read('config.py') def get_path(self): re...
Alas, this is not easily done in general case. Comments are *supposed* to be ignored by the parser. In your specific case, it is easy, because `#` only serves as a comment character if it begins a line. So variable1's value will be `"val1 #comment1"`. I suppose you use something like this, only less brittle: ``` val1...
Asynchronous Requests with Python requests
9,110,593
42
2012-02-02T10:20:07Z
9,189,249
68
2012-02-08T07:23:17Z
[ "python", "asynchronous", "python-requests", "http-request" ]
I tried the sample provided within the documentation of the requests library for python: <http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests> with `async.map(rs)` I get the response codes but I want to get the content of each page requested. ``` out = async.map(rs) print out[0].content ``...
## Note The below answer is *not* applicable to requests v0.13.0+. The asynchronous functionality was moved to [grequests](https://github.com/kennethreitz/grequests) after this question was written. However, you could just replace `requests` with `grequests` below and it should work. I've left this answer as is to re...
Asynchronous Requests with Python requests
9,110,593
42
2012-02-02T10:20:07Z
11,949,710
35
2012-08-14T09:47:09Z
[ "python", "asynchronous", "python-requests", "http-request" ]
I tried the sample provided within the documentation of the requests library for python: <http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests> with `async.map(rs)` I get the response codes but I want to get the content of each page requested. ``` out = async.map(rs) print out[0].content ``...
`async` is now an independent module : `grequests`. See here : <https://github.com/kennethreitz/grequests> And there: [Ideal method for sending multiple HTTP requests over Python?](http://stackoverflow.com/questions/10555292/ideal-method-for-sending-multiple-http-requests-over-python) ## installation: ``` $ pip ins...
Asynchronous Requests with Python requests
9,110,593
42
2012-02-02T10:20:07Z
23,902,034
17
2014-05-28T02:48:59Z
[ "python", "asynchronous", "python-requests", "http-request" ]
I tried the sample provided within the documentation of the requests library for python: <http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests> with `async.map(rs)` I get the response codes but I want to get the content of each page requested. ``` out = async.map(rs) print out[0].content ``...
maybe [requests-futures](https://github.com/ross/requests-futures) is another choice. ``` from requests_futures.sessions import FuturesSession session = FuturesSession() # first request is started in background future_one = session.get('http://httpbin.org/get') # second requests is started immediately future_two = se...
Asynchronous Requests with Python requests
9,110,593
42
2012-02-02T10:20:07Z
33,777,090
8
2015-11-18T10:08:01Z
[ "python", "asynchronous", "python-requests", "http-request" ]
I tried the sample provided within the documentation of the requests library for python: <http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests> with `async.map(rs)` I get the response codes but I want to get the content of each page requested. ``` out = async.map(rs) print out[0].content ``...
I tested both **requests-futures** and **grequests**. Grequests is faser but brings monkey patching and additional problems with dependencies. requests-futures is severl times slower than grequests. I decided to write my own and simply wraped requests into ThreadPollExecutor and it was almost as fast as grequests, but ...
Python: simple list merging based on intersections
9,110,837
27
2012-02-02T10:36:29Z
9,112,588
16
2012-02-02T12:49:03Z
[ "python", "merge", "tree", "set-intersection", "equivalence-classes" ]
Consider there are some lists of integers as: ``` #-------------------------------------- 0 [0,1,3] 1 [1,0,3,4,5,10,...] 2 [2,8] 3 [3,1,0,...] ... n [] #-------------------------------------- ``` The question is to merge lists having at least one common element. So the results only for the given part will be as follo...
My attempt: ``` def merge(lsts): sets = [set(lst) for lst in lsts if lst] merged = 1 while merged: merged = 0 results = [] while sets: common, rest = sets[0], sets[1:] sets = [] for x in rest: if x.isdisjoint(common): sets.append(x) else: merged =...
Python: simple list merging based on intersections
9,110,837
27
2012-02-02T10:36:29Z
9,115,516
7
2012-02-02T16:01:03Z
[ "python", "merge", "tree", "set-intersection", "equivalence-classes" ]
Consider there are some lists of integers as: ``` #-------------------------------------- 0 [0,1,3] 1 [1,0,3,4,5,10,...] 2 [2,8] 3 [3,1,0,...] ... n [] #-------------------------------------- ``` The question is to merge lists having at least one common element. So the results only for the given part will be as follo...
## Using Matrix Manipulations Let me preface this answer with the following comment: **THIS IS THE WRONG WAY TO DO THIS. IT IS PRONE TO NUMERICAL INSTABILITY AND IS MUCH SLOWER THAN THE OTHER METHODS PRESENTED, USE AT YOUR OWN RISK.** That being said, I couldn't resist solving the problem from a dynamical point of v...
Python: simple list merging based on intersections
9,110,837
27
2012-02-02T10:36:29Z
9,454,893
12
2012-02-26T16:38:06Z
[ "python", "merge", "tree", "set-intersection", "equivalence-classes" ]
Consider there are some lists of integers as: ``` #-------------------------------------- 0 [0,1,3] 1 [1,0,3,4,5,10,...] 2 [2,8] 3 [3,1,0,...] ... n [] #-------------------------------------- ``` The question is to merge lists having at least one common element. So the results only for the given part will be as follo...
I tried to summurize everything that's been said and done about this topic in this question and in the [duplicate one](http://stackoverflow.com/q/9353802/1132524). I tried to **test** and **time** every solution (all the code [**here**](https://github.com/rikpg/IntersectionMerge)). ## Testing This is the `TestCase` ...
python capture environment variables
9,111,235
4
2012-02-02T11:05:45Z
9,111,275
8
2012-02-02T11:08:57Z
[ "python", "linux", "bash" ]
this bash script can catch all the environment variables which are set when data is passed through STDIN eg such as: ``` echo "Hello" | ./script.sh ``` **script.sh** ``` #!/bin/bash CAPTURE_FILE=/var/log/capture_data env >> ${CAPTURE_FILE} exit 1 ``` it there any way i can do same in python?? **RESOLVED:** this ...
Sure, check out [`os.environ`](http://docs.python.org/library/os.html#os.environ). ``` matan@swarm ~ $ python Python 2.7.2+ (default, Jan 20 2012, 17:51:10) [GCC 4.6.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.environ {'LOGNAME': 'matan', 'WINDOWID': ...
Get coordinates of local maxima in 2D array above certain value
9,111,711
13
2012-02-02T11:41:05Z
9,113,227
26
2012-02-02T13:33:19Z
[ "python", "image", "numpy", "scipy" ]
``` from PIL import Image import numpy as np from scipy.ndimage.filters import maximum_filter import pylab # the picture (256 * 256 pixels) contains bright spots of which I wanna get positions # problem: data has high background around value 900 - 1000 im = Image.open('slice0000.png') data = np.array(im) # as far as...
``` import numpy as np import scipy import scipy.ndimage as ndimage import scipy.ndimage.filters as filters import matplotlib.pyplot as plt fname = '/tmp/slice0000.png' neighborhood_size = 5 threshold = 1500 data = scipy.misc.imread(fname) data_max = filters.maximum_filter(data, neighborhood_size) maxima = (data == ...
Get coordinates of local maxima in 2D array above certain value
9,111,711
13
2012-02-02T11:41:05Z
22,631,583
8
2014-03-25T10:22:49Z
[ "python", "image", "numpy", "scipy" ]
``` from PIL import Image import numpy as np from scipy.ndimage.filters import maximum_filter import pylab # the picture (256 * 256 pixels) contains bright spots of which I wanna get positions # problem: data has high background around value 900 - 1000 im = Image.open('slice0000.png') data = np.array(im) # as far as...
``` import numpy as np import scipy import scipy.ndimage as ndimage import scipy.ndimage.filters as filters import matplotlib.pyplot as plt fname = '/tmp/slice0000.png' neighborhood_size = 5 threshold = 1500 data = scipy.misc.imread(fname) data_max = filters.maximum_filter(data, neighborhood_size) maxima = (data == ...
ElementTree findall() returning empty list
9,112,121
13
2012-02-02T12:13:34Z
9,112,373
21
2012-02-02T12:33:12Z
[ "python", "xml", "elementtree", "last.fm" ]
I am trying to write a small script for interacting with the last.fm API. I have a small bit of experience working with `ElementTree`, but the way I used it previously doesn't seem to be working, it instead returns an empty list. I removed the API key as I don't know exactly how private it should be, and gave an exa...
The problem is that `findall` [only searches the immediate descendants of an element if it is given a tag name](http://effbot.org/zone/element.htm#searching-for-subelements). You need to give it an XPath expression that will find `track` anywhere in the tree beneath it. So the following should work, for example: ``` a...
How do I install in-house requirements for Python Heroku projects?
9,112,784
7
2012-02-02T13:02:41Z
9,136,665
8
2012-02-03T23:00:29Z
[ "python", "heroku", "pip" ]
We have a few in-house libraries that we've split off (for several reasons, mostly administrative or to have the possibility to easily open source them later). They live in private Github repositories, if that matters. I'd like to deploy an app to Heroku to try it out. It depends on one of those libraries. I'm suppos...
GitHub allows HTTP Basic authentication on Git repos. So, you can add a line like this: ``` -e git+https://username:password@github.com/kennethreitz/requests.git@v0.10.0#egg=requests ``` And everything will work properly :)
How do I set cookies using Python urlopen?
9,113,652
3
2012-02-02T14:03:56Z
9,115,301
7
2012-02-02T15:49:23Z
[ "python", "cookies", "redirect", "urlopen", "http-error" ]
I am trying to fetch an html site using Python urlopen. I am getting this error: > HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop The code: ``` from urllib2 import Request request = Request(url) response = urlopen(request) ``` I understand that the server ...
Here's an example from [Python documentation](http://docs.python.org/library/cookielib.html#examples), adjusted to your code: ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) request = urllib2.Request(url) response = opener.open(request) ```
Regexp finding longest common prefix of two strings
9,114,402
26
2012-02-02T14:53:16Z
9,114,752
28
2012-02-02T15:14:37Z
[ "python", "ruby", "regex", "perl", "replace" ]
Is there a regexp which would find longest common prefix of two strings? And if this is not solvable by one regexp, what would be the most elegant piece of code or oneliner using regexp (perl, ruby, python, anything). PS: I can do this easily programatically, I am asking rather for curiosity, because it seems to me th...
If there's some character that neither string contains —, say, `\0` — you could write ``` "$first\0$second" =~ m/^(.*).*\0\1/s; ``` and the longest common prefix would be saved as `$1`. --- **Edited to add:** This is obviously very inefficient. I think that if efficiency is a concern, then this simply isn't the app...
Regexp finding longest common prefix of two strings
9,114,402
26
2012-02-02T14:53:16Z
9,114,923
18
2012-02-02T15:25:35Z
[ "python", "ruby", "regex", "perl", "replace" ]
Is there a regexp which would find longest common prefix of two strings? And if this is not solvable by one regexp, what would be the most elegant piece of code or oneliner using regexp (perl, ruby, python, anything). PS: I can do this easily programatically, I am asking rather for curiosity, because it seems to me th...
Here's a Python one-liner: ``` >>> a = 'stackoverflow' >>> b = 'stackofpancakes' >>> a[:[x[0]==x[1] for x in zip(a,b)].index(0)] 0: 'stacko' >>> a = 'nothing in' >>> b = 'common' >>> a[:[x[0]==x[1] for x in zip(a,b)].index(0)] 1: '' >>> ```
Regexp finding longest common prefix of two strings
9,114,402
26
2012-02-02T14:53:16Z
9,120,604
13
2012-02-02T21:56:29Z
[ "python", "ruby", "regex", "perl", "replace" ]
Is there a regexp which would find longest common prefix of two strings? And if this is not solvable by one regexp, what would be the most elegant piece of code or oneliner using regexp (perl, ruby, python, anything). PS: I can do this easily programatically, I am asking rather for curiosity, because it seems to me th...
Here's one fairly efficient way which uses a regexp. The code is in Perl, but the principle should be adaptable to other languages: ``` my $xor = "$first" ^ "$second"; # quotes force string xor even for numbers $xor =~ /^\0*/; # match leading null characters my $common_prefix_length = $+[0]; # g...
How can I achieve a self-referencing many-to-many relationship on the SQLAlchemy ORM back referencing to the same attribute?
9,116,924
14
2012-02-02T17:27:12Z
9,119,764
13
2012-02-02T20:46:40Z
[ "python", "many-to-many", "sqlalchemy", "self-reference" ]
I'm trying to implement a self-referential many-to-many relationship using declarative on SQLAlchemy. The relationship represents friendship between two users. Online I've found (both in the documentation and Google) how to make a self-referential m2m relationship where somehow the roles are differentiated. This means...
Here's the UNION approach I hinted at on the mailing list earlier today. ``` from sqlalchemy import Integer, Table, Column, ForeignKey, \ create_engine, String, select from sqlalchemy.orm import Session, relationship from sqlalchemy.ext.declarative import declarative_base Base= declarative_base() friendship = Ta...
"Insecure HTTP requests not permitted. Use HTTPS." when trying to retrieve user with gdata 2.0.16 python library
9,118,028
5
2012-02-02T18:41:43Z
9,120,241
8
2012-02-02T21:25:32Z
[ "python", "https", "gdata" ]
I'm trying to retrieve a user with the following code found in the [gdata provisioning api documentation](http://code.google.com/googleapps/domain/provisioning_API_v2_developers_guide.html#RetrieveAccountPython). I'm attempting this for a `django 1.3` app, running `gdata-2.0.16` in `python2.7`: ``` from gdata.apps imp...
After creating the client object, execute `client.ssl = True`. This will cause the gdata api to use a secure connection.
Building OpenCV libraries from source files
9,119,253
8
2012-02-02T20:11:04Z
10,602,407
14
2012-05-15T14:01:03Z
[ "python", "opencv", "installation" ]
I have installed `Python 2.7`, but when I try to generate the `OpenCV 2.3.1` project Makefiles using `CMake 2.8`, I get the following message. I am running Windows 7 x86 and using Visual Studio 10. ``` Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE) Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTH...
Yes, this also worked for me. Check advanced, then manually set the values for the three variables. In my case: ``` PYTHON_EXECUTABLE = .../python.exe PYTHON_INCLUDE_DIR = .../include PYTHON_LIBRARY = .../python26.lib ``` Tested with PythonPortable on Windows. (so, no installation required)
how is a dictionary sorted?
9,119,330
2
2012-02-02T20:16:51Z
9,119,349
10
2012-02-02T20:18:37Z
[ "python" ]
Ladies and Gents, I have a question about dictionaries in python. While playing around I noticed something that *to me* seems strange. I define a dict like this stuff={'age':26,'name':'Freddie Mercury', 'ciy':'Vladivostok'} I then add the word 'first' to stuff like this: > stuff[1]='first' When I print it out, it...
Dictionaries are unordered data structures, so you should have no expectations
how is a dictionary sorted?
9,119,330
2
2012-02-02T20:16:51Z
9,119,356
22
2012-02-02T20:19:29Z
[ "python" ]
Ladies and Gents, I have a question about dictionaries in python. While playing around I noticed something that *to me* seems strange. I define a dict like this stuff={'age':26,'name':'Freddie Mercury', 'ciy':'Vladivostok'} I then add the word 'first' to stuff like this: > stuff[1]='first' When I print it out, it...
The order you get from a dictionary is undefined. You should not rely on it. In this case, it happens to depend on the hash values of the underlying keys, but you shouldn't assume that's always the case. If order matters to you, use should use an [OrderedDict](http://docs.python.org/library/collections.html#collection...
how is a dictionary sorted?
9,119,330
2
2012-02-02T20:16:51Z
9,119,376
7
2012-02-02T20:20:45Z
[ "python" ]
Ladies and Gents, I have a question about dictionaries in python. While playing around I noticed something that *to me* seems strange. I define a dict like this stuff={'age':26,'name':'Freddie Mercury', 'ciy':'Vladivostok'} I then add the word 'first' to stuff like this: > stuff[1]='first' When I print it out, it...
Learn what a hashtable is: <http://en.wikipedia.org/wiki/Hash_table> In short, dict has an internal array, and inserts values at slots chosen through a hash function. The nature of this function is that it spreads the entries around evenly.
matplotlib: limits when using plot and imshow in same axes
9,120,749
19
2012-02-02T22:09:05Z
9,120,929
25
2012-02-02T22:24:40Z
[ "python", "plot", "scipy", "matplotlib" ]
I've been trying to plot an ellipse into an imshow plot. It works, but plotting the ellipse after plotting the image seems to increase xlim and ylim, resulting in a border, which I'd like to get rid of: ![](http://i.stack.imgur.com/BBHCh.png) Note that there is NO white border directly after calling imshow only. My ...
What's happening is that the axis is autoscaling to match the extents of each item you plot. Images are autoscaled much tighter than lines, etc (`imshow` basically calls `ax.axis('image')`). Getting the axis limits before and setting them after should have worked. (It's cleaner to just do `limits = axes.axis()` before...
Clear Clipboard?
9,123,090
2
2012-02-03T02:54:34Z
9,123,961
8
2012-02-03T05:06:41Z
[ "python", "clipboard" ]
Is it possible for python to clear the clipboard? If so ... how can I do it? I need this so in my quiz program, students can't copy paste answers from the internet and other files. **EDIT:** Im using WinXP and Python 2.6
``` from ctypes import windll if windll.user32.OpenClipboard(None): windll.user32.EmptyClipboard() windll.user32.CloseClipboard() ``` No external libraries needed.
How do you import a file in python with spaces in the name?
9,123,517
14
2012-02-03T04:04:15Z
9,123,555
21
2012-02-03T04:08:51Z
[ "python", "import", "filenames", "spaces" ]
Do I *have to* take out all the spaces in the file name to import it, or is there some way of telling `import` that there are spaces?
You should take the spaces out of the filename. Because the filename is used as the identifier for imported modules (i.e. `foo.py` will be imported as `foo`) and Python identifiers can't have spaces, this isn't supported by the `import` statement. If you *really* need to do this for some reason, you can use the `__imp...
Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another
9,123,831
11
2012-02-03T04:50:34Z
9,123,949
15
2012-02-03T05:05:00Z
[ "python", "algorithm", "list", "sorting" ]
I'm working with a `list` of `dict` objects that looks like this (the order of the objects differs): ``` [ {'name': 'Foo', 'score': 1}, {'name': 'Bar', 'score': 2}, {'name': 'Foo', 'score': 3}, {'name': 'Bar', 'score': 3}, {'name': 'Foo', 'score': 2}, {'name': 'Baz', 'score': 2}, {'name': '...
One way to do that is: ``` data = collections.defaultdict(list) for i in my_list: data[i['name']].append(i['score']) output = [{'name': i, 'score': max(j)} for i,j in data.items()] ``` so output will be: ``` [{'score': 2, 'name': 'Baz'}, {'score': 3, 'name': 'Foo'}, {'score': 3, 'name': 'Bar'}] ```
Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another
9,123,831
11
2012-02-03T04:50:34Z
9,125,423
11
2012-02-03T07:57:43Z
[ "python", "algorithm", "list", "sorting" ]
I'm working with a `list` of `dict` objects that looks like this (the order of the objects differs): ``` [ {'name': 'Foo', 'score': 1}, {'name': 'Bar', 'score': 2}, {'name': 'Foo', 'score': 3}, {'name': 'Bar', 'score': 3}, {'name': 'Foo', 'score': 2}, {'name': 'Baz', 'score': 2}, {'name': '...
There's no need for defaultdicts or sets here. You can just use dirt simple dicts and lists. Summarize the best running score in a dictionary and convert the result back into a list: ``` >>> s = [ {'name': 'Foo', 'score': 1}, {'name': 'Bar', 'score': 2}, {'name': 'Foo', 'score': 3}, {'name': 'Bar', 's...
Why PEP8 states imports should usually be on separate lines?
9,125,169
11
2012-02-03T07:33:08Z
9,125,214
15
2012-02-03T07:36:47Z
[ "python", "coding-style", "pep8" ]
From [PEP 8](http://www.python.org/dev/peps/pep-0008/): ``` - Imports should usually be on separate lines, e.g.: Yes: import os import sys No: import sys, os it's okay to say this though: from subprocess import Popen, PIPE ``` I thought comma separated style is simpler, shorter, easier to ...
One reason might be that it's easier for source control systems to identify differences on a per-line basis than it is to do that within source lines. Like a lot of PEP 8, it's a matter of preference. Consistency is more important than which option you end up choosing.
difference normal quote and backquote in python
9,126,399
5
2012-02-03T09:30:22Z
9,126,447
14
2012-02-03T09:33:47Z
[ "python" ]
If i write ``` a=eval('[[0]*2]*2') a[0][0]=1 ``` `a` would become `[[1,0],[1,0]]` If I write ``` a=eval(`[[0]*2]*2`) a[0][0]=1 ``` `a` would become `[[1,0],[0,0]]` Can anyone tell me why?
``` >>> '[[0]*2]*2' '[[0]*2]*2' >>> `[[0]*2]*2` '[[0, 0], [0, 0]]' ``` The first one is text, the second evaluates immediately into data structure and returns its text representation `'[[0, 0], [0, 0]]'`. The problem with `[[0]*2]*2` is that this evaluates to a list of references to the same object. That's why you g...
How to create Major and Minor gridlines with different Linestyles in Python
9,127,434
56
2012-02-03T10:51:30Z
9,128,244
18
2012-02-03T11:52:50Z
[ "python", "matplotlib" ]
I am currently using `matplotlib.pyplot` to create graphs and would like to have the major gridlines solid and black and the minor ones either greyed or dashed. in the grid properies which=both/major/mine and then color and linestyle are defined simply by linestyle, is there any way to specify minor linestyle only? Th...
A simple DIY way would be to make the grid yourself: ``` import matplotlib.pyplot as plt fig=plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3],[2,3,4],'ro') for xmaj in ax.xaxis.get_majorticklocs(): ax.axvline(x=xmaj,ls='-') for xmin in ax.xaxis.get_minorticklocs(): ax.axvline(x=xmin,ls='--') for ymaj in ...
How to create Major and Minor gridlines with different Linestyles in Python
9,127,434
56
2012-02-03T10:51:30Z
9,149,619
78
2012-02-05T13:27:40Z
[ "python", "matplotlib" ]
I am currently using `matplotlib.pyplot` to create graphs and would like to have the major gridlines solid and black and the minor ones either greyed or dashed. in the grid properies which=both/major/mine and then color and linestyle are defined simply by linestyle, is there any way to specify minor linestyle only? Th...
Actually, it is as simple as setting `major` and `minor` separately: ``` In [9]: plot([23, 456, 676, 89, 906, 34, 2345]) Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>] In [10]: yscale('log') In [11]: grid(b=True, which='major', color='b', linestyle='-') In [12]: grid(b=True, which='minor', color='r', linestyle='-...
django static files versioning
9,130,555
17
2012-02-03T14:52:06Z
9,131,482
10
2012-02-03T15:52:50Z
[ "python", "django", "django-staticfiles" ]
I'm working on some universal solution for problem with static files and updates in it Example: lets say there was site with /static/styles.css file - and site was used for a long time - so a lot of visitors cached this file in browser Now we doing changes in this css file, and update on server, but some users still ...
I would suggest using something like [django-compressor](https://github.com/jezdez/django_compressor). In addition to automatically handling this type of stuff for you, it will also automatically combine and minify your files for fast page load. Even if you don't end up using it in entirety, you can inspect their code...
django static files versioning
9,130,555
17
2012-02-03T14:52:06Z
14,898,868
17
2013-02-15T16:21:23Z
[ "python", "django", "django-staticfiles" ]
I'm working on some universal solution for problem with static files and updates in it Example: lets say there was site with /static/styles.css file - and site was used for a long time - so a lot of visitors cached this file in browser Now we doing changes in this css file, and update on server, but some users still ...
Django 1.4 now includes [`CachedStaticFilesStorage`](https://docs.djangoproject.com/en/1.9/ref/contrib/staticfiles/#cachedstaticfilesstorage) which does exactly what you need (well... *almost*). You use it with the `manage.py collectstatic` task. All static files are collected from your applications, as usual, but thi...
Finding out if its a leap year and setting accordingly
9,131,293
4
2012-02-03T15:40:33Z
9,131,308
7
2012-02-03T15:41:48Z
[ "python", "django", "django-forms", "leap-year" ]
I have a form that has an initial `end_date`. I am having a Value error because this year is a leap year and we are currently in February. My code has a end day of 30 but I am having trouble figuring out how to write the code that will discover if its a leap year and set the initial `end_date` to the correct last day ...
How about [calendar.isleap(year)](http://docs.python.org/library/calendar.html) ? Also, don't use try/except to handle this but an `if` conditional. Something like: ``` if calendar.isleap(year): do_stuff else: do_other_stuff ```
Problems installing Python Fabric on Windows 7
9,131,323
4
2012-02-03T15:42:20Z
12,619,699
8
2012-09-27T10:51:56Z
[ "python", "windows-7", "fabric", "easy-install" ]
I'm trying to install Python Fabric on Windows 7 using the guide from [Getting Python and Fabric Installed on Windows](http://www.jonnyreeves.co.uk/2011/08/getting-python-and-fabric-installed-on-windows/). What i did so far: * Installed [Python 2.7](http://www.python.org/download/releases/2.7.2/) to C:\Python27 * Add...
I have just managed to install fabric on win7 box, using information from various places in the net. That was really annoying, so just to save others frustration I put together the following list. 1. Install pip <http://www.pip-installer.org/en/latest/index.html> (that's easy, follow the guide on the web site, goes wi...
Feature Detection in OpenCV Python Bindings
9,131,552
5
2012-02-03T15:58:44Z
9,132,736
9
2012-02-03T17:22:14Z
[ "python", "image-processing", "opencv", "computer-vision" ]
I've combed the web looking for a way to get the OpenCV 2.3.1a feature extraction/descriptor bindings to spit out any flavor of image features/descriptors(STAR/SURF/ORB/SIFT/FAST). I am well aware that OpenCV has a method called "goodFeaturesToTrack. This doesn't help me as there are no feature descriptors (which is wh...
Kat, this works for me: ``` s = cv2.SURF() mask = uint8(ones(gray.shape)) keypoints = s.detect(gray,mask) ``` I can plot the key points and all. To get the descriptors you can try this ``` k,d = s.detect(gray,mask,False) d = d.reshape((-1,128)) print d.shape, len(k) ``` d should have the same length at the list of ...
Python Regex: having trouble with # of occurrance
9,131,893
3
2012-02-03T16:23:32Z
9,131,930
9
2012-02-03T16:25:31Z
[ "python", "regex" ]
Can someone tell me why the following does not match: ``` >>> re.search(r'(\d{2, 10})', '153') ``` and this one matches: ``` >>> re.search(r'\d{3}', '153') <_sre.SRE_Match object at 0x02110368> ```
The `re` module does not like the space after the `2,`: ``` In [2]: re.search(r'(\d{2, 10})', '153') In [4]: re.search(r'(\d{2,10})', '153') Out[4]: <_sre.SRE_Match object at 0x15c4648> ``` Once you have the space in there, the expression inside the braces is no longer recognized as the repetition operator. Instead,...
Python - How can you use a module's alias to import its submodules?
9,132,476
6
2012-02-03T17:03:59Z
9,132,498
7
2012-02-03T17:06:17Z
[ "python", "module" ]
I have a long module name and I want to avoid having to type it all over many times in my document. I can simply do `import long_ass_module_name as lamn` and call it that way. However, this module has many submodules that I wish to import and use as well. In this case I won't be able to write `import lamn.sub_module_1...
An aliased object still changes when you import submodules, ``` import my_long_module_name as mlmn import my_long_module_name.submodule mlmn.submodule.function() ``` The `import` statement always takes the full name of the module. The module is just an object, and importing a submodule will add an attribute to that ...
How to Sort 2 Element Tuple of Strings in Mixed Order Using key Parameter (Not cmp)
9,133,847
5
2012-02-03T18:45:32Z
9,133,917
11
2012-02-03T18:52:34Z
[ "python", "sorting", "python-3.x" ]
In Python, I have something like the following (although randomly shuffled): ``` l = [('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'x'), ('b', 'y'), ('b', 'z'), ] ``` If I call `sorted(l)`, I get a sorted result (like above) which is what one would expect. However, what I need is to forward ...
Sorting in Python is [stable](http://docs.python.org/howto/sorting.html#sort-stability-and-complex-sorts) as of Python 2.2. So, you can sort by the **second** value first with the **reverse** flag on: ``` >>> from operator import itemgetter >>> l.sort(key=itemgetter(1), reverse=True) >>> l [('a', 'z'), ('b', 'z'), ('...
Access Gmail Imap with OAuth 2.0 Access token
9,134,491
10
2012-02-03T19:38:15Z
13,025,642
9
2012-10-23T07:40:14Z
[ "python", "gmail", "oauth-2.0", "gmail-imap", "imaplib" ]
I am using Google's Oauth 2.0 to get the user's access\_token, but I dont know how to use it with imaplib to access inbox.
below is the code for IMAP with oauth 2.0 ``` email = 'k@example.com' access_token = 'vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg' auth_string = 'user=%s\1auth=Bearer %s\1\1' % (email, access_token) imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') imap_conn.debug = 4 imap_conn.authenticate('XOAUTH2', lambda x: auth_strin...
How to get rid of specific warning messages in python while keeping all other warnings as normal?
9,134,795
12
2012-02-03T20:05:34Z
9,134,820
7
2012-02-03T20:07:16Z
[ "python" ]
I am doing some simple math recessively in a python script and am getting the follow warning: > "Warning: divide by zero encountered in divide". To provide some context, I am taking two values and trying to find the percent difference in value `(a - b) / a` and if its above a certain range then process it, but someti...
It's easier to fix warnings than to silently suppress them: ``` if a == 0 or b == 0: return False # Your actual code ``` Or if you want to get fancy with Python's syntax: ``` if not all([a, b]): return False # Your actual code ``` --- It's not complicated to do, but I still wouldn't do it. From the [API](htt...
How to get rid of specific warning messages in python while keeping all other warnings as normal?
9,134,795
12
2012-02-03T20:05:34Z
9,134,842
17
2012-02-03T20:09:24Z
[ "python" ]
I am doing some simple math recessively in a python script and am getting the follow warning: > "Warning: divide by zero encountered in divide". To provide some context, I am taking two values and trying to find the percent difference in value `(a - b) / a` and if its above a certain range then process it, but someti...
If Scipy is using the `warnings` module, then you can suppress specific warnings. Try this at the beginning of your program: ``` import warnings warnings.filterwarnings("ignore", message="divide by zero encountered in divide") ``` If you want this to apply to only one section of code, then use the warnings context ma...
Regex in python: is it possible to get the match, replacement, and final string?
9,134,964
21
2012-02-03T20:19:19Z
9,135,062
8
2012-02-03T20:27:25Z
[ "python", "regex" ]
For doing a regex substitution, there are three things that you give it: * The match pattern * The replacement pattern * The original string There are three things that the regex engine finds that are of interest to me: * The matched *string* * The replacement *string* * The final processed string When using `re.su...
I looked at the documentation and it seems like you can pass a function reference into the `re.sub`: ``` import re def re_sub_verbose(pattern, replace, string): def substitute(match): print 'Matched:', match.group(0) print 'Replacing with:', match.expand(replace) return match.expand(replace) result ...
Regex in python: is it possible to get the match, replacement, and final string?
9,134,964
21
2012-02-03T20:19:19Z
9,135,166
19
2012-02-03T20:37:56Z
[ "python", "regex" ]
For doing a regex substitution, there are three things that you give it: * The match pattern * The replacement pattern * The original string There are three things that the regex engine finds that are of interest to me: * The matched *string* * The replacement *string* * The final processed string When using `re.su...
``` class Replacement(object): def __init__(self, replacement): self.replacement = replacement self.matched = None self.replaced = None def __call__(self, match): self.matched = match.group(0) self.replaced = match.expand(self.replacement) return self.replaced ...
How can I create a yaml file from pure python?
9,135,275
8
2012-02-03T20:48:41Z
9,135,643
7
2012-02-03T21:20:18Z
[ "python", "yaml", "pyyaml" ]
Example from [Using YAML with Python](http://mikkel.elmholdt.dk/?p=4) Original YAML file contains this ``` # tree format treeroot: branch1: name: Node 1 branch1-1: name: Node 1-1 branch2: name: Node 2 branch2-1: name: Node 2-1 ``` After loading the cont...
OKay. I just double checked the documentation. We need this at the end of the `yaml.dump(data, optional_args)` The fix is this ``` yaml.dump(dataMap, f, default_flow_style=False) ``` where dataMap is the source `yaml.load()` and f is the file to be written to.
How to use pprint to print an object using the built-in __str__(self) method?
9,135,485
8
2012-02-03T21:06:48Z
9,135,558
10
2012-02-03T21:12:38Z
[ "python", "string", "pprint" ]
I have a Python script which processes a .txt file which contains report usage information. I'd like to find a way to cleanly print the attributes of an object using pprint's pprint(vars(object)) function. The script reads the file and creates instances of a Report class. Here's the class. ``` class Report(object): ...
`pprint.pprint` doesn't return a string; it actually does the printing (by default to stdout, but you can specify an output stream). So when you write `print record`, `record.__str__()` gets called, which calls `pprint`, which returns `None`. `str(None)` is `'None'`, and that gets `print`ed, which is why you see `None`...
While-loop not exiting in python
9,135,730
3
2012-02-03T21:27:15Z
9,135,778
14
2012-02-03T21:32:10Z
[ "python", "while-loop", "infinite-loop" ]
I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so. Right now, I'm working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the f...
I believe you want this. ``` count = int(raw_input("Enter number of cycles: ")) ``` Without converting the input to integer, you end up with a string in the `count` variable, i.e. if you enter `1` when the program asks for input, what goes into count is `'1'`. A comparison between string and integer turns out to be ...
Want datetime in logfile name
9,135,936
9
2012-02-03T21:44:16Z
9,135,989
11
2012-02-03T21:48:51Z
[ "python" ]
When I create my logfile, I want the name to contain the datetime. Now, in python you can get the current datetime as: ``` >>> from datetime import datetime >>> datetime.now() datetime.datetime(2012, 2, 3, 21, 35, 9, 559000) ``` The str version is ``` >>> str(datetime.now()) '2012-02-03 21:35:22.247000' ``` Not a ...
You need [**`datetime.strftime()`**](http://docs.python.org/library/datetime.html#datetime.datetime.strftime), this allows you to format the timestamp using all of the directives of [C's `strftime()`](http://www.manpagez.com/man/3/strftime/). In your specific case: ``` >>> datetime.now().strftime('mylogfile_%H_%M_%d_%...
Want datetime in logfile name
9,135,936
9
2012-02-03T21:44:16Z
9,136,010
14
2012-02-03T21:51:24Z
[ "python" ]
When I create my logfile, I want the name to contain the datetime. Now, in python you can get the current datetime as: ``` >>> from datetime import datetime >>> datetime.now() datetime.datetime(2012, 2, 3, 21, 35, 9, 559000) ``` The str version is ``` >>> str(datetime.now()) '2012-02-03 21:35:22.247000' ``` Not a ...
You could also use a [**`TimedRotatingFileHandler`**](http://docs.python.org/py3k/library/logging.handlers.html#timedrotatingfilehandler) that will handle the date and the rollover every day (or whenever you want) for you. ``` from logging.handlers import TimedRotatingFileHandler fh = TimedRotatingFileHandler('mylogfi...
How do weighted edges affect PageRank in networkx?
9,136,539
13
2012-02-03T22:45:57Z
9,145,155
20
2012-02-04T22:26:58Z
[ "python", "graph-theory", "pagerank", "networkx" ]
I'm playing around with networkx (graph library in python) and I found documentation saying the PageRank algorithm takes edge weights into account when scoring, but I was wondering if larger edge weights were better or lower weights better?
Shortly, large weights are better for incoming nodes. PageRank works on a directed weighted graph. If page A has a link to page B, then the score for B goes up, i.e. the more input the page B (node) have, the higher is its score. [Wikipedia article on PageRank](http://en.wikipedia.org/wiki/Pagerank) for further detai...