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 |
|---|---|---|---|---|---|---|---|---|---|
How to include package data with setuptools/distribute? | 7,522,250 | 58 | 2011-09-22T22:35:23Z | 34,227,576 | 8 | 2015-12-11T15:56:28Z | [
"python",
"setuptools",
"distribute"
] | When using setuptools/distribute, I can not get the installer to pull in any [`package_data`](https://pythonhosted.org/setuptools/setuptools.html#including-data-files) files. Everything I've read says that the following is the correct way to do it. Can someone please advise?
```
setup(
name='myapp',
packages=fin... | `include_package_data=True` worked for me.
If you use git, remember to include `setuptools-git` in `install_requires`. Far less boring than having a `Manifest` or including all path in `package_data` ( in my case it's a django app with all kind of statics )
( pasted the comment I made, as [k3-rnc](http://stackoverflo... |
How can I turn a string into a list in Python? | 7,522,533 | 5 | 2011-09-22T23:08:41Z | 7,522,547 | 17 | 2011-09-22T23:10:01Z | [
"python",
"string",
"list"
] | How can I turn a string (like `'hello'`) into a list (like `[h,e,l,l,o]`)? | The `list()` function [[docs](http://docs.python.org/library/functions.html#list)] will convert a string into a list of single-character strings.
```
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
```
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access in... |
How do you read a specific line of a text file in Python? | 7,523,001 | 2 | 2011-09-23T00:25:14Z | 7,523,021 | 8 | 2011-09-23T00:28:10Z | [
"python",
"line"
] | I'm having trouble reading an entire specific line of a text file using Python. I currently have this:
```
load_profile = open('users/file.txt', "r")
read_it = load_profile.readline(1)
print read_it
```
Of course this will just read one byte of the first line, which is not what I want. I also tried Google but didn't ... | What are the conditions of this line? Is it at a certain index? Does it contain a certain string? Does it match a regex?
This code will match a single line from the file based on a string:
```
load_profile = open('users/file.txt', "r")
read_it = load_profile.read()
myLine = ""
for line in read_it.splitlines():
if... |
Unable to use wx.NotificationMessage properly with wxPython | 7,523,511 | 5 | 2011-09-23T02:00:14Z | 7,526,659 | 9 | 2011-09-23T09:08:38Z | [
"python",
"notifications",
"wxpython",
"message",
"wx"
] | I recently upgraded to the development release of wxPython (wxPython 2.9.2.4) since I needed the functionality of wx.NotificationMessage within my application. I have been trying unsuccessfully to create notification bubbles on certain user events due to something I think might be a possible bug. Before submitting such... | I would not recommend using 2.9 just yet. I have encountered some strange bugs when trying it out.
You can have the same functionality in 2.8. I am using somewhat modified code that I have found some time ago.
```
import wx, sys
try:
import win32gui #, win32con
WIN32 = True
except:
WIN32 = False
class B... |
How to use python timeit when passing variables to functions? | 7,523,767 | 41 | 2011-09-23T02:52:37Z | 7,523,791 | 10 | 2011-09-23T02:57:06Z | [
"python",
"debugging",
"benchmarking"
] | I'm struggling with this using timeit and was wondering if anyone had any tips
Basically I have a function(that I pass a value to) that I want to test the speed of and created this:
```
if __name__=='__main__':
from timeit import Timer
t = Timer(superMegaIntenseFunction(10))
print t.timeit(number=1)
```
... | You should be passing a string. i.e.
```
t = Timer('superMegaIntenseFunction(10)','from __main__ import superMegaIntenseFunction')
``` |
How to use python timeit when passing variables to functions? | 7,523,767 | 41 | 2011-09-23T02:52:37Z | 7,523,810 | 62 | 2011-09-23T03:01:04Z | [
"python",
"debugging",
"benchmarking"
] | I'm struggling with this using timeit and was wondering if anyone had any tips
Basically I have a function(that I pass a value to) that I want to test the speed of and created this:
```
if __name__=='__main__':
from timeit import Timer
t = Timer(superMegaIntenseFunction(10))
print t.timeit(number=1)
```
... | Make it a callable:
```
if __name__=='__main__':
from timeit import Timer
t = Timer(lambda: superMegaIntenseFunction(10))
print t.timeit(number=1)
```
Should work |
How to use python timeit when passing variables to functions? | 7,523,767 | 41 | 2011-09-23T02:52:37Z | 7,523,931 | 16 | 2011-09-23T03:29:31Z | [
"python",
"debugging",
"benchmarking"
] | I'm struggling with this using timeit and was wondering if anyone had any tips
Basically I have a function(that I pass a value to) that I want to test the speed of and created this:
```
if __name__=='__main__':
from timeit import Timer
t = Timer(superMegaIntenseFunction(10))
print t.timeit(number=1)
```
... | `Timer(superMegaIntenseFunction(10))` means "call `superMegaIntenseFunction(10)`, then pass the result to `Timer`". That's clearly not what you want. `Timer` expects either a callable (just as it sounds: something that can be called, such as a function), or a string (so that it can interpret the contents of the string ... |
Outdated book description of Try-Except-Finally statement | 7,524,728 | 8 | 2011-09-23T05:37:18Z | 7,524,752 | 14 | 2011-09-23T05:41:05Z | [
"python",
"exception",
"python-2.x",
"python-2.5"
] | I am following `Apress, Beginning Python from Novice to Professional` book. It is mentioned that:
> finally. You can use try/finally if you need to make sure that some
> code (for example, cleanup code) is executed regardless of whether an
> exception is raised or not. This code is then put in the finally
> clause. No... | This has been fixed since python 2.5, and is clearly noted in the [documentation](http://docs.python.org/whatsnew/2.5.html#pep-341)
In other words, your book is incorrect / out of date |
what's the overhead of passing python callback functions to Fortran subroutines? | 7,524,941 | 5 | 2011-09-23T06:10:07Z | 7,525,100 | 8 | 2011-09-23T06:27:11Z | [
"python",
"optimization",
"fortran",
"wrapper",
"f2py"
] | I just wrapped a Fortran 90 subroutine to python using F2PY. The subtlety here is that the Fortran subroutine aslo takes a python call-back function as one of its arguments:
```
SUBROUTINE f90foo(pyfunc, a)
real(kind=8),intent(in) :: a
!f2py intent(callback) pyfunc
external pyfunc
!f2py real*8 y,x
!f2py y = pyfunc(x)
... | In the code you posted, `a` is double precision float. Passing it from Fortran to Python means wrapping the Fortran double to a PyFloat object, which does have a cost. In the pure Python version, k is a PyFloat and you don't pay the price for wrapping it 1000 times.
Another issue is the function call itself. Calling P... |
How to "scale" a numpy array? | 7,525,214 | 14 | 2011-09-23T06:41:33Z | 7,525,243 | 12 | 2011-09-23T06:44:54Z | [
"python",
"arrays",
"numpy",
"scaling"
] | I would like to scale an array of shape (h, w) by a factor of n, resulting in an array of shape (h\*n, w\*n), with the.
Say that I have a 2x2 array:
```
array([[1, 1],
[0, 1]])
```
I would like to scale the array to become 4x4:
```
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, ... | You could use [`repeat`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html):
```
In [6]: a.repeat(2,axis=0).repeat(2,axis=1)
Out[6]:
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1]])
```
I am not sure if there's a neat way to combine the two operations into one. |
How to "scale" a numpy array? | 7,525,214 | 14 | 2011-09-23T06:41:33Z | 7,525,345 | 29 | 2011-09-23T06:58:09Z | [
"python",
"arrays",
"numpy",
"scaling"
] | I would like to scale an array of shape (h, w) by a factor of n, resulting in an array of shape (h\*n, w\*n), with the.
Say that I have a 2x2 array:
```
array([[1, 1],
[0, 1]])
```
I would like to scale the array to become 4x4:
```
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, ... | You should use the [Kronecker product](http://en.wikipedia.org/wiki/Kronecker_product), [numpy.kron](http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html):
> Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first
```
import numpy as np
a = np.array([[1,... |
django model polymorphism with proxy inheritance | 7,526,088 | 5 | 2011-09-23T08:13:16Z | 7,526,676 | 9 | 2011-09-23T09:10:56Z | [
"python",
"django",
"django-models",
"proxy-classes"
] | My `Discount` model describes common fields for all types of discounts in the system. I have some proxy models which describe concrete algorithm for culculating total. Base `Discount` class has a member field named `type`, which is a string identifing its type and its related class.
```
class Discount(models.Model):
... | Your init method needs to look like this instead:
```
def __init__(self, *args, **kwargs):
super(Discount, self).__init__(*args, **kwargs)
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
```
You need to call super's `__init__` before you will be able to access `se... |
Is it possible to set the python -O (optimize) flag within a script? | 7,527,055 | 8 | 2011-09-23T09:42:53Z | 7,527,449 | 10 | 2011-09-23T10:15:05Z | [
"python",
"optimization",
"runtime",
"assert",
"conditional-compilation"
] | I'd like to set the optimize flag (`python -O myscript.py`) at **runtime** within a python script based on a command line argument to the script like `myscript.py --optimize` or `myscript --no-debug`. I'd like to skip `assert` statements without iffing all of them away. Or is there a better way to efficiently ignore se... | `-O` is a compiler flag, you can't set it at runtime because the script already has been compiled by then.
Python has nothing comparable to compiler macros like `#if`.
Simply write a `start_my_project.sh` script that sets these flags. |
How do I write data to csv file in columns and rows from a list in python? | 7,528,801 | 8 | 2011-09-23T12:16:50Z | 7,529,487 | 8 | 2011-09-23T13:11:49Z | [
"python",
"list",
"csv"
] | everyone.I have a list of lists and I want to write them in a csv file with columns and rows.I have tried the writerows but it isn't what I want.An example of my list is the following:
```
[[1, 2], [2, 3], [4, 5]]
```
Thanks for any help.
With this :
```
example=csv.writer(open('test.csv', 'wb'), delimiter=' ')
exa... | ```
>>> import csv
>>> with open('test.csv', 'wb') as f:
... wtr = csv.writer(f, delimiter= ' ')
... wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
... for line in f:
... print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>
```
To get it so... |
How do I write data to csv file in columns and rows from a list in python? | 7,528,801 | 8 | 2011-09-23T12:16:50Z | 7,529,730 | 9 | 2011-09-23T13:30:36Z | [
"python",
"list",
"csv"
] | everyone.I have a list of lists and I want to write them in a csv file with columns and rows.I have tried the writerows but it isn't what I want.An example of my list is the following:
```
[[1, 2], [2, 3], [4, 5]]
```
Thanks for any help.
With this :
```
example=csv.writer(open('test.csv', 'wb'), delimiter=' ')
exa... | The provided examples, using `csv` modules, are great! Besides, you can always simply write to a text file using formatted strings, like the following tentative example:
```
l = [[1, 2], [2, 3], [4, 5]]
out = open('out.csv', 'w')
for row in l:
for column in row:
out.write('%d;' % column)
out.write('\n... |
Pythonic way to mix two lists | 7,529,376 | 8 | 2011-09-23T13:03:31Z | 7,529,422 | 14 | 2011-09-23T13:06:40Z | [
"python"
] | I have two lists of length n and n+1:
```
[a_1, a_2, ..., a_n]
[b_1, b_2, ..., b_(n+1)]
```
I want a function giving as a result a list with alternate elements from the two, that is
```
[b_1, a_1, ..., b_n, a_n, b_(n+1)]
```
The following works, but does not look smart:
```
def list_mixing(list_long,list_short):
... | ```
>>> import itertools
>>> a
['1', '2', '3', '4', '5', '6']
>>> b
['a', 'b', 'c', 'd', 'e', 'f']
>>> list(itertools.chain.from_iterable(zip(a,b)))
['1', 'a', '2', 'b', '3', 'c', '4', 'd', '5', 'e', '6', 'f']
```
`zip()` produces a iterable with the length of shortest argument. You can either append `a[-1]` to the re... |
Pythonic way to mix two lists | 7,529,376 | 8 | 2011-09-23T13:03:31Z | 7,529,533 | 10 | 2011-09-23T13:15:49Z | [
"python"
] | I have two lists of length n and n+1:
```
[a_1, a_2, ..., a_n]
[b_1, b_2, ..., b_(n+1)]
```
I want a function giving as a result a list with alternate elements from the two, that is
```
[b_1, a_1, ..., b_n, a_n, b_(n+1)]
```
The following works, but does not look smart:
```
def list_mixing(list_long,list_short):
... | IMHO the best way is:
```
result = [item for sublist in zip(a,b) for item in sublist]
```
It's also faster than sum and reduce ways.
**UPD** Sorry missed that your second list is bigger by one element :)
There is another crazy way:
```
result = [item for sublist in map(None, a, b) for item in sublist][:-1]
``` |
Altering numpy function output array in place | 7,529,786 | 6 | 2011-09-23T13:34:50Z | 7,534,456 | 12 | 2011-09-23T20:28:05Z | [
"python",
"arrays",
"function",
"numpy",
"in-place"
] | I'm trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be:
```
def original_func(A):
return A[1:] + A[:-1]
```
For speed-up and to avoid allocating a new output array for each function call, I would like to have the output array as an a... | If you want to perform the operation in-place, do
```
def inplace_func(A, out):
np.add(A[1:], A[:-1], out)
```
This does not create any temporaries (which `A[1:] + A[:-1]`) does.
All Numpy binary operations have corresponding functions, check the list here: <http://docs.scipy.org/doc/numpy/reference/ufuncs.html#... |
ctypes and passing a by reference to a function | 7,530,473 | 6 | 2011-09-23T14:20:28Z | 7,531,537 | 8 | 2011-09-23T15:44:11Z | [
"python",
"ctypes",
"libpcap"
] | I'm trying to use libpcap in python3 using ctypes.
given the following function in C
```
pcap_lookupnet(dev, &net, &mask, errbuf)
```
in python I have the following
```
pcap_lookupnet = pcap.pcap_lookupnet
mask = ctypes.c_uint32
net = ctypes.c_int32
if(pcap_lookupnet(dev,net,mask,errbuf) == -1):
print("Error coul... | You need to create instances for `net` and `mask`, and use `byref` to pass them.
```
mask = ctypes.c_uint32()
net = ctypes.c_int32()
pcap_lookupnet(dev, ctypes.byref(net), ctypes.byref(mask), errbuf)
``` |
Python range function | 7,531,945 | 14 | 2011-09-23T16:14:49Z | 7,531,966 | 19 | 2011-09-23T16:16:24Z | [
"python",
"range"
] | Say I want to loop from 0 to 100 but with a step of 1/2. If you try
```
for i in range(0, 100, 0.5):
whatever
```
it calls an error saying the step must not be 0. Is there any built in way to do something like this?
I'm using Python 2.something by the way.
Thanks | ```
In [1]: for i in range(0, int(100 / 0.5)):
...: print 0.5 * i
...:
...:
0.0
0.5
1.0
1.5
...
98.0
98.5
99.0
99.5
```
If you can use `numpy`, then [`numpy.arange(0, 100, 0.5)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html) would also do the trick. |
Python range function | 7,531,945 | 14 | 2011-09-23T16:14:49Z | 7,532,000 | 8 | 2011-09-23T16:19:39Z | [
"python",
"range"
] | Say I want to loop from 0 to 100 but with a step of 1/2. If you try
```
for i in range(0, 100, 0.5):
whatever
```
it calls an error saying the step must not be 0. Is there any built in way to do something like this?
I'm using Python 2.something by the way.
Thanks | If you have `numpy`, here are two ways to do it:
```
numpy.arange(0, 100, 0.5)
numpy.linspace(0, 100, 200, endpoint=False)
``` |
Why is __init__.py not being called? | 7,533,480 | 6 | 2011-09-23T18:45:15Z | 7,533,499 | 10 | 2011-09-23T18:48:05Z | [
"python"
] | I'm using Python 2.7 and have the following files:
```
./__init__.py
./aoeu.py
```
`__init__.py` has the following contents:
```
aoeu aoeuaoeu aoeuaoeuaoeu
```
so I would expect running aoeu.py to error when Python tries to load `__init__.py`, but it doesn't. The behavior is the same whether PYTHONPATH is set to '.... | `__init__.py` makes the enclosing directory a package. It won't be executed unless you actually try to import the package directly. |
How to define url which accept everykind of strings in django | 7,534,436 | 4 | 2011-09-23T20:25:16Z | 7,534,503 | 8 | 2011-09-23T20:34:16Z | [
"python",
"django",
"django-urls"
] | In django, I defined url like that
```
(r'^checkstring/(?P<string>\w+)/$',views.check_str,name='check str')
```
But, When i enter string inputs like ibrahim.yilmaz, ibrahi!m or ibrahim@ibrahim.com, it returns http 404.
So how can i write the url which accept everykind of string?
any help will be appreciated.
İbrah... | Django uses regular expressions to match incoming requests. In python a dot (.) matches any character except a newline. See [docs](http://docs.python.org/library/re.html) for more information and try:
```
(r'^checkstring/(?P<string>.+)/$',views.check_str,name='check str')
```
Also keep in mind that this will accept a... |
matplotlib does not show my drawings although I call pyplot.show() | 7,534,453 | 98 | 2011-09-23T20:27:47Z | 7,534,680 | 113 | 2011-09-23T20:49:48Z | [
"python",
"matplotlib"
] | I need your help about matplotlib. Yes, I did not forget calling the pyplot.show().
### $ ipython --pylab
```
import matplotlib.pyplot as p
p.plot(range(20), range(20))
```
It returns `matplotlib.lines.Line2D at 0xade2b2c` as the output.
```
p.show()
```
There is nothing to happen. No error message. No new window... | If I set my backend to `template` in `~/.matplotlib/matplotlibrc`,
then I can reproduce your symptoms:
~/.matplotlib/matplotlibrc:
```
# backend : GtkAgg
backend : template
```
Note that the file `matplotlibrc` may not be in directory `~/.matplotlib/`. In this case, the following code shows where it is:
`... |
matplotlib does not show my drawings although I call pyplot.show() | 7,534,453 | 98 | 2011-09-23T20:27:47Z | 13,360,729 | 9 | 2012-11-13T12:25:25Z | [
"python",
"matplotlib"
] | I need your help about matplotlib. Yes, I did not forget calling the pyplot.show().
### $ ipython --pylab
```
import matplotlib.pyplot as p
p.plot(range(20), range(20))
```
It returns `matplotlib.lines.Line2D at 0xade2b2c` as the output.
```
p.show()
```
There is nothing to happen. No error message. No new window... | For future reference,
I have encountered the same problem -- pylab was not showing under ipython. The problem was fixed by changing ipython's config file {ipython\_config.py}. In the config file
`c.InteractiveShellApp.pylab = 'auto'`
I changed 'auto' to 'qt' and now I see graphs |
matplotlib does not show my drawings although I call pyplot.show() | 7,534,453 | 98 | 2011-09-23T20:27:47Z | 13,982,451 | 53 | 2012-12-21T00:05:39Z | [
"python",
"matplotlib"
] | I need your help about matplotlib. Yes, I did not forget calling the pyplot.show().
### $ ipython --pylab
```
import matplotlib.pyplot as p
p.plot(range(20), range(20))
```
It returns `matplotlib.lines.Line2D at 0xade2b2c` as the output.
```
p.show()
```
There is nothing to happen. No error message. No new window... | I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using
```
pip install matplotlib
```
To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its depende... |
matplotlib does not show my drawings although I call pyplot.show() | 7,534,453 | 98 | 2011-09-23T20:27:47Z | 29,121,815 | 9 | 2015-03-18T12:16:03Z | [
"python",
"matplotlib"
] | I need your help about matplotlib. Yes, I did not forget calling the pyplot.show().
### $ ipython --pylab
```
import matplotlib.pyplot as p
p.plot(range(20), range(20))
```
It returns `matplotlib.lines.Line2D at 0xade2b2c` as the output.
```
p.show()
```
There is nothing to happen. No error message. No new window... | %matplotlib inline
For me working with notebook, adding the above line before the plot works. |
selecting an iframe using python selenium | 7,534,622 | 10 | 2011-09-23T20:43:54Z | 24,286,392 | 16 | 2014-06-18T13:05:38Z | [
"python",
"selenium"
] | So, I was absolutely baffled as to how to do this in Selenium, and couldn't find the answer anywhere, so I'm sharing my experience.
I was trying to select an iframe and having no luck (or not repeatably anyway). The HTML looked like this:
```
<iframe id="upload_file_frame" width="100%" height="465px" frameborder=... | This worked for me with Python (v. 2.7), webdriver & Selenium when testing with iframes and trying to insert data within an iframe:
```
self.driver = webdriver.Firefox()
## Give time for iframe to load ##
time.sleep(3)
## You have to switch to the iframe like so: ##
driver.switch_to_frame(driver.find_element_by_tag_n... |
Python sys.exit() help? | 7,535,735 | 3 | 2011-09-23T23:09:31Z | 7,535,796 | 7 | 2011-09-23T23:18:37Z | [
"python"
] | I am working in Python and am trying to have a line of code execute and after it executes I am calling `sys.exit()` to have the script itself "exit." However, it seems that `sys.exit()` is executing before the line of code above it executes. Below is the code I am trying to implement:
```
if something == True:
sel... | There is probably some buffering or asynchrony in `self.redirect()`. People often run into a similar problem when they do a `print`, followed by `sys.exit()`: the `print` output gets buffered, and then the process exits before the in-process output buffer is flushed).
You can work around this by flushing buffers and/o... |
Why doesn't this closure modify the variable in the enclosing scope? | 7,535,857 | 16 | 2011-09-23T23:30:34Z | 7,535,919 | 23 | 2011-09-23T23:45:31Z | [
"python",
"closures",
"generator"
] | This bit of Python does not work:
```
def make_incrementer(start):
def closure():
# I know I could write 'x = start' and use x - that's not my point though (:
while True:
yield start
start += 1
return closure
x = make_incrementer(100)
iter = x()
print iter.next() # E... | Whenever you assign a variable inside of a function it will be a local variable for that function. The line `start += 1` is assigning a new value to `start`, so `start` is a local variable. Since a local variable `start` exists the function will not attempt to look in the global scope for `start` when you first try to ... |
How to increment a variable on a for loop in jinja template? | 7,537,439 | 25 | 2011-09-24T06:31:27Z | 7,537,466 | 57 | 2011-09-24T06:38:33Z | [
"python",
"jinja2",
"jinja"
] | I would like to do something like:
variable p is from test.py wich is a list ['a','b','c','d']
```
{% for i in p %}
{{variable++}}
{{variable}}
```
result output is:
1 2 3 4 | You could use `set` to increment a counter:
```
{% set count = 1 %}
{% for i in p %}
{{ count }}
{% set count = count + 1 %}
{% endfor %}
```
Or you could use `loop.index`:
```
{% for i in p %}
{{ loop.index }}
{% endfor %}
```
Check the [template designer documentation](http://jinja.pocoo.org/docs/templates/... |
How to increment a variable on a for loop in jinja template? | 7,537,439 | 25 | 2011-09-24T06:31:27Z | 32,700,975 | 11 | 2015-09-21T17:12:22Z | [
"python",
"jinja2",
"jinja"
] | I would like to do something like:
variable p is from test.py wich is a list ['a','b','c','d']
```
{% for i in p %}
{{variable++}}
{{variable}}
```
result output is:
1 2 3 4 | As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.
You can defeat this behavior by using an object rather than a scalar for 'count':
```
{% set count = [1] %}
```
You can now manipulate count inside a forloop or even an %include%. Here's how I increment... |
Efficiently average the second column by intervals defined by the first column | 7,538,552 | 7 | 2011-09-24T10:52:33Z | 7,539,263 | 7 | 2011-09-24T13:16:13Z | [
"python",
"perl",
"awk",
"data.table"
] | There are two numeric columns in a data file. I need to calculate the average of the second column by intervals (such as 100) of the first column.
I can program this task in R, but my R code is really slow for a relatively large data file (millions of rows, with the value of first column changing between 1 to 33132539... | You don't really need to set up an output data.frame but you can if you want. Here is how I would have coded it, and I guarantee it will be fast.
```
> dat$incrmt <- dat$V1 %/% 100
> dat
V1 V2 incrmt
1 5380 30.07383 53
2 5390 30.87000 53
3 5393 0.07383 53
4 5404 6.00000 54
5 5428 30.0... |
virtualenvwrapper functions unavailable in shell scripts | 7,538,628 | 40 | 2011-09-24T11:06:40Z | 7,539,449 | 44 | 2011-09-24T13:53:50Z | [
"python",
"bash",
"virtualenv",
"virtualenvwrapper"
] | So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't r... | Just source the `virtualenvwrapper.sh` script in your script to import the virtualenvwrapper's functions. You should then be able to use the `workon` function in your script.
And maybe better, you could create a shell script (you could name it `venv-run.sh` for example) to run any Python script into a given virtualenv... |
zeromq: how to prevent infinite wait? | 7,538,988 | 43 | 2011-09-24T12:25:59Z | 7,540,299 | 51 | 2011-09-24T16:33:21Z | [
"python",
"zeromq"
] | I just got started with ZMQ. I am designing an app whose workflow is:
1. one of many clients (who have random PULL addresses) PUSH a request to a server at 5555
2. the server is forever waiting for client PUSHes. When one comes, a worker process is spawned for that particular request. Yes, worker processes can exist c... | If you are using zeromq >= 3.0, then you can set the RCVTIMEO socket option:
```
client_receiver.RCVTIMEO = 1000 # in milliseconds
```
But in general, you can use pollers:
```
poller = zmq.Poller()
poller.register(client_receiver, zmq.POLLIN) # POLLIN for recv, POLLOUT for send
```
And `poller.poll()` takes a timeo... |
zeromq: how to prevent infinite wait? | 7,538,988 | 43 | 2011-09-24T12:25:59Z | 7,552,686 | 15 | 2011-09-26T08:47:25Z | [
"python",
"zeromq"
] | I just got started with ZMQ. I am designing an app whose workflow is:
1. one of many clients (who have random PULL addresses) PUSH a request to a server at 5555
2. the server is forever waiting for client PUSHes. When one comes, a worker process is spawned for that particular request. Yes, worker processes can exist c... | This was a **quick hack** I made after I referred user938949's answer and <http://taotetek.wordpress.com/2011/02/02/python-multiprocessing-with-zeromq/> . If you do better, please post your answer, **I will recommend your answer**.
For those wanting **lasting solutions** on reliability, refer <http://zguide.zeromq.org... |
How to construct a defaultdict from a dictionary? | 7,539,115 | 36 | 2011-09-24T12:47:55Z | 7,539,127 | 33 | 2011-09-24T12:50:04Z | [
"python",
"dictionary"
] | If I have `d=dict(zip(range(1,10),range(50,61)))` how can I build a `collections.defaultdict` out of the `dict`?
The only argument `defaultdict` seems to take is the factory function, will I have to initialize and then go through the original `d` and update the `defaultdict`? | [Read the docs](http://docs.python.org/library/collections.html#collections.defaultdict):
> The first argument provides the initial value for the default\_factory
> attribute; it defaults to None. **All remaining arguments are treated
> the same as if they were passed to the dict constructor**, including
> keyword arg... |
Avoid a Newline at End of File - Python | 7,539,146 | 3 | 2011-09-24T12:53:52Z | 7,539,151 | 7 | 2011-09-24T12:55:16Z | [
"python",
"list"
] | I'd like to avoid writing a newline character to the end of a text file in python. This is a problem I have a lot, and I am sure can be fixed easily. Here is an example:
```
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
for i in list:
fileout.write('%s\n' % (i))
```
This prints a \n character at the ... | ```
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))
``` |
GUI layout using Tk Grid Geometry Manager | 7,539,401 | 8 | 2011-09-24T13:42:27Z | 7,539,500 | 8 | 2011-09-24T14:02:40Z | [
"python",
"user-interface",
"layout",
"grid",
"tkinter"
] | Building a small application for personal use with Python and thought I'd try my hand with a little GUI programming using Tkinter. This is the GUI I've created so far:

**Application doubts:**
How can I make sure that the three LableFrames - A, B and C i... | If you use the same columnspan and use sticky='WE' on all three LabelFrames then they should have the same width. For example, you want to use
```
stepTwo = Tkinter.LabelFrame(form, text=" 2. Enter Table Details: ")
stepTwo.grid(row=2, columnspan=7, sticky='WE', \
padx=5, pady=5, ipadx=5, ipady=5)
```
**... |
How can I compare two lists in python, and return that the second need to have the same values regardless of order? | 7,539,579 | 6 | 2011-09-24T14:18:39Z | 7,539,589 | 11 | 2011-09-24T14:20:31Z | [
"python",
"list",
"comparison"
] | ```
a = [1, 2, 3, 4]
b = [2, 4, 3, 1]
c = [2, 3]
```
When comparing a to b, should return `True`: all items in `a` are presented in `b`, and all items in `b` are presented in `a`.
When comparing `a` to `c`, should return `False`: there are items in `a` that don't exist on `c`.
What is the *pythonic* way to do it? | Sort, then compare.
```
sorted(a) == sorted(b)
``` |
Finding whether a string starts with one of a list's variable-length prefixes | 7,539,959 | 14 | 2011-09-24T15:29:04Z | 7,540,116 | 8 | 2011-09-24T16:01:41Z | [
"python",
"string",
"variable-length",
"prefixes"
] | I need to find out whether a name starts with any of a list's prefixes and then remove it, like:
```
if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
name = name[2:]
```
The above only works for list prefixes with a length of two. I need the same functionality for **variable-length prefixes**.
Ho... | A bit hard to read, but this works:
```
name=name[len(filter(name.startswith,prefixes+[''])[0]):]
``` |
Finding whether a string starts with one of a list's variable-length prefixes | 7,539,959 | 14 | 2011-09-24T15:29:04Z | 7,540,136 | 26 | 2011-09-24T16:05:50Z | [
"python",
"string",
"variable-length",
"prefixes"
] | I need to find out whether a name starts with any of a list's prefixes and then remove it, like:
```
if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
name = name[2:]
```
The above only works for list prefixes with a length of two. I need the same functionality for **variable-length prefixes**.
Ho... | > str.startswith(prefix[, start[, end]])¶
>
> Return True if string starts with the prefix, otherwise return
> False. prefix can also be a tuple of prefixes to look for. With
> optional start, test string beginning at that position. With
> optional end, stop comparing string at that position. |
Escaping strings with python mysql.connector | 7,540,803 | 5 | 2011-09-24T17:55:38Z | 7,540,828 | 7 | 2011-09-24T17:58:46Z | [
"python",
"mysql"
] | I am trying to insert a bunch of strings into mysql using python and [mysql.connector](https://launchpad.net/myconnpy). My current code looks something like this:
```
db = mysql.connector.Connect('config blah blah')
cursor = db.cursor()
data = (somestring1, somestring2)
sql = "INSERT INTO mytable (col1, col2) VALUES (... | Since mysql.connector is [DB API v2.0](http://www.python.org/dev/peps/pep-0249/) compliant, you do not need to escape the data yourself, it does it automatically for you. |
How is rate_limit enforced in Celery? | 7,541,931 | 6 | 2011-09-24T21:06:47Z | 11,125,501 | 16 | 2012-06-20T18:05:01Z | [
"python",
"django",
"asynchronous",
"queue",
"celery"
] | I'm running a Django website where I use Celery to implement preventive caching - that is, I calculate and cache results even before they are requested by the user.
However, one of my Celery tasks could, in some situation, be called a lot (I'd say sightly quicker than it completes on average, actually). I'd like to ra... | Rate limited tasks are never dropped, they are queued internally in the worker so that they execute as soon as they are allowed to run.
The token bucket algorithm does not specify anything about dropping packets (it is an option, but Celery does not do that). |
is python capable of running on multiple cores? | 7,542,957 | 18 | 2011-09-25T01:00:24Z | 7,542,982 | 23 | 2011-09-25T01:06:56Z | [
"python",
"multithreading"
] | Question: Because of python's use of "GIL" is python capable running its separate threads simultaneously?
---
Info:
After reading [this](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock) I came away rather uncertain on whether or not python is capable of taking advantage of a multi... | The answer is "Yes, But..."
But cPython cannot when you are using regular threads for concurrency.
You can either use something like [`multiprocessing`](http://docs.python.org/library/multiprocessing.html), [`celery`](http://celeryproject.org/) or [`mpi4py`](http://mpi4py.scipy.org/) to split the parallel work into a... |
is python capable of running on multiple cores? | 7,542,957 | 18 | 2011-09-25T01:00:24Z | 7,542,983 | 10 | 2011-09-25T01:06:58Z | [
"python",
"multithreading"
] | Question: Because of python's use of "GIL" is python capable running its separate threads simultaneously?
---
Info:
After reading [this](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock) I came away rather uncertain on whether or not python is capable of taking advantage of a multi... | Python **threads** cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global interpreter lock) in the C implementation of python (cPython) which is almost certainly what you use.
The workaround is the **`multiprocessing`** module <http://www.python.org/dev/peps/pep-03... |
How to select elements row-wise from a NumPy array? | 7,543,250 | 2 | 2011-09-25T02:24:07Z | 7,543,388 | 10 | 2011-09-25T03:04:56Z | [
"python",
"multidimensional-array",
"numpy",
"scipy"
] | I have an array like this numpy array
```
dd= [[foo 0.567 0.611]
[bar 0.469 0.479]
[noo 0.220 0.269]
[tar 0.480 0.508]
[boo 0.324 0.324]]
```
How would one loop through array
selecting foo and getting 0.567 0.611 as floats as a singleton.
Then select bar and getting 0.469 0.479 as floats as a sing... | You have put the *NumPy* tag on your Question, so i'll assume you want NumPy syntax, which the answer before mine doesn't use.
If in fact you wish to use NumPy, then you likely don't want the strings in your array, otherwise you will also have to represent your floats as strings.
What you are looking for is ***the Nu... |
How to launch a pdftk subprocess while in wsgi? | 7,543,452 | 7 | 2011-09-25T03:26:38Z | 7,543,682 | 7 | 2011-09-25T04:33:29Z | [
"python",
"django",
"subprocess",
"mod-wsgi",
"pdftk"
] | I need to launch a pdftk process while serving a web request in Django, and wait for it to finish. My current pdftk code looks like this:
```
proc = subprocess.Popen(["/usr/bin/pdftk",
"/tmp/infile1.pdf",
"/tmp/infile2.pdf",
"cat", "output",... | Try with absolute file system paths to input and output files. The current working directory under Apache will not be same directory as run server and could be anything.
---
Second attempt after eliminating the obvious.
The pdftk program is a Java program which is relying on being able to generate/receive SIGPWR sig... |
Python + Gevent + MultiProcessing : Very Easy beginner question on my first Program | 7,543,579 | 4 | 2011-09-25T04:04:26Z | 7,547,929 | 10 | 2011-09-25T19:17:12Z | [
"python",
"gevent"
] | Anyone know what is wrong with this code? It simply "loads" forever. No output. "Sites" is a list of a few dozen strings.
```
num_worker_threads = 30
def mwRegisterWorker():
while True:
try:
print q.get()
finally:
pass
q = multiprocessing.JoinableQueue()
for i in range(num... | `gevent.spawn()` creates greenlets not processes (even more: all greenlets run in a single OS thread). So `multiprocessing.JoinableQueue` is not appropriate here.
`gevent` is based on *cooperative* multitasking i.e, until you call a blocking function that switches to `gevent`'s event loop other greenlets won't run. Fo... |
How to convert pointer to c array to python array | 7,543,675 | 9 | 2011-09-25T04:30:43Z | 7,555,971 | 21 | 2011-09-26T13:39:44Z | [
"python",
"ctypes"
] | I have a C++ callback function that calls into Python using ctypes. This function's parameters are a pointer to an array of double and the number of elements.
There are a lot of elements, approximately 2,000,000. I need to send this into scipy functions.
The C++ prototype is :
```
bool (*ptsetDataSource)(double*, lo... | If `Data` were `(c_double*DataLength.value)` array then you could:
```
a = np.frombuffer(Data) # no copy. Changes in `a` are reflected in `Data`
```
If `Data` is a `POINTER(c_double)` you could get numpy array using [`numpy.fromiter()`](http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.fromiter.html?hig... |
How to set cookies with GAE/Python for 1 month? | 7,544,197 | 4 | 2011-09-25T07:21:21Z | 7,544,582 | 7 | 2011-09-25T09:02:34Z | [
"python",
"google-app-engine",
"datetime",
"cookies"
] | I need to implement the following:
1. User input user id and pass
2. We validate that on another server
3. If they are correct, cookies with these details should be saved for one month
4. Each time user uses my site, we should look for cookies
5. If they are not found - go to step 1
How can I set cookies for 1 month?... | You can use webapp.Response.set\_cookie() method:
```
import datetime
self.response.set_cookie('name', 'value', expires=datetime.datetime.now(), path='/', domain='example.com')
```
Formatting dates for cookies is something like this:
```
print (datetime.datetime.now() + datetime.timedelta(weeks=4)).strftime('%a, %d... |
"sys.getrefcount()" return value | 7,544,395 | 5 | 2011-09-25T08:13:51Z | 7,544,636 | 9 | 2011-09-25T09:13:28Z | [
"python"
] | Why does
```
sys.getrefcount()
```
return 3 for every large number or simple string?Does that mean that 3 objects reside somewhere in the Program?Also,why doesn't setting x=(very large number) increase that object's ref count?Do those 3 ref counts result from my call to getrefcount?
Thank you for clarifying this.
fo... | Large integer objects are not reused by the interpretor, so you get two distinct objects:
```
>>> a = 11111
>>> b = 11111
>>> id(a)
40351656
>>> id(b)
40351704
```
sys.getrefcount(11111) always returns the same number because it measures the reference count of a fresh object.
For small integers, Python always reuses... |
Is inline code allowed in Jinja templates? | 7,544,461 | 13 | 2011-09-25T08:31:05Z | 7,547,913 | 9 | 2011-09-25T19:14:59Z | [
"python",
"jinja2"
] | I'm [using Jinja](http://pypi.python.org/pypi/Jinja2/2.0) on my site and I like it.
I've come across a simple need. How to display today's date? **Is there a way to inline some Python code in a Jinja template?**
```
import datetime
now = datetime.datetime.utcnow()
print now.strftime("%Y-%m-%d %H:%M")
```
[This artic... | No, there is no way to inline Python into Jinja. However, you can add to the constructs that Jinja knows by extending the [Environment](http://jinja.pocoo.org/docs/api/#basics) of the template engine or the [global namespace](http://jinja.pocoo.org/docs/api/#the-global-namespace) available to all templates. Alternately... |
Python class inheriting multiprocessing, trouble with accessing class members | 7,545,385 | 4 | 2011-09-25T12:08:00Z | 7,545,418 | 9 | 2011-09-25T12:14:56Z | [
"python",
"multiprocessing"
] | In short, say I have the following:
```
import multiprocessing
class Worker(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
print "Init"
self.value = None
def run(self):
print "Running"
self.value = 1
p = Worker()
p.start()
p.join(... | The moment you say `p.start()`, a separate process is forked off of the main process. All variable values are copied. So the main process has one copy of `p`, and the forked process has a separate copy of `p`. The `Worker` modifies the forked process's copy of `p.value`, but the main process's `p.value` still is `None`... |
os.walk() strips polish characters | 7,545,511 | 6 | 2011-09-25T12:35:43Z | 7,545,547 | 7 | 2011-09-25T12:42:41Z | [
"python"
] | So what I'm trying to do is fix some id3tags of mp3 files. It all works, except for files with any kind of accent, because os.walk seems to strip them.
For example, I have the file `01.Co SÅychaÄ.mp3`, which in this code:
```
for root, dirs, files in os.walk(folder):
print files
```
Shows up as `['01.Co Slycha... | Did you define `folder` as a Unicode string? This has implications on how `os.walk()` matches its subdirectories, or better, the type of string that it returns.
```
>>> for a,b,c in os.walk("."):
... print b
... break
...
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'tcl', 'Tools']
>>> for a,b,c in os.walk(u"."):
... ... |
Switch between two frames in tkinter | 7,546,050 | 23 | 2011-09-25T14:14:04Z | 7,557,028 | 45 | 2011-09-26T14:55:21Z | [
"python",
"python-3.x",
"tkinter",
"frame"
] | I have built my first few scripts with a nice little GUI on them, as the tutorials have shown me, but none of them address what to do for a more complex program.
If you have something with a 'start menu', for your opening screen, and upon user selection you move to a different section of the program and redraw the scr... | One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Here's a bit of a contrived... |
numpy uint8 pixel wrapping solution | 7,547,557 | 15 | 2011-09-25T18:18:21Z | 7,547,657 | 19 | 2011-09-25T18:32:49Z | [
"python",
"numpy"
] | For an image processing class, I am doing point operations on monochrome images. Pixels are uint8 [0,255].
numpy uint8 will wrap. For example, 235+30 = 9. I need the pixels to saturate (max=255) or truncate (min=0) instead of wrapping.
My solution uses int32 pixels for the point math then converts to uint8 to save th... | Use [numpy.clip](http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html):
```
import numpy as np
np.clip(data32, 0, 255, out=data32)
data_u8 = data32.astype('uint8')
```
---
Note that you can also brighten images without numpy this way:
```
Import ImageEnhance
enhancer=ImageEnhance.Brightness(img)
outi... |
How to scrape a huge amounts of tweets | 7,547,646 | 5 | 2011-09-25T18:31:12Z | 7,547,721 | 7 | 2011-09-25T18:41:45Z | [
"python",
"twitter",
"screen-scraping"
] | I am building a project in python that needs to scrape huge and huge amounts of Twitter data. Something like 1 million users and all their tweets need to be scraped.
Previously I have used Tweepy and Twython, but hit the limit of Twitter very fast.
How do sentiment analysis companies etc. get their data? How do they ... | I don't know if this will work for what you're trying to do, but the [Tweets2011](http://trec.nist.gov/data/tweets/) dataset was recently released.
From the description:
> As part of the TREC 2011 microblog track, Twitter provided identifiers
> for approximately 16 million tweets sampled between January 23rd and
> Fe... |
How to scrape a huge amounts of tweets | 7,547,646 | 5 | 2011-09-25T18:31:12Z | 7,551,391 | 7 | 2011-09-26T06:35:58Z | [
"python",
"twitter",
"screen-scraping"
] | I am building a project in python that needs to scrape huge and huge amounts of Twitter data. Something like 1 million users and all their tweets need to be scraped.
Previously I have used Tweepy and Twython, but hit the limit of Twitter very fast.
How do sentiment analysis companies etc. get their data? How do they ... | If you want the *latest* tweets from specific users, Twitter offers the [Streaming API](https://dev.twitter.com/docs/streaming-api).
> The Streaming API is the real-time sample of the Twitter Firehose. This API is for those developers with data intensive needs. If you're looking to build a **data mining product** or a... |
Recreating a shell-like interpreter within python? | 7,548,042 | 2 | 2011-09-25T19:32:40Z | 7,548,069 | 15 | 2011-09-25T19:36:33Z | [
"python",
"string",
"parsing",
"shell",
"special-characters"
] | Before I sit down and start hacking it out, I thought I'd come here and see if you all had any tips or even if something like this has been done before.
I want to re-create a basic shell like syntax within a python program. In other words, when people run the file with python, they will be greeted with a little prompt... | Start with the `shlex` module:
```
$ pydoc shlex
Help on module shlex:
NAME
shlex - A lexical analyzer class for simple shell-like syntaxes.
```
You can use it like this:
```
>> import shlex
>> shlex.split('This "is a" test.')
['This', 'is a', 'test']
```
This just splits things up into logical tokens; it won'... |
python: class attributes and instance attributes | 7,548,546 | 5 | 2011-09-25T20:56:31Z | 7,548,659 | 7 | 2011-09-25T21:12:35Z | [
"python"
] | I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code:
```
>>> class Foo:
... a=1
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
1
>>> f1.a=5
>>> f1.a
5
>>> f2.a
1
```
Shouldn't f2.a also equal 5?
If a is defined as a list inste... | You're not doing the same thing in your second example. In you first example, you are assigning `f1.a` a new value:
```
f1.a = 5
```
In your second example, you are simply extending a list:
```
f1.a.append(5)
```
This doesn't change what `f1.a` is pointing to. If you were instead to do this:
```
f1.a = [5]
```
Yo... |
python: class attributes and instance attributes | 7,548,546 | 5 | 2011-09-25T20:56:31Z | 7,548,760 | 9 | 2011-09-25T21:30:22Z | [
"python"
] | I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code:
```
>>> class Foo:
... a=1
...
>>> f1=Foo();
>>> f2=Foo()
>>> f1.a
1
>>> f1.a=5
>>> f1.a
5
>>> f2.a
1
```
Shouldn't f2.a also equal 5?
If a is defined as a list inste... | Python's class attributes and object attributes are stored in separate [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries). For the object `f1`, these can be accessed via, respectively, `f1.__class__.__dict__` and `f1.__dict__`. Executing `print f1.__class__ is Foo` will output `True`.
Whe... |
why would spaces in a Python tuple matter? | 7,548,562 | 2 | 2011-09-25T20:58:50Z | 7,548,565 | 12 | 2011-09-25T21:00:40Z | [
"python",
"iterable-unpacking"
] | I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks!
```
jcomeau@intrepid:/tmp$ cat haversine.py
#!/usr/bin/python
def dms_to_floa... | The spaces should make no difference. The difference is due to the case: `SW` vs `Sw`.
You don't check for `SW` here:
```
compass in ['S', 'W', 'Sw']]
```
Perhaps change it to this:
```
compass.upper() in ['S', 'W', 'SW']]
``` |
Virtualenvwrapper.sh functions not available in bash shell | 7,548,893 | 2 | 2011-09-25T21:56:07Z | 7,548,938 | 7 | 2011-09-25T22:03:33Z | [
"python",
"bash",
"virtualenvwrapper"
] | I'm doing a new install of virtualenvwrapper, and for some reason after running
virtualenvwrapper.sh it's functions aren't available.
```
$ virtualenvwrapper.sh
creating.....
$ workon
workon: command not found
```
I know that it's running, aside from the successful creation of all the VE files, I've wrapped some of t... | Oh I see, the correct thing to do is:
```
$ source virtualenvwrapper.sh
```
it was on my PATH, and getting run in a subshell, I guess. |
Exception handling in Python Tornado | 7,549,120 | 4 | 2011-09-25T22:42:30Z | 7,623,570 | 10 | 2011-10-01T23:18:17Z | [
"python",
"exception-handling",
"tornado"
] | I am trying to handle exception occurred in `AsyncClient.fetch` in this way:
```
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado.stack_context import ExceptionStackContext
from tornado import ioloop
def handle_exc(*args):
print('Exception occured')
return... | According to the [Tornado documentation](http://www.tornadoweb.org/documentation/httpclient.html#tornado.httpclient.AsyncHTTPClient.fetch):
If an error occurs during the fetch, the HTTPResponse given to the callback has a non-None error attribute that contains the exception encountered during the request.
You can call... |
Use lambda expression to count the elements that I'm interested in Python | 7,549,525 | 15 | 2011-09-26T00:16:01Z | 7,549,544 | 19 | 2011-09-26T00:20:08Z | [
"python",
"lambda"
] | Can I use lambda expression to count the elements that I'm interested?
For example, when I need to count the elements in a list that is more than two, I tried this code which returns 0.
```
x = [1,2,3]
x.count(lambda x: x > 2)
``` | Note: "more than" is `>` ... `=>` is not a valid operator.
Try `sum(y > 2 for y in x)`
Or, as suggested by @Jochen, to guard against non-conventional nth-party classes, use this:
`sum(1 for y in x if y > 2)` |
Unexpected behavior for python set.__contains__ | 7,549,709 | 9 | 2011-09-26T00:55:35Z | 7,549,733 | 7 | 2011-09-26T01:00:57Z | [
"python",
"list",
"set"
] | Borrowing the documentation from the `__contains__` documentation
```
print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
```
This seems to work fine for primitive objects such as int, basestring, etc. But for user-defined objects that define the `__ne__` and `__eq__` methods, I get unexpected behavior. Her... | For `set`s and `dicts`, you need to define [`__hash__`](http://docs.python.org/reference/datamodel.html#object.hash). Any two objects that are equal should hash the same in order to get consistent / expected behavior in `set`s and `dicts`.
I would reccomend using a `_key` method, and then just referencing that anywher... |
Why do Python's datetime.strftime('%w') and datetime.weekday() use different indexes for the days of the week? | 7,550,726 | 12 | 2011-09-26T04:42:42Z | 7,550,898 | 11 | 2011-09-26T05:18:22Z | [
"python",
"datetime"
] | In Python, showing the day of the week as an integer using `datetime.strftime()` shows a different result than using `datetime.weekday()`.
```
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime('%A')
'Sunday'
>>> now.strftime('%w') # Day of the week as an integer.
'0'
>>> now.weekday() # Day of the... | Python's `strftime` function emulates that in the c library. Thus, the motivation that `%w` returns `0` for a Sunday comes entirely from that.
In contrast, the method `date.weekday()` returns a `6` for Sunday as it seeks to match the behaviour of the much older `time` module. Within that module times are generally rep... |
Python binding to ImageMagick | 7,550,900 | 8 | 2011-09-26T05:18:31Z | 7,551,083 | 19 | 2011-09-26T05:53:26Z | [
"python",
"binding",
"imagemagick",
"wand"
] | I am looking for a good Python binding to [ImageMagick](http://www.imagemagick.org/), but there seem a lot of bindings already. I am not sure that which of these is the right tool for my job. Can you guys recommend me one?
Here is the list of my requirements and preferences (in order of importance):
1. Must be availa... | ~~I found the package myself: [magickwand](http://pypi.python.org/pypi/magickwand) is a `ctypes`-based ImageMagick binding for Python. Yet it has no documentation at all, it still satisfies most of my requirements.~~
Plus: I finally started my own project: [Wand](http://wand-py.org/). |
Is a day always 86,400 epoch seconds long? | 7,552,104 | 24 | 2011-09-26T07:56:10Z | 7,552,159 | 10 | 2011-09-26T08:00:29Z | [
"python",
"timezone",
"epoch"
] | While reviewing my past answers, I noticed I'd proposed code such as [this](http://stackoverflow.com/questions/5868130/generating-all-dates-within-a-given-range-in-python/5868214#5868214):
```
import time
def dates_between(start, end):
# muck around between the 9k+ time representation systems in Python
# now star... | According to [Wikipedia](http://en.wikipedia.org/wiki/Unix_time),
> UTC days are almost always 86 400 s long, but due to "leap seconds"
> are occasionally 86 401 s and could be 86 399 s long (though the
> latter option has never been used as of December 2010); this keeps the
> days synchronized with the rotation of th... |
Is a day always 86,400 epoch seconds long? | 7,552,104 | 24 | 2011-09-26T07:56:10Z | 17,525,555 | 12 | 2013-07-08T11:31:38Z | [
"python",
"timezone",
"epoch"
] | While reviewing my past answers, I noticed I'd proposed code such as [this](http://stackoverflow.com/questions/5868130/generating-all-dates-within-a-given-range-in-python/5868214#5868214):
```
import time
def dates_between(start, end):
# muck around between the 9k+ time representation systems in Python
# now star... | Whenever doing calendrical calculations, it is almost always better to use whatever API the platform provides, such as Python's [calendar](http://docs.python.org/2/library/calendar.html) module, or a mature high-quality library, than it is to write "simpler" code yourself. Calendar APIs are ugly and complicated, but th... |
Is a day always 86,400 epoch seconds long? | 7,552,104 | 24 | 2011-09-26T07:56:10Z | 20,335,352 | 7 | 2013-12-02T18:35:40Z | [
"python",
"timezone",
"epoch"
] | While reviewing my past answers, I noticed I'd proposed code such as [this](http://stackoverflow.com/questions/5868130/generating-all-dates-within-a-given-range-in-python/5868214#5868214):
```
import time
def dates_between(start, end):
# muck around between the 9k+ time representation systems in Python
# now star... | Number of seconds in a day depends on time system that you use e.g., [in POSIX, a day is exactly 86400 seconds by definition](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15):
> As represented in seconds since the Epoch, each and every day shall be
> accounted for by exactly 86400 sec... |
How can I log all outgoing email in Django? | 7,552,283 | 8 | 2011-09-26T08:11:07Z | 7,553,759 | 7 | 2011-09-26T10:30:27Z | [
"python",
"django",
"logging",
"django-email"
] | My Django application sends out quite a bit of emails and I've tried testing it thoroughly. However, for the first few months, I'd like to log all outgoing emails to ensure that everything is working smoothly. Is there a Django module that allows me to do this and makes the outgoing emails visible through the administr... | I wrote a custom email backend which logs the stuff to a model.
Here's my backend:
```
from django.core.mail.backends.smtp import *
from django.db import transaction
from modules.common.models import *
class LoggingEmailBackend(EmailBackend):
"""
A wrapper around the SMTP backend that logs all emails to the... |
Solving the invalid name for Python module warning in PyDev | 7,552,311 | 6 | 2011-09-26T08:13:35Z | 7,552,404 | 8 | 2011-09-26T08:21:23Z | [
"python",
"pydev"
] | I encountered the `Invalid name for Python module: ...filename (it'll not be analyzed)` warning message in PyDev and I tried to resolve it by replacing `-` in the filename with `_` but the warning didn't disappeared.
One of the problems is that in fact this is not a module, it's just a python script, still I get the w... | See <http://docs.python.org/tutorial/modules.html> for information about modules.
To find out what characters are valid, have a look at the [syntax of the `import` statement](http://docs.python.org/reference/simple_stmts.html#the-import-statement). It shows you that a [module name](http://docs.python.org/reference/sim... |
Python - self, no self and cls | 7,554,738 | 25 | 2011-09-26T11:59:13Z | 7,554,899 | 45 | 2011-09-26T12:14:54Z | [
"python",
"class",
"object",
"self"
] | Yet another question on what the 'self' is for, what happens if you don't use 'self' and what's 'cls' for.
I "have done my homework", I just want to make sure I got it all.
self - To access an attribute of an object, you need to prefix the attribute name with the object name (objname.attributename). The same way self ... | > The same way self is used to access an attribute inside the object (class) itself.
Not inside the object / class, just inside the class' *instance methods*. `self` is just a convention, you could call it whatever you wanted, even something different in each method.
> So if you didn't prefix a variable with self in ... |
Neural Network based ranking of documents | 7,554,873 | 11 | 2011-09-26T12:13:19Z | 7,745,804 | 10 | 2011-10-12T19:58:53Z | [
"python",
"machine-learning",
"neural-network"
] | I'm planning of implementing a document ranker which uses neural networks. How can one rate a document by taking in to consideration the ratings of similar articles?. Any good python libraries for doing this?. Can anyone recommend a good book for AI, with python code.
**EDIT**
I'm planning to make a recommendation en... | The problem you are trying to solve is called "collaborative filtering".
### Neural Networks
One state-of-the-art neural network method is *Deep Belief Networks* and *Restricted Boltzman Machines*. For a fast python implementation for a GPU (CUDA) see [here](http://peekaboo-vision.blogspot.com/2010/11/restricted-bolt... |
How to convert a string to tuple | 7,555,044 | 3 | 2011-09-26T12:27:06Z | 7,555,093 | 13 | 2011-09-26T12:30:49Z | [
"python",
"configparser"
] | I like to convert in a Python script the following string:
```
mystring='(5,650),(235,650),(465,650),(695,650)'
```
to a list of tuples
```
mytuple=[(5,650),(235,650),(465,650),(695,650)]
```
such that
`print mytuple[0]` yields:
```
(5,650)
``` | I'd use [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval):
```
In [7]: ast.literal_eval('(5,650),(235,650),(465,650),(695,650)')
Out[7]: ((5, 650), (235, 650), (465, 650), (695, 650))
```
As seen above, this returns a tuple of tuples. If you want a list of tuples, simply apply `list()` to... |
How to convert a string from CP-1251 to UTF-8? | 7,555,335 | 9 | 2011-09-26T12:51:22Z | 7,555,361 | 16 | 2011-09-26T12:53:30Z | [
"python",
"utf-8",
"wxpython",
"cp1251"
] | I'm using mutagen to convert ID3 tags data from [CP-1251](https://en.wikipedia.org/wiki/Windows-1251)/[CP-1252](https://en.wikipedia.org/wiki/Windows-1252) to UTF-8. In Linux there is no problem. But on Windows, calling [`SetValue()`](http://wxpython.org/Phoenix/docs/html/TextEntry.html#TextEntry.SetValue) on a wx.Text... | If you know for sure that you have cp1251 in your input, you can do
```
d.decode('cp1251').encode('utf8')
``` |
Create DB connection and maintain on multiple processes (multiprocessing) | 7,555,680 | 13 | 2011-09-26T13:19:12Z | 7,556,042 | 24 | 2011-09-26T13:45:24Z | [
"python",
"database-connection",
"multiprocessing"
] | Similar to another post I made, this answers that post and creates a new question.
Recap: I need to update every record in a spatial database in which I have a data set of points that overlay data set of polygons. For each point feature I want to assign a key to relate it to the polygon feature that it lies within. So... | Try to isolate the creation of your connection in the Consumer constructor, then give it to the executed Task :
```
import multiprocessing, time, psycopg2
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue ... |
Python 3 Building an array of bytes | 7,555,689 | 15 | 2011-09-26T13:19:43Z | 7,556,308 | 20 | 2011-09-26T14:05:16Z | [
"python",
"python-3.x",
"bytearray"
] | I need to build a tcp frame with raw binary data, but all examples and tutorials I've found talking about bytes always involve conversion from a string, and that's not what I need.
In short, I need to build just an array of bytes:
`0xA2 0x01 0x02 0x03 0x04`
Please note that I come from C/C++ world.
I've tried this:... | Use a [`bytearray`](http://docs.python.org/library/functions.html#bytearray):
```
>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')
```
or, using your code but fixing the errors:
```
... |
Using Mock() in Python | 7,556,161 | 7 | 2011-09-26T13:53:54Z | 7,622,884 | 13 | 2011-10-01T20:48:55Z | [
"python",
"unit-testing",
"mocking"
] | Can you give some clear examples of uses of the Mock() in Django unittests?
I want to understand it more clearly.
**Update:** I've figured out some things, so I share it below. | ## Part 1: Basics
```
from mock import Mock
```
Mock object is an object that is a kind of a `Dummy` for the code that
we want not to be executed, but for which we want to know some information (number of calls, call arguments). Also we might want to specify a return value for that code.
Let us define simple functio... |
matplotlib interactive mode: determine if figure window is still displayed | 7,557,098 | 7 | 2011-09-26T15:00:10Z | 7,559,647 | 11 | 2011-09-26T18:37:16Z | [
"python",
"matplotlib"
] | I am using matplotlib in interactive mode to show the user a plot that will help them enter a range of variables. They have the option of hitting "?" to show this plot, and the prompt for variables will then be repeated.
How do I know to not re-draw this plot if it's still being displayed?
Superficially, I have this ... | In the same vein as unutbu's answer, you can also check whether a given figure is still opened with
```
import matplotlib.pyplot as plt
if plt.fignum_exists(<figure number>):
# Figure is still opened
else:
# Figure is closed
```
The figure number of a figure is in `fig.number`.
PS: Note that the "number" in... |
Tutorial or Guide for Scripting XCode Build Phases | 7,557,273 | 10 | 2011-09-26T15:15:01Z | 8,274,376 | 20 | 2011-11-25T21:26:30Z | [
"python",
"ruby",
"xcode",
"build-automation"
] | I would like to add some files to the Compile Sources build phase using a script in XCode, which pulls from some folder references. I haven't been able to find much documentation so far.
1. Where is the general documentation (or a good tutorial) for scripting XCode build phases?
2. How can I add files to the Compile S... | To add files to the `Compile Sources` build phase using a script, you will need to manipulate your project's `project.pbxproj` file programmatically.
Generally speaking, you would accomplish this by parsing the `project.pbxproj` file into an in-memory data structure, manipulating that data structure through a programm... |
StringIO with binary files? | 7,558,168 | 5 | 2011-09-26T16:27:27Z | 7,558,264 | 7 | 2011-09-26T16:36:00Z | [
"python",
"string",
"file",
"stringio"
] | I seem to get different outputs:
```
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
```
Why? Is it because StringIO only supports text strings or something? | When you call `file.read()`, it will read the entire file into memory. Then, if you call `file.read()` again on the same file object, it will already have reached the end of the file, so it will only return an empty string.
Instead, try e.g. reopening the file:
```
from StringIO import *
file = open('1.bmp', 'r')
pr... |
Nginx configuration for static sites in root directory, Flask apps in subdirectories | 7,558,249 | 13 | 2011-09-26T16:34:41Z | 7,572,865 | 11 | 2011-09-27T16:55:40Z | [
"python",
"nginx",
"flask",
"gunicorn"
] | I'd like to have a static site in my root public\_html directory, then Flask apps in their own subdirectories (e.g. public\_html/foo). The static root directory functions as expected.
I have spent hours editing the nginx configuration to get the Flask apps working, but always end up back in the same place, namely that... | Got an answer from mitsuhiko (Flask lead dev):
<http://flask.pocoo.org/snippets/35/>
You need to define a ReverseProxied class in your Flask app and add several `proxy-set-header` lines to the `location /foo` block in the nginx config. |
How do I serialize a Java object such that it can be deserialized by pickle (Python)? | 7,558,389 | 7 | 2011-09-26T16:47:38Z | 7,564,184 | 7 | 2011-09-27T04:26:09Z | [
"java",
"python",
"serialization"
] | I'm using a Python service that uses pickled messages as part of its protocol. I'd like to query this service from Java, but to do so, I need to pickle my message on the client (Java). Are there any implementations of `pickle` that run on the JVM (ideally with minimal dependencies)?
Clarification: Modifying the server... | Some additional investigation yielded [pyrolite](http://irmen.home.xs4all.nl/pyrolite/), an MIT-licensed library that allows Java and .NET programs to interface with the Python world. In addition to remote object functionality, it (more importantly) includes a `pickle` serializer and de-serializer. |
Will setuptools work with python 3.2.x | 7,558,518 | 7 | 2011-09-26T16:59:14Z | 7,558,552 | 14 | 2011-09-26T17:02:24Z | [
"python",
"python-3.x",
"setuptools"
] | Will the setuptools for windows python 2.7 <http://pypi.python.org/pypi/setuptools#files> be compatible with a python 3.2.x runtime. The installer fails to detect the python settings during an install. Should I wait for a new release? | NOTE: Answer obsolete, Setuptools now works for Python 3. Distribute is deprecated.
Setuptools itself doesn't work on Python 3. But you can use Distribute, a fork and a drop in replacement for setuptools:
<http://packages.python.org/distribute/>
<http://pypi.python.org/pypi/distribute>
From the bottom of the page t... |
What's the difference between setattr() and object.__setattr__()? | 7,559,170 | 4 | 2011-09-26T17:57:32Z | 7,559,315 | 7 | 2011-09-26T18:10:05Z | [
"python",
"setattr"
] | I know that you can't call `object.__setattr__` on objects not inherited from `object`, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters. | `setattr(instance, name, value)` is syntactic sugar for `instance.__setattr__(name, value)`.
You would only need to call `object.__setattr__(...)` inside a class definition, and then only if directly subclassing `object` -- if you were subclassing something else, `Spam` for example, then you should either use `super()... |
python - Read file from and to specific lines of text | 7,559,397 | 5 | 2011-09-26T18:17:41Z | 7,559,542 | 10 | 2011-09-26T18:29:28Z | [
"python",
"file",
"linecache"
] | I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length.
Say i have this text file:
```
Something here...
... ... ...
Start #I want this block of text
a b c d e f g
h i j k l m n
End #until this line ... | If you simply want the block of text between Start and End, you can do something simple like:
```
with open('test.txt') as input_data:
# Skips text before the beginning of the interesting block:
for line in input_data:
if line.strip() == 'Start': # Or whatever test is needed
break
# Re... |
Python RuntimeWarning: overfow encountered in long scalars | 7,559,595 | 19 | 2011-09-26T18:32:44Z | 7,559,950 | 23 | 2011-09-26T19:02:38Z | [
"python",
"numpy",
"append",
"overflow",
"scalar"
] | I am new to programming and in my latest **Python 2.7** project I encountered the following:
**"RuntimeWarning: overfow encountered in long\_scalars"**
Could someone please elaborate what this means and what I could do to fix that.
The code runs through but I'm not sure if it is a good idea to just ignore the warning.
... | Here's an example which issues the same warning:
```
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
```
yields
```
RuntimeWarning: overflow encountered in long_scalars
```
In the example above it happens because `a` is of dtype `int32`, and the maximim value storable in an `int32` is 2\*\*... |
Decimals to 2 places for money in Python 3 | 7,560,455 | 7 | 2011-09-26T19:46:26Z | 7,560,633 | 15 | 2011-09-26T20:00:16Z | [
"python",
"python-3.x",
"decimal",
"money"
] | How do I get my decimals to stay at 2 places for representing money using the `decimal` module?
I've setting the precision, and damn near everything else, and met with failure. | When working with money you usually want to limit precision as late as possible so things like multiplication don't aggregate rounding errors. In python 2 and 3 you can `.quantize()` a `Decimal` to any precision you want:
```
unit_price = decimal.Decimal('8.0107')
quantity = decimal.Decimal('0.056')
price = unit_price... |
Get the column names of a python numpy ndarray | 7,561,017 | 19 | 2011-09-26T20:38:00Z | 7,561,262 | 18 | 2011-09-26T21:00:08Z | [
"python",
"arrays",
"numpy",
"names"
] | Let's say I have a data file called `data.txt` that looks like:
```
TIME FX FY FZ
0 10 5 6
1 2 4 7
2 5 2 6
...
```
In python run:
```
import numpy as np
myData = np.genfromtxt("data.txt", names=True)
>>> print myData["TIME"]
[0, 1, 2]
```
The names at the top of my data file will vary, so what I wou... | Try:
```
myData.dtype.names
```
This will return a tuple of the field names.
```
In [10]: myData.dtype.names
Out[10]: ('TIME', 'FX', 'FY', 'FZ')
``` |
Retrieve data from public Google Spreadsheet using gdata library? | 7,561,148 | 6 | 2011-09-26T20:50:01Z | 12,031,835 | 16 | 2012-08-20T03:02:36Z | [
"python",
"gdata",
"google-spreadsheet"
] | I'm working in Python and trying to retrieve data from a public Google Spreadsheet ([this one](https://docs.google.com/spreadsheet/ccc?key=0Atncguwd4yTedEx3Nzd2aUZyNmVmZGRHY3Nmb3I2ZXc&hl=en_US#gid=0)) but struggling a bit with [the developer documentation](http://code.google.com/apis/spreadsheets/data/1.0/developers_gu... | I want to start out by echoing your sentiment that the Documentation is really poor. But, here's what I've been able to figure out so far.
**Published of Public**
It is very important that your spreadsheet be "Published to The Web" as opposed to just being "Public on the web." The first is achieved by going to the "F... |
python 3.1.2 gives wrong output when dividing two large numbers? | 7,561,498 | 2 | 2011-09-26T21:23:29Z | 7,561,529 | 9 | 2011-09-26T21:27:15Z | [
"python",
"python-3.x"
] | ```
a = 25! = 15511210043330985984000000
b = 12! = 479001600
c = 13! = 6227020800
```
on dividing ans = (int)(a/(b\*c))
or ans = (int)((a/b)/c)
we get ans = 5200299 instead of 5200300 | In Python 3.x `/` means floating point division and can give small rounding errors. Use `//` for integer division.
```
ans = a // (b*c)
``` |
Transparent PNGs don't retain transparency after being transformed (Django + PIL) | 7,561,815 | 10 | 2011-09-26T21:56:05Z | 7,562,200 | 21 | 2011-09-26T22:39:59Z | [
"python",
"django",
"python-imaging-library"
] | I'm using [sorl-thumbnail](http://thumbnail.sorl.net/), [PIL](http://www.pythonware.com/products/pil/), and [Django](https://www.djangoproject.com/) on a webserver to dynamically create thumbnails in templates.
PIL is installed with PNG support, but for some reason the transformations are creating some really bizarre ... | It looks like your resulting image is a JPEG. The JPEG format does not support transparency. Try changing your thumbnail template to this:
```
{% thumbnail project.image "148x108" crop="center" format="PNG" as im %}
``` |
How to return keys in original order in a dict | 7,562,337 | 2 | 2011-09-26T22:57:57Z | 7,562,357 | 7 | 2011-09-26T23:00:47Z | [
"python",
"dictionary"
] | I'm reading in a file and storing the info in a dict as it reads from top to bottom. I don't want to print out in a wrong order compared to the original file.
Also, a very small question: I remember seeing it somewhere a short form of the if and else statement:
```
if a == 'a':
a = 'b' ? a = 'c'
```
Do you know ... | 1. Use an [OrderedDict](http://docs.python.org/release/3.1.3/library/collections.html#collections.OrderedDict).
2. [`a = 'b' if a == 'a' else 'c'`](http://en.wikipedia.org/wiki/Ternary_operation#Python) |
Deriving a class from TestCase throws two errors | 7,562,775 | 22 | 2011-09-27T00:04:54Z | 7,562,887 | 48 | 2011-09-27T00:22:42Z | [
"python",
"unit-testing"
] | I have some basic setup/teardown code that I want to reuse in a whole bunch of unit tests. So I got the bright idea of creating some derived classes to avoid repeating code in every test class.
In so doing, I received two strange errors. One, I cannot solve. Here is the unsolvable one:
```
AttributeError: 'TestDeskto... | It's because you're overriding `__init__()` incorrectly. Almost certainly, you don't want to override `__init__()` at all; you should do everything in `setUp()`. I've been using `unittest` for >10 years and I don't think I've ever overridden `__init__()`.
However, if you really do need to override `__init__()`, rememb... |
Two basic ANTLR questions | 7,565,974 | 5 | 2011-09-27T08:08:25Z | 7,566,644 | 10 | 2011-09-27T09:08:27Z | [
"python",
"assembly",
"antlr"
] | I'm trying to use ANTLR to take a simple grammar and produce assembly output. My language of choice in ANTLR is Python.
Many tutorials seem very complicated or elaborate on things that aren't relevant to me; I only really need some very simple functionality. So I have two questions:
**'Returning' values from one rule... | ---
## Returning values from one rule to another
Let's say you want to parse simple expressions and provide a map of variables at runtime that can be used in these expressions. A simple grammar including the custom Python code, `returns` statements from the rules, and the parameter `vars` to the entry point of your g... |
Python: parsing binary stl file | 7,566,825 | 3 | 2011-09-27T09:20:52Z | 7,566,944 | 10 | 2011-09-27T09:29:34Z | [
"python",
"binaryfiles"
] | I'm having some difficulties while parsing a binary STL file with Python (2.7.1 32-bit and Windows 7 64). The file is a about 450k in size, but my parser suddenly stops working after parsing 244 triangles out of ~8600 with en exception of struct.unpack:
> Exception unpack requires a string argument of length 12
The c... | Your unpack function calls `f.read` twice. I suspect you've walked off the end of the file.
You'll also have trouble with reading the file in text mode on Windows. Any incidental occurrences of `\r\n` will be read in as `\n`. Make the following change to avoid this problem.
```
f = open(infilename, "rb")
``` |
Python: How to make a list of n numbers and randomly select any number? | 7,567,318 | 16 | 2011-09-27T10:00:25Z | 7,567,352 | 7 | 2011-09-27T10:02:50Z | [
"python",
"list",
"random"
] | I have taken a count of something and it came out to N
Now I would like to have a list, containing 0 to N numbers in it.
Example:
N = 5
then, `count_list = [1, 2, 3, 4, 5]`
How would I be able to do that?
Also, once I have created the list,
I would like to randomly select a number from that list and use that number.... | You can try this code
```
import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)
while count_list:
value = count_list.pop()
# do whatever you want with 'value'
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.