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 implement the having clause in sqlite django ORM
13,344,182
16
2012-11-12T13:01:15Z
13,344,416
30
2012-11-12T13:17:35Z
[ "python", "django", "orm", "django-models", "sqlite3" ]
I've written django sqlite orm syntax to retrieve particular set of records: ``` from django.db.models.aggregates import Count JobStatus.objects.filter( status='PRF' ).values_list( 'job', flat=True ).order_by( 'job' ).aggregate( Count(status)__gt=3 ).distinct() ``` But it gives me an error and the sq...
Finally I've managed to figure it out. The ORM syntax is something like this. ``` from django.db.models.aggregates import Count JobStatus.objects.filter( status='PRF' ).values_list( 'job', flat=True ).order_by( 'job' ).annotate( count_status=Count('status') ).filter( count_status__gt=1 ).distinct(...
As a language, is Python limited due to no end statement?
13,345,191
6
2012-11-12T14:08:56Z
13,345,245
12
2012-11-12T14:12:27Z
[ "python", "design", "coding-style" ]
Since Python uses tabs spacing to indicate scope (and as such, has no `end` of `}` symbols), does that limit the language in any way from having particular functionality? *Note: I'm not talking about personal preferences on coding-style, I'm talking about real language limitation as a direct result of not having an `e...
There is no lack of `end`/ `}`: an end is represented by a "dedent" to the previous depth. So there is no limitation in any way. Example: ``` x = 123 while x > 10: if x % 21: print("x") print("y") print("z") ``` A "begin" corresponds to increasing of indentation level (after `while`, after `if`). An...
Code128 Barcode as HTML Image Tag with Data URI Scheme in Python
13,345,284
7
2012-11-12T14:15:09Z
13,350,788
10
2012-11-12T20:10:19Z
[ "python", "django", "barcode", "reportlab", "data-url" ]
I need to create an Code128 Barcodes with Pyton/Django which have to be embeded in HTML document. I don't want to make any temporary (or cache) files on the disk. That's why I want to embed them as Data URI Scheme. The result have to be something like this: ``` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...
This is my own solution: ``` from base64 import b64encode from reportlab.lib import units from reportlab.graphics import renderPM from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.graphics.shapes import Drawing def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanRe...
Strange behaviour with floats and string conversion
13,345,334
15
2012-11-12T14:18:16Z
13,346,122
12
2012-11-12T15:06:24Z
[ "python", "floating-point", "python-2.x" ]
I've typed this into python shell: ``` >>> 0.1*0.1 0.010000000000000002 ``` I expected that 0.1\*0.1 is not 0.01, because I know that 0.1 in base 10 is periodic in base 2. ``` >>> len(str(0.1*0.1)) 4 ``` I expected to get 20 as I've seen 20 characters above. Why do I get 4? ``` >>> str(0.1*0.1) '0.01' ``` Ok, thi...
The crucial requirement on `repr` is that it should round-trip; that is, `eval(repr(f)) == f` should give `True` in all cases. In Python 2.x (before 2.7) `repr` works by doing a `printf` with format `%.17g` and discarding trailing zeroes. This is guaranteed correct (for 64-bit floats) by IEEE-754. Since 2.7 and 3.1, P...
Python pytz: convert local time to utc. Localize doesn't seem to convert
13,345,948
5
2012-11-12T14:56:48Z
13,346,065
11
2012-11-12T15:03:38Z
[ "python", "timezone", "pytz" ]
I have a database that stores datetime as UTC. I need to look up info from a particular time, but the date and time are given in a local time, let's say 'Europe/Copenhagen'. I'm given these as: ``` year = 2012; month = 12; day = 2; hour = 13; min = 1; ``` So, I need to convert these to UTC so I can look them up in th...
`localize()` attaches the timezone to a naive `datetime.datetime` instance in the *local* timezone. If you have datetime values in a local timezone, localize to that timezone, then use [`.astimezone()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone) to cast the value to UTC: ``` >>> loca...
Create empty matrix Python
13,347,559
4
2012-11-12T16:32:07Z
13,347,614
12
2012-11-12T16:35:33Z
[ "python", "arrays", "vector", "matrix", "initialization" ]
I simply want to create an empty 10\*3\*2 array with Python. I first thought of these one, but this is not working: ``` parameters = [ [ [] * 2 ]*3 ] * 10 ``` this gives me a vector of ten vectors, with three [] elements in it: ``` [[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]...
I would recommend you use Numpy for this kind of stuff. It makes accessing columns or rows much easier. For your use case you'd do ``` import numpy as np matrix = np.zeros((2,3,10)) second_col = matrix[:,1,:] ``` Numpy will also take better care of your data, and it implements a lot of the matrix algebra in Fortran ...
Create empty matrix Python
13,347,559
4
2012-11-12T16:32:07Z
13,347,704
8
2012-11-12T16:41:17Z
[ "python", "arrays", "vector", "matrix", "initialization" ]
I simply want to create an empty 10\*3\*2 array with Python. I first thought of these one, but this is not working: ``` parameters = [ [ [] * 2 ]*3 ] * 10 ``` this gives me a vector of ten vectors, with three [] elements in it: ``` [[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]...
First of all, you should insert something into the innermost list (like None). Secondly, when you use the multiplication in the outermost list it replicates **references** to the inner list, so when you change one element, you will also change this element in all the other lists: ``` >> parameters = [ [ [None] * 2 ]*3...
python bound and unbound method object
13,348,031
22
2012-11-12T17:02:23Z
13,348,193
33
2012-11-12T17:12:11Z
[ "python", "object", "methods" ]
I've tried some code about bound and unbound methods. When we call them, I think both of them would return objects. But when I use `id()` for getting some information, it returns something I don't understand. IDE: Eclipse Plugin: pydev ``` Class C(object): def foo(self): pass cobj = C() print id(C.foo) ...
Whenever you look up a method via `class.name` or `instance.name`, the method object is created a-new. Python uses the [descriptor protocol](http://docs.python.org/2/reference/datamodel.html#implementing-descriptors) to wrap the function in a method object each time. So, when you look up `id(C.foo)`, a new method obje...
How to change a django QueryDict to Python Dict?
13,349,573
42
2012-11-12T18:45:07Z
13,349,753
54
2012-11-12T18:57:47Z
[ "python", "django" ]
Let's pretend I have the following QueryDict: ``` <QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}> ``` I'd like to have a dictionary out of this, eg: ``` {'num': [0], 'var1':['value1', 'value2'], 'var2':['8']} ``` (I don't care if the unicode symbol `u` stays or goes.) If I do `queryDic...
This should work: `myDict = dict(queryDict.iterlists())`
How to change a django QueryDict to Python Dict?
13,349,573
42
2012-11-12T18:45:07Z
15,283,515
80
2013-03-07T23:01:03Z
[ "python", "django" ]
Let's pretend I have the following QueryDict: ``` <QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}> ``` I'd like to have a dictionary out of this, eg: ``` {'num': [0], 'var1':['value1', 'value2'], 'var2':['8']} ``` (I don't care if the unicode symbol `u` stays or goes.) If I do `queryDic...
New in Django >= 1.4. `QueryDict.dict()` <https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.QueryDict.dict>
How to change a django QueryDict to Python Dict?
13,349,573
42
2012-11-12T18:45:07Z
22,100,334
9
2014-02-28T16:18:03Z
[ "python", "django" ]
Let's pretend I have the following QueryDict: ``` <QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}> ``` I'd like to have a dictionary out of this, eg: ``` {'num': [0], 'var1':['value1', 'value2'], 'var2':['8']} ``` (I don't care if the unicode symbol `u` stays or goes.) If I do `queryDic...
This is what I've ended up using: ``` def qdict_to_dict(qdict): """Convert a Django QueryDict to a Python dict. Single-value fields are put in directly, and for multi-value fields, a list of all values is stored at the field's key. """ return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists...
SqlAlchemy: filter to match all instead of any values in list?
13,349,832
6
2012-11-12T19:03:14Z
21,104,689
8
2014-01-14T01:41:43Z
[ "python", "mysql", "sql", "sqlalchemy" ]
I want to query a junction table for the value of column `aID` that matches all values of a list of ids `ids=[3,5]` in column `bID`. This is my junction table (`JT`): ``` aID bID 1 1 1 2 2 5 2 3 1 3 3 5 ``` I have this query: `session.query(JT.aID).filter(JT.bID.in...
Based on @Gordon Linoff answer and with two tables `A` and `B` where `A` has a relation one- to-many towards `B` called `A.bs` the SqlAlchemy equivalent would be: ``` from sqlalchemy import func session.query(A).join(B).filter(B.id.in_(<your_list>)).group_by(A.id).having(func.count(A.bs) == len(<your_list>)).all() `...
Slicing Sparse Matrices in Scipy -- Which Types Work Best?
13,352,280
10
2012-11-12T21:58:56Z
13,352,545
18
2012-11-12T22:22:14Z
[ "python", "indexing", "scipy", "sparse-matrix", "slice" ]
The SciPy [Sparse Matrix tutorial](http://www.scipy.org/SciPyPackages/Sparse) is very good -- but it actually leaves the section on slicing un(der)developed (still in outline form -- see section: "Handling Sparse Matrices"). I will try and update the tutorial, once this question is answered. I have a large sparse mat...
Ok, so I'm pretty sure the "right" way to do this is: if you are slicing columns, use tocsc() and slice using a list/array of integers. Boolean vectors does not seem to do the trick with sparse matrices -- the way it does with ndarrays in numpy. Which means the answer is. ``` indices = np.where(bool_vect)[0] out1 = M....
Python equivalent for #ifdef DEBUG
13,352,677
13
2012-11-12T22:33:08Z
27,455,446
12
2014-12-13T04:05:52Z
[ "python", "debugging" ]
In C we write code like ``` #ifdef DEBUG printf("Some debug log... This could probably be achieved by python logging.Logger"); /* Do some sanity check code */ assert someCondition /* More complex sanitycheck */ while(list->next){ assert fooCheck(list) } #endif ``` Is there a way to do this in python? Edit: I got my...
Use `__debug__` in your code: ``` if __debug__: print 'Debug ON' else: print 'Debug OFF' ``` Create a script `abc.py` with the above code and then 1. Run with `python -O abc.py` 2. Run with `python abc.py` Observe the difference.
Is Python's bool sorting defined?
13,353,744
6
2012-11-13T00:12:20Z
13,353,837
12
2012-11-13T00:21:28Z
[ "python", "sorting", "undefined-behavior" ]
Is the ordering of True and False well defined in Python, or is it left as an implementation detail? From the console, I'm seeing False sort before True...but I don't know if that's a behavior I should rely on or not. (I'm sure there's some Python doc about this, but I can't find it...)
<http://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy> > **Booleans**: These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the value...
How to symlink python in Homebrew?
13,354,207
11
2012-11-13T01:07:13Z
13,354,417
38
2012-11-13T01:35:11Z
[ "python", "symlink", "homebrew" ]
For some reason it's no symlinking when I run `brew link python.' I'm getting the following error and I do what it tells me to do but it's not working. I have tried doing what it tells me to do but maybe I'm not putting the formula\_name right. Also, when I do 'which python' it doesn't point to the Homebrew python and ...
Did you try `brew link --overwrite python`?
Python lambda closure scoping
13,355,233
21
2012-11-13T03:34:45Z
13,355,291
39
2012-11-13T03:43:26Z
[ "python", "lambda", "python-2.7", "closures" ]
I am trying to use closures to eliminate a variable from a function signature (the application is to make writing all the functions needed for connecting Qt signals for an interface to control a largish number of parameters to the dictionary that stores the values ). I do not understand why the case of using the `lamb...
The reason is that closures (lambdas or otherwise) close over names, not values. When you define `lambda x: test_fun(n, x)`, the n is not evaluated, because it is inside the function. It is evaluated when the function is *called*, at which time the value that is there is the last value from the loop. You say at the be...
Why python does not include a ordered dict (by default)?
13,355,239
2
2012-11-13T03:35:31Z
13,355,382
16
2012-11-13T03:56:53Z
[ "python", "design" ]
Python have some great structures to model data. Here are some : ``` +-------------------+-----------------------------------+ | indexed by int | no-indexed by int | +-------------+-------------------+-----------------------------------+ | no-indexed | [1, 2, 3] ...
Python's dictionaries are implemented as hash tables. Those are inherently unordered data structures. While it is possible to add extra logic to keep track of the order (as is done in [`collections.OrderedDict`](http://docs.python.org/3/library/collections.html#ordereddict-objects) in Python 2.7 and 3.1+), there's a no...
Password protect a whole django app
13,358,809
3
2012-11-13T10:09:35Z
13,360,732
9
2012-11-13T12:25:31Z
[ "python", "django", "authentication" ]
I am running a simple staging env on heroku and I am now looking to password protect the whole app with some sort of simple authentication I am wondering if there is a simple app or middleware that already supports this. Have tried looking around for solutions with Heroku / Cloudflare and django, but nothing seems rea...
I use `django-lockdown` for exactly this purpose. It allows you to add a simple password over the whole of a dev site, without having to add in any extra auth bits on your views that aren't used outside of a dev environment. It also means you can login as admin, or regular users to test whatever your site does <https:...
python mock side_effect or return_value dependent on call_count
13,358,939
18
2012-11-13T10:19:48Z
13,359,519
32
2012-11-13T10:57:15Z
[ "python", "mocking" ]
To test a polling function I want to mock the calling of a sub function so that the first time it is called it will fail, and the second time it is called it will succeed. Here's a very simplified version of it: ``` poll_function(var1): value = sub_function(var1) # First call will return None while not value:...
If I understand your question correctly, you do it by [setting `side_effect` to an iterable](http://www.voidspace.org.uk/python/mock/getting-started.html#side-effect-functions-and-iterables). For your simple case: ``` >>> mock_poll = Mock(side_effect=[None, 'data']) >>> mock_poll() None >>> mock_poll() 'data' ``` If ...
Is there a list of line styles in matplotlib?
13,359,951
35
2012-11-13T11:28:01Z
13,360,032
62
2012-11-13T11:33:39Z
[ "python", "matplotlib", "linestyle" ]
I'm writing a script that will do some plotting. I want it to plot several data series, each with its unique line style (not color). I can easily iterate through a list, but is there such a list already available in python?
According to [the doc](http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.lineStyles) you could find them by doing this : ``` from matplotlib import lines lines.lineStyles.keys() >>> ['', ' ', 'None', '--', '-.', '-', ':'] ``` You can do the same with [markers](http://matplotlib.org/api/artist_api.html...
SymPy cannot solve an equation that Matlab can
13,360,496
9
2012-11-13T12:09:08Z
13,361,101
9
2012-11-13T12:54:31Z
[ "python", "sympy" ]
I have an equation which is related to the sun-synchronous resonance condition in orbital mechanics. I'm learning Python at the moment, so I attempted to solve it in SymPy using the following code: ``` from sympy import symbols,solve [n_,Re_,p_,i_,J2_,Pe_] = symbols(['n_','Re_','p_','i_','J2_','Pe_']) del_ss = -((3*...
1. Use the sympy version of Pi. 2. Substitute `cos(i_)` by a new variable `ci_`, replace `sin(i_)**2` by `1-ci_**2`, and solve for `ci_`. This should do it: ``` from sympy import symbols,solve,sin,cos,pi [n_,Re_,p_,ci_,J2_,Pe_] = symbols(['n_','Re_','p_','ci_','J2_','Pe_']) del_ss = -((3*n_*(Re_**2)*J2_/(4*(p_**2))...
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
13,361,510
5
2012-11-13T13:25:57Z
13,361,543
7
2012-11-13T13:28:08Z
[ "python", "python-3.x" ]
I try to sum two dictionaries like that: ``` my_new_dict = dict(my_existing_dict.items() + my_new_dict.items()) ``` but recieve error ``` TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' ``` What I do wrong?
The first problem is this is ambiguous - dictionaries can't have duplicate keys, so it is unclear what you mean, what should happen if both contain the same key? The main issue here, however, is that [dictionary views are set-like](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects), so they don't ...
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
13,361,510
5
2012-11-13T13:25:57Z
13,361,547
12
2012-11-13T13:28:18Z
[ "python", "python-3.x" ]
I try to sum two dictionaries like that: ``` my_new_dict = dict(my_existing_dict.items() + my_new_dict.items()) ``` but recieve error ``` TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' ``` What I do wrong?
In python3, `dict.items()` returns an object with type `dict_items` which apparently can't be added. (in python 2, it returned a `list` which could be added). An alternative way to add a pair of dictionaries which works on py2k and py3k: ``` d = dict1.copy() d.update(dict2) ``` Of course, there's some ambiguity abou...
Django: Can I create a QueryDict from a dictionary?
13,363,628
18
2012-11-13T15:31:14Z
13,363,666
21
2012-11-13T15:34:11Z
[ "python", "django" ]
Imagine that I have a dictionary in my Django application: ``` dict = {'a': 'one', 'b': 'two', } ``` Now I want to easily create an urlencoded list of GET parameters from this dictionary. Of course I could loop through the dictionary, urlencode keys and values and then concatenate the string by myself, but there must...
How about? ``` dict = {'a': 'one', 'b': 'two', } qdict = QueryDict('', mutable=True) qdict.update(dict) ```
Django: Can I create a QueryDict from a dictionary?
13,363,628
18
2012-11-13T15:31:14Z
13,363,676
12
2012-11-13T15:34:28Z
[ "python", "django" ]
Imagine that I have a dictionary in my Django application: ``` dict = {'a': 'one', 'b': 'two', } ``` Now I want to easily create an urlencoded list of GET parameters from this dictionary. Of course I could loop through the dictionary, urlencode keys and values and then concatenate the string by myself, but there must...
Python has a built in tool for encoding a dictionary (any mapping object) into a query string ``` params = {'a': 'one', 'b': 'two', } urllib.urlencode(params) 'a=one&b=two' ``` <http://docs.python.org/2/library/urllib.html#urllib.urlencode> `QueryDict` takes a querystring as first param of its contstructor `def _...
Printing exceptions in Python, instead of raising them
13,364,023
3
2012-11-13T15:54:18Z
13,364,058
9
2012-11-13T15:55:54Z
[ "python", "exception", "exception-handling" ]
I want to catch a Python exception and print it rather than re-raising it. For example: ``` def f(x): try: return 1/x except: print <exception_that_was_raised> ``` This should then do: ``` >>> f(0) 'ZeroDivisionError' ``` without an exception being raised. Is there a way to do this, other t...
use the `message` attribute of exception or `e.__class__.__name__` if you want the name of the Base exception class , i.e `ZeroDivisionError'` in your case ``` In [30]: def f(x): try: return 1/x except Exception as e: print e.message ....: In [31]: f(2) Out[31]:...
Passing Python variables via command line?
13,364,119
2
2012-11-13T15:59:26Z
13,364,152
7
2012-11-13T16:01:16Z
[ "python", "command-line", "command-line-arguments" ]
I'm new to Python (as in, yesterday), so bear with me if I don't know 'the obvious' yet. There are two ways I could go about this, and either would work fine for me, and I'm not sure if `getopt` or `optparse` contains what I want/need (from what I'm reading)? I would like to do something similar to the following: ```...
You definitely want a commandline argument parser. Python ships with a few. Python2.7 has [`argparse`](http://docs.python.org/dev/library/argparse.html) which can be back-ported to earlier versions as necessary and is what I would recommend. There's also [`optparse`](http://docs.python.org/dev/library/optparse.html). I...
Python error: AttributeError: 'int' object has no attribute 'append'
13,365,053
2
2012-11-13T16:53:54Z
13,365,098
8
2012-11-13T16:55:58Z
[ "python", "dictionary" ]
So I've looked through similar questions, and I'm still getting the same problem and can't figure it out. For this programming assignment, I'm creating a simplified version of lexical analysis for a small subset of the Clite lexicon. I'm extracting tokens from an input file, outputting the results of my analysis. I'm c...
You first set your `dict` values to be an `int`: ``` stable[x1]=y ``` but then you later on you try to treat it as if it is a `list`: ``` stable[x1].append(y) ``` Start out with a `list` containing your first `int` instead: ``` stable[x1]=[y] ``` and the `.append()` will work. Alternatively, you coul...
What does 'result[::-1]' mean?
13,365,424
6
2012-11-13T17:15:29Z
13,365,445
9
2012-11-13T17:16:37Z
[ "python", "slice" ]
I am just coming cross the following python code which confuses me a bit: ``` res = self.result[::-1].encode('hex') ``` The encode stuff is pretty clear, it should be represented as hex value. However, what does this self.result[::-1] mean, especially the colons?
It represents the 'slice' to take from the result. The first element is the starting position, the second is the end (non-inclusive) and the third is the step. An empty value before/after a colon indicates you are either starting from the beginning (`s[:3]`) or extending to the end (`s[3:]`). You can include actual num...
Large number of subplots with matplotlib
13,365,617
6
2012-11-13T17:26:57Z
13,365,719
8
2012-11-13T17:33:15Z
[ "python", "graphics", "plot", "matplotlib", "subplot" ]
I would like to create plot with many (100) subplots with Python matplotlib. I cannot find appropriate syntax for it: I would like something like (this is not working) ``` plt.subplot(10,10,i,X1, Y) ``` in a loop with i from 0 to 99, then ``` plt.show() ``` Syntax is available in many tutorials for case when there...
Try this: ``` fig, ax = plt.subplots(10, 10) ``` where ax will contain one hundred axis in a list (of lists). It is a really handy function, from [the docs](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots): ``` Definition: plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,...
Install Python-Dbus in virtualenv
13,365,697
13
2012-11-13T17:31:50Z
13,367,493
9
2012-11-13T19:36:17Z
[ "python", "installation", "virtualenv", "dbus" ]
I am running an application in a virtual environment that needs access to DBus (to interact with the Network Manager, mainly). I tried to install Dbus-Python with easyinstall and pip, but both fail. When I try to do this: ``` (myvirtualenv)borrajax@borrajax-computer:~/Documents/Projects/VirtualEnvs/current_env$ bin/...
My suggestion is to install the system package for the Python DBUS bindings and then create the *virtualenv* with the `--system-site-packages` command line option to enable access to the system-wide Python packages (including the `dbus` package) from the activated *virtualenv*. For example on Debian/Ubuntu (or a derive...
Install Python-Dbus in virtualenv
13,365,697
13
2012-11-13T17:31:50Z
13,367,555
12
2012-11-13T19:40:07Z
[ "python", "installation", "virtualenv", "dbus" ]
I am running an application in a virtual environment that needs access to DBus (to interact with the Network Manager, mainly). I tried to install Dbus-Python with easyinstall and pip, but both fail. When I try to do this: ``` (myvirtualenv)borrajax@borrajax-computer:~/Documents/Projects/VirtualEnvs/current_env$ bin/...
When `pip` tries to install a package, it looks for `setup.py`, which `dbus-python` doesn't have, so you'll have to [download the source](http://dbus.freedesktop.org/releases/dbus-python/) and compile it manually. Shouldn't be too hard: ``` PYTHON=python3.3 ./configure --prefix=/tmp/dbus-python make make install ``` ...
Install Python-Dbus in virtualenv
13,365,697
13
2012-11-13T17:31:50Z
23,237,728
8
2014-04-23T07:30:47Z
[ "python", "installation", "virtualenv", "dbus" ]
I am running an application in a virtual environment that needs access to DBus (to interact with the Network Manager, mainly). I tried to install Dbus-Python with easyinstall and pip, but both fail. When I try to do this: ``` (myvirtualenv)borrajax@borrajax-computer:~/Documents/Projects/VirtualEnvs/current_env$ bin/...
Another workaround is to just manually copy the `dbus` files/libraries directly to your virtualenv: ``` cp -r /usr/lib/pythonX.X/{site or dist}-packages/dbus myvirtenv/usr/lib/pythonX.X/site-packages/ cp -r /usr/lib/pythonX.X/{site or dist}-packages/_dbus_*.so myvirtenv/usr/lib/pythonX.X/site-packages/ ```
When do we need Python Import Statements?
13,365,848
5
2012-11-13T17:42:13Z
13,365,954
9
2012-11-13T17:49:41Z
[ "python", "python-import" ]
A piece of code works that I don't see why. It shouldn't work from my understanding. The problem is illustrated easily below: "Main.py" ``` from x import * #class x is defined from y import * #class y is defined xTypeObj = x() yTypeObj = y() yTypeObj.func(xTypeObj) ``` "x.py" ``` class x(object): def __init_...
Python is an object-oriented programming language. In such a language, values are objects, and objects can have methods. The `functionThatReturnsAString` function is a method on a class, and `objOfTypeX` is an *instance* of that class. Instances of a class carry with them all the methods of it's class. This is why, f...
How to convince python tox to run tests only for the available python interpreters?
13,365,876
7
2012-11-13T17:44:17Z
26,246,795
9
2014-10-07T23:15:25Z
[ "python", "tox" ]
I am using python [tox](http://pypi.python.org/pypi/tox) to run python unittest for several versions of python, but these python interpreters are not all available on all machines or platforms where I'm running tox. How can I configure tox so it will run tests only when python interpretors are available. Example of `...
As of Tox version 1.7.2, you can pass the `--skip-missing-interpreters` flag to achieve this behavior. You can also set `skip_missing_interpreters=true` in your `tox.ini` file. More info [here](http://tox.readthedocs.org/en/latest/config.html#confval-skip_missing_interpreters=BOOL). ``` [tox] envlist = py24, py25,...
Django Celery Logging Best Practice
13,366,312
42
2012-11-13T18:14:11Z
13,429,851
45
2012-11-17T10:53:03Z
[ "python", "django", "logging", "celery", "django-celery" ]
I'm trying to get Celery logging working with `Django`. I have logging set-up in `settings.py` to go to console (that works fine as I'm hosting on `Heroku`). At the top of each module, I have: ``` import logging logger = logging.getLogger(__name__) ``` And in my tasks.py, I have: ``` from celery.utils.log import get...
When your logger initialized in the beginning of "another module" it links to another logger. Which handle your messages. It can be root logger, or usually I see in Django projects - logger with name `''`. Best way here, is overriding your logging config: ``` LOGGING = { 'version': 1, 'disable_existing_logger...
Django Celery Logging Best Practice
13,366,312
42
2012-11-13T18:14:11Z
13,504,469
7
2012-11-22T01:00:33Z
[ "python", "django", "logging", "celery", "django-celery" ]
I'm trying to get Celery logging working with `Django`. I have logging set-up in `settings.py` to go to console (that works fine as I'm hosting on `Heroku`). At the top of each module, I have: ``` import logging logger = logging.getLogger(__name__) ``` And in my tasks.py, I have: ``` from celery.utils.log import get...
It is troubling that Celery interferes with the root logger (which is not best practice and can't be controlled completely), but it does not disable your app's custom loggers in any way, so use your own handler names and define your own behavior rather than trying to fix this issue with Celery. [I like to keep my appli...
Collatz conjecture sequence
13,366,830
2
2012-11-13T18:50:16Z
13,366,858
7
2012-11-13T18:52:12Z
[ "python" ]
The Collatz conjecture what i am trying to do: Write a function called collatz\_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1,...
You forgot to append the `x` values to the `seq` list: ``` def collatz_sequence(x): seq = [x] if x < 1: return [] while x > 1: if x % 2 == 0: x = x / 2 else: x = 3 * x + 1 seq.append(x) # Added line return seq ``` Verification: ``` ~/tmp$ python colla...
How do I reload this module?
13,367,386
2
2012-11-13T19:29:16Z
13,367,389
8
2012-11-13T19:29:41Z
[ "python", "module", "reload" ]
``` from mypackage.pkg import mymodule ... reload(mypackage.pkg.mymodule) ``` results in `NameError: global name 'mypackage' is not defined.` How should mymodule be reloaded?
``` from mypackage.pkg import mymodule reload(mymodule) ``` or ``` import mypackage.pkg.mymodule ... reload(mypackage.pkg.mymodule) ```
Having trouble with scipy Minimize function, it is giving me odd results
13,367,576
4
2012-11-13T19:41:55Z
14,382,625
7
2013-01-17T15:37:47Z
[ "python", "scipy", "minimize" ]
Created an objective function Added constraints The problem is no matter what initial guess I use, the minimize functions just keeps on using that number. for example: If I use 15 for the initial guess, the solver will not try any other number and say the answer is 15. I'm sure the ere is an issue with the code but ...
Your function is piecewise constant between integer input values, as seen in the plot below (plotted in steps of 0.1 on the x axis): ![function plot](http://i.stack.imgur.com/uRWIU.png) So the derivative is zero at almost all points, and that's why a gradient based minimization method will return any given initial po...
What is the workflow for a secure 'verify by email' system?
13,367,709
10
2012-11-13T19:51:13Z
13,368,052
12
2012-11-13T20:15:21Z
[ "python", "email", "flask", "email-verification" ]
I am thinking of a forum type system that will allow users to post/edit posts without an account but thru e-mail verification. So you would fill out the form, supply email address, submit, and then receive a link in an email that would 'activate' your post. Same thing to edit. Click 'edit', receive email with link, li...
Since you are using flask, you might want to look at this: <http://flask.pocoo.org/snippets/50/> using the example from above link, the workflow could be something like: 1. User enters the email and post. 2. Generate the secure link using `itsdangerous` module which can be tied to the specific email (explained in sn...
How to create a tuple of tuples in python?
13,367,710
2
2012-11-13T19:51:14Z
13,367,719
11
2012-11-13T19:52:09Z
[ "python" ]
I want to combine: ``` A = (1,3,5) B = (2,4,6) ``` into: ``` C = ((1,2), (3,4), (5,6)) ``` Is there a function that does this in python?
Yes: ``` tuple(zip(A, B)) ``` And this is all. The result will be as follows (both in Python 2.x and 3.x): ``` >>> tuple(zip(A, B)) ((1, 2), (3, 4), (5, 6)) ```
Are python Exceptions as class attributes a bad thing?
13,368,100
7
2012-11-13T20:19:36Z
13,368,180
8
2012-11-13T20:25:01Z
[ "python", "exception" ]
I find myself often wanting to structure my exception classes like this: ``` # legends.py class Error(Exception): pass class Rick(object): class Error(Error): pass class GaveYouUp(Error): pass class LetYouDown(Error): pass class Michael(object): class Error(Error): pass class BlamedItOnTheSunshin...
This is the exact pattern used by Django for certain ORM-related exceptions. The advantage is that you can have an except clause which checks against a type accessed through an instance: ``` rick = Rick() try: rick.roll() except rick.GaveYouUp: never() except rick.LetYouDown: never_ever() ``` This doesn't ...
Python split a list into subsets based on pattern
13,368,723
7
2012-11-13T21:02:22Z
13,368,753
13
2012-11-13T21:04:45Z
[ "python" ]
I'm doing this but it feels this can be achieved with much less code. It is Python after all. Starting with a list, I split that list into subsets based on a string prefix. ``` # Splitting a list into subsets # expected outcome: # [['sub_0_a', 'sub_0_b'], ['sub_1_a', 'sub_1_b']] mylist = ['sub_0_a', 'sub_0_b', 'sub_1...
You could use [`itertools.groupby`](https://docs.python.org/library/itertools.html#itertools.groupby): ``` >>> import itertools >>> mylist = ['sub_0_a', 'sub_0_b', 'sub_1_a', 'sub_1_b'] >>> for k,v in itertools.groupby(mylist,key=lambda x:x[:5]): ... print k, list(v) ... sub_0 ['sub_0_a', 'sub_0_b'] sub_1 ['sub_1...
Drawing a line consisting of multiple points using PyQt
13,368,947
2
2012-11-13T21:16:42Z
13,370,267
9
2012-11-13T22:49:57Z
[ "python", "pyqt", "drawing", "pyqt4" ]
I want to draw a line consisting of multiple points via mouse click in a Python script using PyQt. I need all coordinates of the ponts and I want to be able to delete the line. Here's my script doing all the work, except for the graphical line drawing itself, it just prints what it does: ``` #!/usr/bin/python3 import...
You should probably use the [graphics view framework](http://doc.qt.nokia.com/latest/graphicsview.html) for drawing the lines, rather than attempting to paint them directly. Here's a basic demo to get you started: ``` from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui....
Why is "aClass.aProperty" not callable?
13,369,051
3
2012-11-13T21:24:15Z
13,369,120
9
2012-11-13T21:28:13Z
[ "python" ]
``` class A: @property def p(self): return 2 def q(self): return 2 a = A() A.p(a) #>> TypeError: 'property' object is not callable A.q(a) #>> no error, returns 2 ``` Why is this? I understand if I referred to the property on an *instance* : a.p would simply return the method return value, but I am trying to s...
You're digging into the world of [`descriptors`](http://docs.python.org/2/howto/descriptor.html). `A.p` is a `property` and properties are *descriptors*. It's a class that has magic methods (`__get__`, `__set__` ...) which get called when the descriptor is accessed on an *instance*. The particular method accessed depen...
matplotlib y-axis label on right side
13,369,888
19
2012-11-13T22:20:51Z
13,369,977
25
2012-11-13T22:28:18Z
[ "python", "matplotlib", "labels" ]
Is there a simple way to put the y-axis label on the right-hand side of the plot? I know that this can be done for the tick labels using `ax.yaxis.tick_right()`, but I would like to know if it can be done for the axis label as well. One idea which came to mind was to use ``` ax.yaxis.tick_right() ax2 = ax.twinx() ax2...
It looks like you can do it with: ``` ax.yaxis.set_label_position("right") ``` See [here](http://web.archive.org/web/20120618121009/http://notes.brooks.nu/2008/03/plotting-on-left-and-right-axis-simulateously-using-matplotlib-and-numpy) for an example.
SQLAlchemy default DateTime
13,370,317
39
2012-11-13T22:55:02Z
13,370,382
60
2012-11-13T23:01:29Z
[ "python", "date", "sqlalchemy" ]
This is my declarative model: ``` import datetime from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) created_date = DateTime(default=datetime.datetime.utc...
`DateTime` doesn't have a default key as an input. The default key should be an input to the `Column` function. Try this: ``` import datetime from sqlalchemy import Column, Integer, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test'...
SQLAlchemy default DateTime
13,370,317
39
2012-11-13T22:55:02Z
30,083,454
28
2015-05-06T17:17:25Z
[ "python", "date", "sqlalchemy" ]
This is my declarative model: ``` import datetime from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) created_date = DateTime(default=datetime.datetime.utc...
You can also use sqlalchemy builtin function for default DateTime ``` from sqlalchemy.sql import func DT = Column(DateTime(timezone=True), default=func.now()) ```
SQLAlchemy default DateTime
13,370,317
39
2012-11-13T22:55:02Z
33,532,154
22
2015-11-04T21:15:47Z
[ "python", "date", "sqlalchemy" ]
This is my declarative model: ``` import datetime from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) created_date = DateTime(default=datetime.datetime.utc...
### Calculate timestamps within your DB, not your client For sanity, you probably want to have all `datetimes` calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different c...
Filling continuous pandas dataframe from sparse dataframe
13,370,525
9
2012-11-13T23:14:28Z
13,371,090
16
2012-11-14T00:10:23Z
[ "python", "python-2.7", "pandas" ]
I have a dictionary name date\_dict keyed by datetime dates with values corresponding to integer counts of observations. I convert this to a sparse series/dataframe with censored observations that I would like to join or convert to a series/dataframe with continuous dates. The nasty list comprehension is my hack to get...
You can just use reindex on a time series using your date range. Also it looks like you would be better off using a TimeSeries instead of a DataFrame (see [documentation](http://pandas.pydata.org/pandas-docs/stable/timeseries.html)), although reindexing is also the correct method for adding missing index values to Data...
SQLAlchemy Query and_/or_ Issue
13,370,993
2
2012-11-14T00:00:03Z
13,371,600
7
2012-11-14T01:05:08Z
[ "python", "sql", "sqlalchemy" ]
I have a query that I'm trying to build. The query seems to work in parts, both separate parts of the query return the correct number of elements. However, the combined query returns an empty result set, which is incorrect. Note: I know the and\_'s are not needed for Query 1 and 2, but I wanted to make sure that and\_...
I'm seeing the same problem you're on SA 0.7.9 What seems to be happing is that the parentheses aren't being applied correctly the way you want them. I used self\_group() which makes this work but the thing is you shouldn't have to use it. Here are the docs for [self\_group](http://docs.sqlalchemy.org/en/latest/core/s...
Django/Python code: readable vs fast code
13,371,246
2
2012-11-14T00:26:48Z
13,371,285
11
2012-11-14T00:30:51Z
[ "python", "django" ]
Lets say I want to get a record that match a value and I have 2 approaches to do it: First: ``` try: obj = Model.objects.get(field = value) except pass ``` Second: ``` if Model.objects.filter(field = value).count() > 0: obj = Model.objects.filter(field_value)[0] ``` Lets put the code comments aside,which way...
The first is preferred in Python, based on the **EAFP** design principle ("Easier to Ask Forgiveness than Permission"). Aside from speed, one advantage of this system is that there is no race condition -- in the second example, if other concurrent access to the database changes the results between the execution of the ...
Multi-tenancy with SQLAlchemy
13,372,001
7
2012-11-14T02:02:14Z
18,757,049
7
2013-09-12T06:36:22Z
[ "python", "postgresql", "sqlalchemy", "multi-tenant" ]
I've got a web-application which is built with Pyramid/SQLAlchemy/Postgresql and allows users to manage some data, and that data is almost completely independent for different users. Say, Alice visits `alice.domain.com` and is able to upload pictures and documents, and Bob visits `bob.domain.com` and is also able to up...
After pondering on jd's answer I was able to achieve the same result for postgresql 9.2, sqlalchemy 0.8, and flask 0.9 framework: ``` from sqlalchemy import event from sqlalchemy.pool import Pool @event.listens_for(Pool, 'checkout') def on_pool_checkout(dbapi_conn, connection_rec, connection_proxy): tenant_id = se...
Python ElementTree parsing unbound prefix error
13,372,604
8
2012-11-14T03:30:54Z
14,849,891
8
2013-02-13T09:07:07Z
[ "python", "xml", "prefix", "elementtree" ]
I am learning ElementTree in python. Everything seems fine except when I try to parse the xml file with prefix: `test.xml`: ``` <?xml version="1.0"?> <abc:data> <abc:country name="Liechtenstein" rank="1" year="2008"> </abc:country> <abc:country name="Singapore" rank="4" year="2011"> </abc:country> <abc...
Add the abc namespace to your xml file. ``` <?xml version="1.0"?> <abc:data xmlns:abc="your namespace"> ```
Keyword argument performance (python)
13,372,740
3
2012-11-14T03:49:42Z
13,372,805
9
2012-11-14T03:58:15Z
[ "python", "performance", "keyword-argument" ]
I am trying to optimise some python code, via testing (timing) various functions using timeit. I have found that I am getting different speeds depending on whether a variable is a keyword argument or within the function. That is: ``` def test_function(A = value()): #rest of function.... ``` Is returning a diffe...
Keyword arguments are evaluated once at function definition time. So in your first example `value()` is called exactly once, no matter how often you call the test function. If `value()` is expensive-ish this explains the difference in runtime between the two versions.
Use uuid.uuid4() to create new file
13,372,951
7
2012-11-14T04:15:21Z
13,372,966
19
2012-11-14T04:17:08Z
[ "python" ]
How do you concatenate the uuid.uuid4() value with a literal when creating a file? The below isn't correct but should illustrate what I'm attempting to do... ``` fo = open(uuid.uuid4() + ".txt", "wb") ```
You need to convert the `uuid` to a `str`: ``` >>> import uuid >>> str(uuid.uuid4()) + ".txt" '13eb9327-f40e-4ef1-8020-1c36af1b4b70.txt' ```
How to check if record exists with Python MySQdb
13,373,843
6
2012-11-14T06:06:17Z
13,373,969
10
2012-11-14T06:21:35Z
[ "python", "mysql", "mysql-python" ]
Im creating a python program that connects to mysql. i need to check if a table contains the number 1 to show that it has connected successfully, this is my code thus far: ``` xcnx.execute('CREATE TABLE settings(status INT(1) NOT NULL)') xcnx.execute('INSERT INTO settings(status) VALUES(1)') cnx.commit() sqlq =...
I believe the most efficient "does it exist" query is just to do a `count`: ``` sqlq = "SELECT COUNT(1) FROM settings WHERE status = '1'" xcnx.execute(sqlq) if xcnx.fetchone()[0]: # exists ``` Instead of asking the database to perform any count operations on fields or rows, you are just asking it to return a 1 or...
Django Storages - Could Not Load Amazon's S3 Bindings Errors
13,374,247
8
2012-11-14T06:50:16Z
13,381,890
15
2012-11-14T15:32:07Z
[ "python", "django", "amazon-s3", "amazon-web-services", "django-storage" ]
Hey so trying to connect my user uploaded images to my S3 bucket so the images will store there. Using django storages (did some research, seemed to be what everyone suggested, but open to ideas) Here's what I did: Installed django storages ``` pip install django-storages ``` Added it to my INSTALLED\_APPS ``` #se...
Do you have python-boto installed? `pip install boto`
Dictionary where keys are pair of integers in Python
13,375,301
4
2012-11-14T08:30:10Z
13,375,323
7
2012-11-14T08:31:35Z
[ "python", "string", "performance", "dictionary", "tuples" ]
How is possible in Python to create a dictionary where the keys are pairs of integers? For example, if I do this: ``` mydict=dict() mydict[ [1,2] ] = 'xxx' ``` I get the error `TypeError: unhashable type: 'list'` So I came up with two different solutions: strings or tuples as keys. A first solution seems to conver...
You should probably use a tuple, which can be hashed: ``` mydict = {} mydict[(1, 2)] = 'xxx' # or more concisely (@JamesHenstridge): mydict[1,2] = 'xxx' ``` If that is actually too slow (don't optimise unnecessarily), then given a maximum value for the one integer, construct an index: ``` def index(a, b, maxB): ...
"Proper" way to handle signals other than SIGINT in Python?
13,377,773
3
2012-11-14T11:16:56Z
13,378,244
7
2012-11-14T11:48:45Z
[ "python", "signals" ]
I had some Python code that needed to be able to handle SIGINT. For this purpose I used something like this: ``` def mymethod(*params): obj = MyObj(params) try: obj.do_some_long_stuff() except KeyboardInterrupt: obj.cleanup() ``` Awesome and really straightforward. Yay, Python is great! However, I now ...
Or use a closure: ``` import os import signal def create_handler(obj): def _handler(signum, frame): print "obj is availiable here!" print obj signal.signal(signum, signal.SIG_DFL) os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it return _handler def ...
Is it possible to get an Excel document's row count without loading the entire document into memory?
13,377,793
13
2012-11-14T11:18:02Z
13,380,771
12
2012-11-14T14:32:13Z
[ "python", "openpyxl" ]
I'm working on an application that processes huge Excel 2007 files, and I'm using [OpenPyXL](http://packages.python.org/openpyxl/) to do it. OpenPyXL has two different methods of reading an Excel file - one "normal" method where the entire document is loaded into memory at once, and one method where iterators are used ...
Taking a look at the source code of OpenPyXL ([IterableWorksheet](https://bitbucket.org/ericgazoni/openpyxl/src/94b05cf9defb9787b4dfbf9e8dca7ba6e0b33d56/openpyxl/reader/iter_worksheet.py?at=default#cl-251)) I've figured out how to get the column and row count from an iterator worksheet: ``` wb = load_workbook(path, us...
Is it possible to get an Excel document's row count without loading the entire document into memory?
13,377,793
13
2012-11-14T11:18:02Z
32,512,850
15
2015-09-10T22:52:10Z
[ "python", "openpyxl" ]
I'm working on an application that processes huge Excel 2007 files, and I'm using [OpenPyXL](http://packages.python.org/openpyxl/) to do it. OpenPyXL has two different methods of reading an Excel file - one "normal" method where the entire document is loaded into memory at once, and one method where iterators are used ...
Adding on to what Hubro said, apparently `get_highest_row()` has been deprecated. Using the `max_row` and `max_column` properties returns the row and column count. For example: ``` wb = load_workbook(path, use_iterators=True) sheet = wb.worksheets[0] row_count = sheet.max_row column_count = sheet.max_...
Are Django Model instances Hashable?
13,378,318
5
2012-11-14T11:53:51Z
13,381,568
9
2012-11-14T15:14:37Z
[ "python", "django", "django-models" ]
Are Django Model instances Hashable? For example, can I use a Django Model instance as a dictionary key, or create a Set of unique models? If they are Hashable, what causes two Django Model instances to be considered the same? Does it implement Hashable naively such that it only consider them to be the same if they ar...
Model instances are Hashable. They are considered to be the same if they are Models of the same type and have the same primary key. You can see this [defined in `django.db.models.base`](https://github.com/django/django/blob/master/django/db/models/base.py#L456): ``` class Model(object): ... def __hash__(self...
checking if the first letter of a word is a vowel
13,379,243
3
2012-11-14T12:56:16Z
13,379,266
11
2012-11-14T12:57:52Z
[ "python", "list", "search" ]
Before I ask the question I want to let you know that I am not an experienced programmer but someone learning the basics of python on codecademy.com. I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So f...
try `my_word[0].lower() in the_vowel`
checking if the first letter of a word is a vowel
13,379,243
3
2012-11-14T12:56:16Z
13,379,302
9
2012-11-14T13:00:01Z
[ "python", "list", "search" ]
Before I ask the question I want to let you know that I am not an experienced programmer but someone learning the basics of python on codecademy.com. I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So f...
Here are some hints to help you figure it out. To get a single letter from a string subscript the string. ``` >>> 'abcd'[2] 'c' ``` Note that the first character is character zero, the second character is character one, and so forth. The next thing to note is that an upper case letter does not compare equal to a lo...
checking if the first letter of a word is a vowel
13,379,243
3
2012-11-14T12:56:16Z
13,379,373
10
2012-11-14T13:04:38Z
[ "python", "list", "search" ]
Before I ask the question I want to let you know that I am not an experienced programmer but someone learning the basics of python on codecademy.com. I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So f...
I don't know if it is better than the answers already posted here, but you could also do: ``` vowels = ('a','e','i','o','u','A','E','I','O','U') myWord.startswith(vowels) ```
Right way to clean up a temporary folder in Python class
13,379,742
15
2012-11-14T13:29:40Z
13,379,969
29
2012-11-14T13:42:59Z
[ "python", "destructor", "temporary-directory" ]
I am creating a class in which I want to generate a temporary workspace of folders that will persist for the life of the object and then be removed. I am using tempfile.mkdtemp() in the def **init** to create the space, but I have read that I can't rely on **del** being called. I am wanting something like this: ``` c...
Caveat: you can never *guarantee* that the temp folder will be deleted, because the user could always hard kill your process and then it can't run anything else. That said, do ``` temp_dir = tempfile.mkdtemp() try: <some code> finally: shutil.rmtree(temp_dir) ``` --- Since this is a very common operation, P...
Compare similarity of images using OpenCV with Python
13,379,909
27
2012-11-14T13:39:48Z
13,483,835
22
2012-11-20T23:13:00Z
[ "python", "opencv", "computer-vision" ]
I'm trying to compare a image to a list of other images and return a selection of images (like Google search images) of this list with up to 70% of similarity. I get this code in [this post](http://stackoverflow.com/questions/10984313/opencv-2-4-1-computing-surf-descriptors-in-python/10987035#10987035) and change for ...
I suggest you to take a look to the earth mover's distance (EMD) between the images. This metric gives a feeling on how hard it is to tranform a normalized grayscale image into another, but can be generalized for color images. A very good analysis of this method can be found in the following paper: [robotics.stanford....
Compare similarity of images using OpenCV with Python
13,379,909
27
2012-11-14T13:39:48Z
13,505,123
9
2012-11-22T02:34:45Z
[ "python", "opencv", "computer-vision" ]
I'm trying to compare a image to a list of other images and return a selection of images (like Google search images) of this list with up to 70% of similarity. I get this code in [this post](http://stackoverflow.com/questions/10984313/opencv-2-4-1-computing-surf-descriptors-in-python/10987035#10987035) and change for ...
You are embarking on a massive problem, referred to as "content based image retrieval", or CBIR. It's a massive and active field. There are no finished algorithms or standard approaches yet, although there are a lot of techniques all with varying levels of success. Even Google image search doesn't do this (yet) - they...
Compare similarity of images using OpenCV with Python
13,379,909
27
2012-11-14T13:39:48Z
13,517,771
11
2012-11-22T17:43:33Z
[ "python", "opencv", "computer-vision" ]
I'm trying to compare a image to a list of other images and return a selection of images (like Google search images) of this list with up to 70% of similarity. I get this code in [this post](http://stackoverflow.com/questions/10984313/opencv-2-4-1-computing-surf-descriptors-in-python/10987035#10987035) and change for ...
I wrote a program to do something very similar maybe 2 years ago using Python/Cython. Later I rewrote it to Go to get better performance. The base idea comes from [findimagedupes](http://www.jhnc.org/findimagedupes/) IIRC. It basically computes a "fingerprint" for each image, and then compares these fingerprints to ma...
Modify an existing Excel file using Openpyxl in Python
13,381,384
5
2012-11-14T15:04:11Z
13,382,230
8
2012-11-14T15:50:05Z
[ "python", "csv", "openpyxl" ]
I am basically trying to copy some specific columns from a CSV file and paste those in an existing excel file[\*.xlsx] using python. Say for example, you have a CSV file like this : ``` col_1 col_2 col_3 col_4 1 2 3 4 5 6 7 8 9 10 11 12 ``` So, i wanted to c...
You can try the following implementation ``` from openpyxl import load_workbook import csv def update_xlsx(src, dest): #Open an xlsx for reading wb = load_workbook(filename = dest) #Get the current Active Sheet ws = wb.get_active_sheet() #You can also select a particular sheet #based on sheet n...
OpenCV 2.4.3 and Python
13,381,574
12
2012-11-14T15:14:56Z
13,385,670
8
2012-11-14T19:14:05Z
[ "python", "opencv", "documentation" ]
Few days ago I went into searching for a good way to make a simple computer vision system. OpenCV library is something I need but it proved hard to learn with Python especially after OpenCV 2.4.3 update which have very slim Python related documentation. So I now understand that there was a bunch of changes in OpenCV, f...
I think you are taking it in the reverse path. Actually, with the new `cv2` module, OpenCV has become far more simple compared to old `cv` interface. Not just simple, but very fast and highly productive, due to the Numpy support. Only thing is that, we should know how to use it appropriately. Here, you should use the...
Initialize list with same bool value
13,382,774
15
2012-11-14T16:21:03Z
13,382,804
50
2012-11-14T16:22:48Z
[ "python", "list", "initialization", "boolean" ]
Is it possible without loops initialize all list values to some bool? For example I want to have a list of N elements all False.
You can do it like this: - ``` >>> [False] * 10 [False, False, False, False, False, False, False, False, False, False] ``` **NOTE: -** Note that, you should never do this with a `list` of `mutable types` with same value, else you will see surprising behaviour like the one in below example: - ``` >>> my_list = [[10]]...
Initialize list with same bool value
13,382,774
15
2012-11-14T16:21:03Z
13,383,348
7
2012-11-14T16:50:40Z
[ "python", "list", "initialization", "boolean" ]
Is it possible without loops initialize all list values to some bool? For example I want to have a list of N elements all False.
``` my_list = [False for i in range(1,n+1)] ``` This will allow you to change individual elements since it builds each element independently. Although, this technically *is* a loop, I suppose.
python centre string using format specifier
13,383,244
11
2012-11-14T16:44:18Z
13,383,534
12
2012-11-14T17:00:21Z
[ "python", "python-3.x", "formatting", "string-formatting", "python-3.2" ]
I have a string called Message. ``` Message = "Hello, welcome!\nThis is some text that should be centered!" ``` Yeah, it's just a test statement... And I'm trying to centre it for a default Terminal window, i.e. of 80 width, with this statement: ``` print('{:^80}'.format(Message)) ``` Which prints: ``` ...
You need to centre each line separately: ``` '\n'.join('{:^80}'.format(s) for s in Message.split('\n')) ```
uwsgi - not using python2.7.3 from virtualenv, but using 2.6 from venv even though 2.6 installed only globally
13,383,628
6
2012-11-14T17:06:28Z
13,451,118
9
2012-11-19T09:42:09Z
[ "python", "django", "uwsgi" ]
My system(ubuntu) has python 2.6.5 version (globally installed in /usr/bin/). I want to use python 2.7.3 . For this, I tried creating a virtualenv using this answer [It is possible to install another version of Python to Virtualenv?](http://stackoverflow.com/questions/5506110/python-it-is-possible-to-install-anothe...
1. **Activate virtualenv**, 2. **Install uwsgi**: `pip install uwsgi` 3. **Run uwsgi** from the virtualenv.
Imshow: extent and aspect
13,384,653
35
2012-11-14T18:09:03Z
13,390,798
71
2012-11-15T02:36:17Z
[ "python", "matplotlib" ]
I'm writing a software system that visualizes slices and projections through a 3D dataset. I'm using matplotlib and specifically imshow to visualize the image buffers I get back from my analysis code. Since I'd like to annotate the images with plot axes, I use the extent keyword that imshow supplies to map the image b...
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure). By default, `imshow` sets the aspect of the plot to 1, as this is often what people want for image data. In your case, you can do something like: ``` import matplotlib.pyplot as plt import num...
How to display html using QWebView. Python
13,384,749
6
2012-11-14T18:13:44Z
13,386,109
13
2012-11-14T19:42:33Z
[ "python", "pyqt", "qwebview" ]
I have a question: how to display webpage in HTML format in console. ``` import sys from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView app = QApplication(sys.argv) view = QWebView() view.load(QUrl('http://example.com') # What's next? how to do something like: # prin...
As QT is an async library, you probably won't have any result if you immediately try to look at the html data of your webview after calling *load*, because it returns immediately, and will trigger the *loadFinished* signal once the result is available. You can of course try to access the html data the same way as I did...
How do I set attribute default values in sqlalchemy declarative?
13,384,996
7
2012-11-14T18:29:24Z
13,390,300
9
2012-11-15T01:33:44Z
[ "python", "sqlalchemy" ]
In SQLAlchemy Declarative, how do I set up default values for columns, such that transient or pending object instances will have those default values? A short example: ``` from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class A(Base): ...
Add a constructor to your class and set the default value there. The constructor doesn't run when the rows are loaded from the database so it is fine to do this. ``` class A(Base): __tablename__ = "A" id = Column(Integer, primary_key=True) word = Column(String) def __init__(self): self.word = ...
Why doesn't Python use C++/Java-like syntax to define instance variables?
13,385,194
3
2012-11-14T18:41:30Z
13,385,626
8
2012-11-14T19:11:18Z
[ "java", "python", "class", "instance-variables" ]
This plagued me for hours, as I am from the C++ world. I finally found out what was going on, but I do not know why this is the default behaviour. I'd like to understand why the language is designed this way. I wanted an instance variable `mem`. So I tried this: ``` class x(object): mem = [] obj = x() obj.mem.app...
The intuition is that in Python, *everything* is an object, including classes themselves. There's no such thing as a "static" keyword in Python; there are classes, which are objects, and those classes have attributes. *Everything* that appears in the class definition is a class attribute -- that includes both methods a...
Distribute/distutils specify Python version
13,385,337
3
2012-11-14T18:52:09Z
13,385,468
8
2012-11-14T18:59:52Z
[ "python", "distribution", "setuptools", "distribute" ]
Kinda followup to [this](http://stackoverflow.com/q/13379483/675646)... :) My project is Python 3-only and my question is basically how I tell distutils/distribute/whoever that this package is Python 3-only?
Not sure if there's some special setting, but this in the beginning of setup.py might help: ``` import sys if sys.version_info.major < 3: print("I'm only for 3, please upgrade") sys.exit(1) ```
How can I remove extra whitespace from strings when parsing a csv file in Pandas?
13,385,860
20
2012-11-14T19:25:28Z
13,385,921
15
2012-11-14T19:29:04Z
[ "python", "parsing", "pandas" ]
I have the following file named 'data.csv': ``` 1997,Ford,E350 1997, Ford , E350 1997,Ford,E350,"Super, luxurious truck" 1997,Ford,E350,"Super ""luxurious"" truck" 1997,Ford,E350," Super luxurious truck " "1997",Ford,E350 1997,Ford,E350 2000,Mercury,Cougar ``` And I would like to parse...
Well, the whitespace is in your data, so you can't read in the data without reading in the whitespace. However, after you've read it in, you could strip out the whitespace by doing, e.g., `df["Make"] = df["Make"].map(str.strip)` (where `df` is your dataframe).
How can I remove extra whitespace from strings when parsing a csv file in Pandas?
13,385,860
20
2012-11-14T19:25:28Z
13,386,025
22
2012-11-14T19:35:40Z
[ "python", "parsing", "pandas" ]
I have the following file named 'data.csv': ``` 1997,Ford,E350 1997, Ford , E350 1997,Ford,E350,"Super, luxurious truck" 1997,Ford,E350,"Super ""luxurious"" truck" 1997,Ford,E350," Super luxurious truck " "1997",Ford,E350 1997,Ford,E350 2000,Mercury,Cougar ``` And I would like to parse...
You could use converters: ``` import pandas as pd def strip(text): try: return text.strip() except AttributeError: return text def make_int(text): return int(text.strip('" ')) table = pd.read_table("data.csv", sep=r',', names=["Year", "Make", "Model", "Description"]...
Streaming data with Python and Flask
13,386,681
15
2012-11-14T20:22:21Z
13,388,915
30
2012-11-14T23:04:05Z
[ "python", "flask" ]
I can't seem to figure out how to using Flask's streaming. Here's my code: ``` @app.route('/scans/') def scans_query(): url_for('static', filename='.*') def generate(): yield render_template('scans.html') for i in xrange(50): sleep(.5) yield render_template('scans.html',...
To replace existing content on the page you might need javascript i.e., you could send it or make it to make requests for you, use long polling, websockets, etc. There are many ways to do it, here's one that uses [server send events](http://dev.w3.org/html5/eventsource/): ``` #!/usr/bin/env python import itertools imp...
Format of complex number in Python
13,387,782
14
2012-11-14T21:38:29Z
13,388,061
12
2012-11-14T21:56:38Z
[ "python", "complex-numbers" ]
I am wondering about the way Python (3.3.0) prints complex numbers. I am looking for an explanation, not a way to change the print. Example: ``` >>> complex(1,1)-complex(1,1) 0j ``` Why doesn't it just print "0"? My guess is: to keep the output of type complex. Next example: ``` >>> complex(0,1)*-1 (-0-1j) ``` We...
It prints `0j` to indicate that it's still a `complex` value. You can also type it back in that way: ``` >>> 0j 0j ``` The rest is probably the result of the magic of [IEEE 754 floating point representation](http://en.wikipedia.org/wiki/IEEE_floating_point), which makes a distinction between 0 and -0, the so-called [...
pandas: slice a MultiIndex by range of secondary index
13,389,203
10
2012-11-14T23:29:30Z
13,389,808
12
2012-11-15T00:30:57Z
[ "python", "pandas" ]
I have a series with a MultiIndex like this: ``` import numpy as np import pandas as pd buckets = np.repeat(['a','b','c'], [3,5,1]) sequence = [0,1,5,0,1,2,4,50,0] s = pd.Series( np.random.randn(len(sequence)), index=pd.MultiIndex.from_tuples(zip(buckets, sequence)) ) # In [6]: s # Out[6]: # a 0 -1.10...
As [Robbie-Clarken answers](http://stackoverflow.com/a/31490891/1240268), since 0.14 you can pass a [slice in the tuple you pass to loc](http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers): ``` In [11]: s.loc[('b', slice(2, 10))] Out[11]: b 2 -0.65394 4 0.08227 dtype: float64 ``` Indeed,...
design of python: why is assert a statement and not a function?
13,390,401
36
2012-11-15T01:45:30Z
13,390,618
14
2012-11-15T02:16:20Z
[ "python", "language-design", "assert" ]
**In Python, `assert` is a statement, and not a function. Was this a deliberate decision? Are there any advantages to having `assert` be a statement (and reserved word) instead of a function?** According to [the](http://docs.python.org/2/reference/simple_stmts.html#assert) [docs](http://docs.python.org/3.2/reference/s...
One of the wonderful things about `assert` in python and in other languages (specifically C) is that you can remove them to optimize your code by just adding the correct `#define` (optionally on the commandline with any compiler I've ever used) or optimization flags (`-O` in python). If `assert` became a function, this...
design of python: why is assert a statement and not a function?
13,390,401
36
2012-11-15T01:45:30Z
13,390,646
23
2012-11-15T02:20:53Z
[ "python", "language-design", "assert" ]
**In Python, `assert` is a statement, and not a function. Was this a deliberate decision? Are there any advantages to having `assert` be a statement (and reserved word) instead of a function?** According to [the](http://docs.python.org/2/reference/simple_stmts.html#assert) [docs](http://docs.python.org/3.2/reference/s...
> Are there any advantages to having assert be a statement (and reserved word) instead of a function? 1. Cannot be reassigned to a user function, meaning it can be effectively disabled at compile time as @mgilson pointed out. 2. The evaluation of the second, optional parameter is deferred until if/when the assertion f...
Why doesn't 2.__add__(3) work in Python?
13,390,458
12
2012-11-15T01:52:58Z
13,390,475
17
2012-11-15T01:55:35Z
[ "python", "methods", "int", "syntax-error" ]
The integer `2` has an `__add__` method: ``` >>> "__add__" in dir(2) True ``` ... but calling it raises a SyntaxError: ``` >>> 2.__add__(3) File "<stdin>", line 1 2.__add__(3) ^ SyntaxError: invalid syntax ``` Why can't I use the `__add__` method?
`2.` is parsed as a float, so `2.__add__` is a SyntaxError. You can evaluate `(2).__add__(3)` instead. --- ``` In [254]: (2).__add__(3) Out[254]: 5 ```
How to use numpy to add any two elements in an array and produce a matrix?
13,390,497
5
2012-11-15T01:58:38Z
13,390,506
9
2012-11-15T01:59:28Z
[ "python", "numpy", "scipy" ]
The native python codes are like this: ``` >>> a=[1,2,3,4,5,6] >>> [[i+j for i in a] for j in a] [[2, 3, 4, 5, 6, 7], [3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10, 11], [7, 8, 9, 10, 11, 12]] ``` However, I have to use numpy to do this job as the array is very large. Does any...
Many NumPy binary operators have an `outer` method which can be used to form the equivalent of a multiplication (or in this case, addition) table: ``` In [260]: import numpy as np In [255]: a = np.arange(1,7) In [256]: a Out[256]: array([1, 2, 3, 4, 5, 6]) In [259]: np.add.outer(a,a) Out[259]: array([[ 2, 3, 4, ...
How to re-arrange list like this (python)?
13,391,334
3
2012-11-15T03:55:56Z
13,391,409
12
2012-11-15T04:05:44Z
[ "python", "algorithm", "list" ]
For example, list `to_be` consists of: 3 of `"a"`, 4 of `"b"`, 3 of `"c"`, 5 of `"d"`... ``` to_be = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "d", "d", "d", "d", "d", ...] ``` Now I want it to be like this: ``` done = ["a", "b", "c", "d", ... , "a", "b", "c", "d", ... , "b", "d", ...] (notice: some items a...
Presuming I am understanding what you want, it can be done relatively easily by combining [`itertools.zip_longest`](http://docs.python.org/3/library/itertools.html#itertools.zip_longest), [`itertools.groupby`](http://docs.python.org/3/library/itertools.html#itertools.groupby) and [`itertools.chain.from_iterable()`](htt...
Are python sort keys guaranteed to be called only once?
13,391,553
6
2012-11-15T04:23:52Z
13,391,596
8
2012-11-15T04:30:47Z
[ "python", "sorting" ]
While answering [another question](http://stackoverflow.com/a/13391422/748858), I ended up creating a sortkey function which modified a dictionary in order to save state which would then be used for subsequent items in the sort. While my answer *seemed* to work, my question is this: Is it actually defined in the pytho...
From the section of the docs you link: > In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while **key and reverse touch each element only once**. That would seem to be a "yes" ...
Python: Making a class variable static even when a module is imported in different ways
13,392,038
4
2012-11-15T05:30:41Z
13,392,127
7
2012-11-15T05:41:47Z
[ "python", "class", "static", "import" ]
Let's consider the package structure as below: ``` myApp |-- myPackage | |-- __init__.py | +-- myModule.py |-- __init__.py +-- main.py ``` myModule.py contains a single class such as: ``` class MyClass( object ): _myList = [] @classmethod def test( cls ): cls._myList.append( len( cls._myL...
No. (At least, not without very ugly and fragile hacks.) When you import it in those two different ways, the module is actually imported twice. Python usually re-uses an already-imported module if you import it again, but this is based not on the actual file imported, but on the path relative to `sys.path`. So if you i...
Possible to store Python ints in less than 12 bytes?
13,393,395
5
2012-11-15T07:54:06Z
13,393,442
10
2012-11-15T07:57:55Z
[ "python", "int" ]
Is it possible to make Python use less than 12 bytes for an int? ``` >>> x=int() >>> x 0 >>> sys.getsizeof(x) 12 ``` I am not a computer specialist but isn't 12 bytes excessive? The smallest int I want to store is 0, the largest int 147097614, so I shouldn't really need more than 4 bytes. (There is probably somethi...
In python, `int`s are objects just like everything else. Because of that, there is a little extra overhead just associated with the fact that you're using an object which has some associated meta-data. If you're going to use *lots* of ints, and it makes sense to lay them out in an array-like structure, you should look...
Possible to store Python ints in less than 12 bytes?
13,393,395
5
2012-11-15T07:54:06Z
13,393,467
7
2012-11-15T07:59:42Z
[ "python", "int" ]
Is it possible to make Python use less than 12 bytes for an int? ``` >>> x=int() >>> x 0 >>> sys.getsizeof(x) 12 ``` I am not a computer specialist but isn't 12 bytes excessive? The smallest int I want to store is 0, the largest int 147097614, so I shouldn't really need more than 4 bytes. (There is probably somethi...
Size of an integer object includes the overhead of maintaining other object information along with its value. The additional information can include object type, reference count and other implementation-specific details. If you store many integers and want to optimize the space spent, use the [`array` module](http://d...
Determinant of Multidimensional array
13,393,733
8
2012-11-15T08:21:47Z
13,397,915
8
2012-11-15T12:54:15Z
[ "python", "numpy", "multidimensional-array" ]
I´m trying to compute the determinant of a numpy array M, with np.shape(M) = (N, L, L) is something like: ``` import numpy as np M = np.random.rand(1000*10*10).reshape(1000, 10, 10) dm = np.zeros(1000) for _ in xrange(len(dm)): dm[_] = np.linalg.det(M[_]) ``` Is there a way without looping? "N" is some orders o...
You need to modify `np.linalg.det` to get the speed. The idea is that `det()` is a Python function, it does a lot of check first, and call the fortran routine, and does some array calculate to get the result. Here is the code from numpy: ``` def slogdet(a): a = asarray(a) _assertRank2(a) _assertSquareness...
Wrapping python doctest results that are longer than 80 characters
13,395,610
16
2012-11-15T10:30:28Z
13,395,612
20
2012-11-15T10:30:28Z
[ "python", "doctest", "pep8" ]
I'm trying to keep my source code under the 80 character *guideline* width that PEP8 recommends, but can't figure out how to wrap my doctest which has results longer than 80 characters. A noddy example: ``` def long_string(): """ Returns a string which is wider than the recommended PEP8 linewidth >>> pri...
Just figured out: ``` def long_string(): """ Returns a string which is wider than the recommended PEP8 linewidth >>> print long_string() 01234567890123456789012345678901234567890123456789012345678901234567890\ 12345678901234567890123456789 """ return '0123456789' * 10 ``` Hope that helps som...
How can I get the color of the last figure in matplotlib?
13,395,888
7
2012-11-15T10:46:32Z
13,397,102
11
2012-11-15T11:57:46Z
[ "python", "colors", "matplotlib" ]
I'm plotting some data sets with linear fits. I want the linear fit to have the same color as the plotted data (error bars). How can I get that color?
You might try this: ``` x = np.arange(10) y = np.arange(10) err = np.ones(10) ebar = plt.errorbar(x,y, yerr=err) color = ebar[0].get_color() ``` `ebar` is a container of artist, so you might modify the index in the last line to match the artist you want to get color from. You can also easily set the color of the err...