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 |
|---|---|---|---|---|---|---|---|---|---|
In django, can you load a django app into the python interpreter like in rails? | 4,961,951 | 2 | 2011-02-10T19:56:40Z | 4,961,970 | 19 | 2011-02-10T19:58:17Z | [
"python",
"django"
] | In django, can you load a django app into the python interpreter like in rails?
i.e. does django have: irb
? | you mean `python manage.py shell` ? |
Fast tensor rotation with NumPy | 4,962,606 | 40 | 2011-02-10T20:58:26Z | 4,962,909 | 31 | 2011-02-10T21:28:43Z | [
"python",
"optimization",
"numpy",
"rotation",
"scipy"
] | At the heart of an application (written in Python and using [NumPy](http://en.wikipedia.org/wiki/NumPy)) I need to rotate a 4th order tensor. Actually, I need to rotate a lot of tensors many times and this is my bottleneck. My naive implementation (below) involving eight nested loops seems to be quite slow, but I canno... | Here is how to do it with a single Python loop:
```
def rotT(T, g):
Tprime = T
for i in range(4):
slices = [None] * 4
slices[i] = slice(None)
slices *= 2
Tprime = g[slices].T * Tprime
return Tprime.sum(-1).sum(-1).sum(-1).sum(-1)
```
Admittedly, this is a bit hard to grasp ... |
Fast tensor rotation with NumPy | 4,962,606 | 40 | 2011-02-10T20:58:26Z | 4,963,113 | 37 | 2011-02-10T21:45:27Z | [
"python",
"optimization",
"numpy",
"rotation",
"scipy"
] | At the heart of an application (written in Python and using [NumPy](http://en.wikipedia.org/wiki/NumPy)) I need to rotate a 4th order tensor. Actually, I need to rotate a lot of tensors many times and this is my bottleneck. My naive implementation (below) involving eight nested loops seems to be quite slow, but I canno... | To use `tensordot`, compute the outer product of the `g` tensors:
```
def rotT(T, g):
gg = np.outer(g, g)
gggg = np.outer(gg, gg).reshape(4 * g.shape)
axes = ((0, 2, 4, 6), (0, 1, 2, 3))
return np.tensordot(gggg, T, axes)
```
On my system, this is around seven times faster than Sven's solution. If the... |
Fast tensor rotation with NumPy | 4,962,606 | 40 | 2011-02-10T20:58:26Z | 4,973,390 | 10 | 2011-02-11T19:54:37Z | [
"python",
"optimization",
"numpy",
"rotation",
"scipy"
] | At the heart of an application (written in Python and using [NumPy](http://en.wikipedia.org/wiki/NumPy)) I need to rotate a 4th order tensor. Actually, I need to rotate a lot of tensors many times and this is my bottleneck. My naive implementation (below) involving eight nested loops seems to be quite slow, but I canno... | Out of curiosity I've compared [Cython](http://pypi.python.org/pypi/Cython/) implementation of a naive code from [the question](http://stackoverflow.com/questions/4962606/fast-tensor-rotation-with-numpy) with the numpy code from [@Philipp's answer](http://stackoverflow.com/questions/4962606/fast-tensor-rotation-with-nu... |
Fast tensor rotation with NumPy | 4,962,606 | 40 | 2011-02-10T20:58:26Z | 5,060,109 | 16 | 2011-02-20T21:20:15Z | [
"python",
"optimization",
"numpy",
"rotation",
"scipy"
] | At the heart of an application (written in Python and using [NumPy](http://en.wikipedia.org/wiki/NumPy)) I need to rotate a 4th order tensor. Actually, I need to rotate a lot of tensors many times and this is my bottleneck. My naive implementation (below) involving eight nested loops seems to be quite slow, but I canno... | Thanks to hard work by M. Wiebe, the next version of Numpy (which will probably be 1.6) is going to make this even easier:
```
>>> Trot = np.einsum('ai,bj,ck,dl,abcd->ijkl', g, g, g, g, T)
```
Philipp's approach is at the moment 3x faster, though, but perhaps there is some room for improvement. The speed difference i... |
Asynchronous HTTP calls in Python | 4,962,808 | 9 | 2011-02-10T21:17:33Z | 4,963,208 | 8 | 2011-02-10T21:55:31Z | [
"python",
"asynchronous",
"asyncore"
] | I have a need for a callback kind of functionality in Python where I am sending a request to a webservice multiple times, with a change in the parameter each time. I want these requests to happen concurrently instead of sequentially, so I want the function to be called asynchronously.
It looks like asyncore is what I ... | [Twisted framework](http://twistedmatrix.com/trac/) is just the ticket for that. But if you don't want to take that on you might also use [pycurl](http://pycurl.sourceforge.net/), wrapper for libcurl, that has its own async event loop and supports callbacks. |
Asynchronous HTTP calls in Python | 4,962,808 | 9 | 2011-02-10T21:17:33Z | 4,963,934 | 10 | 2011-02-10T23:32:20Z | [
"python",
"asynchronous",
"asyncore"
] | I have a need for a callback kind of functionality in Python where I am sending a request to a webservice multiple times, with a change in the parameter each time. I want these requests to happen concurrently instead of sequentially, so I want the function to be called asynchronously.
It looks like asyncore is what I ... | Starting in Python 3.2, you can use `concurrent.futures` for launching parallel tasks.
Check out this `ThreadPoolExecutor` example:
<http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example>
It spawns threads to retrieve HTML and acts on responses as they are received.
```
import concur... |
Asynchronous HTTP calls in Python | 4,962,808 | 9 | 2011-02-10T21:17:33Z | 4,972,883 | 14 | 2011-02-11T18:54:03Z | [
"python",
"asynchronous",
"asyncore"
] | I have a need for a callback kind of functionality in Python where I am sending a request to a webservice multiple times, with a change in the parameter each time. I want these requests to happen concurrently instead of sequentially, so I want the function to be called asynchronously.
It looks like asyncore is what I ... | Do you know about [eventlet](http://eventlet.net/)? It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.
Here's an example of a super minimal crawler:
```
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/seco... |
Extract Words from a file | 4,963,499 | 3 | 2011-02-10T22:32:03Z | 4,963,654 | 7 | 2011-02-10T22:53:24Z | [
"python"
] | I open a file using python to find whether a predefined set of words are present in the opened file or not. I took the predefined set of words in a list and opened the file that has to be tested. Now is there any method to extract words in python rather than lines. Thats makes my work lot easier. | ```
import re
def get_words_from_string(s):
return set(re.findall(re.compile('\w+'), s.lower()))
def get_words_from_file(fname):
with open(fname, 'rb') as inf:
return get_words_from_string(inf.read())
def all_words(needle, haystack):
return set(needle).issubset(set(haystack))
def any_words(needl... |
Python RegEx multiple groups | 4,963,691 | 13 | 2011-02-10T22:57:47Z | 4,963,707 | 13 | 2011-02-10T22:59:16Z | [
"python",
"regex"
] | I'm getting confused returning multiple groups in Python. My RegEx is this:
```
lun_q = 'Lun:\s*(\d+\s?)*'
```
And my string is
```
s = '''Lun: 0 1 2 3 295 296 297 298'''`
```
I return a matched object, and then want to look at the groups, but all it shows it the last number (258):
```
r.groups... | Your regex only contains a single pair of parentheses (one capturing group), so you only get one group in your match. If you use a repetition operator on a capturing group (`+` or `*`), the group gets "overwritten" each time the group is repeated, meaning that only the last match is captured.
In your example here, you... |
Max Value within a List of Lists of Tuple | 4,963,957 | 7 | 2011-02-10T23:34:16Z | 4,964,034 | 16 | 2011-02-10T23:43:10Z | [
"python",
"list",
"max"
] | I have a problem to get the highest Value in a dynamic List of Lists of Tuples.
The List can looks like this:
```
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
```
Now I loop through the List to get the highest Value (integer):
```
total = {}
y=0
while y < len(ad... | To clarify, looks like you've got a list of lists of tuples. It doesn't look like we care about what list they are in, so we can simplify this to two steps
* Flatten the list of lists to a list of tuples
* Find the max value
The first part can be accomplished via `itertools.chain` (see e.g., [Flattening a shallow lis... |
Quicksort sorts larger numbers faster? | 4,964,004 | 19 | 2011-02-10T23:40:06Z | 4,964,085 | 34 | 2011-02-10T23:48:58Z | [
"python",
"algorithm",
"performance",
"sorting",
"quicksort"
] | I was messing around with Python trying to practice my sorting algorithms and found out something interesting.
I have three different pieces of data:
* x = number of numbers to sort
* y = range the numbers are in (all random generated ints)
* z = total time taken to sort
When:
x = 100000 and
y = (0,100000) then ... | I think this has to do with the choice of a pivot. Depending on how your partition step works, if you have a lot of duplicate values, your algorithm can degenerate to quadratic behavior when confronted with many duplicates. For example, suppose that you're trying to quicksort this stream:
```
[0 0 0 0 0 0 0 0 0 0 0 0... |
PEP 3118 warning when using ctypes array as numpy array | 4,964,101 | 9 | 2011-02-10T23:51:44Z | 4,968,684 | 9 | 2011-02-11T11:53:15Z | [
"python",
"numpy",
"warnings",
"ctypes"
] | I'm getting the following warning message when I try to use a ctypes array as a numpy array:
```
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes, numpy
>>> TenByteBuffer = ctypes.c_ubyte * 10
... | It's a bug in Python. ctypes currently produces invalid PEP 3118 type codes, which Numpy notices:
<http://bugs.python.org/issue10746>
<http://bugs.python.org/issue10744>
When such an inconsistency is present, Numpy skips using the PEP 3118 buffer interface, and falls back to the old (obsolete) buffer interface. This s... |
Make Javascript do List Comprehension | 4,964,456 | 54 | 2011-02-11T00:44:37Z | 4,964,550 | 45 | 2011-02-11T01:01:42Z | [
"javascript",
"jquery",
"python",
"list-comprehension"
] | What is the cleanest way to make Javascript do something *like* Python's list comprehension?
In Python if I have a list of objects whose name's I want to 'pull out' I would do this...
```
list_of_names = [x.name for x in list_of_objects]
```
In javascript I don't really see a more 'beautiful' way of doing that other... | generic case using [Array.map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map), requires javascript 1.6 (that means, works on every browser but IE < 9) *or* with an object augmenting framework like MooTools works on every browser:
```
var list_of_names = document.getElementsByTagName('i... |
Make Javascript do List Comprehension | 4,964,456 | 54 | 2011-02-11T00:44:37Z | 11,530,639 | 7 | 2012-07-17T20:48:03Z | [
"javascript",
"jquery",
"python",
"list-comprehension"
] | What is the cleanest way to make Javascript do something *like* Python's list comprehension?
In Python if I have a list of objects whose name's I want to 'pull out' I would do this...
```
list_of_names = [x.name for x in list_of_objects]
```
In javascript I don't really see a more 'beautiful' way of doing that other... | Those interested in "beautiful" Javascript should probably check out [CoffeeScript](http://coffeescript.org/), a language which compiles to Javascript. It essentially exists because Javascript is missing things like list comprehension.
In particular, Coffeescript's list comprehension is even more flexible than Python'... |
Make Javascript do List Comprehension | 4,964,456 | 54 | 2011-02-11T00:44:37Z | 18,541,365 | 10 | 2013-08-30T20:56:37Z | [
"javascript",
"jquery",
"python",
"list-comprehension"
] | What is the cleanest way to make Javascript do something *like* Python's list comprehension?
In Python if I have a list of objects whose name's I want to 'pull out' I would do this...
```
list_of_names = [x.name for x in list_of_objects]
```
In javascript I don't really see a more 'beautiful' way of doing that other... | A list comprehension has a few parts to it.
1. Selecting a set of something
2. From a set of Something
3. Filtered by Something
In JavaScript, as of ES5 (so I think that's supported in IE9+, Chrome and FF) you can use the `map` and `filter` functions on an array.
You can do this with map and filter:
```
var list = ... |
Python: How to Redirect Output with Subprocess? | 4,965,159 | 47 | 2011-02-11T02:49:01Z | 4,965,176 | 22 | 2011-02-11T02:51:17Z | [
"python",
"subprocess"
] | What I do in the command line:
```
cat file1 file2 file3 > myfile
```
What I want to do with python:
```
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
``` | UPDATE: os.system is discouraged, albeit still available in Python 3.
---
Use `os.system`:
```
os.system(my_cmd)
```
If you really want to use subprocess, here's the solution (mostly lifted from the documentation for subprocess):
```
p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)
```
OTOH, you can ... |
Python: How to Redirect Output with Subprocess? | 4,965,159 | 47 | 2011-02-11T02:49:01Z | 6,482,200 | 101 | 2011-06-26T04:49:16Z | [
"python",
"subprocess"
] | What I do in the command line:
```
cat file1 file2 file3 > myfile
```
What I want to do with python:
```
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
``` | To answer your original question, to redirect output, just pass an open file handle for the `stdout` argument to `subprocess.call`:
```
# Use a list of args instead of a string
input_files = ['file1', 'file2', 'file3']
my_cmd = ['cat'] + input_files
with open('myfile', "w") as outfile:
subprocess.call(my_cmd, stdo... |
Python. Class, Struct, Dictionary? | 4,965,262 | 3 | 2011-02-11T03:11:43Z | 4,965,280 | 8 | 2011-02-11T03:15:22Z | [
"python",
"tcp",
"ctypes",
"pcap"
] | I am disassembling TCP/IP packet into string format. What is the best way to structure and store it? Should I store it as a ctypes struct, python class, dictionary, or some other way? What are the pros and cons of each method? | You should use a class. It gives you the most flexibility to grow in the future.
Dictionaries have more verbose syntax to access their contents, and don't allow you to add methods if you need them.
ctypes is really for accessing structures packed for use in other APIs. If your data is going to stay in Python, the onl... |
How do I select all of the tr's except the last two tr's | 4,965,342 | 3 | 2011-02-11T03:29:54Z | 4,972,258 | 9 | 2011-02-11T17:41:49Z | [
"python",
"xpath",
"lxml",
"except"
] | In lxml, I'm using xpath to select all of the tr's in a table (that has varying number of rows) except for the last two rows which contain gibberish.
Is there a pattern match that excludes the last two rows? I was looking through xpath tutorials and apparently there is an "except" operator and also a "last()," but can... | **Use**:
```
expressionSelectingTheTable/tr[not(position() > last() -2)]
```
where `expressionSelectingTheTable` should be substituted with a specific XPath expression that selects the table, for which the question is being asked (such as `//table[@id='foo']`)
This single XPath expression selects all `tr` children o... |
Python - How can I make this code asynchronous? | 4,966,129 | 8 | 2011-02-11T06:12:19Z | 4,966,459 | 8 | 2011-02-11T07:06:57Z | [
"python",
"asynchronous",
"twisted",
"nonblocking",
"event-driven"
] | Here's some code that illustrates my problem:
```
def blocking1():
while True:
yield 'first blocking function example'
def blocking2():
while True:
yield 'second blocking function example'
for i in blocking1():
print 'this will be shown'
for i in blocking2():
print 'this will not be ... | You can use generators for cooperative multitasking, but you have to write your own main loop that passes control between them.
Here's a (very simple) example using your example above:
```
def blocking1():
while True:
yield 'first blocking function example'
def blocking2():
while True:
yield ... |
Python - How can I make this code asynchronous? | 4,966,129 | 8 | 2011-02-11T06:12:19Z | 4,976,167 | 26 | 2011-02-12T03:40:33Z | [
"python",
"asynchronous",
"twisted",
"nonblocking",
"event-driven"
] | Here's some code that illustrates my problem:
```
def blocking1():
while True:
yield 'first blocking function example'
def blocking2():
while True:
yield 'second blocking function example'
for i in blocking1():
print 'this will be shown'
for i in blocking2():
print 'this will not be ... | A blocking function is a function which doesn't return, but still leaves your process idle - unable to complete more work.
You're asking us to make *your* blocking functions non-blocking. However â unless you're writing an operating system â *you* don't have any blocking functions. You might have functions which b... |
Print Difference Between Time in Ms | 4,967,512 | 2 | 2011-02-11T09:41:01Z | 4,967,659 | 7 | 2011-02-11T09:57:33Z | [
"python"
] | I am reading a log file in my `python` script, and I have got a list of tuples of `startTimes` and `endTimes` -
```
('[19:49:40:680]', '[19:49:49:128]')
('[11:29:10:837]', '[11:29:15:698]')
('[11:30:18:291]', '[11:30:21:025]')
('[11:37:44:293]', '[11:38:02:008]')
('[11:39:14:897]', '[11:39:21:572]')
('[11:42:19:968]',... | ```
>>> import datetime
>>> a = ('[19:49:40:680]', '[19:49:49:128]')
>>> start = datetime.datetime.strptime(a[0][:-1]+"000", "[%H:%M:%S:%f")
>>> end = datetime.datetime.strptime(a[1][:-1]+"000", "[%H:%M:%S:%f")
>>> delta = end-start
>>> ms = delta.seconds*1000 + delta.microseconds/1000
>>> ms
8448.0
```
This even work... |
How to get the size of a string in Python? | 4,967,580 | 43 | 2011-02-11T09:48:16Z | 4,967,619 | 87 | 2011-02-11T09:53:38Z | [
"python",
"string",
"string-length"
] | For example, I get a string:
```
str = "please answer my question"
```
I want to write it to a file.
But I need to know the size of the string before writing the string to the file. What function can I use to calculate the size of the string? | If you are talking about the length of the string, you can use [`len()`](https://docs.python.org/2/library/functions.html#len):
```
>>> s = 'please answer my question'
>>> len(s) # number of characters in s
25
```
If you need the size of the string in bytes, you need [`sys.getsizeof()`](http://docs.python.org/librar... |
Python lists and their splitting | 4,968,072 | 4 | 2011-02-11T10:43:11Z | 4,968,769 | 9 | 2011-02-11T12:04:08Z | [
"python",
"list"
] | For example, I have such code
```
a = ["a;b", "c;d",...,"y;z"]
```
I want to split every list element into to items of the same list. So i wanna get something like this:
```
["a", "b", "c", "d", ...., "y", "z"]
```
How can I do such thing? Thanks for your answers. | Using only string operations seem to be *simplest* (this is subjective, of course) and **fastest** (by a huge margin, compared to other solutions posted so far).
```
>>> a = ["a;b", "c;d", "y;z"]
>>> ";".join(a).split(";")
['a', 'b', 'c', 'd', 'y', 'z']
```
### Proof / benchmarks
Sorted in ascending order of elapsed... |
Infinte recursion while extending the admin's app change_form template | 4,968,910 | 9 | 2011-02-11T12:21:13Z | 15,320,335 | 10 | 2013-03-10T08:24:35Z | [
"python",
"django",
"django-admin",
"django-templates"
] | I have the following template in `template/admin/change_form.html`:
```
{% extends "admin/change_form.html" %}
{% block extrahead %}
{% include "dojango/base.html" %}
{% block dojango_content %}
{% endblock %}
{% endblock %}
```
However for some reason it throws a
```
TemplatesyntaxError: TemplateSyntaxError a... | I know it's late, but...
If extending - which is a far better option than duplicating - the key is to have it named anything ***except*** `/admin/change_form.html`.
(Although the OP referred to `template/admin/change_form.html`, this is simply because a path in his TEMPLATE\_DIRS tuple ends in '/template' - mine gene... |
Video meta data using python | 4,969,497 | 5 | 2011-02-11T13:25:37Z | 4,969,601 | 8 | 2011-02-11T13:35:04Z | [
"python",
"meta-tags"
] | Hi want to extract video meta tags using Python as described.
On [stackoverflow](http://stackoverflow.com/questions/2999444/python-file-meta-tag-reading), I found kaa module which is not supported in Windows.
Can anyone suggest me python library that can work on across the platforms? | Have you seen [Hachoir](http://pypi.python.org/pypi/hachoir-metadata/1.3.3)? It 'extracts metadata from multimedia files'.
The different file format parsers give differing levels of detail, but it might be what you are looking for. Here's an example of metatdata extraction from an AVI file:
```
$ hachoir-metadata pac... |
Colour chart for Tkinter and Tix Using Python | 4,969,543 | 29 | 2011-02-11T13:29:23Z | 6,928,588 | 7 | 2011-08-03T15:00:51Z | [
"python",
"tkinter",
"tix"
] | This isn't a question but an answer to help others that might run into this issue.
I wanted to visualise some basic colours so I could pick the appropriate ones for my colour scheme.
I couldn't find a colour chart anywhere so modified a sample to display it
Hope you find it useful.
```
import Tix as tk
COLORS =['sn... | What about reading colors names from a file?
```
import sys, os
rgb_path = ["/usr/share/X11/rgb.txt", # linux
"/usr/X11/share/X11/rgb.txt", # OS X
]
COLORS = []
for filename in rgb_path:
if os.path.exists(filename):
with open(filename, 'r') as filedesc:
for line i... |
Colour chart for Tkinter and Tix Using Python | 4,969,543 | 29 | 2011-02-11T13:29:23Z | 6,932,500 | 8 | 2011-08-03T19:59:42Z | [
"python",
"tkinter",
"tix"
] | This isn't a question but an answer to help others that might run into this issue.
I wanted to visualise some basic colours so I could pick the appropriate ones for my colour scheme.
I couldn't find a colour chart anywhere so modified a sample to display it
Hope you find it useful.
```
import Tix as tk
COLORS =['sn... | There is even the *official colour names* documented in the [colours man page](http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm) for Tk. |
Colour chart for Tkinter and Tix Using Python | 4,969,543 | 29 | 2011-02-11T13:29:23Z | 8,954,505 | 20 | 2012-01-21T16:14:47Z | [
"python",
"tkinter",
"tix"
] | This isn't a question but an answer to help others that might run into this issue.
I wanted to visualise some basic colours so I could pick the appropriate ones for my colour scheme.
I couldn't find a colour chart anywhere so modified a sample to display it
Hope you find it useful.
```
import Tix as tk
COLORS =['sn... | For what it's worth, here's a version that doesn't require `Tix`. It uses a `grid` manager so you can see all the colors at the same time. You may want to adjust `MAX_ROWS` and `FONT_SIZE` for your display.
```
import tkinter as tk
COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace... |
Why does Python's != operator think that arguments are equal and not equal at the same time? | 4,969,629 | 12 | 2011-02-11T13:38:35Z | 4,969,675 | 25 | 2011-02-11T13:42:21Z | [
"python"
] | Take the following example:
```
>>> class C(object):
... def __init__(self, p):
... self.p = p
... def __eq__(self, o):
... return True
...
>>> C(1) is C(2)
False
>>> C(1) == C(2)
True
>>> C(1) != C(2)
True # <- Why?!?
```
So now the two objects are equal and not-equal at the same time. I tho... | Pythonâs [âData modelâ](http://docs.python.org/reference/datamodel.html#object.__lt__) explains it all:
> There are no implied relationships among the comparison operators. The truth of `x==y` does not imply that `x!=y` is false. Accordingly, when defining `__eq__()`, one should also define `__ne__()` so that th... |
Why does Python's != operator think that arguments are equal and not equal at the same time? | 4,969,629 | 12 | 2011-02-11T13:38:35Z | 4,969,706 | 8 | 2011-02-11T13:45:18Z | [
"python"
] | Take the following example:
```
>>> class C(object):
... def __init__(self, p):
... self.p = p
... def __eq__(self, o):
... return True
...
>>> C(1) is C(2)
False
>>> C(1) == C(2)
True
>>> C(1) != C(2)
True # <- Why?!?
```
So now the two objects are equal and not-equal at the same time. I tho... | There is a separate function for `!=` which is `__ne__` which is implicitly defined to compare the instance members.
What you want to do is:
```
def __ne__(self, other):
return not self.__eq__(other)
```
or some variant of this. |
Importing a module dynamically using imp | 4,970,235 | 7 | 2011-02-11T14:37:33Z | 4,970,947 | 16 | 2011-02-11T15:38:45Z | [
"python",
"dynamic",
"import"
] | I am trying to import a module from a different directory dynamically. I am following an answer from [this question](http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder). I have a module named bar in a directory named foo. The main script will be running in the parent directory to foo.
Here ... | `imp.load_source` requires the pathname + file name of the module to import, you should change your source for the one below:
```
mod = imp.load_source("bar","./foo/bar.py")
``` |
What could cause a Django error when debug=False that isn't there when debug=True | 4,970,489 | 16 | 2011-02-11T15:01:04Z | 4,975,210 | 7 | 2011-02-11T23:49:42Z | [
"python",
"django",
"apache",
"debugging",
"importerror"
] | Using the development server, it works with debug=True or False.
In production, everything works if debug=True, but if debug=False, I get a 500 error and the apache logs end with an import error: "ImportError: cannot import name Project".
Nothing in the import does anything conditional on debug - the only code that d... | This happens if you have a circular import in one of your files. Check and see if you are importing something from Project and then importing something in Project from the original file that originally imported Project.
I ran into this same problem recently, and rearranging some of my imports helped fix the problem. |
What could cause a Django error when debug=False that isn't there when debug=True | 4,970,489 | 16 | 2011-02-11T15:01:04Z | 15,335,956 | 76 | 2013-03-11T10:14:06Z | [
"python",
"django",
"apache",
"debugging",
"importerror"
] | Using the development server, it works with debug=True or False.
In production, everything works if debug=True, but if debug=False, I get a 500 error and the apache logs end with an import error: "ImportError: cannot import name Project".
Nothing in the import does anything conditional on debug - the only code that d... | Just to say, I ran into a similar error today and it's because Django 1.5 requires the `ALLOWED_HOSTS` parameter in the settings.
You simply need to place this row to make it work ;)
```
...
ALLOWED_HOSTS = '*'
...
```
However, **be aware** that you need to set this parameter properly according to your actual host(s)... |
ReportLab: How to align a textobject? | 4,970,921 | 12 | 2011-02-11T15:36:55Z | 4,972,548 | 15 | 2011-02-11T18:13:30Z | [
"python",
"pdf",
"pdf-generation",
"reportlab"
] | I have the following ReportLab code:
```
t = c.beginText()
t.setFont('Arial', 25)
t.setCharSpace(3)
t.setTextOrigin(159,782)
t.textLine("Some string")
c.drawText(t)
```
What I want to achieve is: have a 3 (pixels?) space between each character (`setCharSpace`), and align the resulting string i... | Basically you only have to calculate the width of the string, the width of the area where you want to center it, and you're done.
Use [Canvas.stringWidth](http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html#reportlab.pdfgen.canvas.Canvas.stringWidth) to determine the width a given string (with a font and size) occ... |
Embedding Python into C++ application | 4,971,928 | 5 | 2011-02-11T17:09:54Z | 4,972,033 | 7 | 2011-02-11T17:18:33Z | [
"c++",
"python",
"boost"
] | **Context:**
An ongoing problem we have been facing is unit testing our market data applications. These applications sit and observe data being retrieved from feeds and does something. Some critical events which are hard to trigger rarely occur and it is are difficult for the Testers to verify our applications perform... | I do something similar to this in one of my projects by using [SWIG](http://www.swig.org/) to generate python bindings for the relevant parts of the C++ code. Then I embed the interpreter as others have suggested. Having done that I can execute python code at will (e.g. `PyRun_SimpleString`), which can access C++ code.... |
escaping characters in a xml file with python | 4,972,210 | 6 | 2011-02-11T17:38:07Z | 4,997,458 | 7 | 2011-02-14T21:25:54Z | [
"python",
"xml",
"special-characters",
"beautifulsoup"
] | I need to escape special characters in an ugly XML file (5000 lines or so long). Here's an example of XML I have to deal with:
```
<root>
<element>
<name>name & surname</name>
<mail>name@name.org</mail>
</element>
</root>
```
Here the problem is the character "&" in the name. How would you escape special charac... | If you don't care about invalid characters in the xml you could use XML parser's `recover` option (see [Parsing broken XML with lxml.etree.iterparse](http://stackoverflow.com/q/2352840/4279)):
```
from lxml import etree
parser = etree.XMLParser(recover=True) # recover from bad characters.
root = etree.fromstring(brok... |
multi-parameter 'in' in python | 4,972,735 | 2 | 2011-02-11T18:35:26Z | 4,972,761 | 8 | 2011-02-11T18:38:59Z | [
"python"
] | Let `L = [1,2,3,4]` be our list.
Then `1 in L` is `True`. `2 in L` is also `True`.
Is there a clean way to write `(1,2) in L` and have it come out true?
That is, given a list `L` and a test list `T` and the relation multi-in, if all members of `T` are in `L`, then `T multi-in L` is `True`, otherwise `T multi-in L` i... | You want to treat `(1,2)` and `L` as `set`s:
```
set((1,2)).issubset(L)
```
or, nicer if you understand the notation:
```
set((1,2)) <= set(L)
``` |
R equivalent of python "_"? | 4,973,185 | 27 | 2011-02-11T19:29:43Z | 4,973,224 | 39 | 2011-02-11T19:34:07Z | [
"python",
"ipython"
] | Python has an identifier `_` that allows for storing the result of the [last evaluation](http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers) which makes it great for speeding up data exploration and introspection.
```
In [1]: 43 * 2
Out[1]: 86
In [2]: _ + 1
Out[2]: 87
```
Is there... | Tis a faff to type, but .Last.value:
```
> sqrt(2)
[1] 1.414214
> .Last.value
[1] 1.414214
``` |
Reading non-uniform data from file into array with NumPy | 4,974,290 | 9 | 2011-02-11T21:31:44Z | 4,974,424 | 11 | 2011-02-11T21:48:07Z | [
"python",
"file-io",
"numpy"
] | Suppose I have a text file that looks like this:
> 33 3
> 46 12
> 23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16
> 33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19
> 41 32 41 33 42 32 42 33
I would like to read each line... | Here's a one-liner:
```
arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]
```
`arrays` is a list of numpy arrays. |
Method for Saving / Loading Game Levels in Python | 4,974,510 | 2 | 2011-02-11T21:58:54Z | 4,974,534 | 8 | 2011-02-11T22:01:25Z | [
"python",
"yaml",
"pygame",
"pickle"
] | I'm writing a game using Python and PyGame. (This is perscribed in the assignment, so it's no use suggesting another game dev. library that has built-in level parsing)
I'm at the stage now where the game physics etc. are complete, but I am yet to work out a method for saving and loading levels into the game. Here's wh... | If you don't need to edit by hand, or read the levels in any other program, just use `pickle`.
Store your level data in a single Python object, and it's (nearly) a one-liner in your code to read and write. |
Python - Setting a datetime in a specific timezone (without UTC conversions) | 4,974,712 | 10 | 2011-02-11T22:27:29Z | 4,974,930 | 10 | 2011-02-11T23:01:20Z | [
"python",
"datetime",
"pst",
"pytz"
] | Just to be clear, this is python 2.6, I am using pytz.
This is for an application that only deals with US timezones, I need to be able to anchor a date (today), and get a unix timestamp (epoch time) for 8pm and 11pm in PST only.
This is driving me crazy.
```
> pacific = pytz.timezone("US/Pacific")
> datetime(2011,2... | Create a tzinfo object `utc` for the UTC time zone, then try this:
```
#XXX: WRONG (for any timezone with a non-fixed utc offset), DON'T DO IT
datetime(2011,2,11,20,0,0,0,pacific).astimezone(utc).strftime("%s")
```
**Edit:** As pointed out in the comments, putting the timezone into the `datetime` constructor isn't al... |
Python: Preventing "if" staircases? | 4,975,457 | 3 | 2011-02-12T00:33:43Z | 4,975,474 | 8 | 2011-02-12T00:37:20Z | [
"python",
"list",
"if-statement"
] | Whenever I'm coding something that requires a lot of conditionals, I end up doing this:
```
if foo:
if bar:
if foobar:
if barfoo:
if foobarfoo:
if barfoobar:
# And forever and ever and ever
```
I can't write `if foo and bar and foobar and ...` because I check for the value li... | > I can't write if foo and bar and foobar and ... because I call list elements inside of an if somewhere down the line, and if the list index don't exist, I get an error.
in python,`and` short circuits. If the left side of the expression is false, the right side is not evaluated at all.
```
foo = dict()
if 'bar' in ... |
What would be a good way to deal with backslash escaped characters? | 4,975,654 | 4 | 2011-02-12T01:14:50Z | 4,975,677 | 11 | 2011-02-12T01:19:28Z | [
"python",
"string",
"escaping"
] | I have a string in the following format;
```
s="part1,part2,part3,part4"
```
I can split the string into pieces by just invoking the `s.split(",")` command.
Now, the question is what if I have a backslash escaped comma in the string? Assuming I have the following string,
```
s="part1,part2,pa\\,rt3,part4"
```
I'd ... | Replacing it with a non-existing string is a nice option.
And otherwise, you could use a regular expression with a negative lookbehind like this:
```
re.split(r'(?<!\\),', 'part1,part2,pa\\,rt3,part4')
``` |
Multiple self referential relationships in SQLAlchemy | 4,975,793 | 7 | 2011-02-12T01:49:14Z | 5,887,836 | 14 | 2011-05-04T18:02:00Z | [
"python",
"sqlalchemy"
] | I have a database model where I need a one-to-many relationship and two one-to-one relationships. Here's the model i've made, but it's throwing errors
```
class Page(Base):
__tablename__ = 'pages'
id = Column(Integer, primary_key=True)
title = Column(String(100), nullable=False)
content ... | The topic is old, but since this is so confusing i'll write it down.
You don't need separate 'prev' column, you already have it as backref for 'next'.
Also, since you have multiple foreign keys to the same target, you need to specify primary joins manually:
```
class Page(Base):
__tablename__ = 'pages'
id ... |
Django, how to see session data in the admin interface | 4,976,015 | 8 | 2011-02-12T02:55:35Z | 4,978,234 | 17 | 2011-02-12T13:15:02Z | [
"python",
"django",
"django-sessions"
] | I'm using [Django sessions](http://docs.djangoproject.com/en/1.2/topics/http/sessions/) and I would like a way of seeing the session data in the admin interface. Is this possible?
I.e. for each session I want to see the data stored in the session database (which is essentially a dictionary as far as I can gather).
Cu... | You can do something like this:
```
from django.contrib.sessions.models import Session
class SessionAdmin(ModelAdmin):
def _session_data(self, obj):
return obj.get_decoded()
list_display = ['session_key', '_session_data', 'expire_date']
admin.site.register(Session, SessionAdmin)
```
It might be even t... |
Django, how to see session data in the admin interface | 4,976,015 | 8 | 2011-02-12T02:55:35Z | 9,267,401 | 7 | 2012-02-13T20:17:52Z | [
"python",
"django",
"django-sessions"
] | I'm using [Django sessions](http://docs.djangoproject.com/en/1.2/topics/http/sessions/) and I would like a way of seeing the session data in the admin interface. Is this possible?
I.e. for each session I want to see the data stored in the session database (which is essentially a dictionary as far as I can gather).
Cu... | Continuing from Tomasz's answer, I went with:
```
import pprint
from django.contrib.sessions.models import Session
class SessionAdmin(admin.ModelAdmin):
def _session_data(self, obj):
return pprint.pformat(obj.get_decoded()).replace('\n', '<br>\n')
_session_data.allow_tags=True
list_display = ['sess... |
python mongodb regex: ignore case | 4,976,278 | 10 | 2011-02-12T04:14:50Z | 4,976,333 | 24 | 2011-02-12T04:29:13Z | [
"python",
"regex",
"mongodb"
] | How can I specify a REGEX and ignore the case:
```
regex = ".*" + filter + ".*";
config.gThingCollection.find({"name":{"$regex":regex}})
```
I want the filter to be case-insensitive, how to achieve that? | Try using the python regex objects instead. Pymongo will serialize them properly:
```
import re
config.gThingCollection.find({"name": re.compile(regex, re.IGNORECASE)})
``` |
python mongodb regex: ignore case | 4,976,278 | 10 | 2011-02-12T04:14:50Z | 15,872,110 | 11 | 2013-04-08T05:50:58Z | [
"python",
"regex",
"mongodb"
] | How can I specify a REGEX and ignore the case:
```
regex = ".*" + filter + ".*";
config.gThingCollection.find({"name":{"$regex":regex}})
```
I want the filter to be case-insensitive, how to achieve that? | You can use MongoDB regex options in your query.
```
config.gThingCollection.find({"name":{"$regex":regex, "$options": "-i"}})
``` |
Is there function in Python which serves as main in C | 4,976,906 | 2 | 2011-02-12T07:24:02Z | 4,976,911 | 10 | 2011-02-12T07:26:17Z | [
"python"
] | I want to know whether there is a main function in Python as in C, etc. ? | The short answer is **no**. Typically,
```
if __name__ == '__main__':
import sys
argc = len(sys.argv)
argv = sys.argv
```
is the closest thing you get to a `main` in Python. More info [here](http://en.wikipedia.org/wiki/Main_function#Python). |
Is there function in Python which serves as main in C | 4,976,906 | 2 | 2011-02-12T07:24:02Z | 4,976,912 | 10 | 2011-02-12T07:27:14Z | [
"python"
] | I want to know whether there is a main function in Python as in C, etc. ? | No. Python scripts are executed from beginning to end, which means that there is no need for a `main()` function.
Having said that, many scripts use a **main sentinel**, which checks the value of a certain global to see if the script/module is being run directly:
```
if __name__ == '__main__':
dosomething()
``` |
Passing value from PHP script to Python script | 4,977,125 | 11 | 2011-02-12T08:28:21Z | 4,977,634 | 18 | 2011-02-12T10:49:38Z | [
"php",
"python",
"variables",
"exec"
] | I looked at the other questions similar to this one, but can't figure this out still.
I have a basic php file that does this:
```
?php
$item='example';
$tmp = exec("python testscriptphp.py .$item");
echo $tmp;
?
```
While succesfully calls python that I have running on my webhostserver. Now in my python script i wan... | Although netcoder pretty much gave you the answer in his comment, here's an example:
Python->PHP
example.py
```
import os
os.system("/usr/bin/php example2.php whatastorymark")
```
example2.php
```
<?php
echo $argv[1];
?>
```
PHP->Python
```
<?php
$item='example';
$tmp = exec("python testscriptphp.py... |
python twitter Api() not found error | 4,977,883 | 2 | 2011-02-12T11:52:35Z | 4,978,395 | 7 | 2011-02-12T13:49:43Z | [
"python",
"api",
"twitter"
] | I'm trying to use the python-twitter module, but still having problems initiating the twitter.Api(). I've checked and rechecked that no other file named twitter.py or twitter.pyc is on my system. On a clean install i first try to
```
>>> import twitter
```
and correctly get a response of 'module unknown'
I do a `eas... | It appears that you are trying to follow the documentation for one Python Twitter module when you are in fact using another Python Twitter module.
The `Api()` method call you mention is part of [this Python Twitter module](http://code.google.com/p/python-twitter/). However, when you use `easy_install twitter`, you act... |
Create custom buttons in admin change_form in Django | 4,978,362 | 12 | 2011-02-12T13:41:39Z | 6,262,229 | 14 | 2011-06-07T07:58:24Z | [
"python",
"django",
"django-admin"
] | I want to add custom buttons to the add/change form at the administration interface. By default, there are only three:
* Save and add another
* Save and continue editing
* Save
I have created some custom methods in my `forms.py` file, and I want to create buttons to call these methods. I have used the snippet <http:/... | You can override `admin/change_form.html`. Copy the version in `contrib.admin.templates` into your project. Mine is `myproject/templates/admin/change_form.html`, but you could use `/myproject/myapp/templates/admin/change_form.html`.
Next, edit the copy and change the two references to the existing template tag, `{% su... |
Create custom buttons in admin change_form in Django | 4,978,362 | 12 | 2011-02-12T13:41:39Z | 30,755,936 | 14 | 2015-06-10T12:09:13Z | [
"python",
"django",
"django-admin"
] | I want to add custom buttons to the add/change form at the administration interface. By default, there are only three:
* Save and add another
* Save and continue editing
* Save
I have created some custom methods in my `forms.py` file, and I want to create buttons to call these methods. I have used the snippet <http:/... | One simple way I found to add buttons is to add another row for the custom buttons. Create an admin directory in your template dir based on your needs. For example I usually add buttons for specific models in a custom template. Make a "templates/admin/app/model/" directory.
Then add a file *change\_form.html*.
```
{%... |
Should a return statement have parentheses? | 4,978,567 | 14 | 2011-02-12T14:24:47Z | 4,978,586 | 21 | 2011-02-12T14:27:06Z | [
"python"
] | Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:
```
>>> def dbl_a(p): return p*2
>>> def dbl_b(p): return(p*2)
>>> def dbl_c(p): return (p*2)
```
If we run them we get:
```
>>> dbl_a(42)
84
>>> dbl_b(42)
84
>>> dbl_c(42)
84
```
The three functions provide the... | `return value` is the "correct" way - return is a language construct, not a function.
If you want to return a tuple, use `return your, values, here`
There's no need for any parenthesis (tuples are created by the `,` "operator", not the `()`) |
Should a return statement have parentheses? | 4,978,567 | 14 | 2011-02-12T14:24:47Z | 4,979,486 | 10 | 2011-02-12T17:33:39Z | [
"python"
] | Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:
```
>>> def dbl_a(p): return p*2
>>> def dbl_b(p): return(p*2)
>>> def dbl_c(p): return (p*2)
```
If we run them we get:
```
>>> dbl_a(42)
84
>>> dbl_b(42)
84
>>> dbl_c(42)
84
```
The three functions provide the... | There are generally 4 uses for the parentheses `()` in Python.
1. It acts the same way as most of the other mainstream languages - it's a construct to force an evaluation precedence, like in a math formula. Which also means it's only used when it is necessary, like when you need to make sure additions and subtractions... |
Is there a Python equivalent of the C# null-coalescing operator? | 4,978,738 | 103 | 2011-02-12T15:04:49Z | 4,978,745 | 166 | 2011-02-12T15:06:31Z | [
"python",
"null-coalescing-operator"
] | In C# there's a [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx) (written as `??`) that allows for easy (short) null checking during assignment:
```
string s = null;
var other = s ?? "some default value";
```
Is there a python equivalent?
I know that I can do:
```
s = None
other = s... | ```
other = s or "some default value"
```
Ok, it must be clarified how the `or` operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.
Note that the `or` operator does not return only `True` or `False`.... |
Is there a Python equivalent of the C# null-coalescing operator? | 4,978,738 | 103 | 2011-02-12T15:04:49Z | 4,978,959 | 26 | 2011-02-12T15:52:48Z | [
"python",
"null-coalescing-operator"
] | In C# there's a [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx) (written as `??`) that allows for easy (short) null checking during assignment:
```
string s = null;
var other = s ?? "some default value";
```
Is there a python equivalent?
I know that I can do:
```
s = None
other = s... | strictly,
```
other = s if s is not None else "default value"
```
otherwise s=False will become "default value", which may not be what was intended.
If you want to make this shorter, try
```
def notNone(s,d):
if s is None:
return d
else:
return s
other = notNone(s, "default value")
``` |
Is there a Python equivalent of the C# null-coalescing operator? | 4,978,738 | 103 | 2011-02-12T15:04:49Z | 16,247,152 | 20 | 2013-04-27T00:45:21Z | [
"python",
"null-coalescing-operator"
] | In C# there's a [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx) (written as `??`) that allows for easy (short) null checking during assignment:
```
string s = null;
var other = s ?? "some default value";
```
Is there a python equivalent?
I know that I can do:
```
s = None
other = s... | Here's a function that will return the first argument that isn't None:
```
def coalesce(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
# Prints "banana"
print coalesce(None, "banana", "phone", None)
```
reduce() might needlessly iterate over all the arguments even if the first argument is not No... |
Why is this regular expression not working ({m, n})? | 4,978,765 | 2 | 2011-02-12T15:11:00Z | 4,978,783 | 9 | 2011-02-12T15:13:45Z | [
"python",
"regex"
] | Trying to understand regular expressions and I am on the repetitions part: `{m, n}`.
I have this code:
```
>>> p = re.compile('a{1}b{1, 3}')
>>> p.match('ab')
>>> p.match('abbb')
```
As you can see both the strings are not matching the pattern. Why is this happening? | You shouldn't put a space after the comma, and the `{1}` is redundant. |
How to split a string into array of characters with Python? | 4,978,787 | 172 | 2011-02-12T15:14:38Z | 4,978,792 | 402 | 2011-02-12T15:16:17Z | [
"python",
"split"
] | I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method
`str.split(//)` does not seem to work like Ruby does. Is there a simple way of doing this without looping? | ```
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
```
You need [list](http://docs.python.org/library/functions.html#list) |
How to split a string into array of characters with Python? | 4,978,787 | 172 | 2011-02-12T15:14:38Z | 4,978,794 | 45 | 2011-02-12T15:16:39Z | [
"python",
"split"
] | I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method
`str.split(//)` does not seem to work like Ruby does. Is there a simple way of doing this without looping? | You take the string and pass it to list()
```
s = "mystring"
l = list(s)
print l
``` |
How to split a string into array of characters with Python? | 4,978,787 | 172 | 2011-02-12T15:14:38Z | 25,773,198 | 13 | 2014-09-10T19:07:52Z | [
"python",
"split"
] | I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method
`str.split(//)` does not seem to work like Ruby does. Is there a simple way of doing this without looping? | I explored another two ways to accomplish this task. It may be helpful for someone.
The first one is easy:
```
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
```
And the second one use [`map`](https://docs.python.org/2/library/functions.html#map) and `lambda`... |
How to split a string into array of characters with Python? | 4,978,787 | 172 | 2011-02-12T15:14:38Z | 29,225,966 | 27 | 2015-03-24T06:00:18Z | [
"python",
"split"
] | I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method
`str.split(//)` does not seem to work like Ruby does. Is there a simple way of doing this without looping? | You can also do it in this very simple way without list():
```
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
``` |
Python - use list as function parameters | 4,979,542 | 45 | 2011-02-12T17:43:28Z | 4,979,555 | 11 | 2011-02-12T17:45:30Z | [
"python",
"list",
"function-parameter"
] | How can I use a Python list (e.g. `params = ['a',3.4,None]`) as parameters to a function, e.g.:
```
def some_func(a_char,a_float,a_something):
# do stuff
``` | Use an asterisk:
```
some_func(*params)
``` |
Python - use list as function parameters | 4,979,542 | 45 | 2011-02-12T17:43:28Z | 4,979,569 | 65 | 2011-02-12T17:48:17Z | [
"python",
"list",
"function-parameter"
] | How can I use a Python list (e.g. `params = ['a',3.4,None]`) as parameters to a function, e.g.:
```
def some_func(a_char,a_float,a_something):
# do stuff
``` | You can do this using the splat operator:
```
some_func(*params)
```
This causes the function to receive each list item as a separate parameter. There's a description here: <http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists> |
Python - use list as function parameters | 4,979,542 | 45 | 2011-02-12T17:43:28Z | 4,979,579 | 7 | 2011-02-12T17:50:01Z | [
"python",
"list",
"function-parameter"
] | How can I use a Python list (e.g. `params = ['a',3.4,None]`) as parameters to a function, e.g.:
```
def some_func(a_char,a_float,a_something):
# do stuff
``` | You want the [argument unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) operator \*. |
Python - use list as function parameters | 4,979,542 | 45 | 2011-02-12T17:43:28Z | 16,044,013 | 22 | 2013-04-16T18:04:55Z | [
"python",
"list",
"function-parameter"
] | How can I use a Python list (e.g. `params = ['a',3.4,None]`) as parameters to a function, e.g.:
```
def some_func(a_char,a_float,a_something):
# do stuff
``` | This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.
```
def some_func(a_char, a_float, a_something):
print a_char
params = ['a', 3.4, None]
some_func(*params)
>> a
``` |
Django star rating system and AJAX | 4,980,110 | 4 | 2011-02-12T19:28:00Z | 4,981,334 | 8 | 2011-02-12T23:30:45Z | [
"python",
"ajax",
"django",
"jquery",
"rating-system"
] | I am trying to implement a star rating system on a Django site.
Storing the ratings in my models is sorted, as is displaying the score on the page. But I want the user's to be able to rate a page (from 1 to 5 essentially) without a refresh or change of page.
I have found the following, and like the style of the stars... | AJAX sounds scary and confusing but it doesn't have to be. Essentially what you want to do is post some data to a particular url/view combo. See [jQuery.post](http://api.jquery.com/jQuery.post/) for more information on using AJAX to send data to the server.
```
#urls
urlpatterns += patterns('',
url(r'^article/rate/', ... |
Django NameError [app name] is not defined | 4,980,297 | 5 | 2011-02-12T20:02:45Z | 4,980,323 | 11 | 2011-02-12T20:07:33Z | [
"python",
"django",
"django-grappelli"
] | Trying to use django-grappelli for my admin theme, install has been surprisingly challenging. Running into the following in my urls.py:
```
NameError .. name 'grappelli' is not defined
```
The error is thrown on the line
```
(r'^grappelli/', include(grappelli.urls))
```
Installed grappelli with pip, and grappelli i... | Line should read:
```
(r'^grappelli/', include('grappelli.urls'))
```
`include` either takes a path to a urls module OR it can be a python object that returns the url patterns
<http://docs.djangoproject.com/en/dev/topics/http/urls/#include>
So your two options are either the line above (path to urls) or
```
from gr... |
Django NameError [app name] is not defined | 4,980,297 | 5 | 2011-02-12T20:02:45Z | 10,557,898 | 8 | 2012-05-11T20:04:27Z | [
"python",
"django",
"django-grappelli"
] | Trying to use django-grappelli for my admin theme, install has been surprisingly challenging. Running into the following in my urls.py:
```
NameError .. name 'grappelli' is not defined
```
The error is thrown on the line
```
(r'^grappelli/', include(grappelli.urls))
```
Installed grappelli with pip, and grappelli i... | I realize this is over a year old, but it was one of the top results on Google when I was having this same problem.
Rather than importing urlpatterns from grapelli.urls, you can also change the include() statement
```
(r'^grappelli/', include(grappelli.urls))
```
to
```
(r'^grappelli/', include('grappelli.urls'))
`... |
What can you do with Lisp macros that you can't do with first-class functions? | 4,980,520 | 16 | 2011-02-12T20:44:32Z | 4,980,557 | 8 | 2011-02-12T20:52:16Z | [
"python",
"macros",
"lisp"
] | I think I understand Lisp macros and their role in the compilation phase.
But in Python, you can pass a function into another function
```
def f(filename, g):
try:
fh = open(filename, "rb")
g(fh)
finally:
close(fh)
```
So, we get lazy evaluation here. What can I do... | Macros are expanded in a compile-time. Closures are constructed in runtime. With macros you can implement highly efficient compilers of embedded domain specific languages, and with high order functions you can only implement inefficient interpreters. That eDSL compilers may do all kinds of static checks, do whatever ex... |
What can you do with Lisp macros that you can't do with first-class functions? | 4,980,520 | 16 | 2011-02-12T20:44:32Z | 4,980,563 | 11 | 2011-02-12T20:52:59Z | [
"python",
"macros",
"lisp"
] | I think I understand Lisp macros and their role in the compilation phase.
But in Python, you can pass a function into another function
```
def f(filename, g):
try:
fh = open(filename, "rb")
g(fh)
finally:
close(fh)
```
So, we get lazy evaluation here. What can I do... | Here's Matthias Felleisen's answer from 2002 (via <http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01539.html>):
> I'd like to propose that there are
> three disciplined uses of macros:
>
> 1. data sublanguages: I can write simple looking expressions and create
> complex nested lists/arrays/tables
> ... |
What can you do with Lisp macros that you can't do with first-class functions? | 4,980,520 | 16 | 2011-02-12T20:44:32Z | 4,980,585 | 20 | 2011-02-12T20:57:55Z | [
"python",
"macros",
"lisp"
] | I think I understand Lisp macros and their role in the compilation phase.
But in Python, you can pass a function into another function
```
def f(filename, g):
try:
fh = open(filename, "rb")
g(fh)
finally:
close(fh)
```
So, we get lazy evaluation here. What can I do... | First of all Lisp has first-class functions too, so you could as well ask: "Why do I need macros in Lisp if I already have first-class functions". The answer to that is that first-class functions don't allow you to play with syntax.
On a cosmetic level, first-class functions allow you to write `f(filename, some_functi... |
What can you do with Lisp macros that you can't do with first-class functions? | 4,980,520 | 16 | 2011-02-12T20:44:32Z | 4,981,059 | 7 | 2011-02-12T22:34:08Z | [
"python",
"macros",
"lisp"
] | I think I understand Lisp macros and their role in the compilation phase.
But in Python, you can pass a function into another function
```
def f(filename, g):
try:
fh = open(filename, "rb")
g(fh)
finally:
close(fh)
```
So, we get lazy evaluation here. What can I do... | The macro transforms source code. A lazy evaluation does not. Imagine that you can now write functions which transform arbitrary code to arbitrary different code.
The creation of simple language constructs is also only a very simple example. Consider your example of opening a file:
```
(with-open-file (stream file :d... |
Is there any way to convert Wikitext to Markdown in python? | 4,980,904 | 12 | 2011-02-12T22:02:27Z | 11,029,690 | 14 | 2012-06-14T08:50:22Z | [
"python",
"mediawiki",
"markdown",
"text-processing"
] | Is there a python library which takes wikitext (as used in mediawiki) input and converts it to markdown? | Since is something that I need, I packaged both together:
<http://bitbucket.org/wikier/mw2md>
So now it's easier to perform both tasks. |
Migrating to pip+virtualenv from setuptools | 4,981,174 | 13 | 2011-02-12T22:59:28Z | 5,185,772 | 21 | 2011-03-03T19:52:37Z | [
"python",
"matplotlib",
"packaging",
"virtualenv",
"pip"
] | So `pip` and `virtualenv` sound wonderful compared to `setuptools`. Being able to uninstall would be great. But my project is already using `setuptools`, so how do I migrate? The web sites I've been able to find so far are very vague and general. So here's an anthology of questions after reading the main web sites and ... | Wow, that's quite a set of questions. Many of them would really deserve their own SO question with more details. I'll do my best:
> First of all, are virtualenv and pip
> supposed to be in a usable state by
> now?
Yes, although they don't serve everyone's needs. Pip and virtualenv (along with everything else in Pytho... |
Scrapy - how to manage cookies/sessions | 4,981,440 | 25 | 2011-02-12T23:51:01Z | 25,516,223 | 14 | 2014-08-26T22:33:09Z | [
"python",
"session",
"cookies",
"session-cookies",
"scrapy"
] | I'm a bit confused as to how cookies work with Scrapy, and how you manage those cookies.
This is basically a simplified version of what I'm trying to do:

---
## The way the website works:
When you visit the website you get a session cookie.
When y... | Three years later, I think this is exactly what you were looking for:
<http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-cookiejar>
Just use something like this in your spider's start\_requests method:
```
for i, url in enumerate(urls):
yield scrapy.Request("http://www.example.com", me... |
Django: use render_to_response and set cookie | 4,981,601 | 11 | 2011-02-13T00:27:51Z | 4,981,612 | 24 | 2011-02-13T00:31:03Z | [
"python",
"django",
"django-templates"
] | Currently, I'm using `render_to_response(template_name, locals(), context-etc..)`
Trying to set a cookie right now and I'm wondering if I can do it with `render_to_response`.
All the examples I see are using `HttpResponse` object. They set the cookie in the response object, like this
```
response = HttpResponseObjec... | Yes, not a problem. The principle is exactly the same.
```
response = render_to_response(template_name, locals(), context-etc..)
response.set_cookie("favorite_color",request.GET["favorite_color"])
return response
``` |
How to remove lines in a Matplotlib plot | 4,981,815 | 44 | 2011-02-13T01:19:11Z | 4,981,918 | 28 | 2011-02-13T01:47:12Z | [
"python",
"matplotlib",
"plot"
] | How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())
```
from matplotlib import pyplot
import numpy
a = numpy.arange(i... | I'm showing that a combination of `lines.pop(0)` `l.remove()` and `del l` does the trick.
```
from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)
l = lines.pop(0)
wl = weakref.ref(l) # create a weak reference to see if... |
How to remove lines in a Matplotlib plot | 4,981,815 | 44 | 2011-02-13T01:19:11Z | 9,896,338 | 8 | 2012-03-27T19:29:37Z | [
"python",
"matplotlib",
"plot"
] | How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())
```
from matplotlib import pyplot
import numpy
a = numpy.arange(i... | I've tried lots of different answers in different forums. I guess it depends on the machine your developing. But I haved used the statement
```
ax.lines = []
```
and works perfectly. I don't use cla() cause it deletes all the definitions I've made to the plot
Ex.
```
pylab.setp(_self.ax.get_yticklabels(), fontsize=... |
How to remove lines in a Matplotlib plot | 4,981,815 | 44 | 2011-02-13T01:19:11Z | 13,575,495 | 35 | 2012-11-27T00:24:45Z | [
"python",
"matplotlib",
"plot"
] | How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())
```
from matplotlib import pyplot
import numpy
a = numpy.arange(i... | This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your `Line2D` objects hanging around.
**WARNING:** One other no... |
How to handle response encoding from urllib.request.urlopen() | 4,981,977 | 18 | 2011-02-13T02:05:24Z | 4,981,999 | 26 | 2011-02-13T02:09:29Z | [
"python",
"regex",
"encoding",
"urllib"
] | I'm trying to search a webpage using regular expressions, but I'm getting the following error:
> TypeError: can't use a string pattern on a bytes-like object
I understand why, urllib.request.urlopen() returns a bytestream and so, at least I'm guessing, re doesn't know the encoding to use. What am I supposed to do in ... | You just need to decode the response, using the `Content-Type` header typically the last value. There is an example given in [the tutorial](http://docs.python.org/dev/tutorial/stdlib.html#internet-access) too.
```
output = response.decode('utf-8')
``` |
How to handle response encoding from urllib.request.urlopen() | 4,981,977 | 18 | 2011-02-13T02:05:24Z | 19,156,107 | 34 | 2013-10-03T09:54:13Z | [
"python",
"regex",
"encoding",
"urllib"
] | I'm trying to search a webpage using regular expressions, but I'm getting the following error:
> TypeError: can't use a string pattern on a bytes-like object
I understand why, urllib.request.urlopen() returns a bytestream and so, at least I'm guessing, re doesn't know the encoding to use. What am I supposed to do in ... | As for me, the solution is as following (python3):
```
resource = urllib.request.urlopen(an_url)
content = resource.read().decode(resource.headers.get_content_charset())
``` |
Questions about Django development on Mac OS X | 4,982,967 | 2 | 2011-02-13T07:15:23Z | 4,983,149 | 9 | 2011-02-13T08:11:04Z | [
"python",
"django",
"osx"
] | I'm new to Mac (as of yesterday), and I have Snow Leopard. I've just `easy_install` virtualenv, and it doesn't work. I read a couple other SO questions about the same exception I had, and it seems that I need XCode installed. Before I go down a rabbit hole, installing a 3.5Gb Apple-specific code library for something P... | You will need XCode, yes. You'll need it for any libraries that need compiling, apart from anything else.
Please don't install MacPorts, though, as recommended by titaniumdecoy. It tries to install its own versions of everything, which is unnecessarily confusing, and takes you out of the usual Mac development stack. A... |
how to convert 8-bit hebrew to utf-8 in python | 4,982,968 | 3 | 2011-02-13T07:15:29Z | 4,982,998 | 7 | 2011-02-13T07:24:34Z | [
"python",
"utf-8"
] | I have hebrew data such that \xe0 is the hebrew aleph,
and wish to convert it into utf-8 | In general in Python, if you have a byte string you need to use decode first to convert it to the internal representation, afterwards you can encode it to UTF-8. Of course, you need to know the coding of `\xe0` for this to work (I assume your character is encoded using ISO-8859-8):
```
'\xe0'.decode('iso-8859-8').enco... |
Python - How to check list monotonicity | 4,983,258 | 36 | 2011-02-13T08:45:49Z | 4,983,308 | 22 | 2011-02-13T08:56:32Z | [
"python",
"list",
"performance"
] | What would be an **efficient and pythonic** way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?
Examples:
```
[0,1,2,3,3,4] # This is a monotonically increasing list
[4.3,4.2,-2] # This is a monotonically decreasing list
[2,3,1] # This is neither
``` | ```
import itertools
import operator
def monotone_increasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.le, pairs))
def monotone_decreasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.ge, pairs))
def monotone(lst):
return monotone_increasing(ls... |
Python - How to check list monotonicity | 4,983,258 | 36 | 2011-02-13T08:45:49Z | 4,983,359 | 67 | 2011-02-13T09:11:02Z | [
"python",
"list",
"performance"
] | What would be an **efficient and pythonic** way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?
Examples:
```
[0,1,2,3,3,4] # This is a monotonically increasing list
[4.3,4.2,-2] # This is a monotonically decreasing list
[2,3,1] # This is neither
``` | ```
def strictly_increasing(L):
return all(x<y for x, y in zip(L, L[1:]))
def strictly_decreasing(L):
return all(x>y for x, y in zip(L, L[1:]))
def non_increasing(L):
return all(x>=y for x, y in zip(L, L[1:]))
def non_decreasing(L):
return all(x<=y for x, y in zip(L, L[1:]))
``` |
Python - How to check list monotonicity | 4,983,258 | 36 | 2011-02-13T08:45:49Z | 4,983,495 | 19 | 2011-02-13T09:47:54Z | [
"python",
"list",
"performance"
] | What would be an **efficient and pythonic** way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?
Examples:
```
[0,1,2,3,3,4] # This is a monotonically increasing list
[4.3,4.2,-2] # This is a monotonically decreasing list
[2,3,1] # This is neither
``` | If you have large lists of numbers it might be best to use numpy, and if you are:
```
import numpy as np
def monotonic(x):
dx = np.diff(x)
return np.all(dx <= 0) or np.all(dx >= 0)
```
should do the trick. |
Python - How to check list monotonicity | 4,983,258 | 36 | 2011-02-13T08:45:49Z | 4,985,520 | 11 | 2011-02-13T17:03:12Z | [
"python",
"list",
"performance"
] | What would be an **efficient and pythonic** way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?
Examples:
```
[0,1,2,3,3,4] # This is a monotonically increasing list
[4.3,4.2,-2] # This is a monotonically decreasing list
[2,3,1] # This is neither
``` | @6502 has the perfect code for lists, I just want to add a general version that works for all sequences:
```
def pairwise(seq):
items = iter(seq)
last = next(items)
for item in items:
yield last, item
last = item
def strictly_increasing(L):
return all(x<y for x, y in pairwise(L))
def ... |
Python - How to check list monotonicity | 4,983,258 | 36 | 2011-02-13T08:45:49Z | 34,644,854 | 8 | 2016-01-06T23:31:56Z | [
"python",
"list",
"performance"
] | What would be an **efficient and pythonic** way to check list monotonicity?
i.e. that it has monotonically increasing or decreasing values?
Examples:
```
[0,1,2,3,3,4] # This is a monotonically increasing list
[4.3,4.2,-2] # This is a monotonically decreasing list
[2,3,1] # This is neither
``` | Here is a functional solution using `reduce` of complexity `O(n)`:
```
is_increasing = lambda L: reduce(lambda a,b: b if a < b else 9999 , L)!=9999
is_decreasing = lambda L: reduce(lambda a,b: b if a > b else -9999 , L)!=-9999
```
Replace `9999` with the top limit of your values, and `-9999` with the bottom limit. F... |
IntelliJ IDEA: Python plugin does not highlight Python code | 4,983,715 | 4 | 2011-02-13T10:52:17Z | 4,984,030 | 8 | 2011-02-13T12:09:10Z | [
"python",
"intellij-idea"
] | I have some problems whith IntelliJ IDEA Python plugin.
I've got a Java project with a few modules. And I want to add one module for Python tools-scripts which I use to generate some files.
I downloaded and installed Python plugin (version 2.6.6.) for my IDEA (10.0.2 Ultimate). Then I added Python SDK to the project ... | See **Settings | File Types**, verify that .py extension is associated with Python file type. |
A create_or_get method in Django | 4,983,873 | 2 | 2011-02-13T11:31:55Z | 4,983,895 | 11 | 2011-02-13T11:37:56Z | [
"python",
"django",
"django-models"
] | I was looking if Django had some kind of `create_or_get` method but it seems that it doesn't have one. What I'm looking for the method to is that if the record doesn't exist, it is created but if it exits, it is returned.
I wrote one and here's what it looks like:
```
def create_or_get(self, url):
try:
re... | There is already [get\_or\_create](http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create), to be used like:
```
obj, created = MyModel.objects.get_or_create(keywordArguments)
``` |
Python subprocess get children's output to file and terminal? | 4,984,428 | 12 | 2011-02-13T13:35:23Z | 4,985,080 | 18 | 2011-02-13T15:43:08Z | [
"python",
"subprocess",
"parent"
] | I'm running a script that executes a number of executables by using
```
subprocess.call(cmdArgs,stdout=outf, stderr=errf)
```
when `outf`/`errf` is either None or a file descriptor (different files for `stdout`/`stderr`).
Is there any way I can execute each exe so that the stdout and stderr will be written to the fi... | The [`call()`](http://docs.python.org/library/subprocess.html#subprocess.call) function is just [`Popen(*args, **kwargs).wait()`](http://svn.python.org/view/python/trunk/Lib/subprocess.py?view=markup). You could call `Popen` directly and use `stdout=PIPE` argument to read from `p.stdout`:
```
import sys
from subproces... |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 4,984,667 | 75 | 2011-02-13T14:26:39Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | You can have all legal string characters as part of the key if you use array notation.
For example, `obj['!#$%^&*()_']` |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 4,984,668 | 15 | 2011-02-13T14:26:46Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | What if you wanted a key which was a method, such as `__eq__` or `__getattr__`?
And you wouldn't be able to have an entry that didn't start with a letter, so using `0343853` as a key is out.
And what if you didn't want to use a string? |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 4,984,671 | 8 | 2011-02-13T14:27:17Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | It doesn't work in generality. Not all valid dict keys make addressable attributes ("the key"). So, you'll need to be careful.
Python objects are all basically dictionaries. So I doubt there is much performance or other penalty. |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 4,984,707 | 9 | 2011-02-13T14:34:14Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | tuples can be used dict keys. How would you access tuple in your construct?
Also, [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple) is a convenient structure which can provide values via the attribute access. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.