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
Django admin - 'NoneType' object has no attribute 'rindex'
6,295,598
2
2011-06-09T15:46:04Z
20,615,760
8
2013-12-16T16:27:17Z
[ "python", "django", "django-admin" ]
I'm working through the Django 1.0 Website Development book. At Chapter 8, I can't get the admin application to work. Here is the traceback I'm getting. ``` Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.3 Python Version: 2.6.5 Installed Applications: ['django.contrib.au...
This also happened to me when I forgot to return decorator in one of my decorators: ``` from django.http import HttpResponseForbidden def admin_required(func): def decorator(request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseForbidden() if not request...
Multi-threaded use of SQLAlchemy
6,297,404
18
2011-06-09T18:20:19Z
18,265,238
22
2013-08-16T03:10:50Z
[ "python", "multithreading", "sqlalchemy" ]
I want to make a Database Application Programming Interface written in Python and using SQLAlchemy (or any other database connectors if it is told that using SQLAlchemy for this kind of task is not the good way to go). The setup is a MySQL server running on Linux or BSD and a the Python software running on a Linux or B...
Session objects are **not** thread-safe, but are **thread-local**. [From the docs:](http://docs.sqlalchemy.org/en/rel_0_7/orm/session.html#thread-local-scope) > "The `Session` object is entirely designed to be used in a **non-concurrent** fashion, which in terms of multithreading means "only in one thread at a time" ....
How to check if this is the index page in Django?
6,298,003
3
2011-06-09T19:13:28Z
6,298,266
8
2011-06-09T19:37:26Z
[ "python", "django" ]
How can I check of the present page is the index page in a Django template? ``` {% if What Goes Here??? %} // whatever {% endif %} ```
``` TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', ... ) {% if request.path == "/" %} ... {% endif %} ```
What can be done about "The command is too long to execute" error in MATLAB?
6,298,619
4
2011-06-09T20:07:57Z
6,300,626
8
2011-06-10T00:03:08Z
[ "python", "matlab" ]
I am calling a Python program from MATLAB and passing an array to the program. I am writing the following lines in MATLAB workspace: ``` % Let us assume some random array num1 = ones(1,100); % I am forced to pass parameters as string due to the MATLAB-Python interaction. num2 = num2str(num1); % The function...
On Windows, the command passed to the `dos` function is limited to 32768 characters. This limitation comes from the Windows limitation on the `lpCommandLine` parameter to [CreateProcess](http://msdn.microsoft.com/en-us/library/ms682425%28v=vs.85%29.aspx). I think Fredrik's idea of writing the data to a file and readin...
How can I fit a Bézier curve to a set of data?
6,299,019
18
2011-06-09T20:44:53Z
6,304,825
14
2011-06-10T10:02:00Z
[ "python", "algorithm", "bezier-curve", "curve-fitting" ]
I have a set of data points (which I can thin out) that I need to fit with a [Bézier curve](http://en.wikipedia.org/wiki/B%C3%A9zier_curve). I need speed over accuracy, but the fit should be decent enough to be recognizable. I'm also looking for an algorithm I can use that doesn't make much use of libraries (specifica...
I have similar problem and I have found "An algorithm for automatically fitting digitized curves" from Graphics Gems (1990) about Bezier curve fitting. Additionally to that I have found [source code](http://webdocs.cs.ualberta.ca/~graphics/books/GraphicsGems/gems/FitCurves.c) for that article. Unfortunately it is writ...
Writing a file upload API using Django
6,299,584
7
2011-06-09T21:33:17Z
6,328,574
10
2011-06-13T09:17:03Z
[ "python", "django", "post", "file-upload" ]
I have a Django app that revolves around users uploading files, and I'm attempting to make an API. Basically, the idea is that a POST request can be sent (using curl for example) with the file to my app which would accept the data and handle it. How can I tell Django to listen for and accept files this way? All of Dja...
Create a small view which ignores every method but POST and make sure it does not have [CSRF](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/) protection: ``` from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() from django.views....
How can I pass a Python StringIO() object to a ZipFile(), or is it not supported?
6,299,724
8
2011-06-09T21:47:50Z
6,299,855
9
2011-06-09T22:03:06Z
[ "python", "zipfile", "stringio" ]
So I have a [`StringIO()`](http://docs.python.org/library/stringio.html#cStringIO.StringIO) file-like object, and I am trying to write it to a [`ZipFile()`](http://docs.python.org/library/zipfile.html#zipfile-objects), but I get this TypeError: ``` coercing to Unicode: need string or buffer, cStringIO.StringI found ``...
To add a string to a ZipFile you need to use the writestr method and pass the string from StringIO using getvalue method of the StringIO instance e.g. ``` archive.writestr("name of file in zip", my_file.getvalue()) ``` Note you also need to give the name of the string to say where it is placed in the zip file.
Python reraise/recatch exception
6,299,756
8
2011-06-09T21:51:36Z
6,299,776
14
2011-06-09T21:54:09Z
[ "python", "exception", "raise" ]
I would like to know if it is possible in python to raise an exception in one except block and catch it in a later except block. I believe some other languages do this by default. Here is what it would look like" ``` try: something except SpecificError, ex: if str(ex) = "some error I am expecting" print "...
Only a single `except` clause in a `try` block is invoked. If you want the exception to be caught higher up then you will need to use nested `try` blocks.
Python reraise/recatch exception
6,299,756
8
2011-06-09T21:51:36Z
6,299,795
15
2011-06-09T21:56:00Z
[ "python", "exception", "raise" ]
I would like to know if it is possible in python to raise an exception in one except block and catch it in a later except block. I believe some other languages do this by default. Here is what it would look like" ``` try: something except SpecificError, ex: if str(ex) = "some error I am expecting" print "...
What about writing 2 try...except blocks like this: ``` try: try: something except SpecificError, ex: if str(ex) == "some error I am expecting" print "close softly" else: raise ex except Exception, ex: print "did not close softly" raise ex ```
find the dot product of sub-arrays in numpy
6,299,770
5
2011-06-09T21:53:40Z
6,300,980
7
2011-06-10T01:09:37Z
[ "python", "numpy", "matrix-multiplication" ]
In numpy, the `numpy.dot()` function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where `Z[i] == numpy.dot(X[i], Y[i])` for all `i`. Is this possible to do non-iteratively?
How about: ``` from numpy.core.umath_tests import inner1d Z = inner1d(X,Y) ``` For example: ``` X = np.random.normal(size=(10,5)) Y = np.random.normal(size=(10,5)) Z1 = inner1d(X,Y) Z2 = [np.dot(X[k],Y[k]) for k in range(10)] print np.allclose(Z1,Z2) ``` returns `True` **Edit** Correction since I didn't see the 3D...
"Unrolling" a recursive function?
6,300,695
13
2011-06-10T00:14:37Z
6,300,994
13
2011-06-10T01:12:06Z
[ "python", "recursion", "cuda", "opencl" ]
I'm writing a path tracer in C++ and I'd like to try and implement the most resource-intensive code into CUDA or OpenCL (I'm not sure which one to pick). I've heard that my graphics card's version of CUDA doesn't support recursion, which is something my path tracer utilizes heavily. As I have it coded both in Python ...
In a recursive function, each time a recursive call occurs, the state of the caller is saved to a stack, then restored when the recursive call is complete. To convert a recursive function to an iterative one, you need to turn the state of the suspended function into an explicit data structure. Of course, you can create...
stopping setup.py from installing as egg
6,301,003
26
2011-06-10T01:13:48Z
27,175,492
8
2014-11-27T16:46:05Z
[ "python", "pydev", "setuptools", "easy-install" ]
How do I stop `setup.py` from installing a package as an egg? Or even better, how do I `easy_install` from installing a package as an `egg`? > sudo python setup.py install The reason being that `PyDev` is rather picky about packages in `egg` format... The package I am interested in at the moment is `boto`. **Update:...
Years later, same problem, not satisfied with the accepted answer. Found this in Google groups: ``` pushd /path/to/my/package/ python setup.py sdist popd pip install /path/to/my/package/dist/package-1.0.tar.gz ``` Explanation: `python setup.py sdist` creates a *source distribution* which naturally is not an \*.egg...
stopping setup.py from installing as egg
6,301,003
26
2011-06-10T01:13:48Z
33,791,008
10
2015-11-18T21:44:28Z
[ "python", "pydev", "setuptools", "easy-install" ]
How do I stop `setup.py` from installing a package as an egg? Or even better, how do I `easy_install` from installing a package as an `egg`? > sudo python setup.py install The reason being that `PyDev` is rather picky about packages in `egg` format... The package I am interested in at the moment is `boto`. **Update:...
I feel like I'm missing something subtle or important (encountering this page years after the question was asked and not finding a satisfying answer) however the following works fine for me: ``` python setup.py install --single-version-externally-managed --root=/ ``` Compressed `*.egg` files are an invention of [setu...
Python Yield Statement does not appear to continue where it left off
6,301,249
4
2011-06-10T02:05:25Z
6,301,265
15
2011-06-10T02:08:10Z
[ "python", "yield" ]
I must be overlooking the obvious, but I cannot for the life of me figure out why this yield statement does not continually give me a new datetime value that is 15 minutes later than the previous one. The gettime function is behaving more like a function that "returns" rather than "yields". ``` import datetime #funct...
It's because you're calling the generator each time, starting it anew. Here is a fixed version: ``` dates = gettime(nextdate) for i in range(0, 25): print dates.next() # note that you're not initializing it each time here # just calling next() ``` That gives me: ``` 2011-08-22 11:00:0...
Django IntegerField with Choice Options (how to create 0-10 integer options)
6,301,741
21
2011-06-10T03:43:11Z
6,301,819
30
2011-06-10T03:59:04Z
[ "python", "django" ]
I want to limit the field to values *0-10* in a select widget. ``` field=models.IntegerField(max_length=10, choices=CHOICES) ``` I could just write out all the choices tuples from *(0,0),(1,1)* on, but there must be an obvious way to handle this. Help is highly appreciated.
Use a Python list comprehension: ``` CHOICES = [(i,i) for i in range(11)] ``` This will result in: ``` [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10,10)] ```
Best pythonic way to populate the list containing the date type data?
6,302,447
7
2011-06-10T05:45:35Z
6,302,500
11
2011-06-10T05:53:04Z
[ "list", "python" ]
I have the following list data. ``` data = [['2009-01-20', 3000.0], ['2011-03-01', 6000.0], ['2008-12-15', 6000.0], ['2002-02-15', 6000.0], ['2009-04-20', 6000.0], ['2010-08-01', 4170.0], ['2002-07-15', 6000.0], ['2008-08-15', 6000.0], ['2010-12-01', 6000.0], ['2011-02-01', 8107.0], ['2011-04-01', 8400.0], ['2011-05-1...
``` from collections import defaultdict yeartotal = defaultdict(float) monthtotal = defaultdict(float) for s in data: d = s[0].split('-') yeartotal[d[0]] += s[1] monthtotal[d[1]] += s[1] In [37]: [item for item in yeartotal.iteritems()] Out[37]: [('2002', 12000.0), ('2005', 6000.0), ('2008', 12000.0),...
Ball Physics problem Python
6,302,835
4
2011-06-10T06:41:59Z
6,303,157
7
2011-06-10T07:18:21Z
[ "python", "physics", "game-physics" ]
I am trying to make a ball bounce within a box correctly, specifically handling corners at specific angles and handling a corner head on. I have a problem, because my ball keeps coming out of the box. I have this function that tells if my ball is out of the box and it handles corners and walls. The code is this: ``` ...
Rewrite this code. It is way too complex for the simple problem you're trying to solve. **First**, a 2D motion of a ball is just 2 1D problems. You can completely separate X and Y. For example, hitting a corner is completely equivalent of hitting a wall in X axis + hitting a wall in Y axis. Hitting a wall in X just re...
split a list by a lambda function in python
6,302,901
8
2011-06-10T06:48:52Z
6,302,929
15
2011-06-10T06:52:18Z
[ "python", "list" ]
Is there any version of `split` that works on generic list types? For example, in Haskell ``` Prelude> import Data.List.Split Prelude Data.List.Split> splitWhen (==2) [1, 2, 3] [[1],[3]] ```
Nope. But you can use `itertools.groupby()` to mimic it. ``` >>> [list(x[1]) for x in itertools.groupby([1, 2, 3], lambda x: x == 2) if not x[0]] [[1], [3]] ```
Real world example about how to use property feature in python?
6,304,040
92
2011-06-10T08:48:36Z
6,304,123
54
2011-06-10T08:55:58Z
[ "python", "oop", "properties", "python-decorators" ]
I am interested in how to use `@property` in Python. I've read the python docs and the example there, in my opinion, is just a toy code: ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def ...
One simple use case will be to set a read only instance attribute , as you know leading a variable name with one underscore `_x` in python usually mean it's *private* (internal use) but sometimes we want to be able to read the instance attribute and not to write it so we can use `property` for this: ``` >>> class C(ob...
Real world example about how to use property feature in python?
6,304,040
92
2011-06-10T08:48:36Z
6,304,151
17
2011-06-10T08:58:22Z
[ "python", "oop", "properties", "python-decorators" ]
I am interested in how to use `@property` in Python. I've read the python docs and the example there, in my opinion, is just a toy code: ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def ...
Take a look at [this article](http://eli.thegreenplace.net/2009/02/06/getters-and-setters-in-python/) for a very practical use. In short, it explains how in Python you can usually ditch explicit getter/setter method, since if you come to need them at some stage you can use `property` for a seamless implementation.
Real world example about how to use property feature in python?
6,304,040
92
2011-06-10T08:48:36Z
6,304,227
14
2011-06-10T09:05:32Z
[ "python", "oop", "properties", "python-decorators" ]
I am interested in how to use `@property` in Python. I've read the python docs and the example there, in my opinion, is just a toy code: ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def ...
One thing I've used it for is caching slow-to-look-up, but unchanging, values stored in a database. This generalises to any situation where your attributes require computation or some other long operation (eg. database check, network communication) which you only want to do on demand. ``` class Model(object): def g...
Real world example about how to use property feature in python?
6,304,040
92
2011-06-10T08:48:36Z
6,304,235
71
2011-06-10T09:06:20Z
[ "python", "oop", "properties", "python-decorators" ]
I am interested in how to use `@property` in Python. I've read the python docs and the example there, in my opinion, is just a toy code: ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def ...
Other examples would be validation/filtering of the set attributes (forcing them to be in bounds or acceptable) and lazy evaluation of complex or rapidly changing terms. Complex calculation hidden behind an attribute: ``` class PDB_Calculator(object): ... @property def protein_folding_angle(self): ...
How to plot a 3D patch collection in matplotlib?
6,304,116
7
2011-06-10T08:55:32Z
6,350,476
9
2011-06-14T21:41:16Z
[ "python", "matplotlib", "mplot3d" ]
I'm trying to make a 3D plot in matplotlib with three circles on it, each centered at the origin and with a radius of 1, pointing in different directions - to illustrate a sphere of radius 1, for example. In 2D I would make a circle patch collection and add it to the axes. In 3D I'm having trouble getting the patches ...
``` import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from mpl_toolkits.mplot3d import Axes3D import mpl_toolkits.mplot3d.art3d as art3d fig = plt.figure() ax=fig.gca(projection='3d') for i in ["x","y","z"]: circle = Circle((0, 0), 1) ax.add_patch(circle) art3d.pathpatch_2...
Are there sideeffects in python using `if a == b == c: pass;`?
6,304,509
3
2011-06-10T09:33:21Z
6,304,552
7
2011-06-10T09:36:55Z
[ "python", "string", "if-statement" ]
``` if a == b == c: # do something ``` Let's assume `a, b, c` are string variables. Are there any possible side effects if I use the snippet above to execute `# do something` if and only if all three strings are equal? I am asking because I have to check three variables against each other and I get many cases: `...
From [the documentation](http://docs.python.org/library/stdtypes.html): > Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). There should be no side effec...
How to pass tuple as argument in Python?
6,304,808
7
2011-06-10T10:00:17Z
6,304,835
23
2011-06-10T10:02:37Z
[ "python", "list", "tuples" ]
Suppose I want a list of tuples. Here's my first idea: ``` li = [] li.append(3, 'three') ``` Which results in: ``` Traceback (most recent call last): File "./foo.py", line 12, in <module> li.append('three', 3) TypeError: append() takes exactly one argument (2 given) ``` So I resort to: ``` li = [] item = 3, ...
Add more parentheses: ``` li.append((3, 'three')) ``` Parentheses with a comma create a tuple, unless it's a list of arguments. That means: ``` () # this is a 0-length tuple (1,) # this is a tuple containing "1" 1, # this is a tuple containing "1" (1) # this is number one - it's exactly the same as: 1 ...
Get an object attribute
6,305,061
16
2011-06-10T10:25:03Z
6,305,083
33
2011-06-10T10:26:45Z
[ "python" ]
Simple question but since I'm new to python, comming over from php, I get a few errors on it. I have the following simple class: ``` User(object) fullName = "John Doe" user = User() ``` In PHP I could do the following: ``` $param = 'fullName'; echo $user->$param; // return John Doe ``` How do I do this i...
To access field or method of an object use dot `.`: ``` user = User() print user.fullName ``` If a name of the field will be defined at run time, use buildin `getattr` function: ``` field_name = "fullName" print getattr(user, field_name) # prints content of user.fullName ```
Get an object attribute
6,305,061
16
2011-06-10T10:25:03Z
6,305,097
8
2011-06-10T10:28:21Z
[ "python" ]
Simple question but since I'm new to python, comming over from php, I get a few errors on it. I have the following simple class: ``` User(object) fullName = "John Doe" user = User() ``` In PHP I could do the following: ``` $param = 'fullName'; echo $user->$param; // return John Doe ``` How do I do this i...
Use [`getattr`](http://docs.python.org/library/functions.html#getattr) if you have an attribute in a string form: ``` >>> class User(object): name = 'John' >>> u = User() >>> param = 'name' >>> getattr(u, param) 'John' ``` Otherwise use the dot `.`: ``` >>> class User(object): name = 'John' >>> u = U...
Python: inconsistence in the way you define the function __setattr__?
6,305,267
15
2011-06-10T10:47:10Z
6,305,727
7
2011-06-10T11:30:15Z
[ "python", "getattr", "setattr" ]
Consider this code: ``` class Foo1(dict): def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value class Foo2(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ o1 = Foo1() o1.x = 42 print(o1, o1.x) o2 = Foo2() o2.x = 42 print(o2, o2.x) ``` ...
I suspect it has to do with a lookup optimization. From the source code: ``` /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with __getattr__, even when the attribute is present. So we use _PyType_Lookup and create the method...
To ask permission or apologize?
6,305,551
12
2011-06-10T11:14:20Z
6,305,632
14
2011-06-10T11:22:02Z
[ "c#", "python", "performance", "rules-of-thumb" ]
I come from a python background, where it's often said that it's easier to apologize than to ask permission. Specifically given the two snippets: ``` if type(A) == int: do_something(A) else: do_something(int(A)) try: do_something(A) except TypeError: do_something(int(A)) ``` Then under most usage scenarios t...
Probably not. .NET exceptions are relatively expensive. Several .NET functions offer both variants for this reason. (`int.TryParse`, which returns a success code is often recommended because it is faster than `int.Parse` which throws an exception on failure) But the only answer that matters is what your own profiling...
To ask permission or apologize?
6,305,551
12
2011-06-10T11:14:20Z
6,305,638
7
2011-06-10T11:22:28Z
[ "c#", "python", "performance", "rules-of-thumb" ]
I come from a python background, where it's often said that it's easier to apologize than to ask permission. Specifically given the two snippets: ``` if type(A) == int: do_something(A) else: do_something(int(A)) try: do_something(A) except TypeError: do_something(int(A)) ``` Then under most usage scenarios t...
Exceptions in .NET are fairly heavyweight, so the philosophy in C# is to use exceptions only for exceptional situations, not for program flow. The philosophy in C# is also geared towards checking all input received from external code before using it. Example: ``` public void Foo(int i) { if (i == 0) // ...
RegExp match repeated characters
6,306,098
11
2011-06-10T12:04:21Z
6,306,113
22
2011-06-10T12:05:37Z
[ "python", "regex", "pattern-matching" ]
For example I have string: ``` aacbbbqq ``` As the result I want to have following matches: ``` (aa, c, bbb, qq) ``` I know that I can write something like this: ``` ([a]+)|([b]+)|([c]+)|... ``` But I think i's ugly and looking for better solution. I'm looking for regular expression solution, not self-written ...
You can match that with: `(\w)\1*`
RegExp match repeated characters
6,306,098
11
2011-06-10T12:04:21Z
6,306,128
14
2011-06-10T12:07:18Z
[ "python", "regex", "pattern-matching" ]
For example I have string: ``` aacbbbqq ``` As the result I want to have following matches: ``` (aa, c, bbb, qq) ``` I know that I can write something like this: ``` ([a]+)|([b]+)|([c]+)|... ``` But I think i's ugly and looking for better solution. I'm looking for regular expression solution, not self-written ...
`itertools.groupby` is not a RexExp, but it's not self-written either. :-) A quote from python docs: ``` # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D ```
RegExp match repeated characters
6,306,098
11
2011-06-10T12:04:21Z
6,309,535
9
2011-06-10T16:43:39Z
[ "python", "regex", "pattern-matching" ]
For example I have string: ``` aacbbbqq ``` As the result I want to have following matches: ``` (aa, c, bbb, qq) ``` I know that I can write something like this: ``` ([a]+)|([b]+)|([c]+)|... ``` But I think i's ugly and looking for better solution. I'm looking for regular expression solution, not self-written ...
### Generally The trick is to match a single char of the range you want, and then make sure you match all repetitions of the same character: ``` >>> matcher= re.compile(r'(.)\1*') ``` This matches any single character (`.`) and then its repetitions (`\1*`) if any. For your input string, you can get the desired outp...
How can you use os.chdir to go to a path minus the last step of it?
6,306,287
2
2011-06-10T12:22:44Z
6,306,377
10
2011-06-10T12:30:08Z
[ "python", "operating-system" ]
For example, a method is passed a path as a parameter, this path might be "C:/a/b/c/d", what if I want to use os.chdir() to change to C:/a/b/c (without the last folder)? Can os.chdir() take the ".." command?
`os.chdir()` can take `'..'` as argument, yes. However, Python provides a platform-agnostic way: by using `os.pardir`: ``` os.chdir(os.pardir) ```
Best way to extract datetime from string in python
6,307,176
3
2011-06-10T13:42:15Z
6,307,430
7
2011-06-10T14:03:22Z
[ "python", "regex", "datetime" ]
I have a script that is parsing out fields within email headers that represent dates and times. Some examples of these strings are as follows: ``` Fri, 10 Jun 2011 11:04:17 +0200 (CEST) Tue, 1 Jun 2011 11:04:17 +0200 Wed, 8 Jul 1992 4:23:11 -0200 Wed, 8 Jul 1992 4:23:11 -0200 EST ``` Before I was confronted with the ...
From [python time to age part 2, timezones](http://stackoverflow.com/questions/526406/python-time-to-age-part-2-timezones/526976#526976): ``` from email import utils utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200 (CEST)') utils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200') utils.parsedate_tz('Fri, 10 Jun 2011 ...
removing dictonary entries with no values- Python
6,307,394
2
2011-06-10T14:00:18Z
6,307,455
7
2011-06-10T14:05:12Z
[ "python", "dictionary" ]
If I have a dictionary, and I want to remove the entries in which the value is an empty list `[]` how would I go about doing that? I tried: ``` for x in dict2.keys(): if dict2[x] == []: dict2.keys().remove(x) ``` but that didn't work.
`.keys()` provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. You need to use `del dictionary[key]` or `dictionary.pop(key)` to remove it. Because of the behaviour in some version of Python, you need to create a of copy of the list of your keys fo...
removing dictonary entries with no values- Python
6,307,394
2
2011-06-10T14:00:18Z
6,307,724
7
2011-06-10T14:25:22Z
[ "python", "dictionary" ]
If I have a dictionary, and I want to remove the entries in which the value is an empty list `[]` how would I go about doing that? I tried: ``` for x in dict2.keys(): if dict2[x] == []: dict2.keys().remove(x) ``` but that didn't work.
Newer versions of python support dict comprehensions: ``` dic = {i:j for i,j in dic.items() if j != []} ``` These are much more readable than filter or for loops
Python console default hex display
6,307,433
4
2011-06-10T14:03:37Z
6,307,672
17
2011-06-10T14:21:27Z
[ "python" ]
I'm doing a bunch of work in the Python console, and most of it is referring to addresses, which I'd prefer to see in hex. So if `a = 0xBADF00D`, when I simply enter `Python> a` into the console to view its value, I'd prefer python to reply with `0xBADF00D` instead of `195948557`. I know I can enter `'0x%X' % a` to s...
The regular Python interpreter will call `sys.displayhook` to do the actual displaying of expressions you enter. You can replace it with something that displays exactly what you want, but you have to keep in mind that it is called for *all* expressions the interactive interpreter wants to display: ``` >>> import sys >...
How can I decorate all functions of a class without typing it over and over for each method added? Python
6,307,761
22
2011-06-10T14:28:42Z
6,307,868
31
2011-06-10T14:36:39Z
[ "python", "wrapper", "decorator" ]
Lets say my class has many methods, and I want to apply my decorator on each one of them, later when I add new methods, I want the same decorator to be applied, but I dont want to write @mydecorator above the method declaration all the time? If I look into `__call__` is that the right way to go? Thanks **IMPORTANT:*...
Decorate the class with a function that walks through the class's attributes and decorates callables. This may be the wrong thing to do if you have class variables that may happen to be callable, and will also decorate nested classes (credits to Sven Marnach for pointing this out) but generally it's a rather clean and ...
How can I decorate all functions of a class without typing it over and over for each method added? Python
6,307,761
22
2011-06-10T14:28:42Z
6,307,917
18
2011-06-10T14:40:15Z
[ "python", "wrapper", "decorator" ]
Lets say my class has many methods, and I want to apply my decorator on each one of them, later when I add new methods, I want the same decorator to be applied, but I dont want to write @mydecorator above the method declaration all the time? If I look into `__call__` is that the right way to go? Thanks **IMPORTANT:*...
While I'm not fond of using magical approaches when an explicit approach would do, you can probably use a metaclass for this. ``` def myDecorator(fn): fn.foo = 'bar' return fn class myMetaClass(type): def __new__(cls, name, bases, local): for attr in local: value = local[attr] ...
"Best" way to integrate Django with an Ajax library
6,307,992
8
2011-06-10T14:45:28Z
6,308,575
8
2011-06-10T15:29:24Z
[ "jquery", "python", "ajax", "django", "json" ]
Obviously, horses for courses, but what are some good ways to integrate javascript libraries with one's Django application? I'm planning on using jQuery, mostly because it seems popular and looks powerful (but I'm open to other suggestions). Are there python-side libraries that are very helpful or essential? Or is it...
Remember, Just because it's ajax does not mean you need to return a json dump. You can indeed return a rendered template. It's true, that the 'right way' is to construct all your tags in javascript, and fill in that data with the json data, but let's face it, that's such a pain in the rump... so much so that they're d...
How do you skip over a list comprehension in Python's debugger (pdb)?
6,308,569
43
2011-06-10T15:28:42Z
6,308,596
52
2011-06-10T15:30:52Z
[ "python", "pdb" ]
In `pdb` the `next` instruction does not step over list comprehensions, instead it steps through each iteration. Is there a way to step over them so debugging will continue at the next line after the list comprehension? I've had to resort to listing the code, setting a breakpoint at the next line, and then continuing ...
You can use the `until` command. Output of `help until` in `pdb`: > unt(il) > Continue execution until the line with a number greater than the current > one is reached or until the current frame returns
Testing a C++ library with Python
6,308,649
3
2011-06-10T15:33:52Z
6,308,733
8
2011-06-10T15:40:05Z
[ "c++", "python", "shared-libraries" ]
I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check the output). While I could do that in C/C++ with a main file that links to the library in question and build my tests, bu...
Honestly C++ is a bit messy. You could do something like create a pure C function which wraps the C++ functionality (which you then call from python) but at that point you might as well write your tests in C++. Unfortunately the only tool out there for this (that I know of) is SWIG. It's sad that it's called the "simp...
Python: Counting the items in a generator consumed by other code
6,309,277
8
2011-06-10T16:22:42Z
6,309,403
8
2011-06-10T16:33:17Z
[ "python", "count", "generator" ]
I'm creating a generator that gets consumed by another function, but I'd still like to know how many items were generated: ``` lines = (line.rstrip('\n') for line in sys.stdin) process(lines) print("Processed {} lines.".format( ? )) ``` The best I can come up with is to wrap the generator with a class that keeps a co...
Usually, I'd just turn the generator into a list and take its length. If you have reasons to assume that this will consume too much memory, your best bet indeed seems to be the wrapper class you suggested yourself. It's not too bad, though: ``` class CountingIterator(object): def __init__(self, it): self.i...
Python: Counting the items in a generator consumed by other code
6,309,277
8
2011-06-10T16:22:42Z
6,309,645
7
2011-06-10T16:54:53Z
[ "python", "count", "generator" ]
I'm creating a generator that gets consumed by another function, but I'd still like to know how many items were generated: ``` lines = (line.rstrip('\n') for line in sys.stdin) process(lines) print("Processed {} lines.".format( ? )) ``` The best I can come up with is to wrap the generator with a class that keeps a co...
Here is another way using [itertools.count()](http://docs.python.org/library/itertools.html#itertools.count) example: ``` import itertools def generator(): for i in range(10): yield i def process(l): for i in l: if i == 5: break def counter_value(counter): import re return...
Python: Counting the items in a generator consumed by other code
6,309,277
8
2011-06-10T16:22:42Z
10,592,271
12
2012-05-14T23:19:03Z
[ "python", "count", "generator" ]
I'm creating a generator that gets consumed by another function, but I'd still like to know how many items were generated: ``` lines = (line.rstrip('\n') for line in sys.stdin) process(lines) print("Processed {} lines.".format( ? )) ``` The best I can come up with is to wrap the generator with a class that keeps a co...
If you don't care that you are consuming the generator, you can just do: ``` sum(1 for x in gen) ```
Regular expressions and Unicode in Python: difference between sub and findall
6,309,387
5
2011-06-10T16:31:48Z
6,309,738
7
2011-06-10T17:05:33Z
[ "python", "regex", "unicode" ]
I am having difficulty trying to figure out a bug in my Python (2.7) script. I am getting an difference with using sub and findall in recognizing special characters. Here is the code: ``` >>> re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.UNICODE) u'Castaeda' >>> re.findall(ur"[^-' ().,\w]+", u'Castañeda', re.UNIC...
The call signature of `re.sub` is: ``` re.sub(pattern, repl, string, count=0) ``` So ``` re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.UNICODE) ``` is setting `count` to `re.UNICODE`, which has value 32. Try instead: ``` In [57]: re.sub(ur"(?u)[^-' ().,\w]+", '', u'Castañeda') Out[57]: u'Casta\xf1eda' ``` Pl...
Is there anyway to put a django site into maintenance mode using fabric?
6,309,417
6
2011-06-10T16:34:00Z
6,311,033
8
2011-06-10T19:13:19Z
[ "python", "django", "fabric", "maintenance-mode" ]
I'm currently using MaintenanceModeMiddleware to put my site into maintenance mode, but it requires you make the change in the settings.py file on the remote server. I would like to use fabric to remotely put the site into maintenance mode. Is there a way to achieve this? Or is there a better method for doing this? Tha...
Fabric does have commands to help you comment or uncomment lines in a given file in `fabric.contrib.files`. See the docs here: <http://docs.fabfile.org/en/1.0.1/api/contrib/files.html> Personally I prefer to handle this at the front-end proxy rather than in a Django middleware. I would take a look at this question [Sh...
matplotlib: can I create AxesSubplot objects, then add them to a Figure instance?
6,309,472
27
2011-06-10T16:38:43Z
6,309,636
15
2011-06-10T16:54:31Z
[ "python", "matplotlib" ]
Looking at the `matplotlib` documentation, it seems the standard way to add an `AxesSubplot` to a `Figure` is to use `Figure.add_subplot`: ``` from matplotlib import pyplot fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.hist( some params .... ) ``` I would like to be able to create `AxesSubPlot`-like objects i...
Typically, you just pass the axes instance to a function. For example: ``` import matplotlib.pyplot as plt import numpy as np def main(): x = np.linspace(0, 6 * np.pi, 100) fig1, (ax1, ax2) = plt.subplots(nrows=2) plot(x, np.sin(x), ax1) plot(x, np.random.random(100), ax2) fig2 = plt.figure() ...
call up an EDITOR (vim) from a python script
6,309,587
20
2011-06-10T16:48:40Z
6,309,753
36
2011-06-10T17:06:52Z
[ "python", "vim", "editor", "command-line-interface" ]
I want to call up an editor in a python script to solicit input from the user, much like `crontab e` or `git commit` does. Here's a snippet from what I have running so far. (In the future, I might use $EDITOR instead of vim so that folks can customize to their liking.) ``` tmp_file = '/tmp/up.'+''.join(random.choice(...
Calling up $EDITOR is easy. I've written this kind of code to call up editor: ``` import sys, tempfile, os from subprocess import call EDITOR = os.environ.get('EDITOR','vim') #that easy! initial_message = "" # if you want to set up the file somehow with tempfile.NamedTemporaryFile(suffix=".tmp") as tf: tf.write(i...
Encrypting a file with RSA in Python
6,309,958
7
2011-06-10T17:25:33Z
9,039,039
21
2012-01-27T19:37:29Z
[ "python", "encryption", "public-key-encryption" ]
I'm implementing file encryption with RSA, using PyCrypto. I know it's somewhat wrong, first of all because RSA is very slow and second because PyCrypto RSA can only encrypt 128 characters, so you have to explode the file in 128 characters chunks. This is the code so far: ``` from Crypto.PublicKey import RSA file_t...
Public-key cryptography is usually used for small amounts of data only. It is slow, and can be hard to use right. The usual practice is to use other methods to reduce the asymmetric problem to one where the security is provided by a shared key, then use public-key cryptography to protect that shared key. For example: ...
datetime.datetime.now() + 1
6,310,475
7
2011-06-10T18:17:38Z
6,310,490
27
2011-06-10T18:19:23Z
[ "python", "django" ]
I would like to add 1 day with 3 hours + datetime.now. ``` mante = Employee() mante.usercompany = idnamez mante.knowledgelost = datetime.datetime.now()+1 day more 3 hours. mante.seguemplelost = datetime.datetime.now()+1 mante.put() ``` Someone knows how to do it?
``` datetime.datetime.now() + datetime.timedelta(days=1, hours=3) ```
Why aren't Python sets hashable?
6,310,867
25
2011-06-10T18:56:59Z
6,310,880
20
2011-06-10T18:58:23Z
[ "python", "hash", "set" ]
I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted...
Because they're mutable. If they were hashable, a hash could silently become "invalid", and that would pretty much make hashing pointless.
Why aren't Python sets hashable?
6,310,867
25
2011-06-10T18:56:59Z
6,310,888
61
2011-06-10T18:58:58Z
[ "python", "hash", "set" ]
I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted...
Generally, only immutable objects are hashable in Python. The immutable variant of `set()` -- `frozenset()` -- is hashable.
Why aren't Python sets hashable?
6,310,867
25
2011-06-10T18:56:59Z
6,310,901
13
2011-06-10T19:00:13Z
[ "python", "hash", "set" ]
I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted...
From the Python docs: > **hashable** > An object is hashable if it > has a hash value which never changes > during its lifetime (it needs a > **hash**() method), and can be compared to other objects (it needs an > **eq**() or **cmp**() method). Hashable objects which compare equal > must have the same hash value. > ...
How do I get Python XML to stop having wasted Child Nodes
6,311,824
7
2011-06-10T20:41:06Z
6,312,121
9
2011-06-10T21:12:54Z
[ "python", "xml", "whitespace", "nodes" ]
I have a simple XML document I'm trying to read in with Python DOM (see below): **XML File:** ``` <?xml version="1.0" encoding="utf-8"?> <HeaderLookup> <Header> <Reserved>2</Reserved> <CPU>1</CPU> <Flag>1</Flag> <VQI>12</VQI> <Group_ID>16</Group_ID> <DI>2</DI> ...
Whitespace is significant in XML, but check out [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html), which has a different API for processing XML than the DOM. ### Example ``` from xml.etree import ElementTree as et data = '''\ <?xml version="1.0" encoding="utf-8"?> <HeaderLookup> <Header> ...
python .rstrip removes one additional character
6,311,968
6
2011-06-10T20:53:35Z
6,311,992
7
2011-06-10T20:56:25Z
[ "python" ]
I try to remove seconds from date: ``` >>> import datetime >>> test1 = datetime.datetime(2011, 6, 10, 0, 0) >>> test1 datetime.datetime(2011, 6, 10, 0, 0) >>> str(test1) '2011-06-10 00:00:00' >>> str(test1).rstrip('00:00:00') '2011-06-10 ' >>> str(test1).rstrip(' 00:00:00') '2011-06-1' ``` Why 0 at end of '10' is rem...
`rstrip` takes a set (although the argument can be any iterable, like `str` in your example) of characters that are removed, not a single string. And by the way, the string representation of `datetime.datetime` is not fixed, you can't rely on it. Instead, use [`isoformat`](http://docs.python.org/library/datetime.html#...
python .rstrip removes one additional character
6,311,968
6
2011-06-10T20:53:35Z
6,312,005
7
2011-06-10T20:58:03Z
[ "python" ]
I try to remove seconds from date: ``` >>> import datetime >>> test1 = datetime.datetime(2011, 6, 10, 0, 0) >>> test1 datetime.datetime(2011, 6, 10, 0, 0) >>> str(test1) '2011-06-10 00:00:00' >>> str(test1).rstrip('00:00:00') '2011-06-10 ' >>> str(test1).rstrip(' 00:00:00') '2011-06-1' ``` Why 0 at end of '10' is rem...
`str.rstrip()` doesn't remove an exact string -- it removes all characters that occur in the string. Since you know the length of the string to remove, you can simply use ``` str(test1)[:-9] ``` or even better ``` test1.date().isoformat() ```
Find all possible combinations
6,312,396
2
2011-06-10T21:45:51Z
6,312,410
9
2011-06-10T21:47:49Z
[ "python", "list" ]
I asked this question earlier but regarding another programming languages. Let's say I have a couple roots, prefixes, and suffixes. ``` roots = ["car insurance", "auto insurance"] prefix = ["cheap", "budget"] suffix = ["quote", "quotes"] ``` Is there a simple function in Python which will allow me to construct all p...
Use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` for p, r, s in itertools.product(prefix, roots, suffix): print p, r, s ```
Get all the diagonals in a matrix/list of lists in Python
6,313,308
27
2011-06-11T00:38:53Z
6,313,407
8
2011-06-11T00:59:42Z
[ "python", "matrix", "diagonal" ]
I'm looking for a Pythonic way to get all the diagonals of a (square) matrix, represented as a list of lists. Suppose I have the following matrix: ``` matrix = [[-2, 5, 3, 2], [ 9, -6, 5, 1], [ 3, 2, 7, 3], [-1, 8, -4, 8]] ``` Then the large diagonals are easy: ``` l = len(ma...
Start with the diagonals that slope up-and-right. If (x,y) is a rectangular coordinate inside the matrix, you want to transform to/from a coordinate scheme (p,q), where p is the number of the diagonal and q is the index along the diagonal. (So p=0 is the [-2] diagonal, p=1 is the [9,5] diagonal, p=2 is the [3,-6,3] di...
Get all the diagonals in a matrix/list of lists in Python
6,313,308
27
2011-06-11T00:38:53Z
6,313,414
33
2011-06-11T01:01:38Z
[ "python", "matrix", "diagonal" ]
I'm looking for a Pythonic way to get all the diagonals of a (square) matrix, represented as a list of lists. Suppose I have the following matrix: ``` matrix = [[-2, 5, 3, 2], [ 9, -6, 5, 1], [ 3, 2, 7, 3], [-1, 8, -4, 8]] ``` Then the large diagonals are easy: ``` l = len(ma...
There are probably better ways to do it in [numpy](http://numpy.scipy.org/) than below, but I'm not too familiar with it yet: ``` import numpy as np matrix = np.array( [[-2, 5, 3, 2], [ 9, -6, 5, 1], [ 3, 2, 7, 3], [-1, 8, -4, 8]]) diags = [matrix[::-1,:].diagonal(i) ...
Can I mark variables as transient so they won't be pickled?
6,313,421
10
2011-06-11T01:04:00Z
6,313,474
19
2011-06-11T01:18:25Z
[ "python", "pickle" ]
Let's say I have a class: ``` class Thing(object): cachedBar = None def __init__(self, foo): self.foo = foo def bar(self): if not self.cachedBar: self.cachedBar = doSomeIntenseCalculation() return self.cachedBar ``` To get bar some intense calculation, so I cache it i...
According to the [Pickle documentation](http://docs.python.org/dev/library/pickle.html#pickle-inst), you can provide a method called `__getstate__()`, which returns something representing the state you want to have pickled (if it isn't provided, `pickle` uses `thing.__dict__`). So, you can do something like this: ``` ...
Match any unicode letter?
6,314,614
7
2011-06-11T07:05:17Z
6,314,634
14
2011-06-11T07:09:36Z
[ "python", "regex", "character-properties" ]
In .net you can use `\p{L}` to match any letter, how can I do the same in Python? Namely, I want to match any uppercase, lowercase, and accented letters.
Python's `re` module doesn't support Unicode properties yet. But you can compile your regex using the `re.UNICODE` flag, and then the character class shorthand `\w` will match Unicode letters, too. Since `\w` will also match digits, you need to then subtract those from your character class, along with the underscore: ...
TypeError: 'RelatedManager' object is not iterable
6,314,841
24
2011-06-11T08:02:42Z
6,314,856
66
2011-06-11T08:04:54Z
[ "python", "django", "django-models", "django-queryset" ]
Django I have next models: ``` class Group(models.Model): name = models.CharField(max_length=100) parent_group = models.ManyToManyField("self", blank=True) def __unicode__(self): return self.name class Block(models.Model): name = models.CharField(max_length=100) app = models.CharField(...
Try this: ``` block in group.block_set.all() ```
TypeError: 'RelatedManager' object is not iterable
6,314,841
24
2011-06-11T08:02:42Z
6,314,857
14
2011-06-11T08:04:59Z
[ "python", "django", "django-models", "django-queryset" ]
Django I have next models: ``` class Group(models.Model): name = models.CharField(max_length=100) parent_group = models.ManyToManyField("self", blank=True) def __unicode__(self): return self.name class Block(models.Model): name = models.CharField(max_length=100) app = models.CharField(...
Use it [like a `Manager`](https://docs.djangoproject.com/en/dev/topics/db/managers/). If you want all the objects then call the `all()` method.
How to solve AttributeError when importing igraph?
6,315,440
10
2011-06-11T10:47:37Z
6,315,463
23
2011-06-11T10:52:58Z
[ "python", "import", "packages", "igraph" ]
When I import the igraph package in my project, I get an AttributeError. This only happens in the project directory: ``` [12:34][~]$ python2 Python 2.7.1 (r271:86832, Apr 15 2011, 12:09:10) [GCC 4.5.2 20110127 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import ig...
Most likely, there is a module `io` in `~/projectdir` or one of the paths the project configures. The gzip module imported by igraph starts with ``` import io ``` and expect the built-in io module, not your project's one. Look for an `io` directory, or `io.py` or `io.pyc`. It can also help to scrutinize `sys.path` fo...
Is there generic inheritance in python?
6,315,935
2
2011-06-11T12:29:59Z
6,315,943
9
2011-06-11T12:33:00Z
[ "python", "inheritance" ]
I was wondering if there is generic inheritance in python. For example, ``` Class A(object): def foo(): Class B(object): def foo(): Class C(<someParentClass>): def bar(): ``` so effectively, I would like to do something like ``` myClass1 = C()<A> myClass2 = C()<B> ``` Im guessing this is not possible ...
There's nothing preventing it. Everything in Python is essentially generic. Everything is runtime, including class statements, so you can do something like: ``` def make_C(parent): class C(parent): def bar(self): ... return C myClass1 = make_C(A) myClass2 = make_C(B) ``` If you want the C...
Django's Querydict bizarre behavior: bunches POST dictionary into a single key
6,315,960
3
2011-06-11T12:36:21Z
6,322,561
7
2011-06-12T14:45:45Z
[ "python", "django", "rest", "post" ]
I'm experiencing a really bizarre behavior when using the test client in django. I'm using a `POST` to send data to my django app. I usually do this from an iPhone app and/or a test html form. On the server side, this is how I handle it: ``` def handle_query(request): print request q = con.QueryLog() q.ID = ...
The problem is that you're supplying a content\_type. Since you did so, the client is expecting a urlencoded string like ``` "username=hi&password=there&this_is_the_login_form=1" ``` instead of a dictionary like ``` {'username': 'hi', 'password': 'there', 'this_is_the_login_form': 1} ``` If you remove the content\_...
Access USB serial ports using Python and pyserial
6,316,584
8
2011-06-11T14:31:27Z
6,316,585
8
2011-06-11T14:41:12Z
[ "python", "osx", "serial-port", "usb", "pyserial" ]
How do I access the USB port using pyserial? I have seen an [example](http://electronics.stackexchange.com/questions/13665/what-is-the-simplest-and-cheapest-way-to-interface-with-usb/13678#13678) with: ``` import serial ser = serial.Serial('/dev/ttyUSB0') ``` I used to access the serial port from MATLAB on Windows a...
You can only access USB Serial Adapters using pyserial (i.e., USB RS-232 dongles). If you want generic USB access you should be looking into "libusb". If it is RS-232 you are trying to access through USB then you should look for a file in /dev starting with cu.usb\* (/dev/cu.usbserial-181 for example).
How can I splice a string?
6,317,500
11
2011-06-11T17:39:19Z
6,317,509
11
2011-06-11T17:40:48Z
[ "python", "string", "splice" ]
I know I can *slice* a string in Python by using array notation: `str[1:6]`, but how do I *splice* it? i.e., replace `str[1:6]` with another string, possibly of a different length?
You can't do this since strings in Python are immutable. Try next: ``` new_s = ''.join((s[:1], new, s[6:])) ```
How can I splice a string?
6,317,500
11
2011-06-11T17:39:19Z
6,317,510
16
2011-06-11T17:40:49Z
[ "python", "string", "splice" ]
I know I can *slice* a string in Python by using array notation: `str[1:6]`, but how do I *splice* it? i.e., replace `str[1:6]` with another string, possibly of a different length?
Strings are immutable in Python. The best you can do is construct a new string: ``` t = s[:1] + "whatever" + s[6:] ```
How to Eat Memory using Python?
6,317,818
10
2011-06-11T18:43:26Z
6,317,871
15
2011-06-11T18:51:36Z
[ "python", "memory", "memory-management" ]
Just for experiment, and Fun... I am trying to create an app that can "Purposely" consume RAM as much as we specify immediately. e.g. I want to consume 512 MB RAM, then the app will consume 512 MB directly. I have search on the web, most of them are using while loop to fill the ram with variable or data. But I think i...
One simple way might be: ``` some_str = ' ' * 512000000 ``` Seemed to work pretty well in my tests. **Edit**: in Python 3, you might want to use `bytearray(512000000)` instead.
Does CouchDB have an equivalent to Redis' expire?
6,317,979
4
2011-06-11T19:15:42Z
6,318,504
7
2011-06-11T20:56:48Z
[ "python", "redis", "couchdb", "key-value-store" ]
Does CouchDB have an equivalent to expire like in Redis? Example for Redis expire: ``` #!/usr/bin/env python import redis redis_server = redis.Redis(host='localhost',port=5477,db=0) r.set('cat','meow') r.expire('cat',10) # do some work and ten seconds later... r.get('cat') # returns None ```
### No. CouchDB does not have this. `Redis` uses a lazy approach and deletes keys when they are inspected even though they may have expired much earlier. Also, as @antirez pointed out Redis will remove a random set of expired keys every second or so to keep the database size under control. If CouchDB does not nativel...
Why do you need to create a cursor when querying a sqlite database?
6,318,126
50
2011-06-11T19:41:17Z
6,318,154
20
2011-06-11T19:46:35Z
[ "python", "sqlite", "sqlite3", "cursor" ]
I'm completely new to python's sqlite3 module (and SQL in general for that matter), and this just completely stumps me. The abundant lack of descriptions of cursor objects (rather, their necessity) also seems odd. This snippet of code is the preferred way of doing things: ``` import sqlite3 conn = sqlite3.connect("db...
You need a cursor object to fetch results. Your example works because it's an `INSERT` and thus you aren't trying to get any rows back from it, but if you look at the [`sqlite3` docs](http://docs.python.org/library/sqlite3.html), you'll notice that there aren't any `.fetchXXXX` methods on connection objects, so if you ...
Why do you need to create a cursor when querying a sqlite database?
6,318,126
50
2011-06-11T19:41:17Z
6,556,536
12
2011-07-02T10:47:13Z
[ "python", "sqlite", "sqlite3", "cursor" ]
I'm completely new to python's sqlite3 module (and SQL in general for that matter), and this just completely stumps me. The abundant lack of descriptions of cursor objects (rather, their necessity) also seems odd. This snippet of code is the preferred way of doing things: ``` import sqlite3 conn = sqlite3.connect("db...
To add to the answers, Python docs say that connection.execute() is a **nonstandard shortcut** that creates an intermediate cursor object. <http://docs.python.org/library/sqlite3.html#sqlite3.Connection.execute>
Why do you need to create a cursor when querying a sqlite database?
6,318,126
50
2011-06-11T19:41:17Z
13,639,222
26
2012-11-30T04:52:28Z
[ "python", "sqlite", "sqlite3", "cursor" ]
I'm completely new to python's sqlite3 module (and SQL in general for that matter), and this just completely stumps me. The abundant lack of descriptions of cursor objects (rather, their necessity) also seems odd. This snippet of code is the preferred way of doing things: ``` import sqlite3 conn = sqlite3.connect("db...
Just a misapplied abstraction it seems to me. A db cursor is an abstraction meant for data set traversal: <http://en.wikipedia.org/wiki/Cursor_%28databases%29> > In computer science and technology, a database cursor is a control > structure that enables traversal over the records in a database. > Cursors facilitate s...
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
6,318,175
9
2011-06-11T19:50:41Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
You can set the path from the **current cmd window** using the `PATH =` command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables) You would goto your cmd instance, and put in `PATH...
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
6,318,188
227
2011-06-11T19:53:23Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
1. Hold `Win` and press `Pause`. 2. Click Advanced System Settings. 3. Click Environment Variables. 4. Append `;C:\python27` to the `Path` variable. 5. Restart Command Prompt.
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
10,666,810
26
2012-05-19T16:07:42Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
I've had a problem with this for a LONG time. I added it to my path in every way I could think of but here's what finally worked for me: 1. Right click on "My computer" 2. Click "Properties" 3. Click "Advanced system settings" in the side panel 4. Click "Environment Variables" 5. **Click the "New" below system variabl...
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
12,469,747
7
2012-09-18T02:50:18Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
Make sure you don't add a space before the new directory. Good: old;old;old;new Bad: old;old;old; new
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
12,592,280
90
2012-09-25T22:57:01Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
When setting Environmental Variables in Windows, I have gone wrong on many, many occasions. I thought I should share a few of my past mistakes here hoping that it might help someone. (These apply to all Environmental Variables, not just when setting Python Path) Watch out for these possible mistakes: 1. Kill and reop...
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
13,811,145
13
2012-12-10T23:33:24Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
Try adding this `python.bat` file to `System32` folder and the command line will now run python when you type in `python` **python.bat** ``` @C:\Python27\python.exe %* ``` Source: <https://github.com/KartikTalwar/dotfiles/blob/master/bat/python.bat>
Adding Python Path on Windows 7
6,318,156
114
2011-06-11T19:46:56Z
14,649,949
39
2013-02-01T15:47:15Z
[ "python", "windows", "python-2.7", "path" ]
I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the `set` command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this ``` python = c:\...
Open **cmd**.exe with administrator privileges (right click on app). Then type: > **setx** path "%path%;C:\Python27;" Remember to end with a semi-colon and don't include a trailing slash.
Large matplotlib pixel figure best approach
6,318,170
3
2011-06-11T19:49:55Z
6,318,319
8
2011-06-11T20:16:22Z
[ "python", "colors", "matplotlib", "figure" ]
I have a large 2D dataset where I want to associate to each X,Y pair a color and plot it with matplotlib. I am talking about 1000000 points. I wonder what is the best approach in terms of performance (speed) and if you could point to some example
If you're dealing with a regular grid, just treat it as an image: ``` import numpy as np import matplotlib.pyplot as plt nrows, ncols = 1000, 1000 z = 500 * np.random.random(nrows * ncols).reshape((nrows, ncols)) plt.imshow(z, interpolation='nearest') plt.colorbar() plt.show() ``` ![enter image description here](ht...
How do I execute an arbitrary script in the context of my Django project?
6,318,482
9
2011-06-11T20:51:31Z
6,321,598
9
2011-06-12T11:07:58Z
[ "python", "django", "django-testing", "django-command-extensions" ]
Sometimes I want to execute a file in the context of my Django project, just as if I were using the shell, but with the convenience of using a text editor. This is mainly to try something out, or quickly prototype some functionality before putting it into a view, test, recurring task, or management command. I know I c...
The best way to execute a script with the correct django context is to set the `DJANGO_SETTINGS_MODULE` environment variable to your settings module (and appropriate `PYTHONPATH` if needed). In windows this usually means executing: ``` set DJANGO_SETTINGS_MODULE=setting ``` and in bash : ``` export DJANGO_SETTINGS_M...
How can I tell PyCharm what type a parameter is expected to be?
6,318,814
141
2011-06-11T22:09:34Z
6,318,911
67
2011-06-11T22:31:00Z
[ "python", "pycharm", "code-completion", "type-hinting" ]
When it comes to constructors, and assignments, and method calls, the PyCharm IDE is pretty good at analyzing my source code and figuring out what type each variable should be. I like it when it's right, because it gives me good code-completion and parameter info, and it gives me warnings if I try to access an attribut...
Yes, you can use special documentation format for methods and their parameters so that PyCharm can know the type. Recent PyCharm version [supports most common doc formats](http://blogs.jetbrains.com/pycharm/2011/06/pycharm-1-5-released-documentation-sqldatabase-django-templates-debugging-and-more/). For example, PyCha...
How can I tell PyCharm what type a parameter is expected to be?
6,318,814
141
2011-06-11T22:09:34Z
11,601,126
33
2012-07-22T14:31:21Z
[ "python", "pycharm", "code-completion", "type-hinting" ]
When it comes to constructors, and assignments, and method calls, the PyCharm IDE is pretty good at analyzing my source code and figuring out what type each variable should be. I like it when it's right, because it gives me good code-completion and parameter info, and it gives me warnings if I try to access an attribut...
If you are using Python 3.0 or later, you can also use annotations on functions and parameters. PyCharm will interpret these as the type the arguments or return values are expected to have: ``` class King: def repress(self, peasant: Person) -> bool: peasant.knock_over() # Shows a warning. And there was muc...
Show the final y-axis value of each line with matplotlib
6,319,155
4
2011-06-11T23:33:30Z
6,320,364
7
2011-06-12T05:37:54Z
[ "python", "matplotlib" ]
I'm drawing a graph with some lines using matplotlib and I want to display the final `y` value next to where each line ends on the right hand side like this: ![enter image description here](http://i.stack.imgur.com/6VECZ.png) Any solutions or pointers to the relevant parts of the API? I'm quite stumped. I'm using mat...
While there's nothing wrong with Ofri's answer, `annotate` is intended especially for this purpose: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(61).astype(np.float) y1 = np.exp(0.1 * x) y2 = np.exp(0.09 * x) plt.plot(x, y1) plt.plot(x, y2) for var in (y1, y2): plt.annotate('%0.2f' % var...
Are lists thread-safe
6,319,207
71
2011-06-11T23:46:12Z
6,319,267
87
2011-06-12T00:00:40Z
[ "python", "multithreading", "list", "python-3.x", "python-multithreading" ]
I notice that it is often suggested to use queues with multiple treads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists *themselves* can't go corrupt by attempts to concurrently access, the lists's ...
Are lists thread-safe
6,319,207
71
2011-06-11T23:46:12Z
18,568,017
24
2013-09-02T07:45:07Z
[ "python", "multithreading", "list", "python-3.x", "python-multithreading" ]
I notice that it is often suggested to use queues with multiple treads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?
To clarify a point in Thomas' excellent answer, it should be mentioned that `append()` *is* thread safe. This is because there is no concern that data being *read* will be in the same place once we go to *write* to it. The `append()` operation does not read data, it only writes data to the list.
Are lists thread-safe
6,319,207
71
2011-06-11T23:46:12Z
19,728,536
18
2013-11-01T14:15:20Z
[ "python", "multithreading", "list", "python-3.x", "python-multithreading" ]
I notice that it is often suggested to use queues with multiple treads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?
[Here's a comprehensive yet non-exhaustive list of examples](http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm) of `list` operations and whether or not they are thread safe. Hoping to get an answer regarding the `obj in a_list` language construct [here](http://stackoverflow.com/q/19727759/...
What happened to thread.start_new_thread in python 3
6,319,268
7
2011-06-12T00:00:41Z
6,319,283
15
2011-06-12T00:03:23Z
[ "python", "multithreading", "python-3.x", "python-multithreading" ]
I liked the ability to turn a function into a thread without the unnecessary line to define a class. I know about \_thread, however it appears that you are not supposed to use \_thread. Is there a good-practice equivalent of thread.start\_new\_thread for python 3?
``` threading.Thread(target=some_callable_function).start() ``` or if you wish to pass arguments, ``` threading.Thread(target=some_callable_function, args=(tuple, of, args), kwargs={'dict': 'of', 'keyword': 'args'}, ).start() ```
Python shared object module naming convention
6,319,379
19
2011-06-12T00:31:01Z
6,319,436
10
2011-06-12T00:45:37Z
[ "python", "module", "naming-conventions", "shared-libraries" ]
I have written a Python module in C++ and built it as a shared object library and it worked fine. But while figuring all that out, I noticed (via strace) that Python looks for a few different variations `import` is called. In particular, when I say `import foo`, Python searches for, in order: * foo (a directory) * foo...
This is merely a guess, but I can only assume this is related to the below, from [Extending Python with C or C++](http://docs.python.org/extending/extending.html#extending-python-with-c-or-c). > Begin by creating a file spammodule.c. (Historically, if a module is called spam, the C file containing its implementation i...
Python shared object module naming convention
6,319,379
19
2011-06-12T00:31:01Z
6,531,558
17
2011-06-30T07:47:59Z
[ "python", "module", "naming-conventions", "shared-libraries" ]
I have written a Python module in C++ and built it as a shared object library and it worked fine. But while figuring all that out, I noticed (via strace) that Python looks for a few different variations `import` is called. In particular, when I say `import foo`, Python searches for, in order: * foo (a directory) * foo...
This is actually platform-dependent, Python has different suffixes that it tries depending on the operating system. Here is the initialization of the suffix table in `import.c`: ``` #ifdef HAVE_DYNAMIC_LOADING memcpy(filetab, _PyImport_DynLoadFiletab, countD * sizeof(struct filedescr)); #endif memcp...
How to convert Python decimal to SQLite numeric?
6,319,409
7
2011-06-12T00:39:55Z
6,319,513
12
2011-06-12T01:12:31Z
[ "python", "sqlite", "decimal", "numeric" ]
I have a program that reads financial data in JSON and inserts it into an SQLite database. The problem is when I'm inserting it into SQLite numeric column and it doesn't seem to like the [decimal](http://docs.python.org/library/decimal.html) object. I've found this question [answered before](http://stackoverflow.com/q...
`sqlite3` allows you to register an adapter (to transparently convert `Decimals` to `TEXT` when inserting) and a converter (to transparently convert `TEXT` into `Decimals` when fetching). The following is a lightly modified version of the example code from [the docs](http://docs.python.org/library/sqlite3.html#convert...
Objective-c Server Side
6,319,507
6
2011-06-12T01:09:56Z
6,319,528
16
2011-06-12T01:17:02Z
[ "python", "objective-c", "cocoa", "server-side" ]
**A bit of background:** I have been developing apps for the past 2 years for Mac and iOS. I really like Objective-c and Cocoa/Cocoa-Touch framework. I did java and c++ before I started programing for iOS and now when I look at these languages i literally get a headache (The syntax mainly but also lack of classes provi...
What's stopping you from writing server-side applications in Objective-C? Xcode comes with templates for command-line applications (choose 'Foundation' rather than 'C' or 'Core Foundation'). If the requirement of using OS X on the server is too much, you can opt for a Linux/BSD distribution and use [GNUstep](http://ww...
python decompose a list
6,319,612
2
2011-06-12T01:41:45Z
6,319,653
9
2011-06-12T01:53:18Z
[ "python", "list", "operators" ]
I remember I once seen a operator which is able to decompose a list in python. for example ``` [[1],[2],[3]] ``` by applying that operator, you get ``` [1], [2], [3] ``` what is that operator, any help will be appreciated.
If you want to pass a list of arguments to a function, you can use `*`, the splat operator. Here's how it works: ``` list = [1, 2, 3] function_that_takes_3_arguments(*list) ``` If you want to assign the contents of a list to a variable, you can list unpacking: ``` a, b, c = list # a=1, b=2, c=3 ```
Why I am getting AttributeError: "'NoneType' object has no attribute 'get'" with Python and Tkinkter?
6,319,942
2
2011-06-12T03:27:54Z
6,319,963
9
2011-06-12T03:34:47Z
[ "python" ]
``` from tkinter import * app=Tk() app.title(" BRAIN SYNCRONIZATION SOFTWARE ") e1=Entry(app).pack() t1=Text(app).pack() def InputFun(): file=open("acad.txt","a") file.write("%s;%s"%(t1.get("0.1",END),e1.get())) file.close() b1=Button(app,text="INPUT",command=InputFun,height=3,width=4).pack(...
``` t1=Text(app).pack() ``` should be ``` t1=Text(app) t1.pack() ``` The Tkinkter `pack()` method returns None, you can't run `.get()` on it, but need to keep `t1` referring to the text object itself.
django-taggit: make the tags not required in the admin
6,320,686
14
2011-06-12T07:18:57Z
6,321,078
26
2011-06-12T08:59:54Z
[ "python", "django", "django-taggit" ]
I've started using django-taggit and it seems to fit the bill. But for me there is still an issue with the admin site: I included the `tags` attribute in the ModelAdmin like this: ``` class MyModel(db.models.Model): name = models.CharField(max_length=200) tags = TaggableManager() class MyModelAdmin(admin.Mod...
Did you try `tags = TaggableManager(blank=True)`? > blank – Controls whether this field is > required ... at least that's what [the docs](http://django-taggit.readthedocs.org/en/latest/api.html#TaggableManager) say.
IDLE can't import Tkinter. Your Python may not be configured for Tk
6,320,954
4
2011-06-12T08:27:41Z
10,779,522
7
2012-05-28T04:55:54Z
[ "python", "linux", "ubuntu", "python-3.x", "tkinter" ]
I am running Ubuntu 10.10, and I installed Python 3.2 today. The system is already running Python 2.6. I typed idle3.2 in the terminal and it gave me: > IDLE can't import Tkinter. Your Python may not be configured for Tk. So I searched on *Stack Overflow* (and in some other places) for a solution, I installed `pytho...
On OSX, this can be resolved with macports by installing the python tkinter package for your python version. In my case, with python 2.7, I ran on the terminal: ``` sudo port install py27-tkinter ``` change the "27" to your python version number.