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
Counting instances of a class?
8,628,123
8
2011-12-25T03:55:13Z
8,628,132
27
2011-12-25T03:59:23Z
[ "class", "python" ]
I've been cleaning up some code from a module I'm extending and I can't seem to find a way to Pythonify this code: ``` global_next_id = 1 class Obj: def __init__(self): global global_next_id self.id = global_next_id global_next_id += 1 ``` This code uses a global id to keep track of instances of a cla...
Try something like this: ``` from itertools import count class Obj(object): _ids = count(0) def __init__(self): self.id = self._ids.next() ```
URL Decode with Python 3
8,628,152
21
2011-12-25T04:05:23Z
8,628,164
30
2011-12-25T04:12:35Z
[ "python", "html", "python-3.x" ]
Is there a way to URL decode a string in Python 3 to take something like this ``` id%253D184ff84d27c3613d%26quality%3Dmedium ``` and decode it twice to get ``` id=184ff84d27c3613d&quality=medium ```
Just use `urllib.parse.unquote()`: ``` >>> import urllib.parse >>> urllib.parse.unquote('id%253D184ff84d27c3613d%26quality%3Dmedium') 'id%3D184ff84d27c3613d&quality=medium' >>> urllib.parse.unquote('id%3D184ff84d27c3613d&quality=medium') id=184ff84d27c3613d&quality=medium ```
Determining the location of distutils data files programmatically in Python
8,628,495
9
2011-12-25T06:24:47Z
9,226,980
8
2012-02-10T11:20:12Z
[ "python", "packaging", "setuptools", "distutils", "python-module" ]
I'm trying to include data files in distutils for my package and then refer to them using relative paths (following <http://docs.python.org/distutils/setupscript.html#distutils-additional-files>) My dir structure is: ``` myproject/ mycode.py data/ file1.dat ``` the code in `mycode.py`, which is actually a sc...
I think the confusion arises from the usage of scripts. Scripts should refer to a runnable executable, perhaps a utility script related to your package or perhaps an entry point into functionality for your package. In either case, you should expect that any scripts will not be installed alongside the rest of your packa...
Python 3.2: can't import sqlite3 module
8,628,774
7
2011-12-25T08:04:57Z
8,628,886
9
2011-12-25T08:45:20Z
[ "python", "python-3.x" ]
I've just installed python 3.2.2 on ubuntu 10.04.3 (following all instraction from readme file) and tried to import sqlite3 module - the result: ``` No module named _sqlite3 ``` Then I've looked into lib-dynload directory and there is **no file \_sqlite3.so** (but it is in python 2.6). How to fix this problem? Than...
If you installed from source, you need to install the development libraries for sqlite3. ``` sudo apt-get install libsqlite3-dev ``` You probably also want to install `libreadline-dev` and `libssl-dev`.
Twisted Installation Failed on Linux
8,629,198
17
2011-12-25T10:22:55Z
8,629,280
41
2011-12-25T10:48:58Z
[ "python", "twisted" ]
I tried to install twisted on Linux from source code on my Linux sever. When I use this command `setup.py install`, it failed with a error message below: ``` twisted/runner/portmap.c:10:20: error: Python.h: No such file or directory twisted/runner/portmap.c:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or â...
The compiler can't find python development headers. Asking the system administrator to install `python-devel` in case of CentOS or to install `python-dev` on Debian, Ubuntu and their derivatives. That should help.
calling function in print(""" """)
8,629,699
2
2011-12-25T13:01:05Z
8,629,708
13
2011-12-25T13:03:49Z
[ "python" ]
I want to call a function in formatted output of string using `print(""" """)` function of Python. For example: ``` print(""" something.......something... abs(-10.5) and then again some string...... """) ``` Is there any way to do it?
This is how you can do it using the new and improved string [`format`](http://docs.python.org/library/string.html#new-string-formatting)ting method (Python 2.6 and up): ``` print(""" something.......something... {0} and then again some string...... """.format(abs(-10.5))) ```
Hyperlinks in web.py
8,630,456
3
2011-12-25T16:31:16Z
8,630,477
8
2011-12-25T16:38:26Z
[ "python", "web.py" ]
How do I make web.py fetch a page when I click on a link? I have this in my template: `<a href='add.html'>Home</a>` When I click on 'Home', I get 'not found'. In my application, I have '/add' mapped to the 'Add' class which returns 'Boom!' using the template add.html. ``` urls = ('/', 'Index', '/add','Add') cl...
The origin of a page URI ending in .html lilke /add.html is that in static hosting environments those were traditionally really single text files with html-content and the file ending for such a file is .html But your system is dynamic and creates web pages on the fly. It does not necessarily need the pages ending in ...
applying python functions directly to Qt designer as signals
8,630,749
7
2011-12-25T17:55:06Z
8,631,201
14
2011-12-25T19:37:17Z
[ "python", "pyqt", "pyqt4", "signals", "qt-designer" ]
I am new to Qt and GUI programming overall but i have done a fair bit of coding in python - writing modules and so on. I need to develop simple GUIs for some of my old modules. What i am trying to do can be represented by the following simple example: ``` def f(x, y): z = x + y return z ``` For this function...
The basic workflow when writing a PyQt4 gui is: 1. Design the UI using Qt Designer. 2. Generate a Python module from the UI file using `pyuic4`. 3. Create an Application module for the main program logic. 4. Import the GUI class into the Application module. 5. Connect the GUI to the program logic. So, given the UI fi...
What is the fastest way to generate image thumbnails in Python?
8,631,076
13
2011-12-25T19:09:56Z
8,631,924
15
2011-12-25T22:35:56Z
[ "python", "imagemagick", "python-imaging-library" ]
I'm building a photo gallery in Python and want to be able to quickly generate thumbnails for the high resolution images. What's the fastest way to generate high quality thumbnails for a variety of image sources? Should I be using an external library like imagemagick, or is there an efficient internal way to do this?...
You want PIL it does this with ease ``` from PIL import Image sizes = [(120,120), (720,720), (1600,1600)] files = ['a.jpg','b.jpg','c.jpg'] for image in files: for size in sizes: Image.open(image).thumbnail(size).save("thumbnail_%s_%s" % (image, "_".join(size))) ``` If you desperately need speed. Then thre...
What is the fastest way to generate image thumbnails in Python?
8,631,076
13
2011-12-25T19:09:56Z
19,731,584
11
2013-11-01T17:03:43Z
[ "python", "imagemagick", "python-imaging-library" ]
I'm building a photo gallery in Python and want to be able to quickly generate thumbnails for the high resolution images. What's the fastest way to generate high quality thumbnails for a variety of image sources? Should I be using an external library like imagemagick, or is there an efficient internal way to do this?...
A little late to the question (only a year!), but I'll piggy backing on the "multiprocess it" part of @JakobBowyer's answer. This is a good example of an [embarrassingly parallel](http://en.wikipedia.org/wiki/Embarrassingly_parallel) problem, as the main bit of code doesn't mutate any state external to itself. It simp...
Click the javascript popup through webdriver
8,631,500
13
2011-12-25T20:50:13Z
10,804,853
17
2012-05-29T18:44:15Z
[ "python", "selenium", "webdriver", "web-scraping", "alert" ]
I am scraping a webpage using Selenium webdriver in Python The webpage I am working on, has a form. I am able to fill the form and then I click on the Submit button. It generates an popup window( Javascript Alert). I am not sure, how to click the popup through webdriver. Any idea how to do it ? Thanks
Python Webdriver Script: ``` from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/alert.html") alert = browser.switch_to_alert() alert.accept() browser.close() ``` Webpage (alert.html): ``` <html><body> <script>alert("hey");</script> </body></html> ``` Running the webdri...
How to perform element wise boolean operations on numpy arrays
8,632,033
23
2011-12-25T23:03:50Z
8,632,049
38
2011-12-25T23:06:55Z
[ "python", "numpy", "boolean-operations" ]
For example I would like to create a mask that masks elements with value between 40 and 60: ``` foo = np.asanyarray(range(100)) mask = (foo < 40).__or__(foo > 60) ``` Which just looks ugly, I can't write: ``` (foo < 40) or (foo > 60) ``` because I end up with: ``` ValueError Traceback (most recent call last) ....
Have you tried this? ``` mask = (foo < 40) | (foo > 60) ``` Note: the `__or__` method in an object overloads the bitwise or operator (`|`), not the boolean `or` operator.
How to perform element wise boolean operations on numpy arrays
8,632,033
23
2011-12-25T23:03:50Z
11,246,936
11
2012-06-28T14:31:55Z
[ "python", "numpy", "boolean-operations" ]
For example I would like to create a mask that masks elements with value between 40 and 60: ``` foo = np.asanyarray(range(100)) mask = (foo < 40).__or__(foo > 60) ``` Which just looks ugly, I can't write: ``` (foo < 40) or (foo > 60) ``` because I end up with: ``` ValueError Traceback (most recent call last) ....
If you have comparisons within only booleans, as in your example, you can use the bitwise OR operator `|` as suggested by Jcollado. But beware, this can give you strange results if you ever use non-booleans, such as `mask = (foo < 40) | override`. Only as long as `override` guaranteed to be either False, True, 1, or 0,...
Python argparse custom actions with additional arguments passed
8,632,354
8
2011-12-26T00:50:47Z
8,632,404
17
2011-12-26T01:08:40Z
[ "python", "action", "argparse" ]
``` import argparse class customAction(argparse.Action): def __call__(self, parser, args, values, option_string=None): setattr(args, self.dest, values) parser = argparse.ArgumentParser() parser.add_argument('-e', '--example', action=customAction) ``` I want to pass additional arguments to customAction whe...
``` def make_action(additional_arg): class customAction(argparse.Action): def __call__(self, parser, args, values, option_string=None): print(additional_arg) setattr(args, self.dest, values) return customAction #... parser.add_argument('-e', '--example', action=make_action('your ...
Python argparse custom actions with additional arguments passed
8,632,354
8
2011-12-26T00:50:47Z
16,414,640
7
2013-05-07T08:32:25Z
[ "python", "action", "argparse" ]
``` import argparse class customAction(argparse.Action): def __call__(self, parser, args, values, option_string=None): setattr(args, self.dest, values) parser = argparse.ArgumentParser() parser.add_argument('-e', '--example', action=customAction) ``` I want to pass additional arguments to customAction whe...
Another solution is to derive the based class `argparse.Action` like this: ``` class CustomAction(argparse.Action): def __init__(self,option_strings, additional_arg1,additional_arg2, dest=None, nargs=0, default=None, required=Fals...
Qt - Get the pixel length of a string in a QLabel
8,633,433
10
2011-12-26T06:23:14Z
8,638,114
14
2011-12-26T18:17:31Z
[ "python", "pyqt", "width", "pyqt4", "qlabel" ]
I have a QLabel of a fixed width. I need to check (periodically) that the entire string fits inside the QLabel at its current width, so I can resize it appropriately. To do this, I need to obtain the 'pixel length' of the string. (The total amount of horizontal pixels required to display the string). It should b...
To get the precise pixel-width of the text, you must use [QFontMetrics.boundingRect](http://developer.qt.nokia.com/doc/qt-4.8/qfontmetrics.html#boundingRect-2). Do not use [QFontMetrics.width](http://developer.qt.nokia.com/doc/qt-4.8/qfontmetrics.html#width), because it takes into account the left and right bearing of...
Ensuring __init__ is only called once when class instance is created by constructor or __new__
8,633,959
8
2011-12-26T07:58:53Z
8,634,126
8
2011-12-26T08:34:16Z
[ "python" ]
I'm trying to understand how new instances of a Python class should be created when the creation process can either be via the constructor or via the `__new__` method. In particular, I notice that when using the constructor, the `__init__` method will be automatically called after `__new__`, while when invoking `__new_...
First, some basic facts about `__new__` and `__init__`: * `__new__` is a **constructor**. * `__new__` typically returns an instance of `cls`, its first argument. * By `__new__` returning an instance of `cls`, [`__new__` causes Python to call `__init__`](http://docs.python.org/reference/datamodel.html#object.__new__). ...
Shortest Repeating Sub-String
8,633,996
6
2011-12-26T08:07:20Z
8,634,017
14
2011-12-26T08:11:08Z
[ "python", "regex", "string-matching" ]
I am looking for an efficient way to extract the shortest repeating substring. For example: ``` input1 = 'dabcdbcdbcdd' ouput1 = 'bcd' input2 = 'cbabababac' output2 = 'ba' ``` I would appreciate any answer or information related to the problem. Also, in [this post](http://stackoverflow.com/questions/7883688/smalles...
A quick fix for this pattern could be ``` (.+?)\1+ ``` Your regex failed because it anchored the repeating string to the start and end of the line, only allowing strings like `abcabcabc` but not `xabcabcabcx`. Also, the minimum length of the repeated string should be 1, not 0 (or any string would match), therefore `....
Sending JSON request with Python
8,634,473
12
2011-12-26T09:31:41Z
8,634,905
18
2011-12-26T10:34:07Z
[ "python", "json" ]
I'm new to web services and am trying to send the following JSON based request using a python script: ``` http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx&json={power:290.4,temperature:19.4} ``` If I paste the above into a browser, it works as expected. However, I am struggling to send the request from Python. ...
Instead of using urllib2, you can use [requests](http://docs.python-requests.org/). This new python lib is really well written and it's easier and more intuitive to use. To send your json data you can use something like the following code: ``` import json import requests data = {'temperature':'24.3'} data_json = json...
Python IndentationError: unexpected indent
8,634,700
19
2011-12-26T10:03:45Z
8,634,745
34
2011-12-26T10:08:59Z
[ "python" ]
I really can't see the indentation error here, i'm getting crazy with this -> ``` # loop while d <= end_date: # print d.strftime("%Y%m%d") fecha = d.strftime("%Y%m%d") # set url url = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1' # Descargamos fichero res...
Run your program with ``` python -t script.py ``` This will warn you if you have mixed tabs and spaces. On \*nix systems, you can see where the tabs are by running ``` cat -A script.py ``` and you can automatically convert tabs to 4 spaces with the command ``` expand -t 4 script.py > fixed_script.py ``` PS. Be s...
Python IndentationError: unexpected indent
8,634,700
19
2011-12-26T10:03:45Z
16,575,302
7
2013-05-15T21:31:21Z
[ "python" ]
I really can't see the indentation error here, i'm getting crazy with this -> ``` # loop while d <= end_date: # print d.strftime("%Y%m%d") fecha = d.strftime("%Y%m%d") # set url url = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1' # Descargamos fichero res...
find all tabs and replaced by 4 spaces in notepad ++ .It worked.
More pythonic way to iterate in Numpy
8,634,850
3
2011-12-26T10:25:25Z
8,634,953
7
2011-12-26T10:40:58Z
[ "python", "numpy", "iterator", "scientific-computing" ]
I am an engineering student and I'm accustomed to write code in Fortran, but now I'm trying to get more into Python for my numerical recipes using Numpy. If I needed to perform a calculation repeatedly using elements from several arrays, the immediate translation from what I'd write in Fortran would be ``` k = np.zer...
Almost all numpy operations are performed element-wise. So instead of writing an explicit loop, try defining `k` using an array-based formula: ``` r_shifted = np.roll(x, shift = 1) k = ... # some formula in terms of u, M, r, r_shifted ``` For example, instead of ``` import numpy as np N=5 k = np.zeros(N, dtype=np.f...
How to get BPM and tempo audio features in Python
8,635,063
5
2011-12-26T10:54:30Z
14,573,319
7
2013-01-28T23:43:36Z
[ "python", "audio", "tempo" ]
I am involved in a project which requires me to extract song features like beats per minute (BPM), tempo, etc. However, I have not found a suitable Python library that can accurately detect these features. Does anyone have any advice? (In Matlab, I do know of a project called Mirtoolbox, which can give the BPM and te...
This answer comes a year later, but anyway, for the record. I found three audio libraries with python bindings that extract features from audio. They are not that easy to install since they are really in C and you need to properly compile the python bindings and add them to the path to import, but here they are: * [Ya...
Python itertools.combinations' results
8,635,073
5
2011-12-26T10:56:25Z
8,635,126
16
2011-12-26T11:04:15Z
[ "python", "combinations", "itertools" ]
I don't get the number of results I should obtain from that function in the Title, so I'm hoping in your help. Looking at the Docs <http://docs.python.org/library/itertools.html#itertools.combinations> the number of results should be > The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or > zero when r...
itertools.combinations should be returning an iterator with 20 items: ``` In [40]: len(list(itertools.combinations('ABCDEF',3))) Out[40]: 20 ``` Note that ``` In [41]: len(list(itertools.combinations('ABCDEF',2))) Out[41]: 15 ``` and the output posted ``` combinations('ABCDEF', 3) --> AB AC AD AE AF BC BD BE BF CD...
Does coverage.py measure the function and class definitions?
8,636,828
10
2011-12-26T14:59:05Z
8,637,093
10
2011-12-26T15:38:31Z
[ "python", "testing", "code-coverage" ]
I am trying to achieve a 100% coverage for a basic python module. I use Ned Batchelder's coverage.py module to test it. ``` 1 class account(object): 2 def __init__(self, initial_balance=0): 3 self.balance = initial_balance 4 def add_one(self): 5 self.balance = self.balance + 1 ``` These are the tests. ```...
I think your problem is described in the [FAQ](http://nedbatchelder.com/code/coverage/faq.html#faq): > Q: Why do the bodies of functions (or classes) show as executed, but > the def lines do not? > > This happens because coverage is started after the functions are > defined. The definition lines are executed without c...
How to return images in flask response?
8,637,153
39
2011-12-26T15:47:34Z
8,637,217
64
2011-12-26T15:56:47Z
[ "python", "flask" ]
As an example, this URL: ``` http://example.com/get_image?type=1 ``` should return a response with a `image/gif` MIME type. I have two static `.gif` images, and if type is 1, it should return `ok.gif`, else return `error.gif`. How to do that in flask?
You use something like ``` from flask import send_file @app.route('/get_image') def get_image(): if request.args.get('type') == '1': filename = 'ok.gif' else: filename = 'error.gif' return send_file(filename, mimetype='image/gif') ``` to send back `ok.gif` or `error.gif`, depending on the t...
How to use Python string formatting to convert an integer representing cents to a float representing dollars?
8,637,628
4
2011-12-26T16:53:48Z
8,637,689
11
2011-12-26T17:03:06Z
[ "python", "django-templates", "string-formatting", "money" ]
I have an integer representing a price in cents. Using Python format strings, how can I convert this value into dollars with two decimal places? Examples: ``` 1234 => 12.34 5 => 0.05 999 => 9.99 ``` EDIT: I should give some background. I am storing prices in a database as integers in order to make sure I don't loose ...
You should try hard to avoid ever using floats to represent money (numerical inaccuracy can too easily creep in). The decimal module provides a useful datatype for representing money as it can exactly represent decimal numbers such as 0.05. It can be used like this: ``` import decimal cents = 999 dollars = decimal.De...
Python/Numpy/Scipy - Converting string to mathematical function
8,639,871
5
2011-12-26T23:27:21Z
8,639,937
8
2011-12-26T23:37:41Z
[ "python", "numpy", "scipy", "root-framework" ]
I am in the somewhat unfortunate position to try to convert a program from the depths of CERN ROOT to python. In ROOT code (CINT in itself is an abomination imo), one can store mathematical functions as a "string" and pass these along to ROOT for fitting, plotting, etc. because of how ROOT defines these as "strings." ...
Since, presumably, you can trust the strings to be non-malicious, you could build a string which defines a function which evaluates the expression and use `exec` to execute that string as a statement. For example, ``` import numpy as np import scipy.special as special expr='(1+p[1])**(1+p[1])/special.gamma(1+p[1]) * ...
How to store data like Freebase does?
8,639,888
7
2011-12-26T23:31:22Z
12,428,232
8
2012-09-14T16:10:09Z
[ "python", "database-design", "rdf", "freebase", "triplestore" ]
*I admit that this is basically a duplicate question of [Use freebase data on local server?](http://stackoverflow.com/questions/4837936/use-freebase-data-on-local-server) but I need more detailed answers than have already been given there* I've fallen absolutely in love with Freebase. What I want now is to essentially...
This is what worked for me. It allows you to load all of a Freebase dump in a standard MySQL installation on less than 100GB of disk. The key is understanding the data layout in a dump and then transforming it (optimizing it for space and speed). **Freebase notions** you should understand before you attempt to use thi...
How to plot with x-axis at the top of the figure?
8,639,973
7
2011-12-26T23:46:16Z
8,640,615
9
2011-12-27T02:18:45Z
[ "python", "matplotlib", "plot" ]
I would like to ask how to produce a plot similar to that in the figure below? Basically, how to have x-axis at the top of the figure. Thanks ![enter image description here](http://i.stack.imgur.com/aOehD.jpg) Image from: <http://oceanographyclay1987.blogspot.com/2010/10/light-attenuation-in-ocean.html>
Use ``` ax.xaxis.set_ticks_position("top") ``` For example, ``` import numpy as np import matplotlib.pyplot as plt numdata = 100 t = np.linspace(0, 100, numdata) y = 1/t**(1/2.0) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis.set_ticks_position('top') ax.yaxis.grid(linestyle = '-', color = 'gray') ax.in...
NLTK Performance
8,640,246
8
2011-12-27T00:48:36Z
8,640,574
17
2011-12-27T02:07:50Z
[ "python", "performance", "nlp", "nltk" ]
Alright, I've been pretty interested in natural language processing recently: however, I've used C until now for most of my work. I heard of NLTK, and I didn't know Python, but it seems quite easy to learn, and it's looking like a really powerful and interesting language. In particular, the NLTK module seems very, very...
I believe you're conflating training time with processing time. Training a model, like a UnigramTagger, can take a lot of time. So can loading that trained model from a pickle file on disk. But once you have a model loaded into memory, processing can quite fast. See the section called "Classifier Efficiency" at the bot...
Python Manager dict in Multiprocessing
8,640,367
8
2011-12-27T01:22:03Z
8,644,552
7
2011-12-27T12:19:37Z
[ "python", "multiprocessing" ]
Here is a simple multiprocessing code: ``` from multiprocessing import Process, Manager manager = Manager() d = manager.dict() def f(): d[1].append(4) print d if __name__ == '__main__': d[1] = [] p = Process(target=f) p.start() p.join() ``` Output I get is: ``` {1: []} ``` Why don't I get...
I think this is a bug in manager proxy calls. You can circumvent avoiding call methods of shared list, like: ``` from multiprocessing import Process, Manager manager = Manager() d = manager.dict() def f(): # get the shared list shared_list = d[1] shared_list.append(4) # forces the shared list to ...
Python Manager dict in Multiprocessing
8,640,367
8
2011-12-27T01:22:03Z
9,536,888
14
2012-03-02T16:34:07Z
[ "python", "multiprocessing" ]
Here is a simple multiprocessing code: ``` from multiprocessing import Process, Manager manager = Manager() d = manager.dict() def f(): d[1].append(4) print d if __name__ == '__main__': d[1] = [] p = Process(target=f) p.start() p.join() ``` Output I get is: ``` {1: []} ``` Why don't I get...
Here is what you wrote: ``` # from here code executes in main process and all child processes # every process makes all these imports from multiprocessing import Process, Manager # every process creates own 'manager' and 'd' manager = Manager() # BTW, Manager is also child process, and # in its initialization it cr...
pymongo: how to use $or operator to an column that is an array?
8,640,921
5
2011-12-27T03:36:51Z
8,641,011
7
2011-12-27T04:00:58Z
[ "python", "mongodb", "pymongo" ]
I have a collection like this: ``` user_id albums 1 [1 2 3 4] 2 [3 5 7 8] ``` I want to find out all the records that, the albums contains 3 or 7 or 8, I wrote the code like this but not working: ``` or_array = [] or_array.append({"albums":3}) or_array.append({"albums":7}) or_array.append({"a...
try this ``` collection1.find({'albums': {'$in': [3, 7, 8]}}) ``` from the mongodb docs, `[IN] allow[s] you to specify an array of possible matches` If that doesn't work, maybe back track and look at the actual types of `3` `7` and `8` in the collection to ensure they are ints. ``` print type(collection1.find_one()...
How can I control what scalar form PyYAML uses for my data?
8,640,959
14
2011-12-27T03:49:20Z
8,641,732
14
2011-12-27T06:16:43Z
[ "python", "yaml", "pyyaml" ]
I've got an object with a short string attribute, and a long multi-line string attribute. I want to write the short string as a YAML quoted scalar, and the multi-line string as a literal scalar: ``` my_obj.short = "Hello" my_obj.long = "Line1\nLine2\nLine3" ``` I'd like the YAML to look like this: ``` short: "Hello"...
Based on [Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?](http://stackoverflow.com/questions/6432605/any-yaml-libraries-in-python-that-support-dumping-of-long-strings-as-block-liter) ``` import yaml from collections import OrderedDict class quoted(str): pass def...
How can I control what scalar form PyYAML uses for my data?
8,640,959
14
2011-12-27T03:49:20Z
15,423,007
9
2013-03-15T01:07:55Z
[ "python", "yaml", "pyyaml" ]
I've got an object with a short string attribute, and a long multi-line string attribute. I want to write the short string as a YAML quoted scalar, and the multi-line string as a literal scalar: ``` my_obj.short = "Hello" my_obj.long = "Line1\nLine2\nLine3" ``` I'd like the YAML to look like this: ``` short: "Hello"...
I wanted any input with a `\n` in it to be a block literal. Using the code in `yaml/representer.py` as a base I got: ``` # -*- coding: utf-8 -*- import yaml def should_use_block(value): for c in u"\u000a\u000d\u001c\u001d\u001e\u0085\u2028\u2029": if c in value: return True return False d...
Compare multiple variables to the same value in "if" in Python?
8,641,008
17
2011-12-27T04:00:18Z
8,641,040
13
2011-12-27T04:06:35Z
[ "python", "if-statement" ]
I am using Python and I would like to have an if statement with many variables in it. such as: ``` if A, B, C, and D >= 2: print (A, B, C, and D) ``` I realize that this is not the correct syntax and that is exactly the question I am asking - what is the correct Python syntax for this type of an if statem...
Another idea: ``` if min(A, B, C, D) >= 2: print A, B, C, D ```
Compare multiple variables to the same value in "if" in Python?
8,641,008
17
2011-12-27T04:00:18Z
8,641,096
30
2011-12-27T04:16:34Z
[ "python", "if-statement" ]
I am using Python and I would like to have an if statement with many variables in it. such as: ``` if A, B, C, and D >= 2: print (A, B, C, and D) ``` I realize that this is not the correct syntax and that is exactly the question I am asking - what is the correct Python syntax for this type of an if statem...
What about this: ``` if all(x >= 2 for x in (A, B, C, D)): print A, B, C, D ``` This should be helpful if you're testing a *long* list of variables with the same condition.
Python equivalent of LINQ All function?
8,641,089
14
2011-12-27T04:14:37Z
8,641,115
24
2011-12-27T04:19:11Z
[ "python", "linq" ]
What is the idiomatic Python way to test if all elements in a collection satisfy a condition? (The [.NET `All()` method](http://msdn.microsoft.com/en-us/library/bb548541.aspx) fills this niche nicely in C#.) There's the obvious loop method: ``` all_match = True for x in stuff: if not test(x): all_match = ...
``` all_match = all(test(x) for x in stuff) ``` This short-circuits and doesn't require stuff to be a list -- anything iterable will work -- so has several nice features. There's also the analogous ``` any_match = any(test(x) for x in stuff) ```
Function parameters - Python
8,641,934
8
2011-12-27T06:51:31Z
8,641,975
13
2011-12-27T07:01:01Z
[ "python" ]
``` def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-- This parrot wouldn’t", action print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It’s", state, "!" ``` I started learning python. I can call this function using par...
You can't use a non-keyword argument (`'arg_value'`) after a keyword argument (`arg_name='arg_value'`). This is because of how Python is designed. See here: <http://docs.python.org/tutorial/controlflow.html#keyword-arguments> Therefore, you must enter all arguments following a keyword-argument as keyword-arguments......
Building a huge numpy array using pytables
8,642,626
7
2011-12-27T08:40:33Z
8,643,448
8
2011-12-27T10:12:25Z
[ "python", "arrays", "numpy", "pytables" ]
How can I create a huge numpy array using pytables. I tried this but gives me the "ValueError: array is too big." error: ``` import numpy as np import tables as tb ndim = 60000 h5file = tb.openFile('test.h5', mode='w', title="Test Array") root = h5file.root h5file.createArray(root, "test", np.zeros((ndim,ndim), dtype=...
You could try to use tables.CArray class as it supports compression but... I think questions is more about numpy than pytables because you are creating array using numpy before storing it with pytables. In that way you need a lot of ram to execute **np.zeros((ndim,ndim)** - and this is probably the place where except...
Building a huge numpy array using pytables
8,642,626
7
2011-12-27T08:40:33Z
8,645,829
14
2011-12-27T14:39:45Z
[ "python", "arrays", "numpy", "pytables" ]
How can I create a huge numpy array using pytables. I tried this but gives me the "ValueError: array is too big." error: ``` import numpy as np import tables as tb ndim = 60000 h5file = tb.openFile('test.h5', mode='w', title="Test Array") root = h5file.root h5file.createArray(root, "test", np.zeros((ndim,ndim), dtype=...
Piggybacking off of @b1r3k's response, to create an array that you are not going to access all at once (i.e. bring the whole thing into memory), you want to use a `CArray` (Chunked Array). The idea is that you would then fill and access it incrementally: ``` import numpy as np import tables as tb ndim = 60000 h5file =...
Python: Is it possible to know how many iterations are in an iterator object beforehand?
8,643,315
4
2011-12-27T09:57:52Z
8,643,378
10
2011-12-27T10:04:08Z
[ "python", "iterator" ]
So far if I wanted to know how many iterations there are in an iterator (in my case that's how many protein sequences in a file) I did: ``` count = 0 for stuff in iterator: count += 1 print count ``` However, I want to seperate the iterator into half so I need to know the total amount of iterations. Is there a wa...
There is no way to know how many values an iterator will produce without consuming it until the end. Note that an iterator can also be infinite, so in that case the total count is not even defined. If you can ensure the iterator to be finite, one way to do what you ask is to convert it to list (using `list(iterator)`)...
Delete/retrieve an element from an array
8,644,305
2
2011-12-27T11:52:11Z
8,644,333
9
2011-12-27T11:54:43Z
[ "python" ]
When an element from an array is deleted using del, is it possible to retrieve the deleted element.. ``` del_ele = [] arr=[1,2,3,4,5,6,7,8,9,10] del_ele.append(del arr[6]) ```
Use the `pop` method. ``` del_ele.append(arr.pop(6)) ```
Take screenshot in Python -- Cross Platform
8,644,908
8
2011-12-27T12:56:33Z
8,645,278
9
2011-12-27T13:40:50Z
[ "python", "screenshot" ]
I need to take a screenshot and send it via post to a web service. I think for the post part i will use liburl. Can this be accomplished completely cross platform and without having the need for the final user to install additional libraries/software?
There is not anything in the standard library that can do this for you. Theoretically, you might do it yourself by making os-dependent system calls with ctypes but that seems like a lot of unnecessary work to me. Here is a working script to make a screenshot using wxPython: ``` import wx app = wx.App(False) s = wx.S...
Flask virtualenv
8,645,093
3
2011-12-27T13:18:04Z
8,648,294
9
2011-12-27T19:09:06Z
[ "python", "virtualenv", "ubuntu-10.04", "flask" ]
I am trying to set up Flask on Ubuntu 10.04 LTS. I have install virtualenv 1.7 I am using python 2.6 I set my virtualenv and easy\_install Flask But when I check in my python import Flask fails The Flask.egg is present in my virtualenv site-pakages. Any suggestions ?
* use lowercase: ``` import flask ``` * “multi-version” mode might be in effect. Try `pkg_resources.require()` before importing Flask.
python exit infinite while loop with KeyboardInterrupt exception
8,645,632
4
2011-12-27T14:20:05Z
8,646,065
10
2011-12-27T15:03:57Z
[ "python", "infinite-loop", "keyboardinterrupt", "try-except", "systemexit" ]
My while loop does not exit when Ctrl+C is pressed. It seemingly ignores my KeyboardInterrupt exception. The loop portion looks like this: ``` while True: try: if subprocess_cnt <= max_subprocess: try: notifier.process_events() if notifier.check_events(): notifier.read_events() ...
Replace your `break` statement with a `raise` statement, like below: ``` while True: try: if subprocess_cnt <= max_subprocess: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() print 'K...
Converting to and from Hindu calendar
8,645,956
42
2011-12-27T14:53:25Z
9,443,332
16
2012-02-25T10:48:01Z
[ "java", "php", "python", "perl", "calendar" ]
How can I convert `unix` time to [Hindu calendar*­Wikipedia*](http://en.wikipedia.org/wiki/Hindu_calendar) time and the other way round in `php`, `Perl` or `Python` or `Java`? I know I can convert to `Hebrew` and `Jewish`. But `Hindu` is not an option. To be more specific, I'm talking about the Hindu lunar calendar. T...
Did you check [DateTime-Indic-0.1](https://metacpan.org/release/DateTime-Indic) family of modules? At least [DateTime::Indic::Chandramana](https://metacpan.org/module/DateTime%3a%3aIndic%3a%3aChandramana) seems to have a method to convert traditional date into UTC values (utc\_rd\_values). **UPDATE:** I suppose [Cale...
Converting to and from Hindu calendar
8,645,956
42
2011-12-27T14:53:25Z
9,511,949
11
2012-03-01T07:00:31Z
[ "java", "php", "python", "perl", "calendar" ]
How can I convert `unix` time to [Hindu calendar*­Wikipedia*](http://en.wikipedia.org/wiki/Hindu_calendar) time and the other way round in `php`, `Perl` or `Python` or `Java`? I know I can convert to `Hebrew` and `Jewish`. But `Hindu` is not an option. To be more specific, I'm talking about the Hindu lunar calendar. T...
For Python, use [calendar2](http://pypi.python.org/pypi/Calendar/1.11.4p) (note: this is not the built-in calendar module). Sample use: ``` >>> from calendar2 import * >>> old_hindu_solar_from_absolute(absolute_from_gregorian(3,1,2012)) (11, 16, 5112) >>> old_hindu_lunar_from_absolute(absolute_from_gregorian(3,1,2012...
Converting to and from Hindu calendar
8,645,956
42
2011-12-27T14:53:25Z
9,531,466
7
2012-03-02T10:13:05Z
[ "java", "php", "python", "perl", "calendar" ]
How can I convert `unix` time to [Hindu calendar*­Wikipedia*](http://en.wikipedia.org/wiki/Hindu_calendar) time and the other way round in `php`, `Perl` or `Python` or `Java`? I know I can convert to `Hebrew` and `Jewish`. But `Hindu` is not an option. To be more specific, I'm talking about the Hindu lunar calendar. T...
Paper: [Indian Calendrical Calculations](http://emr.cs.iit.edu/~reingold/hindu-paper.pdf) Provides Common Lisp code in the appendix. While a Python (or other language) solution could be written according to the paper, the authors enumerate the Indian calendar rules pretty well, so it's a pretty solid paper if you're...
How do I read cx_Oracle.LOB data in Python?
8,646,968
7
2011-12-27T16:39:07Z
12,590,977
10
2012-09-25T21:00:16Z
[ "python", "cx-oracle" ]
I have this code: ``` dsn = cx_Oracle.makedsn(hostname, port, sid) orcl = cx_Oracle.connect(username + '/' + password + '@' + dsn) curs = orcl.cursor() sql = "select TEMPLATE from my_table where id ='6'" curs.execute(sql) rows = curs.fetchall() print rows template = rows[0][0] orcl....
I've found out that this happens in case when connection to Oracle is closed before the cx\_Oracle.LOB.read() method is used. ``` orcl = cx_Oracle.connect(usrpass+'@'+dbase) c = orcl.cursor() c.execute(sq) dane = c.fetchall() orcl.close() # before reading LOB to str wkt = dane[0][0].read() ``` And I get: **Databas...
How to apply a disc shaped mask to a numpy array?
8,647,024
20
2011-12-27T16:44:38Z
8,650,741
26
2011-12-28T00:41:46Z
[ "python", "arrays", "numpy", "mask", "circle" ]
I have an array like this: ``` >>> np.ones((8,8)) array([[ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., ...
I would do it like this, where (a, b) is the center of your mask: ``` import numpy as np a, b = 1, 1 n = 7 r = 3 y,x = np.ogrid[-a:n-a, -b:n-b] mask = x*x + y*y <= r*r array = np.ones((n, n)) array[mask] = 255 ```
Tkinter Listbox
8,647,735
3
2011-12-27T18:01:47Z
8,647,914
7
2011-12-27T18:23:48Z
[ "python", "listbox", "tkinter" ]
I want to execute function with one click on listbox. This is my idea: ``` from Tkinter import * import Tkinter def immediately(): print Lb1.curselection() top = Tk() Lb1 = Listbox(top) Lb1.insert(1, "Python") Lb1.insert(2, "Perl") Lb1.insert(3, "C") Lb1.insert(4, "PHP") Lb1.insert(5, "JSP") Lb1.insert(6, "Ruby...
You can bind to the `<<ListboxSelect>>` event as described in this post: [Getting a callback when a Tkinter Listbox selection is changed?](http://stackoverflow.com/questions/6554805/getting-a-callback-when-a-tkinter-listbox-selection-is-changed) TKinter is somewhat strange in that the information does not seemed to be ...
How does this for loop work?
8,648,532
3
2011-12-27T19:36:56Z
8,648,613
8
2011-12-27T19:46:53Z
[ "python", "for-loop" ]
I am trying to learn python and I am going through the book programming python. I know java pretty well so I decided to give python a try as well. I am going through an example using loops and I am confused about what is happening in this code ``` for person in people: for (name, value) in person: if name == 'na...
Most likely it's supposed to deal with three dimensional list of the following format: ``` people = [ [['name', 'John'], ['age', 21]], [['name', 'Ann'], ['age', 45]], [['name', 'Tom'], ['age', 32]], ] for person in people: # person is like [['name', 'Ann'], ['age', 45]] here for (name, value) in pe...
how to show instance attributes in sphinx doc?
8,649,105
20
2011-12-27T20:43:24Z
8,659,919
27
2011-12-28T18:43:30Z
[ "python", "documentation", "python-sphinx" ]
Is there any way how to automaticaly show variables **var1** and **var2** and their init-values in sphinx documentation? ``` class myClass(): """ Description for class """ def __init__(self, par1, par2): self.var1 = par1 self.var2 = par2 def method(): pass ```
Your variables are instance variables, not class variables. Without attaching a docstring (or a `#:` "doc comment") to the variables, they won't be documented. You could do as follows: ``` class MyClass(object): """ Description for class """ def __init__(self, par1, par2): self.var1 = p...
Importing a python module into a dict (for use as globals in execfile())?
8,649,824
6
2011-12-27T22:13:01Z
8,649,875
7
2011-12-27T22:20:13Z
[ "python", "python-module" ]
I'm using the Python `execfile()` function as a simple-but-flexible way of handling configuration files -- basically, the idea is: ``` # Evaluate the 'filename' file into the dictionary 'foo'. foo = {} execfile(filename, foo) # Process all 'Bar' items in the dictionary. for item in foo: if isinstance(item, Bar): ...
Maybe you can use the `__dict__` defined by the module. ``` >>> import os >>> str = 'getcwd()' >>> eval(str,os.__dict__) ```
how to get setuptools and easy_install
8,650,459
31
2011-12-27T23:48:38Z
19,673,702
71
2013-10-30T04:13:35Z
[ "python", "egg" ]
I downloaded the `ez_setup` code from here: <http://peak.telecommunity.com/dist/ez_setup.py> and ran it, but i don't think `setuptools` was properly installed. When i try to open an egg using `easy_install` i am getting a NameError. Any thoughts? Here is the specific error: ``` Traceback (most recent call last): Fi...
For linux versions(ubuntu/linux mint), you can always type this in the command prompt: `sudo apt-get install python-setuptools` this will automatically install eas-\_install
how to get setuptools and easy_install
8,650,459
31
2011-12-27T23:48:38Z
25,058,035
7
2014-07-31T11:42:18Z
[ "python", "egg" ]
I downloaded the `ez_setup` code from here: <http://peak.telecommunity.com/dist/ez_setup.py> and ran it, but i don't think `setuptools` was properly installed. When i try to open an egg using `easy_install` i am getting a NameError. Any thoughts? Here is the specific error: ``` Traceback (most recent call last): Fi...
For python3 on Ubuntu ``` sudo apt-get install python3-setuptools ```
Using python with selenium to scrape dynamic web pages
8,650,999
3
2011-12-28T01:38:59Z
8,652,092
10
2011-12-28T05:09:55Z
[ "python", "selenium" ]
On the site, there are a couple of links at the top labeled "1", "2", "3", and "next". If a link labeled by a number is pressed, it dynamically loads in some data into a content div. If "next" is pressed, it goes to a page with labels "4", "5", "6", "next" and the data for page 4 is shown. I want to scrape the data fr...
General layout (not tested): ``` #!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox # pip install selenium url = "http://example.com" # use firefox to get page with javascript generated content with closing(Firefox()) as browser: n = 1 while n < 10: browser.ge...
Why are my Amazon S3 key permissions not sticking?
8,651,070
4
2011-12-28T01:52:18Z
8,658,450
11
2011-12-28T16:22:22Z
[ "python", "django", "amazon-s3", "acl", "boto" ]
I'm using the Python library `boto` to connect to Amazon S3 and create buckets and keys for a static website. My keys and values are dynamically generated, hence why I am doing this programmatically and not through the web interface (it works using the web interface). My code currently looks like this: ``` import boto...
I'm still not completely sure why the code above didn't work, but I found a different (or newer?) syntax for creating keys. The order of operations also appears to have some effect. This is what I came up with that worked: ``` conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(st...
Controlling Yaml Serialization Order in Python
8,651,095
8
2011-12-28T01:59:18Z
8,661,021
11
2011-12-28T20:39:53Z
[ "python", "yaml" ]
How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary? I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir...
Took me a few hours of digging through PyYAML docs and tickets, but I eventually discovered [this comment](http://pyyaml.org/ticket/29#comment:11) that lays out some proof-of-concept code for serializing an OrderedDict as a normal YAML map (but maintaining the order). e.g. applied to my original code, the solution loo...
Convert string with parantheses into nested list
8,651,110
3
2011-12-28T02:01:26Z
8,651,171
8
2011-12-28T02:11:21Z
[ "python", "string", "parsing", "list" ]
I want to convert a string like this: ``` "asd foo bar ( lol bla ( gee bee ) lee ) ree" ``` to a list like this: ``` ["asd","foo","bar",["lol","bla",["gee","bee"],"lee"],"ree"] ``` Is there an easy solution? edit: It should work for any number and depth of parantheses, but it only has to work for valid strings (no...
You can use Python's parser to do the job. Just help it a little: ``` >>> a = "asd foo bar ( lol bla ( gee bee ) lee ) ree" >>> eval(str(a.split()).replace("'(',", '[').replace("')'",']')) ['asd', 'foo', 'bar', ['lol', 'bla', ['gee', 'bee'], 'lee'], 'ree'] ``` If you need it to be safe, use `ast.literal_eval` instead...
How do you print superscript in Python?
8,651,361
6
2011-12-28T02:53:17Z
8,651,690
7
2011-12-28T03:59:49Z
[ "python", "math", "superscript" ]
I am aware of the \xb function in python, but it does not seem to work for me. I am aware that I may need to download a third party module to accomplish this, if so, which one would be best? I am a noob with Python, and with StackOverflow hence my basic question. Now a bit about the context... I am currently writing a...
You could use `sympy` module that does necessary formatting for you. It supports many formats such as ascii, unicode, latex, mathml, etc: ``` from sympy import pretty_print as pp, latex from sympy.abc import a, b, n expr = (a*b)**n pp(expr) # default pp(expr, use_unicode=True) print(latex(expr)) print(expr.evalf(subs...
dynamically adding and removing widgets in PyQt
8,651,742
8
2011-12-28T04:07:50Z
8,652,125
11
2011-12-28T05:15:08Z
[ "python", "pyqt", "pyqt4" ]
using PyQt, I am trying to create an interface for which I can add or remove widget dynamically. I want to define a separate class for the widget that will be added or removed. I can't seem to be able to get the widget that I instantiate to display inside the main interface. Here is the code I am using: ``` from PyQt4...
Actually, it does work. Problem is, your `Test` widget has a `QPushButton` without any layout management. So it can't calculate its `minimumSize` with taking the button into consideration. When you put that widget in a layout, it just shrinks to `0` (since a `QWidget` has no default `minimumSize`) and you don't see any...
Caught TypeError while rendering: Decimal('51.8') is not JSON serializable
8,652,497
2
2011-12-28T06:11:51Z
8,652,889
8
2011-12-28T07:02:21Z
[ "python", "django" ]
I am using Python 2.6.5 and Django 1.3 .while running the below code i am getting the above error ``` if chart_list is not None: if isinstance(chart_list, (Chart, PivotChart)): chart_list = [chart_list] chart_list = [c.hcoptions for c in chart_list] render_to_list = [s.strip() for s in render_to.sp...
Use of custom JSONEncoder should help ``` class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return float(o) super(DecimalEncoder, self).default(o) # and then: json.dumps(chart_list,..., cls=DecimalEncoder) ``` --- ## Updated Updated acc...
Python3 subprocess communicate example
8,652,767
8
2011-12-28T06:46:12Z
8,652,799
15
2011-12-28T06:51:15Z
[ "python", "subprocess", "pipe", "communicate" ]
I'm new to subprocessing. I just need a really simple win32 example of communicate() between a **parent.py** and **child.py**. A string sent from parent.py to child.py, altered by child.py and sent back to parent.py for print() from parent.py. I'm posting this because examples I have found end up either not bein...
Here is a simple example as per your requirements. This example is Python 3.x (slight modifications are required for 2.x). ## parent.py ``` import subprocess import sys s = "test" p = subprocess.Popen([sys.executable, "child.py"], stdin=subprocess.PIPE, stdout=subprocess.PIP...
Why does numpy.apply_along_axis seem to be slower than Python loop?
8,652,785
5
2011-12-28T06:48:47Z
8,652,969
9
2011-12-28T07:12:32Z
[ "python", "numpy" ]
I'm confused about when numpy's `numpy.apply_along_axis()` function will outperform a simple Python loop. For example, consider the case of a matrix with many rows, and you wish to compute the sum of each row: ``` x = np.ones([100000, 3]) sums1 = np.array([np.sum(x[i,:]) for i in range(x.shape[0])]) sums2 = np.apply_a...
`np.sum` take an `axis` parameter, so you could compute the sum simply using ``` sums3 = np.sum(x, axis=1) ``` This is much faster than the 2 methods you posed. ``` $ python -m timeit -n 1 -r 1 -s "import numpy as np;x=np.ones([100000,3])" "np.apply_along_axis(np.sum, 1, x)" 1 loops, best of 1: 3.21 sec per loop $ ...
xlrd python library
8,652,821
2
2011-12-28T06:53:44Z
8,652,904
7
2011-12-28T07:03:41Z
[ "python", "xlrd" ]
``` import xlrd wb = xlrd.open_workbook("file.xls") wb.sheet_names() sh = wb.sheet_by_index(0) for item in sh.col(0): value = unicode(item.value) if value.startswith("cheap"): print value ``` when i trying this code, interpritator return me: AttributeError: 'module' object has no attribute 'open\_wo...
The most likely explanation is that you've accidentally created your own xlrd.py file that is being found before the real one. The solution is to find the imposter and delete it. Try `import xlrd; print xlrd.__file__` to find the culprit :-) P.S. You will need to delete both the .py file and its .pyc cached version.
Python list of dictionaries search
8,653,516
145
2011-12-28T08:25:54Z
8,653,558
11
2011-12-28T08:30:16Z
[ "python", "search", "dictionary" ]
Assume I have this: ``` [ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7} ] ``` and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7} How to achieve this ?
``` people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5}, {'name': "Pam", 'age': 7} ] def search(name): for p in people: if p['name'] == name: return p search("Pam") ```
Python list of dictionaries search
8,653,516
145
2011-12-28T08:25:54Z
8,653,568
194
2011-12-28T08:31:48Z
[ "python", "search", "dictionary" ]
Assume I have this: ``` [ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7} ] ``` and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7} How to achieve this ?
You can use a [generator expression](http://www.python.org/dev/peps/pep-0289/): ``` >>> dicts = [ ... { "name": "Tom", "age": 10 }, ... { "name": "Mark", "age": 5 }, ... { "name": "Pam", "age": 7 }, ... { "name": "Dick", "age": 12 } ... ] >>> (item for item in dicts if item["name"] == "Pam").next() {'...
Python list of dictionaries search
8,653,516
145
2011-12-28T08:25:54Z
8,653,572
21
2011-12-28T08:32:09Z
[ "python", "search", "dictionary" ]
Assume I have this: ``` [ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7} ] ``` and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7} How to achieve this ?
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` def search(name, people): return [element for element in people if element['name'] == name] ```
Python list of dictionaries search
8,653,516
145
2011-12-28T08:25:54Z
25,373,204
61
2014-08-18T22:46:19Z
[ "python", "search", "dictionary" ]
Assume I have this: ``` [ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7} ] ``` and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7} How to achieve this ?
This looks to me the most pythonic way: ``` people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5}, {'name': "Pam", 'age': 7} ] filter(lambda person: person['name'] == 'Pam', people) ``` result: ``` [{'age': 7, 'name': 'Pam'}] ```
Disabling python's assert() without -0 flag
8,656,927
10
2011-12-28T14:07:19Z
8,657,731
9
2011-12-28T15:25:57Z
[ "python", "debugging", "assert" ]
I'm running a python script from inside a different software (it provides a python interface to manipulate its data structures). I'm optimizing my code for speed and would like to see what impact on performance my asserts have. I'm unable to use `python -O`. What other options do I have, to programatically disable al...
[The docs say](http://docs.python.org/reference/simple_stmts.html#the-assert-statement), > The value for the built-in variable [**debug**] is determined when the > interpreter starts. So, if you can not control how the python interpreter is started, then it looks like you can not disable assert. Here then are some o...
Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing
8,657,508
22
2011-12-28T15:06:09Z
8,666,415
35
2011-12-29T10:08:47Z
[ "python", "postgresql", "sqlalchemy" ]
I am using hand crafted SQL to fetch data from a PG database, using SqlAlchemy. I am trying a query which contains the SQL like operator '%' and that seems to throw SqlAlcjhemy through a loop: ``` sql = """ SELECT DISTINCT u.name from user u INNER JOIN city c ON u.city_id = c.id WHERE c.designat...
You have to give `%%` to use it as `%` because `%` in python is use as string formatting so when you write single `%` its assume that you are going to replace some value with this. So when you want to place single `%` in string with query allways place double `%`.
Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing
8,657,508
22
2011-12-28T15:06:09Z
14,988,644
13
2013-02-20T19:47:52Z
[ "python", "postgresql", "sqlalchemy" ]
I am using hand crafted SQL to fetch data from a PG database, using SqlAlchemy. I am trying a query which contains the SQL like operator '%' and that seems to throw SqlAlcjhemy through a loop: ``` sql = """ SELECT DISTINCT u.name from user u INNER JOIN city c ON u.city_id = c.id WHERE c.designat...
SQLAlchemy has a text function for wrapping text which appears to correctly escape the SQL for you. i.e. ``` res = executeSql(sqlalchemy.text(sql)) ``` should work for you and save you from having to do the strange escaping.
Interpolating periodic data in Python
8,657,612
3
2011-12-28T15:14:34Z
8,657,668
7
2011-12-28T15:19:12Z
[ "python", "statistics" ]
I have a module that collects stats in an inconsistent time interval. Unfortunately, to use it nicely in a graph, I need the `x` values interpolated to a consistent interval. Given the following `x`, `y` pairs, what's the most Pythonic way to do this? ``` (1, 23), (2, 42), (3.5, 89), (5, 73), (7, 54), (8, 41), (8.5, ...
Use [numpy.interp](http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html): ``` import numpy as np a = np.array([(1, 23), (2, 42), (3.5, 89), (5, 73), (7, 54), (8, 41), (8.5, 37), (9, 23)]) x = np.arange(1, 10) # target x values b = zip(x, np.interp(x, a[:,0], a[:,1])) # b == [(1, 23.0), # (2,...
How to mock an import
8,658,043
59
2011-12-28T15:51:32Z
8,658,332
60
2011-12-28T16:13:38Z
[ "python", "mocking", "python-import" ]
Module `A` includes `import B` at its top. However under test conditions I'd like to [mock](http://www.voidspace.org.uk/python/mock/) `B` in `A` (mock `A.B`) and completely refrain from importing `B`. In fact, `B` isn't installed in the test environment on purpose. How could this be done?
You can assign to `sys.modules['B']` before importing `A` to get what you want: **test.py**: ``` import sys sys.modules['B'] = __import__('mock_B') import A print(A.B.__name__) ``` **A.py**: ``` import B ``` Note B.py does not exist, but when running `test.py` no error is returned and `print(A.B.__name__)` prints...
How to mock an import
8,658,043
59
2011-12-28T15:51:32Z
18,481,028
11
2013-08-28T06:43:36Z
[ "python", "mocking", "python-import" ]
Module `A` includes `import B` at its top. However under test conditions I'd like to [mock](http://www.voidspace.org.uk/python/mock/) `B` in `A` (mock `A.B`) and completely refrain from importing `B`. In fact, `B` isn't installed in the test environment on purpose. How could this be done?
The builtin `__import__` can be mocked with the 'mock' library for more control: ``` # Store original __import__ orig_import = __import__ # This will be the B module b_mock = mock.Mock() def import_mock(name, *args): if name == 'B': return b_mock return orig_import(name, *args) with mock.patch('__bui...
Regex matching Python function calls
8,658,585
3
2011-12-28T16:32:52Z
8,659,251
9
2011-12-28T17:37:13Z
[ "python", "regex" ]
I'd like to create a regular expression in Python that will match against a line in Python source code and return a list of function calls. The typical line would look like this: ``` something = a.b.method(time.time(), var=1) + q.y(x.m()) ``` and the result should be: ``` ["a.b.method()", "time.time()", "q.y()", "x...
I don't think regular expressions is the best approach here. Consider the [ast module](http://docs.python.org/library/ast.html) instead, for example: ``` class ParseCall(ast.NodeVisitor): def __init__(self): self.ls = [] def visit_Attribute(self, node): ast.NodeVisitor.generic_visit(self, node)...
python syntax error in script, fine in REPL
8,658,812
2
2011-12-28T16:53:08Z
8,659,015
11
2011-12-28T17:12:16Z
[ "python", "syntax-error" ]
When I put this python code into the REPL for python (the interactive shell), it works as expected: ``` >>> def get_header(): ... return (None,None,None) ... >>> get_header() (None, None, None) ``` Note that the return statement is indented by four spaces, and I have checked to ensure there are no extraneous spa...
The reason this is not working is that you don’t have anything telling `bash` that this is a Python script, so it tries to execute it as a shell script, then throws an error when the syntax isn’t right. What you need is to start the file with a [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) line, telli...
multiprocessing Listeners and Clients between python and pypy
8,659,180
5
2011-12-28T17:30:29Z
8,659,369
10
2011-12-28T17:47:58Z
[ "python", "multiprocessing", "pypy" ]
Is it possible to have a [Listener server process and a Client process](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.connection) where one of them uses a python interpreter and the other a [pypy](http://pypy.org/) interpreter? Would `conn.send()` and `conn.recv()` interoperate well?
I tried it out to see: ``` import sys from multiprocessing.connection import Listener, Client address = ('localhost', 6000) def client(): conn = Client(address, authkey='secret password') print conn.recv_bytes() conn.close() def server(): listener = Listener(address, authkey='secret password') c...
Run a python script in perl
8,659,226
2
2011-12-28T17:34:30Z
8,659,276
8
2011-12-28T17:39:26Z
[ "python", "perl" ]
I have two scripts, a python script and a perl script. How can I make the perl script run the python script and then runs itself?
Something like this should work: ``` system("python", "/my/script.py") == 0 or die "Python script returned error $?"; ``` If you need to capture the output of the Python script: ``` open(my $py, "|-", "python2 /my/script.py") or die "Cannot run Python script: $!"; while (<$py>) { # do something with the input } cl...
How to store the result of an executed shell command in a variable in python?
8,659,275
9
2011-12-28T17:39:18Z
8,659,316
7
2011-12-28T17:42:17Z
[ "python", "linux", "bash", "shell" ]
I need to store the result of a shell command that I executed in a variable. But i couldn get that. I tried like: ``` call=os.system("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'") print call ``` But it prints the result in terminal and prints the value of call as zero, possibly indicating as success. How ...
[commands.getstatusoutput](http://docs.python.org/library/commands.html#commands.getstatusoutput) would work well for this situation. ``` import commands print(commands.getstatusoutput("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'")) ```
How to store the result of an executed shell command in a variable in python?
8,659,275
9
2011-12-28T17:39:18Z
8,659,333
16
2011-12-28T17:44:32Z
[ "python", "linux", "bash", "shell" ]
I need to store the result of a shell command that I executed in a variable. But i couldn get that. I tried like: ``` call=os.system("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'") print call ``` But it prints the result in terminal and prints the value of call as zero, possibly indicating as success. How ...
Use the [`subprocess`](http://docs.python.org/library/subprocess.html) module instead: ``` import subprocess output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True) ``` Edit: this is new in Python 2.7. In earlier versions this should work (with the command rewritten as ...
Detecting black images on Android or python
8,659,663
2
2011-12-28T18:19:35Z
8,659,785
7
2011-12-28T18:32:20Z
[ "android", "python", "image-processing" ]
I have an Android application that has user contributed images. There are a lot of users that submit black or really dark images to the backend application, that I want to filter out. Best solution would be to filter the images already at the phone and notify the user to make more light and retake the picture. Another ...
You can try using a histogram of the image as a first approximation. An example using PIL that alerts you if there are more 'dark' pixels (first 128 values in a greyscale representation) than 'light' ones: ``` import Image img = Image.open('m.jpg') gsimg = im.convert(mode='L') hg = gsimg.histogram() # count should...
Markov chain on letter scale and random text
8,660,015
4
2011-12-28T18:53:51Z
8,660,104
8
2011-12-28T19:02:08Z
[ "python", "markov-chains" ]
I would like to generate a random text using letter frequencies from a book in a .txt file, so that each new character (`string.lowercase + ' '`) depends on the previous one. How do I use Markov chains to do so? Or is it simpler to use 27 arrays with conditional frequencies for each letter?
> I would like to generate a random text using letter frequencies from a > book in a txt file Consider using *[collections.Counter](http://docs.python.org/library/collections.html#counter-objects)* to build-up the frequencies when looping over the text file two letters at a time. > How do I use markov chains to do so...
Extract video from .swf using Python
8,660,526
2
2011-12-28T19:47:31Z
8,660,620
13
2011-12-28T19:56:59Z
[ "python", "screen-scraping", "web-scraping" ]
I've written code that generated the links to videos such as the one below. Once obtained, I try to download it in this manner: ``` import urllib.request import os url = 'http://www.videodetective.net/flash/players/?customerid=300120&playerid=351&publishedid=319113&playlistid=0&videokbrate=750&sub=RTO&pversion=5.2%22...
With your code, you aren't downloading the encoded video file here, but the flash application (in CWS-format) that is used to play the video. It is executed in the browser and dynamically loads and plays the video. You'd need to apply some reverse-engineering to figure out the actual video source. The following is my a...
mod_wsgi isn't honoring WSGIPythonHome
8,660,896
12
2011-12-28T20:30:13Z
8,662,381
12
2011-12-28T23:19:44Z
[ "python", "apache", "mod-wsgi" ]
I'm trying to get WSGI to run with a virtualenv setup. I have the virtualenv all working right: ``` (virtualenv)dev:/var/www/app$ which python /var/www/virtualenv/bin/python (virtualenv)dev:/var/www/app$ python Python 2.6.1 (r261:67515, Dec 5 2008, 22:09:34) [GCC 4.1.2] on linux2 Type "help", "copyright", "credits" o...
Your mod\_wsgi is likely compiled against a different Python version than you are trying to force it to use. For example, you can not use mod\_wsgi compiled against Python 2.4 with a virtual environment constructed using Python 2.6. Validate what version of Python mod\_wsgi was built for in the first place.
Custom CSS classes for SQLFORM widget input in web2py
8,661,166
3
2011-12-28T20:50:56Z
8,661,906
7
2011-12-28T22:13:43Z
[ "python", "web2py" ]
Given this SQLFORM in the controller: ``` form = SQLFORM.factory(db.source_server, db.target_server) ``` with the following table definition: ``` db.define_table('target_server', Field('target_url', 'string'), Field('target_user', 'string'), Field('target_password', 'p...
Note, all widgets already have a class named for the type of widget (e.g., "string", "integer", "date", etc.) as well as an id of the form "tablename\_fieldname", so you might be able to make use of those in your CSS without needing to add custom classes. See [here](http://web2py.com/books/default/chapter/29/7#CSS-conv...
How to perform bilinear interpolation in Python
8,661,537
12
2011-12-28T21:29:39Z
8,662,355
24
2011-12-28T23:14:56Z
[ "python", "math", "coordinates", "interpolation", "geo" ]
I would like to perform blinear interpolation using python. Example gps point for which I want to interpolate height is: ``` B = 54.4786674627 L = 17.0470721369 ``` using four adjacent points with known coordinates and height values: ``` n = [(54.5, 17.041667, 31.993), (54.5, 17.083333, 31.911), (54.458333, 17.041...
Here's a reusable function you can use. It includes doctests and data validation: ``` def bilinear_interpolation(x, y, points): '''Interpolate (x,y) from values associated with four points. The four points are a list of four triplets: (x, y, value). The four points can be in any order. They should form ...
How to read the file contents from a file?
8,662,641
5
2011-12-28T23:53:09Z
8,664,011
7
2011-12-29T04:29:35Z
[ "python", "python-3.x", "os.walk" ]
Using Python3, hope to `os.walk` a directory of files, read them into a binary object (string?) and do some further processing on them. First step, though: How to read the file(s) results of `os.walk`? ``` # NOTE: Execute with python3.2.2 import os import sys path = "/home/user/my-files" count = 0 successcount = 0 ...
To read a binary file you must open the file in binary mode. Change ``` input = open(fullpath, "r") ``` to ``` input = open(fullpath, "rb") ``` The result of the read() will be a bytes() object.
How to install a Python package from within IPython?
8,663,046
19
2011-12-29T01:13:17Z
8,675,049
34
2011-12-30T00:44:42Z
[ "python", "module", "install", "ipython" ]
I wonder if it's possible to install python packages without leaving the IPython shell.
You can use the `!` prefix like this: ``` !pip install packagename ``` The `!` prefix is a short-hand for the `%sc` command to run a shell command. You can also use the `!!` prefix which is a short-hand for the `%sx` command to execute a shell command and capture its output (saved into the `_` variable by default).
Python: Best way to add to sys.path relative to the current running script
8,663,076
29
2011-12-29T01:19:50Z
8,663,119
45
2011-12-29T01:29:44Z
[ "python", "python-import" ]
I have a directory full of scripts (let's say `project/bin`). I also have a library located in `project/lib` and want the scripts to automatically load it. This is what I normally use at the top of each script: ``` #!/usr/bin/python from os.path import dirname, realpath, sep, pardir import sys sys.path.append(dirname(...
This is what I use: ``` import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), "lib")) ```
Python: Best way to add to sys.path relative to the current running script
8,663,076
29
2011-12-29T01:19:50Z
8,663,557
7
2011-12-29T02:58:40Z
[ "python", "python-import" ]
I have a directory full of scripts (let's say `project/bin`). I also have a library located in `project/lib` and want the scripts to automatically load it. This is what I normally use at the top of each script: ``` #!/usr/bin/python from os.path import dirname, realpath, sep, pardir import sys sys.path.append(dirname(...
Create a wrapper module `project/bin/lib`, which contains this: ``` import sys, os sys.path.insert(0, os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')) import mylib del sys.path[0], sys, os ``` Then you can replace all the cruft at the top of your scripts with: ``` #!/usr/bin...
Opening a .txt file in Python
8,663,680
3
2011-12-29T03:24:55Z
8,689,872
7
2011-12-31T18:36:34Z
[ "python", "string", "list", "file-io", "text-files" ]
I'm trying to open a .txt file in Python with the following function. ``` def get_my_string(): """Returns a string of the text""" f = open("/home/Documents/text.txt", 'r') string = str(f.read()) f.close() return string ``` I want "string" to be a string of the text from the opened file. However, after ...
``` def get_my_string(): """Returns the file inputFn""" inputFn = "/home/Documents/text.txt" try: with open(inputFn) as inputFileHandle: return inputFileHandle.read() except IOError: sys.stderr.write( "[myScript] - Error: Could not open %s\n" % (inputFn) ) sys.exit...
In python, how does one efficiently find the largest consecutive set of numbers in a list that are not necessarily adjacent?
8,664,708
10
2011-12-29T06:34:21Z
8,665,506
12
2011-12-29T08:29:19Z
[ "python", "algorithm", "dynamic-programming" ]
For instance, if I have a list ``` [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11] ``` This algorithm should return [1,2,3,4,5,6,7,8,9,10,11]. To clarify, the longest list should run forwards. I was wondering what is an algorithmically efficient way to do this (preferably not O(n^2))? Also, I'm open to a solution not in pyth...
Here is a simple one-pass O(n) solution: ``` s = [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11,42] maxrun = -1 rl = {} for x in s: run = rl[x] = rl.get(x-1, 0) + 1 print x-run+1, 'to', x if run > maxrun: maxend, maxrun = x, run print range(maxend-maxrun+1, maxend+1) ``` The logic may be a little more self-...
How to upload file ( picture ) with selenium, python
8,665,072
22
2011-12-29T07:27:01Z
8,733,767
7
2012-01-04T20:47:03Z
[ "python", "testing", "file-upload", "selenium", "upload" ]
is there any possibility how to upload on web picture with selenium testing tool ? I am using python. I tryed many things, but nothing didnt work. I am desperate. Upload looks like this : <http://img21.imageshack.us/img21/1954/uploadgr.jpg> Thank you for your help Filip.
Upload input control opens a native dialog (it is done by browser) so clicking on the control or browse button via Selenium will just pop the dialog and the test will hang. The workaround is to set the value of the upload input via JavaScript (in Java it is done via JavascriptExecutor) and then submit the form. See [...
How to upload file ( picture ) with selenium, python
8,665,072
22
2011-12-29T07:27:01Z
10,472,542
54
2012-05-06T17:16:15Z
[ "python", "testing", "file-upload", "selenium", "upload" ]
is there any possibility how to upload on web picture with selenium testing tool ? I am using python. I tryed many things, but nothing didnt work. I am desperate. Upload looks like this : <http://img21.imageshack.us/img21/1954/uploadgr.jpg> Thank you for your help Filip.
What I'm doing is this (make sure drv is an instance of webdriver): ``` drv.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png") ``` and then find your submit button and click it.
Start python .py as a service in windows
8,666,373
8
2011-12-29T10:04:30Z
8,668,133
15
2011-12-29T12:55:29Z
[ "python", "windows-services" ]
I've created a windows service to start a .py script. ``` sc create "Maraschino" binPath= "C:\HTPC\Maraschino\maraschino-cherrypy.py" DisplayName= "Maraschino" depend= "Tcpip" ``` Then I've added a registry key to link the .py to open using python.exe ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\S...
You can do this using the **srvany.exe**, which is a tool from Microsoft dedicated for this kind of tasks. First, download and install the [Windows Resource Kit](http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=17657). Note: You only need srvany.exe, which works on all versions of Windows. Presumin...
delete not cascaded to table in sqlalchemy
8,667,096
3
2011-12-29T11:07:31Z
8,671,600
8
2011-12-29T18:13:35Z
[ "python", "sql", "orm", "foreign-keys", "sqlalchemy" ]
I am developing an extension to an existing app which uses sqlalchemy 0.6. The app has sqlalchemy tables created the non-declarative way. I am trying to create in my extension a new table with a foreign key column pointing at the primary key of the main table in the application database and I am creating it declarativ...
In SQLite you must turn on support for foreign keys explicitly or it just ignores any SQL related to foreign keys. ``` engine = create_engine(database_url) def on_connect(conn, record): conn.execute('pragma foreign_keys=ON') from sqlalchemy import event event.listen(engine, 'connect', on_connect) ```