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
repeating multiple characters regex
3,630,982
10
2010-09-02T20:30:23Z
3,630,992
21
2010-09-02T20:32:11Z
[ "python", "regex" ]
Is there a way using a regex to match a repeating set of characters? For example: `ABCABCABCABCABC` `ABC{5}` I know that's wrong. But is there anything to match that effect? Update: Can you use nested capture groups? So Something like `(?<cap>(ABC){5})` ?
Enclose the regex you want to repeat in parentheses. For instance, if you want 5 repetitions of `ABC`: ``` (ABC){5} ``` Or if you want any number of repetitions (0 or more): ``` (ABC)* ``` Or one or more repetitions: ``` (ABC)+ ``` **edit** to respond to update Parentheses in regular expressions do two things; t...
Why can't I change the system default python the way Apple says I can?
3,631,108
8
2010-09-02T20:44:29Z
3,631,511
12
2010-09-02T21:40:12Z
[ "python", "osx", "wxpython" ]
On this help page <http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html> Apple says: > CHANGING THE DEFAULT PYTHON > > Using > > ``` > % defaults write com.apple.versioner.python Version 2.5 > ``` > > will make version 2.5 the user default when running the both the...
`defaults write com.apple.versioner.python` and `VERSIONER_PYTHON_PREFER_32_BIT` are Apple-developed changes and apply *only* to the Apple-supplied `/usr/bin/python` in OS X 10.6 (Python 2.6.1). (UPDATE: This also applies to OS X 10.7 Lion.) You have likely installed a Python 2.7 using one of the python.org installers....
Django uploading file not in MEDIA_ROOT path is giving me SuspiciousOperation error
3,631,941
11
2010-09-02T23:07:20Z
3,632,247
23
2010-09-03T00:26:29Z
[ "python", "django", "django-uploads" ]
I want to upload files to a path that is still in my django project, but in my `MEDIA_ROOT` path. When I try to do this I get a `SuspiciousOperation` error. Here are the paths as defined in my settings file: ``` MEDIA_ROOT = os.path.join(os.path.dirname( __file__ ), 'static_serve') UPLOAD_DIR = os.path.join(os.path....
Yes [there is a way](http://docs.djangoproject.com/en/dev/topics/files/#the-built-in-filesystem-storage-class): From docs: > For example, the following code will > store uploaded files under > /media/photos regardless of what your > MEDIA\_ROOT setting is: ``` from django.db import models from django.core.files.stor...
Python: Strange behaviour of recursive function with keyword arguments
3,632,041
9
2010-09-02T23:32:26Z
3,632,068
14
2010-09-02T23:37:57Z
[ "python", "recursion", "arguments", "keyword" ]
I've written a small snippet that computes the path length of a given node (e.g. its distance to the root node): ``` def node_depth(node, depth=0, colored_nodes=set()): """ Return the length of the path in the parse tree from C{node}'s position up to the root node. Effectively tests if C{node} is inside a ...
The "default value" for a function parameter in Python is instantiated at function declaration time, not every time the function is called. You rarely want to mutate the default value of a parameter, and so it's often a good idea to use something immutable for the default value. In your case you may want to do somethi...
UDP client and server with Twisted Python
3,632,210
5
2010-09-03T00:15:26Z
3,632,240
10
2010-09-03T00:23:22Z
[ "python", "udp", "twisted" ]
I want to create a server and client that sends and receives UDP packets from the network using Twisted. I've already written this with sockets in Python, but want to take advantage of Twisted's callback and threading features. However, I need help though with the design of Twisted. I have multiple types of packets I ...
Just like the server example above, there is a client example to. This should help you get started: * <http://www.opendocs.net/python/twisted/howto/udp.html> * <http://twistedmatrix.com/documents/current/core/examples/echoclient_udp.py> Ok, here is a simple heart beat sender and receiver using datagram protocol. ```...
Removing SOCKS 4/5 proxy
3,632,821
3
2010-09-03T03:13:03Z
3,647,286
8
2010-09-05T18:45:03Z
[ "python", "sockets", "proxy" ]
This question is sort of the opposite of this: <http://stackoverflow.com/questions/2317849/how-can-i-use-a-socks-4-5-proxy-with-urllib2> Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the **same** process? i.e start process use proxy .. remove pr...
Abra kadabra ``` import socks,socket,urllib2 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 8080) temp = socket.socket socket.socket = socks.socksocket print urllib2.urlopen('http://www.google.com').read() // Proxy socket.socket=temp print urllib2.urlopen('http://www.google.com').read() // No proxy ```
Storing user data in a Python script
3,632,876
3
2010-09-03T03:30:19Z
3,632,889
8
2010-09-03T03:34:19Z
[ "python" ]
What is the preferred/ usual way of storing data that is entered by the user when running a Python script, if I need the data again the next time the script runs? For example, my script performs calculations based on what the user enters and then when the user runs the script again, it fetches the result from the last...
you could use a slite database or a CSV file. They are both very easy to work with but lend themselves to rows with the same type of information. The best option might be [shelve](http://docs.python.org/library/shelve.html) module ``` import shelve shelf = shelve.open(filename) shelf['key1'] = value1 shelf['key2'] =...
Nested For Loops Using List Comprehension
3,633,140
32
2010-09-03T04:57:45Z
3,633,145
48
2010-09-03T04:58:52Z
[ "python", "for-loop", "list-comprehension" ]
If I had two strings, `'abc'` and `'def'`, I could get all combinations of them using two for loops: ``` for j in s1: for k in s2: print(j, k) ``` However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?
``` lst = [j + k for j in s1 for k in s2] ``` or ``` lst = [(j, k) for j in s1 for k in s2] ``` if you want tuples. Like in the question, `for j...` is the outer loop, `for k...` is the inner loop. Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticki...
Nested For Loops Using List Comprehension
3,633,140
32
2010-09-03T04:57:45Z
3,633,907
19
2010-09-03T07:53:08Z
[ "python", "for-loop", "list-comprehension" ]
If I had two strings, `'abc'` and `'def'`, I could get all combinations of them using two for loops: ``` for j in s1: for k in s2: print(j, k) ``` However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?
Since this is essentially a Cartesian product, you can also use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product). I think it's clearer, especially when you have more input iterables. ``` itertools.product('abc', 'def', 'ghi') ```
how to using MySQLdb SELECT with for or while loop
3,633,550
2
2010-09-03T06:44:34Z
3,633,649
7
2010-09-03T07:02:24Z
[ "python", "mysql", "mysql-python" ]
``` import _mysql as mysql db=mysql.connect('localhost','username','password','database') db.query("""select * from news""") result = db.store_result() print result.num_rows()#two records #how to loop? without cursor print result.fetch_row() ```
You can try this: ``` while True: record = result.fetch_row() if not record: break print record ``` I second [@Ignacio](http://stackoverflow.com/users/20862/ignacio-vazquez-abrams)'s [note of caution](http://stackoverflow.com/questions/3633550/how-to-using-mysqldb-select-with-for-or-while-loop/3633624#363...
paramiko's sshclient with sftp
3,635,131
19
2010-09-03T11:05:49Z
3,635,163
69
2010-09-03T11:10:27Z
[ "python", "sftp", "paramiko" ]
How I can make SFTP transport throught SSHClient on the remote server? I have a local host and two remote hosts. Remote hosts are backup server and web server. I need to find on backup server necessary backup file and put it on web server over sftp. How can I make paramiko's SFTP transport work with paramiko's SSHClien...
`paramiko.SFTPClient` Example: ``` import paramiko paramiko.util.log_to_file('/tmp/paramiko.log') # Open a transport host = "example.com" port = 22 transport = paramiko.Transport((host, port)) # Auth password = "foo" username = "bar" transport.connect(username = username, password = password) # Go! sftp = param...
Are there conventions for Python module comments?
3,635,988
14
2010-09-03T13:02:59Z
3,636,024
8
2010-09-03T13:07:25Z
[ "python", "module", "comments", "conventions" ]
It is my understanding that a module docstring should just provide a general description of what a module does and details such as author and version should only be contained in the module's comments. However, I have seen the following in comments **and** docstrings: ``` __author__ = "..." __version__ = "..." __date_...
They are merely conventions, albeit quite widely-used conventions. See [this description](http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting) of a set of Python metadata requirements. `__version__` is mentioned in the [Python Style Guide](http://www.python.org/dev/peps/pep-0008/). Regarding docstrings...
Read flat list into multidimensional array/matrix in python
3,636,344
4
2010-09-03T13:45:34Z
3,636,378
8
2010-09-03T13:48:57Z
[ "python", "multidimensional-array", "numpy" ]
I have a list of numbers that represent the flattened output of a matrix or array produced by another program, I know the dimensions of the original array and want to read the numbers back into either a list of lists or a NumPy matrix. There could be more than 2 dimensions in the original array. e.g. ``` data = [0, 2...
Use [`numpy.reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html): ``` >>> import numpy as np >>> data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] ) >>> shape = ( 2, 4 ) >>> data.reshape( shape ) array([[0, 2, 7, 6], [3, 1, 4, 5]]) ``` You can also assign directly to the `shape` attribute ...
How to debug "glibc detected *** python: malloc(): memory corruption"
3,636,393
4
2010-09-03T13:50:49Z
3,636,459
7
2010-09-03T13:57:52Z
[ "python", "c", "glibc" ]
I'm using python2.5 with scipy.weave to embed c code. In my c code, there is no malloc() function, but I received error like ``` "glibc detected *** python: malloc(): memory corruption" ``` from time to time.(It's a random algorithm) So how shall I debug it out? Thanks
I'd hazard a guess that your code is overflowing an array somewhere (or causing Python to do so). You're going to find debugging this to be hard if you can't reliably reproduce it, so you might want to explicitly seed your random number generator and try to find a seed with which you can reproduce the corruption. You ...
Executing modules as scripts
3,636,798
5
2010-09-03T14:37:59Z
3,636,884
12
2010-09-03T14:48:15Z
[ "python", "windows" ]
I am learn python now, and today, i met a problem in <http://docs.python.org/release/2.5.4/tut/node8.html> > **6.1.1 Executing modules as scripts** > > When you run a Python module with > > `python fibo.py <arguments>` > > the code in the module will be executed, just as if you imported it, but with the > \_\_name\_\_...
What exactly did you do in the shell? What is the code you are running? It sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more. **edit:** I have figured out what is going wrong. You are trying...
Test if a python string is printable
3,636,928
16
2010-09-03T14:54:22Z
3,637,294
27
2010-09-03T15:34:05Z
[ "python", "string" ]
I have some code that pulls data from a com-port and I want to make sure that what I got really is a printable string (i.e. ASCII, maybe UTF-8) before printing it. Is there a function for doing this? The first half dozon places I looked didn't have anything that looks like what I want. ([string has printable](http://do...
As you've said the [`string` module has `printable`](http://docs.python.org/library/string.html#string.printable) so it's just a case of checking if all the characters in your string are in `printable`: ``` >>> hello = 'Hello World!' >>> bell = chr(7) >>> import string >>> all(c in string.printable for c in hello) Tru...
python argparse: How can I display help automatically on error?
3,636,967
11
2010-09-03T14:58:40Z
3,637,103
8
2010-09-03T15:13:37Z
[ "python", "argparse" ]
Currently when I enter invalid options or omit positional arguments, argparse kicks me back to the prompt and displays the usage for my app. This is ok, but I would rather automatically display the full help listing (that explains the options, etc) than require the user to type ``` ./myscript.py -h ``` Thanks! Jamie
This [thread](http://groups.google.com/group/argparse-users/browse_thread/thread/2dacd5fed110bd0c?pli=1) over at Google groups has the following code snippet which seems to do the trick (modified slightly). ``` class DefaultHelpParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('er...
python argparse: How can I display help automatically on error?
3,636,967
11
2010-09-03T14:58:40Z
14,912,282
16
2013-02-16T16:07:50Z
[ "python", "argparse" ]
Currently when I enter invalid options or omit positional arguments, argparse kicks me back to the prompt and displays the usage for my app. This is ok, but I would rather automatically display the full help listing (that explains the options, etc) than require the user to type ``` ./myscript.py -h ``` Thanks! Jamie
To print help you might want to use: `print_help` function on `ArgumentParser` instance ``` parser = argparse.ArgumentParser() (...) parser.print_help() ``` To print help message on error you need to create own subclass of `ArgumentParser` instance, that overrides `error()` method. For example like that: ``` class M...
How to write stereo wav files in Python?
3,637,350
7
2010-09-03T15:41:51Z
3,637,392
9
2010-09-03T15:47:17Z
[ "python", "wav", "wave" ]
The following code writes a simple sine at frequency 400Hz to a mono WAV file. How should this code be changed in order to produce a **stereo** WAV file. The second channel should be in a different frequency. ``` import math import wave import struct freq = 440.0 data_size = 40000 fname = "WaveTest.wav" frate = 11025...
Build a parallel `sine_list_y` list with the other frequency / channel, set `nchannels=2`, and in the output loop use `for s, t in zip(sine_list_x, sine_list_y):` as the header clause, and a body with two `writeframes` calls -- one for `s`, one for `t`. IOW, corresponding frames for the two channels "alternate" in the ...
Multiple Database Config in Django 1.2
3,637,419
20
2010-09-03T15:50:17Z
3,638,091
25
2010-09-03T17:27:40Z
[ "python", "django", "django-models" ]
This is hopefully an easy question. I'm having some trouble understanding the documentation for the new multiple database feature in Django 1.2. Primarily, I cant seem to find an example of how you actually USE the second database in one of your models. When I define a new class in my models.py how do I specify which...
Yeah, it is a little bit complicated. There are a number of ways you could implement it. Basically, you need some way of indicating which models are associated with which database. # First option Here's the code that I use; hope it helps. ``` from django.db import connections class DBRouter(object): """A route...
Multiple Database Config in Django 1.2
3,637,419
20
2010-09-03T15:50:17Z
5,001,553
8
2011-02-15T09:00:33Z
[ "python", "django", "django-models" ]
This is hopefully an easy question. I'm having some trouble understanding the documentation for the new multiple database feature in Django 1.2. Primarily, I cant seem to find an example of how you actually USE the second database in one of your models. When I define a new class in my models.py how do I specify which...
An addendum to Jordans answer above. For the second option, the allow\_syncdb method works correctly as follows: ``` def allow_syncdb(self, db, model): if hasattr(model,'connection_name'): return model.connection_name == db return db == 'default' ```
Python equivalent of PHPs __call() magic method?
3,638,235
7
2010-09-03T17:46:00Z
3,638,349
12
2010-09-03T18:01:39Z
[ "php", "python", "magic-methods" ]
In PHP, I can do something like this: ``` class MyClass { function __call($name, $args) { print('you tried to call a the method named: ' . $name); } } $Obj = new MyClass(); $Obj->nonexistant_method(); // prints "you tried to call a method named: nonexistant_method" ``` This would be handy to be able to do...
Define a [\_\_getattr\_\_](http://docs.python.org/reference/datamodel.html?highlight=getattr#object.__getattr__) method on your object, and return a function (or a closure) from it. ``` In [1]: class A: ...: def __getattr__(self, name): ...: def function(): ...: print("You tried to cal...
What is the difference between LIST.append(1) and LIST = LIST + [1] (Python)
3,638,486
7
2010-09-03T18:19:39Z
3,638,523
15
2010-09-03T18:25:00Z
[ "python", "list", "append" ]
When I execute (I'm using the interactive shell) these statements I get this: ``` L=[1,2,3] K=L L.append(4) L [1,2,3,4] K [1,2,3,4] ``` But when I do exactly the same thing replacing L.append(4) with L=L+[4] I get: ``` L [1,2,3,4] K [1,2,3] ``` Is this some sort of reference thing? Why does this happen? Another ...
``` L.append(4) ``` This adds an element on to the end of the existing list `L`. ``` L += [4] ``` The `+=` operator invokes the magic `__iadd__()` method. It turns out `list` overrides the `__iadd__()` method and makes it equivalent to `extend()` which, like `append()`, adds elements directly onto an existing list. ...
find time difference in seconds as an integer with python
3,638,532
15
2010-09-03T18:26:00Z
3,638,597
18
2010-09-03T18:34:02Z
[ "python" ]
I need to find the time difference in seconds with python. I know I can get the difference like this: ``` from datetime import datetime now = datetime.now() .... .... .... later = datetime.now() difference = later-now ``` how do I get difference in total seconds?
``` import time now = time.time() ... later = time.time() difference = int(later - now) ```
Is Tornado really non-blocking?
3,638,844
18
2010-09-03T19:16:00Z
3,638,905
15
2010-09-03T19:24:00Z
[ "python", "mysql", "tornado", "nonblocking" ]
Tornado advertises itself as "a relatively simple, **non-blocking** web server framework" and was designed to solve the C10k problem. However, looking at their database wrapper, which wraps MySQLdb, I came across the following piece of code: ``` def _execute(self, cursor, query, parameters): try: return cu...
Yes, absent other measures, the server will wait for the query to finish executing. That does not mean Tornado is not a non-blocking web server. A "non-blocking web server" doesn't block on network I/O (and may have some provision for disk I/O if it does static file serving). That does not mean you get instant, causal...
Is Tornado really non-blocking?
3,638,844
18
2010-09-03T19:16:00Z
4,791,279
33
2011-01-25T08:27:55Z
[ "python", "mysql", "tornado", "nonblocking" ]
Tornado advertises itself as "a relatively simple, **non-blocking** web server framework" and was designed to solve the C10k problem. However, looking at their database wrapper, which wraps MySQLdb, I came across the following piece of code: ``` def _execute(self, cursor, query, parameters): try: return cu...
Tornado is non-blocking if you write non-blocking code on the top if it, eg. using [asyncmongo](https://github.com/bitly/asyncmongo) and [@tornado.web.asynchronous](http://tornado.readthedocs.org/en/latest/web.html?highlight=tornado.web.asynchronous#tornado.web.asynchronous) decorator. Tornado as a framework provides t...
Writing a parser for regular expressions
3,639,574
51
2010-09-03T21:07:04Z
3,639,610
34
2010-09-03T21:13:00Z
[ "python", "regex", "parsing" ]
Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find myself using increasingly often. So, to teac...
Writing an implementation of a regular expression engine is indeed a quite complex task. But if you are interested in how to do it, even if you can't understand enough of the details to actually implement it, I would recommend that you at least look at this article: [**Regular Expression Matching Can Be Simple And Fa...
Writing a parser for regular expressions
3,639,574
51
2010-09-03T21:07:04Z
3,639,983
17
2010-09-03T22:26:17Z
[ "python", "regex", "parsing" ]
Even after years of programming, I'm ashamed to say that I've never really fully grasped regular expressions. In general, when a problem calls for a regex, I can usually (after a bunch of referring to syntax) come up with an appropriate one, but it's a technique that I find myself using increasingly often. So, to teac...
I've already given a +1 to Mark Byers - but as far as I remember the paper doesn't really say that much about how regular expression matching works beyond explaining why one algorithm is bad and another much better. Maybe something in the links? I'll focus on the good approach - creating finite automata. If you limit ...
Python, ctypes and mmap
3,640,092
8
2010-09-03T22:51:41Z
3,640,617
9
2010-09-04T02:11:02Z
[ "python", "ctypes" ]
I am wondering if it is possible for the ctypes package to interface with mmap. Currently, my module allocates a buffer (with `create_string_buffer`) and then passes that using `byref` to my libraries `mylib.read` function. This, as the name suggests, reads data into the buffer. I then call `file.write(buf.raw)` to wr...
An `mmap` object "supports the writable buffer interface", therefore you can use the [from\_buffer](http://docs.python.org/library/ctypes.html#ctypes._CData.from_buffer) class method, which all `ctypes` classes have, with the `mmap` instance as the argument, to create a `ctypes` object just like you want, i.e., sharing...
Regular Expressions: Search in list
3,640,359
16
2010-09-04T00:13:18Z
3,640,376
32
2010-09-04T00:17:33Z
[ "python", "regex" ]
I want to filter strings in a list based on a regular expression. Is there something better than `[x for x in list if r.match(x)]` ?
``` filter(r.match, list) ```
Does Lua support Decorators?
3,640,536
7
2010-09-04T01:21:44Z
3,640,593
7
2010-09-04T01:56:27Z
[ "python", "programming-languages", "syntax", "lua", "decorator" ]
I come from a Python background and really like the power of Python Decorators. Does Lua support Decorators? I've read the following link but it's unclear to me: <http://lua-users.org/wiki/DecoratorsAndDocstrings> **UPDATE** Would you also mind given an example how how to implement it in Lua if it's possible.
The "decorators" documented at the page you quote (and used for example in [this one](http://lua-users.org/wiki/LuaTypeChecking) to add type-checking) have little to do with Python's oddly-named "decorator syntax" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in ...
Computing greatest common denominator in python
3,640,955
3
2010-09-04T04:48:36Z
3,640,965
19
2010-09-04T04:53:43Z
[ "python", "division", "integer" ]
If you have a list of integers in python, say `L = [4,8,12,24]`, how can you compute their greatest common denominator/divisor (4 in this case)?
One way to do it is: ``` import fractions def gcd(L): return reduce(fractions.gcd, L) print gcd([4,8,12,24]) ```
CherryPy How to respond with JSON?
3,641,007
12
2010-09-04T05:14:27Z
3,641,019
14
2010-09-04T05:20:06Z
[ "jquery", "python", "json", "cherrypy" ]
In my controller/request-handler, I have the following code: ``` def monkey(self, **kwargs): cherrypy.response.headers['Content-Type'] = "application/json" message = {"message" : "Hello World!" } return message monkey.exposed = True ``` And, in my view, I've got this javascript: ``` $(function() { var body =...
Not sure what you mean by "without using tools" -- Python **is** "a tool", right? With just Python and its standard library (2.6 or better), add at the top of your module ``` import json ``` and change the `return` statement to ``` return json.dumps(message) ```
CherryPy How to respond with JSON?
3,641,007
12
2010-09-04T05:14:27Z
3,643,199
29
2010-09-04T16:58:54Z
[ "jquery", "python", "json", "cherrypy" ]
In my controller/request-handler, I have the following code: ``` def monkey(self, **kwargs): cherrypy.response.headers['Content-Type'] = "application/json" message = {"message" : "Hello World!" } return message monkey.exposed = True ``` And, in my view, I've got this javascript: ``` $(function() { var body =...
Note that in CherryPy 3.2 (almost done!) there will be a pair of JSON tools to make the above even easier: ``` @cherrypy.expose @tools.json_out() def monkey(self, **kwargs): return {"message": "Hello World!"} ``` `json_out` encodes the output and sets the header for you.
How to efficiently filter a string against a long list of words in Python/Django?
3,641,152
9
2010-09-04T06:25:16Z
3,641,471
10
2010-09-04T08:31:29Z
[ "python", "django", "string", "nlp" ]
Stackoverflow implemented its "Related Questions" feature by taking the title of the current question being asked and removing from it the 10,000 most common English words according to Google. The remaining words are then submitted as a fulltext search to find related questions. I want to do something similar in my Dj...
You could do this very simply using the set and string functionality in Python and see how it performs (premature optimisation being the root of all evil!): ``` common_words = frozenset(("if", "but", "and", "the", "when", "use", "to", "for")) title = "When to use Python for web applications" title_words = set(title.lo...
Postfix hangs when sending email
3,641,936
2
2010-09-04T10:54:59Z
3,641,991
11
2010-09-04T11:09:51Z
[ "python", "django", "smtp", "postfix-mta", "ubuntu-10.04" ]
If I try to send an email as follows, the process hangs and nothing happens: ``` >>> from django.core.management import setup_environ >>> from cube import settings >>> setup_environ(settings) 'cube' >>> from django.core.mail import send_mail >>> send_mail('Subject', 'Message', 'sender@domain.com', ['recepient@domain.c...
Your mail server isn't working fine. When you connect to it using `telnet`, you should see a welcome message along the lines of: ``` 220 your.server.name ESMTP Postfix ``` (You can check the greeting that you should be seeing by running `postconf smtpd_banner`.) You don't get that, so the mail server isn't running p...
Using python "with" statement with try-except block
3,642,080
64
2010-09-04T11:35:29Z
3,644,618
97
2010-09-05T01:20:19Z
[ "python", "finally", "with-statement", "try-catch", "except" ]
Is this the right way to use the python "with" statement in combination with a try-except block?: ``` try: with open("file", "r") as f: line = f.readline() except IOError: <whatever> ``` If it is, then considering the old way of doing things: ``` try: f = open("file", "r") line = f.readline()...
1. The two code blocks you gave are **not** equivalent 2. The code you described as *old way of doing things* has a serious bug: in case opening the file fails you will get a second exception in the `finally` clause because `f` is not bound. The equivalent old style code would be: ``` try: f = o...
Is it Pythonic to mimic method overloading?
3,642,748
8
2010-09-04T14:51:52Z
3,642,757
13
2010-09-04T14:55:07Z
[ "python" ]
Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types. Here is an example: ``` class EmployeeCollection(object): @staticmethod def find(value): if isinstan...
Not really, since you lose the ability to use types that are not-quite-that-but-close-enough. Create two separate methods (`find_by_name()` and `find_by_number()`) instead.
Is it Pythonic to mimic method overloading?
3,642,748
8
2010-09-04T14:51:52Z
3,642,819
13
2010-09-04T15:15:12Z
[ "python" ]
Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types. Here is an example: ``` class EmployeeCollection(object): @staticmethod def find(value): if isinstan...
Not very Pythonic, *except* perhaps, in 2.6 or better, if *all* the checks rely on the new abstract base classes, which are intended in part exactly to facilitate such use. If you ever find yourself typechecking for *concrete* classes, then you **know** you're making your code fragile and curtailing its use. So, for e...
Calculating if date is in start, future or present in Python
3,642,892
7
2010-09-04T15:37:34Z
3,642,942
12
2010-09-04T15:50:40Z
[ "python", "django", "datetime", "time" ]
I have two date/time strings: ``` start_date = 10/2/2010 8:00:00 end_date = 10/2/2010 8:59:00 ``` I need to write a function to calculate if the event is in the future, in the past or if it is happening right now - I've read a fair bit of documentation but just finding it quite hard to get this to work. I've not ...
``` from datetime import datetime start_date = "10/2/2010 8:00:00" end_date = "10/2/2010 8:59:00" # format of date/time strings; assuming dd/mm/yyyy date_format = "%d/%m/%Y %H:%M:%S" # create datetime objects from the strings start = datetime.strptime(start_date, date_format) end = datetime.strptime(end_date, date_fo...
Replace non-numeric characters
3,643,065
9
2010-09-04T16:20:47Z
3,643,071
15
2010-09-04T16:21:35Z
[ "python", "regex", "string" ]
I need to replace non-numeric chars from a string. For example, "8-4545-225-144" needs to be "84545225144"; "$334fdf890==-" must be "334890". How can I do this?
``` ''.join(c for c in S if c.isdigit()) ```
Replace non-numeric characters
3,643,065
9
2010-09-04T16:20:47Z
3,643,079
17
2010-09-04T16:22:31Z
[ "python", "regex", "string" ]
I need to replace non-numeric chars from a string. For example, "8-4545-225-144" needs to be "84545225144"; "$334fdf890==-" must be "334890". How can I do this?
It is possible with regex. ``` import re ... return re.sub(r'\D', '', theString) ```
I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors?
3,643,725
12
2010-09-04T19:37:22Z
3,643,758
10
2010-09-04T19:46:30Z
[ "python", "algorithm", "factorization" ]
I'm working on a Project Euler problem which requires factorization of an integer. I can come up with a list of all of the primes that are the factor of a given number. The Fundamental Theorem of Arithmetic implies that I can use this list to derive *every* factor of the number. My current plan is to take each number ...
Instead of a list of exponents, consider simply *repeating* each prime factor by the number of times it *is* a factor. After that, working on the resulting `primefactors` list-with-repetitions, [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations) does just what you need -- you'...
Django / Python how to get the full request header?
3,643,766
4
2010-09-04T19:48:25Z
3,643,783
7
2010-09-04T19:53:28Z
[ "python", "django", "http-headers", "httprequest" ]
I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full headers.. any info is appreciated.
All the headers are available in `request.META`. See [the documentation](http://docs.djangoproject.com/en/1.2/ref/request-response/#attributes).
Multiple values for key in dictionary in Python
3,644,409
7
2010-09-04T23:38:18Z
3,644,431
11
2010-09-04T23:44:56Z
[ "python", "dictionary" ]
What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this: ``` for key in names: posX = names[key][0] posY = names[key][1] posZ = names[key][2] ``` This doesn't seem very intuitive to me even though it works. I've also tried doing this: ``` for key, value in ...
It's not unintuitive at all. The only way to store "multiple values" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example. The only problem with your example is that it's the ...
python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"
3,644,417
10
2010-09-04T23:42:04Z
3,644,459
19
2010-09-04T23:55:55Z
[ "php", "python", "django", "datetime", "format" ]
I would like a python datetime object to output (and use the result in django) like this: ``` Thu the 2nd at 4:30 ``` But I find no way in python to output `st`, `nd`, `rd`, or `th` like I can with PHP datetime format with the `S` string (What they call "English Ordinal Suffix") (<http://uk.php.net/manual/en/function...
The [django.utils.dateformat](http://code.djangoproject.com/browser/django/trunk/django/utils/dateformat.py) has a function `format` that takes two arguments, the first one being the date (a `datetime.date` [[or `datetime.datetime`]] instance, where `datetime` is the module in Python's standard library), the second one...
python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"
3,644,417
10
2010-09-04T23:42:04Z
16,671,271
7
2013-05-21T13:27:25Z
[ "php", "python", "django", "datetime", "format" ]
I would like a python datetime object to output (and use the result in django) like this: ``` Thu the 2nd at 4:30 ``` But I find no way in python to output `st`, `nd`, `rd`, or `th` like I can with PHP datetime format with the `S` string (What they call "English Ordinal Suffix") (<http://uk.php.net/manual/en/function...
dont know about built in but I used this... ``` def ord(n): return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th")) ``` and: ``` def dtStylish(dt,f): return dt.strftime(f).replace("{th}", ord(dt.day)) ```
Python's getattr gets called twice?
3,644,545
3
2010-09-05T00:42:57Z
3,644,609
9
2010-09-05T01:16:36Z
[ "python", "reflection", "python-2.6", "getattr" ]
I am using this simple example to understand Python's **getattr** function: ``` In [25]: class Foo: ....: def __getattr__(self, name): ....: print name ....: ....: In [26]: f = Foo() In [27]: f.bar bar bar ``` Why is `bar` printed twice? Using Python 2.6.5.
I think it's due to IPython. To "fix" it, you have to disable autocall: `%autocall 0` > It's an inevitable side-effect of > %autocall: since it has to analyze the > object in the command line to see if > it's callable, python triggers getattr > calls on it. Source: <http://mail.scipy.org/pipermail/ipython-user/2008-...
Why are mutable strings slower than immutable strings?
3,644,576
4
2010-09-05T01:01:35Z
3,644,631
22
2010-09-05T01:24:52Z
[ "python" ]
Why are mutable strings slower than immutable strings? EDIT: ``` >>> import UserString ... def test(): ... s = UserString.MutableString('Python') ... for i in range(3): ... s[0] = 'a' ... ... if __name__=='__main__': ... from timeit import Timer ... t = Timer("test()", "from __main__ import t...
In a hypothetical language that offers both mutable and immutable, otherwise equivalent, string types (I can't really think of one offhand -- e.g., Python and Java both have immutable strings only, and other ways to make one through mutation which add indirectness and therefore can of course slow things down a bit;-), ...
Python MySQL module
3,644,839
6
2010-09-05T03:02:11Z
3,644,874
7
2010-09-05T03:17:34Z
[ "python", "mysql", "module" ]
I'm developing a web application that needs to interface with a MySQL database, and I can't seem to find any really good modules out there for Python. I'm specifically looking for fast module, capable of handling hundreds of thousands of connections (and queries, all within a short period of time of each other), witho...
[MySQLdb](http://sourceforge.net/projects/mysql-python/) is pretty much the only game in town for python mysql access.
Python MySQL module
3,644,839
6
2010-09-05T03:02:11Z
14,132,434
8
2013-01-03T02:55:22Z
[ "python", "mysql", "module" ]
I'm developing a web application that needs to interface with a MySQL database, and I can't seem to find any really good modules out there for Python. I'm specifically looking for fast module, capable of handling hundreds of thousands of connections (and queries, all within a short period of time of each other), witho...
I think my answer will be an update to the game field. There is now the official MysQL Python Connector. Install: ``` sudo pip install mysql-connector-python ``` Or download it from here: <http://dev.mysql.com/downloads/connector/python/> Documentation: <http://dev.mysql.com/doc/refman/5.5/en/connector-python.htm...
How to check if a user is logged in (how to properly use user.is_authenticated)?
3,644,902
129
2010-09-05T03:30:04Z
3,644,910
286
2010-09-05T03:32:36Z
[ "python", "django", "authentication" ]
I am looking over [this website](http://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.models.User) but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying: ``` request.user.is_authenticated ``` despite ...
`is_authenticated` is a function. You should call it like ``` if request.user.is_authenticated(): # do something if the user is authenticated ``` As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may ha...
set axis limits in matplotlib pyplot
3,645,787
20
2010-09-05T10:48:38Z
3,645,821
10
2010-09-05T11:01:26Z
[ "python", "matplotlib" ]
I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted). Can someone please help me? Here is the code: ``` import matplotlib.pyplot as plt plt.figure(1, figsize = (10, 20)) ## First subplot: Mea...
I searched some more on the matplotlib website and figured a way to do it. If anyone has a better way, please let me know. In the first subplot replace `plt.subplot(211, axisbg = 'w')` by `ax1 = plt.subplot(211, axisbg = 'w')`. Then, in the second subplot, add the arguments `sharex = ax1` and `sharey = ax1` to the sub...
set axis limits in matplotlib pyplot
3,645,787
20
2010-09-05T10:48:38Z
3,681,015
10
2010-09-09T22:29:00Z
[ "python", "matplotlib" ]
I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted). Can someone please help me? Here is the code: ``` import matplotlib.pyplot as plt plt.figure(1, figsize = (10, 20)) ## First subplot: Mea...
Your proposed solution should work, especially if the plots are interactive (they will stay in sync if one changes). As alternative, you can manually set the y-limits of the second axis to match that of the first. Example: ``` from pylab import * x = arange(0.0, 2.0, 0.01) y1 = 3*sin(2*pi*x) y2 = sin(2*pi*x) figure...
How to get the original value of changed fields?
3,645,802
6
2010-09-05T10:54:00Z
3,645,848
7
2010-09-05T11:09:46Z
[ "python", "sqlalchemy", "insert-update" ]
I'm using sqlalchemy as my orm, and use `declarative` as Base. ``` Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) ``` My question is, how do I know a user has been modified, and how to get the original values without query ...
\To see if `user` has been modified you can check if `user in session.dirty`. If it is and you want to undo it, you can execute ``` session.rollback() ``` but be advised that this will rollback everything for the session to the last `session.commit()`. If you want to get the original values and memory serves me corr...
Django, Turbo Gears, Web2Py, which is better for what?
3,646,002
18
2010-09-05T12:11:30Z
3,648,273
19
2010-09-05T23:40:25Z
[ "python", "django", "frameworks", "web2py", "turbogears" ]
I got a project in mind that makes it worth to finally take the plunge into programming. After reading a lot of stuff, here and elsewhere, I'm set on making Python the one I learn for now, over C# or java. What convinced me the most was actually Paul Graham's excursions on programming languages and Lisp, though Arc is...
You should look at the web2py online documentation (<http://web2py.com/book>). It comes with a Role Based Access Control (the most general access control mechanism) and it is very granular, you can grant access for specific operation on specific records. It comes with a web based IDE but you can use [WingIDE](http://ww...
Changing the prompt style of a virtualenv instance with zsh
3,646,014
8
2010-09-05T12:16:32Z
3,646,633
13
2010-09-05T15:45:45Z
[ "python", "zsh", "virtualenv" ]
I would like the change my zsh prompt style for every virtualenv instances that I use or create. My actual prompt is like this: ``` declare PS1="%{$fg[magenta]%}%n%{$reset_color%} at %{$fg[yellow]%}%m%{$reset_color%} in %{$fg_bold[green]%}%3~%{$reset_color%}" ``` When I activate a virtualenv it just adds some informa...
If you use [virtualenvwrapper](http://www.doughellmann.com/docs/virtualenvwrapper/) you can use its [hooks](http://www.doughellmann.com/docs/virtualenvwrapper/scripts.html#postcpvirtualenv) to do this.
Python "ImportError: No module named" Problem
3,646,307
10
2010-09-05T14:04:19Z
3,646,370
12
2010-09-05T14:18:29Z
[ "python", "unit-testing", "pycharm" ]
I'm running Python 2.6.1 on Windows XP SP3. My IDE is PyCharm 1.0-Beta 2 build PY-96.1055. I'm storing my .py files in a directory named "src"; it has an `__init__.py` file that's empty except for an "`__author__`" attribute at the top. One of them is called Matrix.py: ``` #!/usr/bin/env python """ "Core Python Prog...
This is a bit of a guess, but I think you need to [change your PYTHONPATH](http://docs.python.org/using/windows.html#excursus-setting-environment-variables) environment variable to include the src and test directories. Running programs in the `src` directory may have been working, because Python automatically inserts ...
PEP8 and PyQt, how to reconcile
3,647,518
27
2010-09-05T19:46:57Z
3,647,541
23
2010-09-05T19:53:20Z
[ "python", "coding-style", "pyqt", "pyqt4", "pep8" ]
I'm starting to use PyQt in some projects and I'm running into a stylistic dilemma. PyQt's functions use camel case, but PEP8, which I prefer to follow, says to use underscores and all lowercase for function names. So on the one hand, I can continue to follow PEP8, meaning that my code will have mixed functions calls t...
In your shoes, I wouldn't fight your framework, just like, as a general principle, I don't fight City Hall;-). I happen to share your preference for lowercase-with-underscore function names as PEP 8 specifies, but when I'm programming in a framework that forces a different capitalization style, I resign myself to adopt...
PEP8 and PyQt, how to reconcile
3,647,518
27
2010-09-05T19:46:57Z
5,201,198
9
2011-03-05T02:21:31Z
[ "python", "coding-style", "pyqt", "pyqt4", "pep8" ]
I'm starting to use PyQt in some projects and I'm running into a stylistic dilemma. PyQt's functions use camel case, but PEP8, which I prefer to follow, says to use underscores and all lowercase for function names. So on the one hand, I can continue to follow PEP8, meaning that my code will have mixed functions calls t...
The pep8 document says what to do in this case (emphasis mine): > New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, **internal consistency is preferred.**
How do I check if two variables reference the same object in Python?
3,647,546
22
2010-09-05T19:54:34Z
3,647,560
34
2010-09-05T19:56:12Z
[ "python", "equality" ]
x and y are two variables. I can check if they're equal using `x == y`. But how can I check if they have the same identity? Example: ``` x = [1, 2, 3] y = [1, 2, 3] ``` Now `x == y` is True because x and y are equal. However, x and y aren't the same object. I'm looking for something like sameObject(x,y) which in tha...
You can use `is` to check if two objects have the same identity. ``` >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> x == y True >>> x is y False ```
When is the `==` operator not equivalent to the `is` operator? (Python)
3,647,692
9
2010-09-05T20:32:21Z
3,647,780
17
2010-09-05T20:56:41Z
[ "python", "comparison", "equality" ]
I noticed I can use the `==` operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the `==` operator checks if two objects are equal. But in some other cases (trying to compare...
In Python, the `==` operator is implemented in terms of the [magic method `__eq__`](http://docs.python.org/reference/datamodel.html#basic-customization), which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if yo...
When is the `==` operator not equivalent to the `is` operator? (Python)
3,647,692
9
2010-09-05T20:32:21Z
3,647,786
16
2010-09-05T20:59:09Z
[ "python", "comparison", "equality" ]
I noticed I can use the `==` operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the `==` operator checks if two objects are equal. But in some other cases (trying to compare...
`==` and `is` are always conceptually distinct: the former delegates to the left-hand object's `__eq__` [1], the latter always checks identity, without any delegation. What seems to be confusing you is that `object.__eq__` (which gets inherited by default by user-coded classes that don't override it, of course!) is imp...
When is the `==` operator not equivalent to the `is` operator? (Python)
3,647,692
9
2010-09-05T20:32:21Z
3,648,031
7
2010-09-05T22:07:46Z
[ "python", "comparison", "equality" ]
I noticed I can use the `==` operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the `==` operator checks if two objects are equal. But in some other cases (trying to compare...
The `==` does more than comparing identity when ints are involved. It doesn't just check that the two ints are the same object; it actually ensures their values match. Consider: ``` >>> x=10000 >>> y=10000 >>> x==y,x is y (True, False) >>> del x >>> del y >>> x=10000 >>> y=x >>> x==y,x is y (True, True) ``` The "stan...
How to ignore pyc files in Netbeans project browser (regex question)
3,647,771
3
2010-09-05T20:53:26Z
3,647,774
9
2010-09-05T20:54:56Z
[ "python", "regex", "netbeans" ]
I want to ignore .pyc files in the Netbeans project browser. I think I found a way: **TOOLS -> MISCELLANEOUS -> FILES** . Here is a section called: Files ignored by the IDE . The field there is waiting for a regex describing the file pattern . The default value for that field is: ``` ^(CVS|SCCS|vssver.?\.scc|#.*#|%...
Try this : ``` ^(CVS|SCCS|vssver.?\.scc|#.*#|%.*%|_svn|.*\.pyc)$|~$|^\.(?!htaccess$).*$ ``` I just added the `.*\.pyc` in the first group capture.
In Python, how can I access the namespace of the main module from an imported module?
3,648,339
12
2010-09-06T00:04:04Z
3,648,387
10
2010-09-06T00:17:37Z
[ "python", "namespaces", "module" ]
Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction.
``` import __main__ ``` But don't do this.
In Python, how can I access the namespace of the main module from an imported module?
3,648,339
12
2010-09-06T00:04:04Z
3,856,585
9
2010-10-04T15:18:19Z
[ "python", "namespaces", "module" ]
Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction.
The answer you're looking for is: ``` import __main__ main_global1= __main__.global1 ``` However, whenever a module `module1` needs stuff from the `__main__` module, then: * either the `__main__` module should provide all necessary data as parameters to a `module1` function/class, * or you should put everything tha...
python: how to define a structure like in C
3,648,442
11
2010-09-06T00:42:24Z
3,648,589
13
2010-09-06T01:43:01Z
[ "python" ]
I am going to define a structure and pass it into a function: In C: ``` struct stru { int a; int b; }; s = new stru() s->a = 10; func_a(s); ``` How this can be done in Python?
Unless there's something special about your situation that you're not telling us, just use something like this: ``` class stru: def __init__(self): self.a = 0 self.b = 0 s = stru() s.a = 10 func_a(s) ```
python subclass access to class variable of parent
3,648,564
26
2010-09-06T01:34:42Z
3,648,653
21
2010-09-06T02:09:07Z
[ "python", "subclass", "class-variables" ]
I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent: ``` >>> class A(object): ... x = 0 ... >>> class B(A): ... y = x+1 ... Traceback (most recent call last): File "<stdin>", line 1, in <mod...
In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent. For more details, see <http://docs.p...
python subclass access to class variable of parent
3,648,564
26
2010-09-06T01:34:42Z
3,648,704
41
2010-09-06T02:28:09Z
[ "python", "subclass", "class-variables" ]
I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent: ``` >>> class A(object): ... x = 0 ... >>> class B(A): ... y = x+1 ... Traceback (most recent call last): File "<stdin>", line 1, in <mod...
Python's scoping rules for barenames are very simple and straightforward: local namespace first, then (if any) outer functions in which the current one is nested, then globals, finally built-ins. That's all that ever happens when a barename is looked up, and there's no need to memorize or apply any complicated rules (n...
Python: Nested for loops or "next" statement
3,648,602
4
2010-09-06T01:48:29Z
3,648,625
18
2010-09-06T01:58:30Z
[ "python", "optimization", "for-loop" ]
I'm a rookie hobbyist and I nest for loops when I write python, like so: ``` dict = { key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1} } for key in dict: for subkey/value in key: do it to it ``` I'm aware of a "next" keyword that would accomplish the same goal in one li...
`next` is precious to advance an iterator *when necessary*, without that advancement controlling an explicit `for` loop. For example, if you want "the first item in S that's greater than 100", `next(x for x in S if x > 100)` will give it to you, no muss, no fuss, no unneeded work (as everything terminates as soon as a ...
Python Lxml - Append a existing xml with new data
3,648,689
6
2010-09-06T02:22:56Z
3,648,728
12
2010-09-06T02:35:39Z
[ "python", "xml", "lxml" ]
I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample: ``` --------------- <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</...
You *could* make a new tree by copying over **all** of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...: ``` tree = etree.parse('addressbook.xml') root = tree.getroot() NewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' ) tree.write ( 'addressbook1.xml...
Broken Pipe when Using Python Multiprocessing Managers (BaseManager/SyncManager) to Share Queue with Remote Machines
3,649,458
13
2010-09-06T06:33:28Z
3,817,644
7
2010-09-28T23:04:28Z
[ "python", "multiprocessing", "pipe" ]
In the last month, we've had a persistent problem with the Python 2.6.x multiprocessing package when we've tried to use it to share a queue among several different (linux) computers. I've posed this question directly to Jesse Noller as well since we haven't yet found anything that elucidates the issue on StackOverflow,...
FYI In case anyone else runs by this same error, after extensive consulting with Ask Solem and Jesse Noller of Python's core dev team, it looks like this is actually a bug in current python 2.6.x (and possibly 2.7+ and possibly 3.x). They are looking at possible solutions and a fix will probably be included in a future...
Are NumPy's math functions faster than Python's?
3,650,194
31
2010-09-06T09:04:41Z
3,650,761
17
2010-09-06T10:32:23Z
[ "python", "performance", "numpy" ]
i have a function defined by a combination of basic math functions (abs, cosh, sinh, exp ...) I was wondering if it makes a difference (in speed) to use, for example: `numpy.abs()` instead of `abs()`?
You should use numpy function to deal with numpy's types and use regular python function to deal with regular python types. Worst performance usually occurs when mixing python builtins with numpy, because of types conversion. Those type conversion have been optimized lately, but it's still often better to not use them...
Are NumPy's math functions faster than Python's?
3,650,194
31
2010-09-06T09:04:41Z
3,651,058
44
2010-09-06T11:28:31Z
[ "python", "performance", "numpy" ]
i have a function defined by a combination of basic math functions (abs, cosh, sinh, exp ...) I was wondering if it makes a difference (in speed) to use, for example: `numpy.abs()` instead of `abs()`?
Here are the timing results: ``` lebigot@weinberg ~ % python -m timeit 'abs(3.15)' 10000000 loops, best of 3: 0.146 usec per loop lebigot@weinberg ~ % python -m timeit -s 'from numpy import abs as nabs' 'nabs(3.15)' 100000 loops, best of 3: 3.92 usec per loop ``` `numpy.abs()` is slower than `abs()` because it also...
Numpy broadcast array
3,651,099
2
2010-09-06T11:35:29Z
3,651,182
7
2010-09-06T11:47:49Z
[ "python", "arrays", "numpy", "broadcast" ]
I have the following array in NumPy: ``` A = array([1, 2, 3]) ``` How can I obtain the following matrices (without an explicit loop)? ``` B = [ 1 1 1 2 2 2 3 3 3 ] C = [ 1 2 3 1 2 3 1 2 3 ] ``` Thanks!
Edit2: The OP asks in the comments how to compute ``` n(i, j) = l(i, i) + l(j, j) - 2 * l(i, j) ``` I can think of two ways. I like this way because it generalizes easily: ``` import numpy as np l=np.arange(9).reshape(3,3) print(l) # [[0 1 2] # [3 4 5] # [6 7 8]] ``` The idea is to use `np.ogrid`. This defines a...
Adding custom action to UserModel's Admin page
3,652,287
5
2010-09-06T14:39:50Z
3,652,313
11
2010-09-06T14:44:46Z
[ "python", "django", "django-admin", "django-users" ]
Is there any possibility to create custom action in admin page for django UserModel? I want automatize adding user to group (like adding him to staff, set some extra values, etc.), and of course create actions that take these changes back. Thanks for your help.
Import `User` in your admin.py unregister it, create new `ModelAdmin` for it (or subclass the default one) and go wild. It would look something like this I guess: ``` from django.contrib.auth.models import User class UserAdmin(admin.ModelAdmin): actions = ['some_action'] def some_action(self, request, query...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
3,652,674
92
2010-09-06T15:42:13Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
Apparently (having faced related 64- and 32-bit issues on OS X) there is a [bug in the Windows installer](http://bugs.python.org/issue6792). I stumbled across [this workaround](http://selfsolved.com/problems/setuptools-06c11-fails-to-instal/s/63), which might help - basically, you create your own registry value `HKEY_L...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
3,652,687
141
2010-09-06T15:44:51Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
Problem: you have 64-bit Python, and a 32-bit installer. This will cause problems for extension modules. The reasons why the installer doesn't finds Python is the transparent 32-bit emulation from Windows 7. 64-bit and 32-bit programs will write to different parts of the Windows registry. 64-bit: `HKLM|HKCU\SOFTWARE\...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
9,131,949
68
2012-02-03T16:27:03Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
I made a registry (.reg) file that will automatically change the registry for you. It works if it's installed in "C:\Python27": [Download 32-bit version](https://sites.google.com/site/joedfdev/files/hidden/python27patch.reg?attredirects=0) `HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER\SOFTWARE\wow6432node\` [Download 64-bit ...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
12,793,230
26
2012-10-09T05:17:44Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
Yes, you are correct, the issue is with 64-bit Python and 32-bit installer for setuptools. The best way to get 64-bit setuptools installed on Windows is to download [ez\_setup.py](http://peak.telecommunity.com/dist/ez_setup.py) to C:\Python27\Scripts and run it. It will download appropriate 64-bit .egg file for setupt...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
13,087,995
9
2012-10-26T13:36:12Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
Create a file named `python2.7.reg` (registry file) and put this content into it: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7] [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help] [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2...
Installing SetupTools on 64-bit Windows
3,652,625
129
2010-09-06T15:32:42Z
14,533,967
7
2013-01-26T04:47:58Z
[ "python", "setuptools", "easy-install" ]
I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: ``` `Python Version 2.7 required which was not found in the registry` ``` My installed version of Python is: ``` `Python 2.7 (r27:82525, Jul 4 2010, 07...
Get the file `register.py` from [this gist](https://gist.github.com/4640256). Save it on your C drive or D drive, go to CMD to run it with: ``` 'python register.py' ``` Then you will be able to install it.
What is the best way to do automatic attribute assignment in Python, and is it a good idea?
3,652,851
18
2010-09-06T16:13:07Z
3,653,049
17
2010-09-06T16:48:54Z
[ "python", "attributes", "decorator" ]
Instead of writing code like this every time I define a class: ``` class Foo(object): def __init__(self, a, b, c, d, e, f, g): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f self.g = g ``` I could use [this recipe for automatic attribute...
There are some things about the autoassign code that bug me (mostly stylistic, but one more serious problem): 1. `autoassign` does not assign an 'args' attribute: ``` class Foo(object): @autoassign def __init__(self,a,b,c=False,*args): pass a=Foo('IBM','/tmp',True, 100, 101) pr...
Concatenating two lists - difference between '+=' and extend()
3,653,298
111
2010-09-06T17:35:50Z
3,653,314
8
2010-09-06T17:39:13Z
[ "list", "python" ]
I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: ``` a = [1, 2] b = [2, 3] b.extend(a) ``` the other to use the plus(+) operator: ``` b += a ``` Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is the...
According to the [Zen of Python](http://www.python.org/dev/peps/pep-0020/): > Simple is better than complex. `b += a` is more simple than `b.extend(a)`. The builtins are so highly optimized that there's no real performance difference.
Concatenating two lists - difference between '+=' and extend()
3,653,298
111
2010-09-06T17:35:50Z
3,653,339
113
2010-09-06T17:45:10Z
[ "list", "python" ]
I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: ``` a = [1, 2] b = [2, 3] b.extend(a) ``` the other to use the plus(+) operator: ``` b += a ``` Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is the...
The only difference on a bytecode level is that the [`.extend`](https://docs.python.org/2/library/array.html?#array.array.extend) way involves a function call, which is slightly more expensive in Python than the [`INPLACE_ADD`](https://docs.python.org/2/library/dis.html?highlight=inplace_add#opcode-INPLACE_ADD). It's ...
Concatenating two lists - difference between '+=' and extend()
3,653,298
111
2010-09-06T17:35:50Z
24,261,311
86
2014-06-17T10:21:26Z
[ "list", "python" ]
I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: ``` a = [1, 2] b = [2, 3] b.extend(a) ``` the other to use the plus(+) operator: ``` b += a ``` Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is the...
You can't use += for non-local variable (variable which is not local for function and also not global) ``` def main(): l = [1, 2, 3] def foo(): l.extend([4]) def boo(): l += [5] foo() print l boo() # this will fail main() ``` It's because for *extend* case compiler will lo...
Concatenating two lists - difference between '+=' and extend()
3,653,298
111
2010-09-06T17:35:50Z
37,762,884
8
2016-06-11T10:53:54Z
[ "list", "python" ]
I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: ``` a = [1, 2] b = [2, 3] b.extend(a) ``` the other to use the plus(+) operator: ``` b += a ``` Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is the...
You can chain function calls, but you can't += a function call directly: ``` class A: def __init__(self): self.listFoo = [1, 2] self.listBar = [3, 4] def get_list(self, which): if which == "Foo": return self.listFoo return self.listBar a = A() other_list = [5, 6] ...
SciPy Create 2D Polygon Mask
3,654,289
12
2010-09-06T21:05:16Z
3,655,582
17
2010-09-07T03:34:49Z
[ "python", "scipy", "polygon", "sage", "point-in-polygon" ]
I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages. * input: polygon vertices, image dimensions * output: binary mask of polygon (numpy 2D array) (Larger context: I want to get the distance transform of this polygon using scipy.ndimage.morphology.distance\_tr...
As a slightly more direct alternative to @Anil's answer, matplotlib has [`matplotlib.nxutils.points_inside_poly`](http://matplotlib.sourceforge.net/faq/howto_faq.html#test-whether-a-point-is-inside-a-polygon) that can be used to quickly rasterize an arbitrary polygon. E.g. ``` import numpy as np from matplotlib.nxutil...
SciPy Create 2D Polygon Mask
3,654,289
12
2010-09-06T21:05:16Z
3,732,128
29
2010-09-17T01:35:44Z
[ "python", "scipy", "polygon", "sage", "point-in-polygon" ]
I need to create a numpy 2D array which represents a binary mask of a polygon, using standard Python packages. * input: polygon vertices, image dimensions * output: binary mask of polygon (numpy 2D array) (Larger context: I want to get the distance transform of this polygon using scipy.ndimage.morphology.distance\_tr...
The answer turns out to be quite simple: ``` import numpy from PIL import Image, ImageDraw # polygon = [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...] # width = ? # height = ? img = Image.new('L', (width, height), 0) ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1) mask = numpy.array(img) ```
Format date with month name in polish, in python
3,654,423
2
2010-09-06T21:33:37Z
3,654,627
7
2010-09-06T22:30:06Z
[ "python", "django", "date", "internationalization", "format" ]
Is there an out of the box way to format in python (or within django templates), a date with full month name in accordance to polish language rules? I want to get: ``` 6 września 2010 ``` and not: ``` >>> datetime.today().date().strftime("%d %B %Y") '06 wrzesień 2010' ```
Use [Babel](http://babel.edgewall.org/wiki/ApiDocs/0.9/babel.dates): ``` >>> import babel.dates >>> import datetime >>> now = datetime.datetime.now() >>> print babel.dates.format_date(now, 'd MMMM yyyy', locale='pl_PL') 6 września 2010 ``` **Update:** Incorporated Nathan Davis' comment.
Why does the Python/C API crash on PyRun_SimpleFile?
3,654,652
7
2010-09-06T22:37:58Z
7,411,307
10
2011-09-14T04:38:07Z
[ "c++", "python", "scripting", "python-stackless", "cross-language" ]
I've been experimenting with embedding different scripting languages in a C++ application, currently I'm trying Stackless Python 3.1. I've tried several tutorials and examples, what few I can find, to try and run a simple script from an application. ``` Py_Initialize(); FILE* PythonScriptFile = fopen("Python Scripts/...
I was getting a similar crash & did the below: ``` PyObject* PyFileObject = PyFile_FromString("test.py", "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1); ``` Note that this was in **python 2.7** though. I don't know if the API has changed in 3.x.
Why does the Python/C API crash on PyRun_SimpleFile?
3,654,652
7
2010-09-06T22:37:58Z
9,629,271
8
2012-03-09T05:17:04Z
[ "c++", "python", "scripting", "python-stackless", "cross-language" ]
I've been experimenting with embedding different scripting languages in a C++ application, currently I'm trying Stackless Python 3.1. I've tried several tutorials and examples, what few I can find, to try and run a simple script from an application. ``` Py_Initialize(); FILE* PythonScriptFile = fopen("Python Scripts/...
This works for me on Python 3: ``` PyObject *obj = Py_BuildValue("s", "test.py"); FILE *file = _Py_fopen_obj(obj, "r+"); if(file != NULL) { PyRun_SimpleFile(file, "test.py"); } ``` I hope It would be useful.
Is there a structure in Python similar to C++ STL map?
3,654,770
6
2010-09-06T23:12:17Z
3,654,782
7
2010-09-06T23:16:33Z
[ "c++", "python" ]
Is there a structure in `Python` which supports similar operations to `C++ STL map` and complexity of operations correspond to `C++ STL map`?
`dict` is usually close enough - what do you want that it doesn't do? If the answer is "provide order", then what's actually wrong with `for k in sorted(d.keys())`? Uses too much memory, maybe? If you're doing lots of ordered traversals interspersed with inserts then OK, point taken, you really do want a tree. `dict`...
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,654,857
8
2010-09-06T23:37:27Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
It was just designed that way. Increment and decrement operators are just shortcuts for `x = x + 1`. Python has typically adopted a design strategy which reduces the number of alternative means of performing an operation. [Augmented assignment](http://www.python.org/download/releases/2.0/new-python.htm#SECTION000700000...
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,654,936
290
2010-09-06T23:57:42Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x". If you want to know the original reason, you'll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it's easy enough to justify after the ...
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,654,973
70
2010-09-07T00:08:29Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
**This original answer I wrote is a myth from the folklore of computing**: debunked by Dennis Ritchie as "historically impossible" as noted in the letters to the editors of *Communications of the ACM* July 2012 [doi:10.1145/2209249.2209251](http://dx.doi.org/10.1145/2209249.2209251) --- The C increment/decrement oper...
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,654,980
7
2010-09-07T00:11:00Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
I'm very new to python but I suspect the reason is because of the emphasis between mutable and immutable objects within the language. Now, I know that x++ can easily be interpreted as x = x + 1, but it LOOKS like you're incrementing *in-place* an object which could be immutable. Just my guess/feeling/hunch.
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,655,022
10
2010-09-07T00:25:03Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
Because, in Python, integers are immutable (int's += actually returns a different object). Also, with ++/-- you need to worry about pre- versus post- increment/decrement, and it takes only one more keystroke to write `x+=1`. In other words, it avoids potential confusion at the expense of very little gain.
Why are there no ++ and --​ operators in Python?
3,654,830
266
2010-09-06T23:29:24Z
3,655,032
30
2010-09-07T00:28:13Z
[ "python", "operators" ]
Why are there no `++` and `--` operators in Python?
Of course, we could say "Guido just decided that way", but I think the question is really about the reasons for that decision. I think there are several reasons: * It mixes together statements and expressions, which is not good practice. See <http://norvig.com/python-iaq.html> * It generally encourages people to write...