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
Python: How to make a list of n numbers and randomly select any number?
7,567,318
16
2011-09-27T10:00:25Z
7,567,379
26
2011-09-27T10:04:46Z
[ "python", "list", "random" ]
I have taken a count of something and it came out to N Now I would like to have a list, containing 0 to N numbers in it. Example: N = 5 then, `count_list = [1, 2, 3, 4, 5]` How would I be able to do that? Also, once I have created the list, I would like to randomly select a number from that list and use that number....
You can create the enumeration of the elements by something like that: ``` mylist = list(xrange(10)) ``` then you can use the `random.choice` function to select your items: ``` import random ... random.choice(mylist) ``` **EDIT:** As Asim Ihsan correctly stated, my answer does not yet address the full problem of t...
Where to put a configuration file in Python?
7,567,642
34
2011-09-27T10:27:19Z
7,567,946
25
2011-09-27T10:54:18Z
[ "python", "pythonpath", "configparser" ]
In development mode, I have the following directory tree : ``` | my_project/ | setup.py | my_project/ | __init__.py | main.py | conf/ | myproject.conf ``` I use [ConfigParser](http://docs.python.org/library/configparser.html) to parse the `myproject.conf` file. In my code, it's easy to load the f...
Have you seen how configuration files work? Read up on "rc" files, as they're sometimes called. "bashrc", "vimrc", etc. There's usually a multi-step search for the configuration file. 1. Local directory. `./myproject.conf`. 2. User's home directory (`~user/myproject.conf`) 3. A standard system-wide directory (`/etc/m...
Where to put a configuration file in Python?
7,567,642
34
2011-09-27T10:27:19Z
7,567,974
9
2011-09-27T10:56:49Z
[ "python", "pythonpath", "configparser" ]
In development mode, I have the following directory tree : ``` | my_project/ | setup.py | my_project/ | __init__.py | main.py | conf/ | myproject.conf ``` I use [ConfigParser](http://docs.python.org/library/configparser.html) to parse the `myproject.conf` file. In my code, it's easy to load the f...
If you're using `setuptools`, see the chapter on [using non-package data files](http://peak.telecommunity.com/DevCenter/setuptools#non-package-data-files). Don't try to look for the files yourself.
Where to put a configuration file in Python?
7,567,642
34
2011-09-27T10:27:19Z
12,762,593
7
2012-10-06T18:29:52Z
[ "python", "pythonpath", "configparser" ]
In development mode, I have the following directory tree : ``` | my_project/ | setup.py | my_project/ | __init__.py | main.py | conf/ | myproject.conf ``` I use [ConfigParser](http://docs.python.org/library/configparser.html) to parse the `myproject.conf` file. In my code, it's easy to load the f...
The [appdirs](http://pypi.python.org/pypi/appdirs/1.2.0) package does a nice job on finding the standard place for installed apps on various platforms. I wonder if extending it to discover or allow some sort of "uninstalled" status for developers would make sense.
Using Python String Formatting with Lists
7,568,627
35
2011-09-27T11:51:02Z
7,568,645
45
2011-09-27T11:53:09Z
[ "python", "string", "list", "formatting", "string-formatting" ]
I construct a string `s` in Python 2.6.5 which will have a varying number of `%s` tokens, which match the number of entries in list `x`. I need to write out a formatted string. The following doesn't work, but indicates what I'm trying to do. In this example, there are three `%s` tokens and the list has three entries. ...
``` print s % tuple(x) ``` instead of ``` print s % (x) ```
Using Python String Formatting with Lists
7,568,627
35
2011-09-27T11:51:02Z
7,568,689
60
2011-09-27T11:56:14Z
[ "python", "string", "list", "formatting", "string-formatting" ]
I construct a string `s` in Python 2.6.5 which will have a varying number of `%s` tokens, which match the number of entries in list `x`. I need to write out a formatted string. The following doesn't work, but indicates what I'm trying to do. In this example, there are three `%s` tokens and the list has three entries. ...
You should take a look to the [format](http://docs.python.org/library/string.html#format-string-syntax) method of python. You could then define your formatting string like this : ``` >>> s = '{0} BLAH {1} BLAH BLAH {2} BLAH BLAH BLAH' >>> x = ['1', '2', '3'] >>> print s.format(*x) '1 BLAH 2 BLAH BLAH 3 BLAH BLAH BLAH'...
Using Python String Formatting with Lists
7,568,627
35
2011-09-27T11:51:02Z
27,856,822
10
2015-01-09T08:53:31Z
[ "python", "string", "list", "formatting", "string-formatting" ]
I construct a string `s` in Python 2.6.5 which will have a varying number of `%s` tokens, which match the number of entries in list `x`. I need to write out a formatted string. The following doesn't work, but indicates what I'm trying to do. In this example, there are three `%s` tokens and the list has three entries. ...
Following this [resource page](https://sites.google.com/site/kittipat/programming-with-python/formatanddisplayelementsinpythonlist), if the length of x is varying, we can use: ``` ', '.join(['%.2f']*len(x)) ``` to create a place holder for each element from the list `x`. Here is the example: ``` x = [1/3.0, 1/6.0, 0...
Unicode literals causing invalid syntax
7,569,014
3
2011-09-27T12:22:31Z
7,569,029
10
2011-09-27T12:23:47Z
[ "python", "python-3.x", "unicode", "unicode-literals" ]
The following code: ``` s = s.replace(u"&", u"&") ``` is causing an error in python: ``` SyntaxError: invalid syntax ``` removing the `u`'s before the `"` fixes the problem, but this should work as is? I'm using Python 3.1
The `u` is no longer used in Python 3. String literals are unicode by default. See [What's New in Python 3.0](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit). > You can no longer use `u"..."` literals for Unicode text. However, you must use `b"..."` literals for binary ...
Oauth client initialization in python for tumblr API using Python-oauth2
7,569,018
7
2011-09-27T12:23:06Z
7,571,727
11
2011-09-27T15:30:11Z
[ "python", "oauth", "access-token" ]
I'm new to Oauth. In the past for twitter applications written in Python i used python-oauth2 library to initialize client like this: ``` consumer = oauth.Consumer(key = CONSUMER_KEY, secret = CONSUMER_SECRET) token = oauth.Token(key = ACCESS_KEY, secret = ACCESS_SECRET) client = oauth.Client(consumer, token) ``` Tha...
First, import the [oauth2 module](https://github.com/simplegeo/python-oauth2) and set up the service's URL and consumer information: ``` import oauth2 REQUEST_TOKEN_URL = 'http://www.tumblr.com/oauth/request_token' AUTHORIZATION_URL = 'http://www.tumblr.com/oauth/authorize' ACCESS_TOKEN_URL = 'http://www.tumblr.com/o...
How to overwrite the put() method on a python app engine model?
7,569,461
6
2011-09-27T12:55:23Z
7,577,271
7
2011-09-28T01:04:01Z
[ "python", "google-app-engine" ]
In Appengine, I am trying to have a property value computed automatically and stored with the object. I have a class, Rectangle, and it has a width, height and area. Obviously the area is a function of width and height, but I want it to be a property because I want to use it for sorting. So I try to modify the put() f...
Don't override put - as you observe, it's fragile, and doesn't get invoked if you call `db.put` instead of the model's put function. Fortunately, App Engine provides a `ComputedProperty` which makes your use-case really easy: ``` class Rectangle(db.Model): width = db.IntegerProperty() height = db.IntegerPr...
Working with TIFFs (import, export) in Python using numpy
7,569,553
30
2011-09-27T13:01:27Z
7,569,686
27
2011-09-27T13:10:10Z
[ "python", "numpy", "python-imaging-library", "tiff" ]
I need a python routine that can open and import TIFF images into numpy arrays, so I can analyze and modify the contained data and afterwards save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel) I tried to find something, but there is no documen...
I use matplotlib for reading TIFF files: ``` import matplotlib.pyplot as plt I = plt.imread(tiff_file) ``` and `I` will be of type `ndarray`. According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fin...
Working with TIFFs (import, export) in Python using numpy
7,569,553
30
2011-09-27T13:01:27Z
7,570,900
8
2011-09-27T14:33:54Z
[ "python", "numpy", "python-imaging-library", "tiff" ]
I need a python routine that can open and import TIFF images into numpy arrays, so I can analyze and modify the contained data and afterwards save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel) I tried to find something, but there is no documen...
You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product. Link to precompiled GDAL binaries for windows (assuming windows here) <http://www.gisinternals.com/sdk/> To access the array you can use: ``` from osgeo import gdal dataset = gdal....
Working with TIFFs (import, export) in Python using numpy
7,569,553
30
2011-09-27T13:01:27Z
7,572,079
30
2011-09-27T15:55:22Z
[ "python", "numpy", "python-imaging-library", "tiff" ]
I need a python routine that can open and import TIFF images into numpy arrays, so I can analyze and modify the contained data and afterwards save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel) I tried to find something, but there is no documen...
First, I downloaded a test TIFF image from [this page](http://www-eng-x.llnl.gov/documents/tests/tiff.html) called `a_image.tif`. Then I opened with PIL like this: ``` >>> from PIL import Image >>> im = Image.open('a_image.tif') >>> im.show() ``` This showed the rainbow image. To convert to a numpy array, it's as sim...
Efficient Way to Create Numpy Arrays from Binary Files
7,569,563
13
2011-09-27T13:01:58Z
7,576,420
13
2011-09-27T22:28:32Z
[ "python", "numpy" ]
I have very large datasets that are stored in binary files on the hard disk. Here is an example of the file structure: *File Header* ``` 149 Byte ASCII Header ``` *Record Start* ``` 4 Byte Int - Record Timestamp ``` *Sample Start* ``` 2 Byte Int - Data Stream 1 Sample 2 Byte Int - Data Stream 2 Sample 2 Byte Int ...
Some hints: * Don't use the struct module. Instead, use Numpy's structured data types and `fromfile`. Check here: <http://scipy-lectures.github.com/advanced/advanced_numpy/index.html#example-reading-wav-files> * You can read all of the records at once, by passing in a suitable count= to `fromfile`. Something like thi...
Python List Parsing
7,569,748
2
2011-09-27T13:15:06Z
7,569,793
7
2011-09-27T13:18:24Z
[ "python" ]
Probably a simple question, but I am new to Python. I have a file containing email addresses, one per line. I want to read the file and append them together separated by a comma. Is there a more pythonic way of doing this? ``` def getEmailList(file_name): f = open(file_name, 'r') emailstr = '' for line in ...
You could do the following: ``` def getEmailList(file_name): with open(file_name) as f: return ",".join(x.rstrip() for x in f) ``` The key features of that version are: * Using the [`with` statement](http://diveintopython3.org/files.html#with) so that the file is automatically closed when control leaves ...
Subtract SQL DATETIME from datetime.now() in Python
7,570,015
3
2011-09-27T13:32:03Z
7,570,081
11
2011-09-27T13:36:58Z
[ "python", "datetime", "time", "strptime" ]
I have a DATETIME field in SQL. Its content is: 2012-08-26 13:00:00 I want to know how much time has passed from that date until now. In Python 2.7, it's easy: ``` import time,datetime start = datetime.datetime.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.datetime.now() delta = start - end pr...
[time.strptime](http://docs.python.org/release/2.4.4/lib/module-time.html) is in Python 2.4. It returns a time tuple, which can be then converted to a datetime as shown below. ``` start = time.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') start = datetime.datetime(*start[:6]) ```
Pyramid and .ini configuration
7,570,930
12
2011-09-27T14:35:53Z
7,583,431
25
2011-09-28T12:47:26Z
[ "python", "configuration-files", "pyramid", "ini" ]
Each Pyramid application has an associated .ini file that contains its settings. For example, a default might look like: ``` [app:main] use = egg:MyProject pyramid.reload_templates = true pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false ... ``` I am wondering if it i...
Sure you can. In your entry point function (`main(global_config, **settings)` in `__init__.py` in most cases), your config is accessible in the `settings` variable. For example, in your `.ini`: ``` [app:main] blog.title = "Custom blog name" blog.comments_enabled = true ``` In your `__init__.py`: ``` def main(globa...
Django Template Arithmetic
7,571,534
2
2011-09-27T15:16:18Z
7,571,677
7
2011-09-27T15:25:54Z
[ "python", "django", "django-templates" ]
In my template, I am looping through a list, trying to make a two-column layout. Because of the desired two-column layout, the markup I need to write in the for loop is dependent on whether `forloop.counter0` is even or odd. If I had the full power of Python in the template language, determining the parity of `forloop....
You should probably use [`cycle`](https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#cycle) here instead. As for your question, there is a filter called [`divisibleby`](https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#divisibleby). The philosophy behind Django's template system is to avoid doin...
Fastest way to check if a value exist in a list
7,571,635
232
2011-09-27T15:23:26Z
7,571,665
466
2011-09-27T15:25:11Z
[ "python", "performance", "list" ]
I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. **My first methods I try is(3.8sec in my real code):** ``` a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do somet...
``` 7 in a ``` Clearest and fastest way to do it. You can also consider using a `set`, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)
Fastest way to check if a value exist in a list
7,571,635
232
2011-09-27T15:23:26Z
7,571,666
11
2011-09-27T15:25:12Z
[ "python", "performance", "list" ]
I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. **My first methods I try is(3.8sec in my real code):** ``` a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do somet...
You could put your items into a [`set`](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset). Set lookups are very efficient. Try: ``` s = set(a) if 7 in s: # do stuff ``` **edit** In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element p...
Fastest way to check if a value exist in a list
7,571,635
232
2011-09-27T15:23:26Z
7,571,776
23
2011-09-27T15:33:49Z
[ "python", "performance", "list" ]
I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. **My first methods I try is(3.8sec in my real code):** ``` a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do somet...
``` a = [1,2,3,4,'a','b','c'] return 'a' in a ``` with this you can find whatever value you want in an array. This is the fastest way to know if a chosen value is in an array.
Fastest way to check if a value exist in a list
7,571,635
232
2011-09-27T15:23:26Z
7,572,489
12
2011-09-27T16:26:35Z
[ "python", "performance", "list" ]
I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. **My first methods I try is(3.8sec in my real code):** ``` a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do somet...
``` a = [4,2,3,1,5,6] index = dict((y,x) for x,y in enumerate(a)) try: a_index = index[7] except KeyError: print "Not found" else: print "found" ``` This will only be a good idea if a doesn't change and thus we can do the dict() part once and then use it repeatedly. If a does change, please provide more deta...
Python - how to find all intersections of two strings?
7,571,904
5
2011-09-27T15:43:24Z
7,571,964
7
2011-09-27T15:47:05Z
[ "python", "string", "algorithm" ]
How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings? For example, if `S1="never"` and `S2="forever"` then resulted intersection must be `["ever"]` and its positions are `[(1,3)]`. If `S1="address"` and `S2="oddness"` then resulted intersections a...
This can be done in O(n+m) where `n` and `m` are lengths of input strings. The pseudocode is: ``` function LCSubstr(S[1..m], T[1..n]) L := array(1..m, 1..n) z := 0 ret := {} for i := 1..m for j := 1..n if S[i] = T[j] if i = 1 or j = 1 L[i,j] := 1...
Python - how to find all intersections of two strings?
7,571,904
5
2011-09-27T15:43:24Z
7,579,122
12
2011-09-28T06:24:32Z
[ "python", "string", "algorithm" ]
How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings? For example, if `S1="never"` and `S2="forever"` then resulted intersection must be `["ever"]` and its positions are `[(1,3)]`. If `S1="address"` and `S2="oddness"` then resulted intersections a...
Well, you're saying that you can't include any library. However, Python's standard [difflib](http://docs.python.org/library/difflib.html) contains a function which does exactly what you expect. Considering that it is a Python interview question, familiarity with difflib might be what the interviewer expected. ``` In [...
Does Python have C#/Java-style interfaces?
7,572,410
5
2011-09-27T16:21:00Z
7,572,458
13
2011-09-27T16:24:45Z
[ "python", "oop" ]
I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created. I'm about to start on a relatively large project, probably in python (I've written a lot of python before, but mostly my own code for data ...
> If the answer's no, that's fine, but in that case what do people generally do instead? [Duck Typing](http://c2.com/cgi/wiki?DuckTyping). What's important is to approach Python by dropping the technical baggage of C#. Learn Python as a **new** language. Don't try to map concepts between Python and C#. That way lies...
Behaviour of generator in lambda safe against future changes?
7,572,626
3
2011-09-27T16:37:22Z
7,572,684
7
2011-09-27T16:42:34Z
[ "python", "lambda", "generator", "yield", "readline" ]
I have the following function: ``` | def line_reader_iter(file_object): | while True: | a_line = file_object.readline() | if len(a_line)==0: raise StopIteration | yield a_line[:-1] ``` and somewhere I say: ``` | line_reader = lambda: next(line_reader_iter(infile)) ``` Clear...
I think you are actually misunderstanding why this works. Each time you call `line_reader()` a new `line_reader_iter` generator ***is*** created. It appears to work because you use the same `infile` each time, and each call to `readline()` will return the next line of the file. Consider the following simpler example: ...
Change python source while running
7,573,599
11
2011-09-27T17:58:26Z
7,575,998
8
2011-09-27T21:39:04Z
[ "python" ]
Is it possible to change python source file while running an application and have this changes reflected immediately in the application? Let say I have a foo.py file with a class Foo. In other module I'm calling functions on the Foo on user action. Now, I would like to change source of the Foo without restarting the a...
The following module can probably change whatever you need, not that it's a good idea to use, other than to muck around : ) Note that it will not change your source, which would probably be a disaster, especially if you make a coding error. The 'safer' option would be to play with byteplay <http://wiki.python.org/moi...
Convert Unicode Object to Python Dict
7,573,822
6
2011-09-27T18:18:22Z
7,573,869
15
2011-09-27T18:21:43Z
[ "python", "serialization", "json" ]
A request object that I'm dealing with has the following value for the key "address": ``` u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}" ``` I need to operate on this unicode object as a dictionary. Unfortunately, json.loads() fails because it is not a json compatible object. Is th...
``` >>> ast.literal_eval(u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}") {u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'} ```
Python Scapy wrpcap - How do you append packets to a pcap file?
7,574,092
4
2011-09-27T18:40:11Z
20,780,224
7
2013-12-26T06:31:36Z
[ "python", "networking", "network-programming", "scapy", "raw-ethernet" ]
I have some software that can emulate things like BER and delays on the network. I need a way to test the BER module of the software to make sure it actually works correctly. My solution is to create a program that sends out raw Ethernet frames with the type field set to an unused type. Inside the Ethernet frame is jus...
For posterity, PcapWriter or RawPcapWriter looks to be the easier way to deal with this in scapy 2.2.0. Couldn't find much documentation other than browsing the source though. A brief example: ``` from scapy.utils import PcapWriter pktdump = PcapWriter("banana.pcap", append=True, sync=True) ... pktdump.write(pkt) .....
Shebang Notation: Python Scripts on Windows and Linux?
7,574,453
31
2011-09-27T19:11:47Z
7,574,585
27
2011-09-27T19:23:40Z
[ "python", "windows", "linux", "shebang" ]
I have some small utility scripts written in Python that I want to be usable on both Windows and Linux. I want to avoid having to explicitly invoke the Python interpreter. Is there an easy way to point shebang notation to the correct locations on both Windows and Linux? If not, is there another way to allow implicit in...
Unless you are using cygwin, windows has no shebang support. However, when you install python, it add as file association for .py files. If you put just the name of your script on the command line, or double click it in windows explorer, then it will run through python. What I do is include a `#!/usr/bin/env python` s...
Shebang Notation: Python Scripts on Windows and Linux?
7,574,453
31
2011-09-27T19:11:47Z
12,716,560
16
2012-10-03T20:41:24Z
[ "python", "windows", "linux", "shebang" ]
I have some small utility scripts written in Python that I want to be usable on both Windows and Linux. I want to avoid having to explicitly invoke the Python interpreter. Is there an easy way to point shebang notation to the correct locations on both Windows and Linux? If not, is there another way to allow implicit in...
Read about the [Python Launcher for Windows](https://docs.python.org/3/using/windows.html#python-launcher-for-windows) in the docs, which was initially described in [PEP 397](https://www.python.org/dev/peps/pep-0397). It lets you define custom shebang configurations in an ini (e.g. to use pypy), but out of the box you ...
Django -- Can't get static CSS files to load
7,574,759
25
2011-09-27T19:40:02Z
7,574,901
36
2011-09-27T19:53:38Z
[ "python", "django", "static-files" ]
I'm running Django's development server (`runserver`) on my local machine (Mac OS X) and cannot get the CSS files to load. Here are the relevant entries in settings.py: ``` STATIC_ROOT = '/Users/username/Projects/mysite/static/' STATIC_URL = '/static/' STATICFILES_DIRS = ( '/Users/thaymore/Projects/mysite/cal/stati...
Read this carefully: <https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/> Is 'django.contrib.staticfiles' in your INSTALLED\_APPS? Is DEBUG=False? If so, you need to call runserver with the --insecure parameter. 'collectstatic' has no bearing on serving files via the development server. It is for collect...
open a terminal from python
7,574,841
12
2011-09-27T19:48:29Z
7,574,907
10
2011-09-27T19:54:11Z
[ "python", "terminal" ]
I'm developing a program that has a button. When pressed, I want to open a terminal that runs: ``` sudo apt-get update ``` I'm using: ``` os.system("gnome-terminal -e 'sudo apt-get update'") ``` This works fine. The only problem is that when the update is finished, the terminal closes. What can I do to leave the te...
You could do this: ``` os.system("gnome-terminal -e 'bash -c \"sudo apt-get update; exec bash\"'") ```
check output from CalledProcessError
7,575,284
25
2011-09-27T20:32:44Z
7,575,366
8
2011-09-27T20:39:26Z
[ "python", "subprocess" ]
I am using subprocess.check\_output from pythons subprocess module to execute a ping command. Here is how I am doing it: ``` output = subprocess.check_output(["ping","-c 2 -W 2","1.1.1.1") ``` It is raising a CalledProcessError and says the output is one of the arguments of the function. Can anyone help me how to rea...
In the list of arguments, each entry must be on its own. Using ``` output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"]) ``` should fix your problem.
check output from CalledProcessError
7,575,284
25
2011-09-27T20:32:44Z
8,235,171
98
2011-11-22T23:05:48Z
[ "python", "subprocess" ]
I am using subprocess.check\_output from pythons subprocess module to execute a ping command. Here is how I am doing it: ``` output = subprocess.check_output(["ping","-c 2 -W 2","1.1.1.1") ``` It is raising a CalledProcessError and says the output is one of the arguments of the function. Can anyone help me how to rea...
According to the [Python os module documentation](http://docs.python.org/library/os.html#os.popen) os.popen has been deprecated since Python 2.6. I think the solution for modern Python is to use check\_output() from the subprocess module. From the [subprocess Python documentation](http://docs.python.org/library/subpr...
Optional stdin in Python with argparse
7,576,525
31
2011-09-27T22:47:28Z
7,576,567
13
2011-09-27T22:52:40Z
[ "python", "stdin", "argparse" ]
I found the very useful syntax ``` parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default='-') ``` for specifying an input file or using stdin—both of which I want in my program. However, the input file is not always required. If I'm not using `-i` or redirecting input with one of ``` $ som...
Use [isatty](http://docs.python.org/library/os.html#os.isatty) to [detect](http://stackoverflow.com/questions/1077113/how-do-i-detect-whether-sys-stdout-is-attached-to-terminal-or-not) whether your program is in an interactive session or reading from a file: ``` if not sys.stdin.isatty(): # Not an interactive device. ...
Optional stdin in Python with argparse
7,576,525
31
2011-09-27T22:47:28Z
11,038,508
51
2012-06-14T17:43:37Z
[ "python", "stdin", "argparse" ]
I found the very useful syntax ``` parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), default='-') ``` for specifying an input file or using stdin—both of which I want in my program. However, the input file is not always required. If I'm not using `-i` or redirecting input with one of ``` $ som...
The standard library [documentation for argparse](http://docs.python.org/dev/library/argparse.html#nargs) suggests this solution to allow optional input/output files: ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), ... default=sys...
boost-python select between overloaded methods
7,577,410
10
2011-09-28T01:32:06Z
7,577,462
12
2011-09-28T01:41:52Z
[ "c++", "python", "boost" ]
Assume exist some class Foo with two overloaded methods: ``` class Foo { ... void m1(A& a); void m1(B& b); ``` I need expose one of these methods over boost-python: ``` boost::python::class_<Foo>("Foo") .def("m1", &Foo::m1) ``` How should I specify that signature of `m1(A&a)` should be used over `m1(B&b...
``` void (Foo::*m1)(A&) = &Foo::m1; boost::python::class_<Foo>("Foo") .def("m1", m1) ```
Using pandas, how do I subsample a large DataFrame by group in an efficient manner?
7,577,546
9
2011-09-28T01:58:38Z
7,580,456
8
2011-09-28T08:35:50Z
[ "python", "numpy", "pandas", "data.table" ]
I am trying to subsample rows of a DataFrame according to a grouping. Here is an example. Say I define the following data: ``` from pandas import * df = DataFrame({'group1' : ["a","b","a","a","b","c","c","c","c", "c","a","a","a","b","b","b","b"], 'group2' : [1,2,3,4,1,3,5,6,...
I tested with apply, it seems that when there are many sub groups, it's very slow. the groups attribute of grouped is a dict, you can choice index directly from it: ``` subsampled = df.ix[(choice(x) for x in grouped.groups.itervalues())] ``` EDIT: As of pandas version 0.18.1, `itervalues` no longer works on groupby o...
Playing audio file with Python
7,578,238
6
2011-09-28T04:15:39Z
7,578,264
11
2011-09-28T04:20:40Z
[ "python", "audio", "mp3" ]
I've seen most of the questions on this topic but almost all of them are outdated. (This is not a dupe) **My requirement is a preferably light weight library for simply playing audio files such as mp3,etc from Python (2.7)** These are the libraries that I've so far looked into and I'm listing what are the things that...
I'm not sure what your issue is with [`pyglet`](http://www.pyglet.org/). Playing an mp3 using that couldn't be simpler: ``` import pyglet sound = pyglet.media.load('mysound.mp3', streaming=False) sound.play() pyglet.app.run() ``` pyglet is well-maintained, cross-platform, and very small for a multimedia library.
Median code explanation
7,578,689
5
2011-09-28T05:23:57Z
7,578,886
11
2011-09-28T05:51:47Z
[ "python", "median" ]
My professor wrote this median function and I don't understand it very well. Can someone please explain the part about `i = len(list)/2` and `median = avg()` and the `else` statement? ``` def avg_list(numbers): sum = 0 for num in numbers: sum += num avg = float(sum)/len(numbers) print avg ...
Why this is is very wrong, line by line: ``` def median(list): # 1 list.sort() # 2 if len(list)%2 == 0: #have to take avg of middle two i = len(list)/2 # 3 median = avg() # 4 else: #find the middle (remembering that...
Inconsistency of Python plus operator
7,579,719
2
2011-09-28T07:29:19Z
7,579,829
8
2011-09-28T07:40:30Z
[ "python", "operators" ]
``` In [26]: l=[] In [27]: s="asdsad" In [28]: l+=s In [29]: l Out[29]: ['a', 's', 'd', 's', 'a', 'd'] ``` However, ``` In [30]: l+s --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/xiaohan/code/proteincra...
This is explained [here](http://old.nabble.com/Add-vs-in-place-add-of-str-to-list-td19774277.html). Copied from the link: > It's because the `+=` operator is doing the equivalent of calling the `extend` method, which treats its argument as a generic sequence, and doesn't enforce type.
Filtering list of tuples based on the availability of a member in a list
7,580,052
3
2011-09-28T08:02:42Z
7,580,091
8
2011-09-28T08:05:51Z
[ "python", "list", "tuples", "list-comprehension" ]
I want to filter a list of tuples like `[(1,22,1),(5,1,8),(8,3,4),(7,5,6)]` using a list like `[1,7]` which would eventually give me the result `[(1,22,1),(5,1,8),(7,5,6)]`; since `(8,3,4)` does not have either `1` or `7`, it is eliminated. I can write a comprehensive function for this. But I am looking for a short li...
``` >>> tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)] >>> filter_list = [1,7] >>> [tup for tup in tup_list if any(i in tup for i in filter_list)] [(1, 22, 1), (5, 1, 8), (7, 5, 6)] ```
How to check whether a method exists in Python?
7,580,532
31
2011-09-28T08:44:37Z
7,580,608
50
2011-09-28T08:50:23Z
[ "python", "methods" ]
In the function `__getattr__()`, if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object? ``` import string import logging class Dynamo: def __init__(self,x): print "In Init def" self.x=x def __repr__(self): print self.x def __str...
How about `dir()` function before `getattr()`? ``` >>> "mymethod" in dir(dyn) True ```
How to check whether a method exists in Python?
7,580,532
31
2011-09-28T08:44:37Z
7,580,687
34
2011-09-28T08:57:01Z
[ "python", "methods" ]
In the function `__getattr__()`, if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object? ``` import string import logging class Dynamo: def __init__(self,x): print "In Init def" self.x=x def __repr__(self): print self.x def __str...
Check if class has such method? ``` hasattr(Dynamo, key) and callable(getattr(Dynamo, key)) ``` or ``` hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod')) ``` You can use `self.__class__` instead of `Dynamo`
How to check whether a method exists in Python?
7,580,532
31
2011-09-28T08:44:37Z
7,581,689
73
2011-09-28T10:18:52Z
[ "python", "methods" ]
In the function `__getattr__()`, if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object? ``` import string import logging class Dynamo: def __init__(self,x): print "In Init def" self.x=x def __repr__(self): print self.x def __str...
It's easier to ask forgiveness than to ask permission. Don't check to see if a method exists. Don't waste a single line of code on "checking" ``` try: dyn.mymethod() //How to check whether this exist or not # Method exists, and was used. except AttributeError: # Method does not exist. What now? ```
How to use variables in Python regular expression
7,580,790
7
2011-09-28T09:04:53Z
7,580,833
9
2011-09-28T09:07:30Z
[ "python", "regex" ]
i am in need to use a variable in python regular expression ``` for line in re.findall('(.+)33084-2(.+)', Data): ``` i am using above code to match a line with 33084-2, some times this values changes so i need to use a variable like ``` for line in re.findall('(.+)Var_Name(.+)', Data): ``` please help me how to use...
If you know that the variable cannot contain any characters with special meaning in a regular expression just use string concatenation or any of the other ways to create a string. ``` for line in re.findall('(.+)'+Var_Name+'(.+)', Data): ``` If there is a chance the variable could contain special characters then esca...
Script to change ip address on windows
7,580,834
5
2011-09-28T09:07:46Z
7,581,831
11
2011-09-28T10:31:10Z
[ "python", "windows", "windows-7", "batch-file", "ipv4" ]
I use my computer to communicate with a piece of hardware via ethernet. To communicate with this device I set my ip to 192 168 0 11, subnet mask to 255 255 255 0, and default gateway to 192 168 0 1 for IPv4. To use the internet, I choose "Obtain an IP address automatically" via control panel. I'd like to have a script...
You can use the Python [WMI module](http://timgolden.me.uk/python/wmi/index.html) to do this (install the [PyWin32 extensions](http://starship.python.net/crew/mhammond/win32/Downloads.html) and the WMI module before running these scripts). Here is how to configure things to talk to the hardware device: ``` import wmi ...
Why are there no Makefiles for automation in Python projects?
7,580,939
20
2011-09-28T09:16:45Z
7,582,896
9
2011-09-28T12:00:16Z
[ "python", "automation", "makefile", "rake" ]
As a long time Python programmer, I wonder, if a central aspect of Python culture eluded me a long time: What do we do instead of Makefiles? Most ruby-projects I've seen (not just rails) use *Rake*, shortly after *node.js* became popular, there was *cake*. In many other (not only compliled languages) there are classic...
[`Setuptools`](https://pythonhosted.org/setuptools/) can automate a lot of things, and for things that aren't built-in, it's easily extensible. * To run unittests, you can use the `setup.py test` command after having added a `test_suite` argument to the `setup()` call. ([documentation](https://pythonhosted.org/setupto...
Python subprocess.Popen and asynchronous output
7,581,951
6
2011-09-28T10:41:03Z
7,582,065
13
2011-09-28T10:50:23Z
[ "python", "asynchronous", "subprocess" ]
I have simple Python script to execute test suite both under Windows and Linux. Every test writes its output to separate file. I use **subprocess.Popen** class to execute shell command in a cycle. Every shell command starts like that: ``` def system_execute(self, command, path, out_file): params_list = command.sp...
Before `f.close()`, you have to `wait()` for our subprocess. ``` def system_execute(self, command, path, out_file): params_list = command.split(' ') file_path = os.path.join(path, out_file) f = open(file_path, "w") sp = subprocess.Popen(params_list, stdout=f) sp.wait() f.close() ``` or just ...
Python: get datetime of last hour
7,582,333
15
2011-09-28T11:12:57Z
7,582,363
13
2011-09-28T11:15:09Z
[ "python", "datetime", "hour" ]
I want to get the date time object for last hour. Lets say the sys time is "2011-9-28 06:11:30" I want to get the output as "2011-9-28 05" #{06 - 1 hour} I used: ``` lastHourDateTime = date.today() - timedelta(hours = 1) print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S') ``` However, my output is not showi...
This works for me: ``` import datetime lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1) print lastHourDateTime.strftime('%Y-%m-%d %H') # prints "2011-09-28 12" which is the time one hour ago in Central Europe ```
Python: get datetime of last hour
7,582,333
15
2011-09-28T11:12:57Z
7,582,367
34
2011-09-28T11:15:27Z
[ "python", "datetime", "hour" ]
I want to get the date time object for last hour. Lets say the sys time is "2011-9-28 06:11:30" I want to get the output as "2011-9-28 05" #{06 - 1 hour} I used: ``` lastHourDateTime = date.today() - timedelta(hours = 1) print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S') ``` However, my output is not showi...
Date doesn't have the hour - use datetime: ``` from datetime import datetime, timedelta lastHourDateTime = datetime.today() - timedelta(hours = 1) print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S') ```
What does bare strings in the body of a class definition mean?
7,582,961
2
2011-09-28T12:07:06Z
7,582,995
8
2011-09-28T12:09:38Z
[ "python" ]
Here is a snippet of code from `django.core.exceptions`: ``` class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass ``` Is the bare string in the body of the class a mere literal for documentation ? Or does it perform some magic ?
It's a [doc string](http://www.python.org/dev/peps/pep-0257/): > A docstring is a string literal that occurs as the first statement > in a module, function, class, or method definition. Such a docstring > becomes the `__doc__` special attribute of that object. > > All modules should normally have docstrings, and all f...
Python Module with a dash, or hyphen (-) in its name
7,583,652
26
2011-09-28T13:01:33Z
7,583,738
43
2011-09-28T13:08:00Z
[ "python", "module", "import" ]
I have an existing python module with a dash in its name, foo-bar.py Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work. Is there a way to load a module whose name contains the typically forb...
You can do that using [`__import__()`](http://docs.python.org/library/functions.html#__import__). For example: ``` foobar = __import__("foo-bar") ``` But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.
Python Module with a dash, or hyphen (-) in its name
7,583,652
26
2011-09-28T13:01:33Z
24,659,400
15
2014-07-09T16:45:16Z
[ "python", "module", "import" ]
I have an existing python module with a dash in its name, foo-bar.py Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work. Is there a way to load a module whose name contains the typically forb...
I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using `__import__()`. ``` import importlib mod = importlib.import_module("path.to.my-module") # mod.yourmethod() ``` According to the docs: ``` "This provides an implementatio...
Iterate the classes defined in a module imported dynamically
7,584,418
5
2011-09-28T13:57:38Z
7,584,517
8
2011-09-28T14:03:52Z
[ "python", "introspection" ]
I have a module from a child package that is imported dynamically; how can I iterate over the classes that it contains? I have been importing the module and listing the names like this: ``` package = current_module.__name__ package = package[:package.rindex(".")] # get the package package = "%s.sub.%s"%(package,name)...
Example: to create a dict that maps the names to the classes: ``` dict([(name, cls) for name, cls in mod.__dict__.items() if isinstance(cls, type)]) ``` where mod is the loaded module
"TypeError: Unicode-objects must be encoded before hashing"
7,585,307
57
2011-09-28T15:04:48Z
7,585,378
68
2011-09-28T15:10:20Z
[ "python", "unicode", "syntax", "syntax-error", "hashlib" ]
I have this error ``` Traceback (most recent call last): File "python_md5_cracker.py", line 27, in <module> m.update(line) TypeError: Unicode-objects must be encoded before hashing ``` when I try to execute this code in **Python 3.2.2**: ``` import hashlib, sys m = hashlib.md5() hash = "" hash_file = input("What...
It is probably looking for a character encoding from `wordlistfile`. ``` wordlistfile = open(wordlist,"r",encoding='utf-8') ``` Or, if you're working on a line-by-line basis: ``` line.encode('utf-8') ```
"TypeError: Unicode-objects must be encoded before hashing"
7,585,307
57
2011-09-28T15:04:48Z
22,505,259
7
2014-03-19T12:03:59Z
[ "python", "unicode", "syntax", "syntax-error", "hashlib" ]
I have this error ``` Traceback (most recent call last): File "python_md5_cracker.py", line 27, in <module> m.update(line) TypeError: Unicode-objects must be encoded before hashing ``` when I try to execute this code in **Python 3.2.2**: ``` import hashlib, sys m = hashlib.md5() hash = "" hash_file = input("What...
You must have to define `encoding format` like `utf-8`, Try this easy way, In this example generate randow number that are use SHA256 algorithm, ``` >>> import hashlib >>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() 'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f' ```
Best way to convert string to bytes in Python 3?
7,585,435
170
2011-09-28T15:14:07Z
7,585,619
172
2011-09-28T15:27:58Z
[ "python", "string", "character-encoding", "python-3.x" ]
There appears to be two different ways to convert a string to bytes, as seen in the answers to [TypeError: 'str' does not support the buffer interface](http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface) Which of these methods would be better or more Pythonic? Or is it just ...
If you look at the docs for `bytes`, it points you to [`bytearray`](http://docs.python.org/3/library/functions.html#bytearray): > bytearray([source[, encoding[, errors]]]) > > Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods o...
Best way to convert string to bytes in Python 3?
7,585,435
170
2011-09-28T15:14:07Z
17,500,651
37
2013-07-06T07:09:28Z
[ "python", "string", "character-encoding", "python-3.x" ]
There appears to be two different ways to convert a string to bytes, as seen in the answers to [TypeError: 'str' does not support the buffer interface](http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface) Which of these methods would be better or more Pythonic? Or is it just ...
Its easier then it is thought: ``` my_str = "hello world" bytes = str.encode(my_str) type(bytes) # ensure it is byte representation my_decoded_str = str.decode(bytes) type(my_decoded_str) # ensure it is string representation ```
In Python, how can I draw to a pixel on the screen directly?
7,585,447
7
2011-09-28T15:15:27Z
7,585,663
11
2011-09-28T15:32:16Z
[ "python", "pixel" ]
I'm wanting to do something like the following: ``` ... pixel[0,0] = [ 254, 0, 0 ] # Draw R at pixel x0y0 pixel[2,1] = [ 0, 254, 0 ] # Draw G at pixel x2y1 pixel[4,2] = [ 0, 0, 254 ] # Draw B at pixel x4y2 ... ``` I hope to display many different configurations of pixels and colours in a short space of time -- writin...
Direct answer: This can only be done with OS-specific APIs. Some OSes does not allow changing pixels on the screen directly. On Windows, you can use pywin32 libraries to get screen's device context with `dc = GetDC(0)` call, then paint pixels with `SetPixel(dc, x, y, color)`. Of course, what you paint this way can be...
python oauth 2.0 new fbsr facebook cookie, error validating verification code
7,585,488
4
2011-09-28T15:19:08Z
7,597,784
10
2011-09-29T13:08:13Z
[ "python", "google-app-engine", "facebook-oauth" ]
I'm trying to use the new fbsr\_{{appID}} cookie. I'm using the following functions to parse it, but when I try to get the access\_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem? more info: I managed to log users...
There is a modified version of the facebook python SDK which supports OAuth 2.0 and parsing of the fbsr\_ cookie on github here: <https://gist.github.com/1190267> You can look into the code to see how to parse the cookie or just let that file do the work for you.
How to calculate the angle between a line and the horizontal axis?
7,586,063
212
2011-09-28T15:58:40Z
7,586,218
355
2011-09-28T16:10:22Z
[ "c#", "python", "trigonometry" ]
In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis? I think an image describes best what I want: ![no words can describe this](http://i.stack.imgur.com/HUKbR.png) Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate this angle?...
First find the difference between the start point and the end point. ``` deltaY = P2_y - P1_y deltaX = P2_x - P1_x ``` Then calculate the angle. ``` angleInDegrees = arctan(deltaY / deltaX) * 180 / PI ``` If your language includes an `atan2` function it becomes the following instead: ``` angleInDegrees = atan2(del...
How to calculate the angle between a line and the horizontal axis?
7,586,063
212
2011-09-28T15:58:40Z
12,231,601
43
2012-09-01T21:35:37Z
[ "c#", "python", "trigonometry" ]
In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis? I think an image describes best what I want: ![no words can describe this](http://i.stack.imgur.com/HUKbR.png) Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate this angle?...
Sorry, but I'm pretty sure Peter's answer is wrong. Note that the y axis goes down the page (common in graphics). As such the deltaY calculation has to be reversed, or you get the wrong answer. Consider: ``` System.out.println (Math.toDegrees(Math.atan2(1,1))); System.out.println (Math.toDegrees(Math.atan2(-1,1))); S...
Program not entering if statement
7,586,221
4
2011-09-28T16:10:33Z
7,586,247
9
2011-09-28T16:12:41Z
[ "python", "floating-point" ]
In my python program, an if statement is not being entered. I have simplified the code to the following: ``` x = -5 while x < 5: if (x == 0): print 0 x += .01 ``` This program does not output anything. However, changing the last line to x += .5 makes the program output 0. What's the problem?
Floating point number representation might not be accurate enough. You should never test for zero equality but instead use something along ``` if (abs(x) < 1E-10) ... ```
Program not entering if statement
7,586,221
4
2011-09-28T16:10:33Z
7,586,369
7
2011-09-28T16:22:54Z
[ "python", "floating-point" ]
In my python program, an if statement is not being entered. I have simplified the code to the following: ``` x = -5 while x < 5: if (x == 0): print 0 x += .01 ``` This program does not output anything. However, changing the last line to x += .5 makes the program output 0. What's the problem?
Behold the power of the print statement... Let us insert a print statement... ``` x = -5 while x < 5: if (x == 0): print 0 x += .01 print x ``` Running this program, and inspecting the output around 0 reveals the problem: ``` ... -0.13 -0.12 -0.11 -0.1 -0.0900000000001 -0.0800000000001 -0.070000...
Color states with Python's matplotlib/basemap
7,586,384
9
2011-09-28T16:23:41Z
29,397,692
7
2015-04-01T18:03:13Z
[ "python", "matplotlib", "gis" ]
I want to generate a map of the United States and color each state in using a different shade. Is there a way to do this using Python's basemap?
There is a nicely formated example in the Basemap repo on GitHub: [fillstates.py](https://github.com/matplotlib/basemap/blob/master/examples/fillstates.py). The shapefile ([dbf](https://github.com/matplotlib/basemap/raw/master/examples/st99_d00.dbf) | [shp](https://github.com/matplotlib/basemap/raw/master/examples/st99...
Python | accessing dll using ctypes
7,586,504
11
2011-09-28T16:34:37Z
7,586,821
11
2011-09-28T16:57:57Z
[ "python", "windows", "firefox", "dll", "ctypes" ]
I'm trying to access some functions in a dll (**nss3.dll**) that ships with Firefox web browser. To handle this task I have used ctypes in Python. The problem is that it fails at the initial point which is when loading the dll in to the memory. This is the code snippet that I have to do so. ``` >>> from ctypes import...
nss3.dll is linked to the following DLLs, which are all located in the Firefox directory: nssutil3.dll, plc4.dll, plds4.dll, nspr4.dll, and mozcrt19.dll. The system library loader looks for these files in the DLL search path of the process, which includes the application directory, system directories, the current direc...
ImportError: No module named - Python
7,587,457
31
2011-09-28T17:59:58Z
7,587,545
43
2011-09-28T18:08:57Z
[ "python", "import" ]
I have a python application with the following directory structure: ``` src | +---- main | +---- util | +---- gen_py | +---- lib ``` In the package **main**, I have a python module named **MyServer.py** which has an import statement like: ``` from gen_py.lib import MyService ``` In order for...
Your modification of `sys.path` assumes the current working directory is always in `main/`. This is not the case. Instead, just add the parent directory to `sys.path`: ``` import sys import os.path sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import gen_py.lib ``` Don't forget to include a file `__...
Converting Numpy Array to OpenCV Array
7,587,490
15
2011-09-28T18:03:45Z
7,587,819
14
2011-09-28T18:32:35Z
[ "python", "image-processing", "opencv" ]
I'm trying to convert a 2D Numpy array, representing a black-and-white image, into a 3-channel OpenCV array (i.e. an RGB image). Based on [code samples](https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/python2/find_obj.py) and [the docs](http://opencv.willowgarage.com/documentation/cpp/miscellaneous_image...
Your code can be fixed as follows: ``` import numpy as np, cv vis = np.zeros((384, 836), np.float32) h,w = vis.shape vis2 = cv.CreateMat(h, w, cv.CV_32FC3) vis0 = cv.fromarray(vis) cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR) ``` Short explanation: 1. `np.uint32` data type is not supported by OpenCV (it supports `uint8`,...
SciPy LeastSq Goodness of Fit Estimator
7,588,371
12
2011-09-28T19:16:07Z
7,589,017
21
2011-09-28T20:12:06Z
[ "python", "scipy", "data-fitting" ]
I have a data surface that I'm fitting using SciPy's `leastsq` function. I would like to have some estimate of the quality of the fit after `leastsq` returns. I'd expected that this would be included as a return from the function, but, if so, it doesn't seem to be clearly documented. Is there such a return or, barrin...
If you call `leastsq` like this: ``` import scipy.optimize p,cov,infodict,mesg,ier = optimize.leastsq( residuals,a_guess,args=(x,y),full_output=True) ``` where ``` def residuals(a,x,y): return y-f(x,a) ``` then, using the definition of `R^2` given [here](http://en.wikipedia.org/wiki/Goodness_of_fit), `...
How to skip pre header lines with csv.DictReader?
7,588,426
9
2011-09-28T19:20:58Z
7,588,497
10
2011-09-28T19:27:50Z
[ "python", "csv" ]
I want to `csv.DictReader` to deduce the field names from the file. [The docs](http://docs.python.org/library/csv.html#csv.DictReader) say *"If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames."*, but in my case the first row containts a title and the 2nd ro...
After `f.seek(0)`, insert: ``` next(f) ``` to advance the file pointer to the second line before initializing the `DictReader`.
Format a datetime into a string with milliseconds
7,588,511
34
2011-09-28T19:28:56Z
7,588,609
14
2011-09-28T19:35:58Z
[ "python", "datetime", "string-formatting" ]
I want to have a `datetime` string from the date with milliseconds. This code is typical for me and I'm eager to learn how to shorten it. ``` from datetime import datetime timeformatted= str(datetime.utcnow()) semiformatted= timeformatted.replace("-","") almostformatted= semiformatted.replace(":","") formatted=almost...
``` print datetime.utcnow().strftime('%Y%m%d%H%M%S%f') ``` <http://docs.python.org/library/datetime.html#strftime-strptime-behavior>
Format a datetime into a string with milliseconds
7,588,511
34
2011-09-28T19:28:56Z
18,406,412
75
2013-08-23T15:20:33Z
[ "python", "datetime", "string-formatting" ]
I want to have a `datetime` string from the date with milliseconds. This code is typical for me and I'm eager to learn how to shorten it. ``` from datetime import datetime timeformatted= str(datetime.utcnow()) semiformatted= timeformatted.replace("-","") almostformatted= semiformatted.replace(":","") formatted=almost...
The OP asked for a string with milliseconds (3 decimal places behind seconds). To get milliseconds, use this instead: ``` from datetime import datetime print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] >>>> OUTPUT >>>> 2013-08-23 10:18:32.926 ```
Convert letters to lower case
7,588,574
2
2011-09-28T19:33:36Z
7,588,961
7
2011-09-28T20:06:15Z
[ "python", "regex" ]
I use the following with respect to letters from any language: ``` text = regex.sub("[^\p{alpha}\d]+"," ",text ``` Can I use `p{alpha}` to convert letters to their lower case equivalent if such an equivalency exists? How would this regex look?
``` >>> re.sub('[AEIOU]+', lambda m: m.group(0).lower(), 'SOME TEXT HERE') 'SoMe TeXT HeRe' ```
Deleting columns in a CSV with python
7,588,934
11
2011-09-28T20:04:06Z
7,589,615
22
2011-09-28T21:08:34Z
[ "python", "csv", "row-removal" ]
I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will post my first question. My input.csv looks like this: ``` day,month,year,lat,long 01,04,2001,45.00,120.00 02,04,2003,44.00,118.00 ``` I am trying t...
``` import csv with open("source","rb") as source: rdr= csv.reader( source ) with open("result","wb") as result: wtr= csv.writer( result ) for r in rdr: wtr.writerow( (r[0], r[1], r[3], r[4]) ) ``` BTW, the `for` loop can be removed, but not really simplified. ``` in_iter= ...
Combining Two Images with OpenCV
7,589,012
10
2011-09-28T20:11:50Z
21,170,291
22
2014-01-16T18:47:29Z
[ "python", "image-processing", "opencv", "computer-vision" ]
I'm trying to use OpenCV 2.1 to combine two images into one, with the two images placed adjacent to each other. In Python, I'm doing: ``` import numpy as np, cv img1 = cv.LoadImage(fn1, 0) img2 = cv.LoadImage(fn2, 0) h1, w1 = img1.height,img1.width h2, w2 = img2.height,img2.width # Create an array big enough to hol...
For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code. To stack vertically (img1 over img2): ``` vis = np.concatenate((img1, img2), axis=0) ``` To stack horizontally (img1 to the left of img2): `...
Dividing decimals yields invalid results in Python 2.5 to 2.7
7,590,137
12
2011-09-28T22:00:42Z
7,591,190
7
2011-09-29T00:32:33Z
[ "python", "numbers", "decimal" ]
After a very thorough read of the Python's [decimal module documentation](http://docs.python.org/library/decimal.html), I still find myself puzzled by what happens when I divide a decimal. In Python 2.4.6 (makes sense): ``` >>> import decimal >>> decimal.Decimal(1000) / 10 Decimal("100") ``` In Python 2.5.6, Python ...
From your MacPorts bug, you have installed Xcode 4 and your version of Python 2.7.2 was built with the clang C compiler, rather than gcc-4.2. There is at least [one known problem with building with clang](http://bugs.python.org/issue11149) on OS X that has been fixed in Python subsequent to the 2.7.2. release. Either a...
Django setting for default template tag output when variable is None?
7,590,198
21
2011-09-28T22:06:20Z
7,590,291
30
2011-09-28T22:15:34Z
[ "python", "django", "django-templates" ]
I am looking for a django setting or programmatic way to make all django template tags show the empty string when the value is None. For example, imagine that I have some django template: ``` {{cat}} chases {{mouse}} ``` if both cat and mouse are None, it will render as: ``` None chases None ``` I am aware that I c...
No such thing exists. That's why the [`default`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#default) and [`default_if_none`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#default-if-none) filters exist. This is a *feature*; it makes you think about what you're doing instead of relying...
Simple, hassle-free, zero-boilerplate serialization in Scala/Java similar to Python's Pickle?
7,590,557
34
2011-09-28T22:47:13Z
7,619,508
11
2011-10-01T09:55:53Z
[ "java", "python", "scala", "serialization", "pickle" ]
Is there a simple, hassle-free approach to serialization in Scala/Java that's similar to Python's pickle? Pickle is a dead-simple solution that's reasonably efficient in space and time (i.e. not abysmal) but doesn't care about cross-language accessibility, versioning, etc. and allows for optional customization. What I...
I actually think you'd be best off with kryo (I'm not aware of alternatives that offer less schema defining other than non-binary protocols). You mention that pickle is not susceptible to the slowdowns and bloat that kryo gets without registering classes, but kryo is still faster and less bloated than pickle even witho...
Simple, hassle-free, zero-boilerplate serialization in Scala/Java similar to Python's Pickle?
7,590,557
34
2011-09-28T22:47:13Z
17,165,637
9
2013-06-18T09:46:22Z
[ "java", "python", "scala", "serialization", "pickle" ]
Is there a simple, hassle-free approach to serialization in Scala/Java that's similar to Python's pickle? Pickle is a dead-simple solution that's reasonably efficient in space and time (i.e. not abysmal) but doesn't care about cross-language accessibility, versioning, etc. and allows for optional customization. What I...
Scala now has [Scala-pickling](https://github.com/scala/pickling) which performs as good or better than Kyro depending on scenario - See slides 34-39 in [this](https://speakerdeck.com/heathermiller/on-pickles-and-spores-improving-support-for-distributed-programming-in-scala?slide=34) presentation.
Access self from decorator
7,590,682
34
2011-09-28T23:04:55Z
7,590,709
55
2011-09-28T23:07:37Z
[ "python", "unit-testing", "scope" ]
In setUp() method of unittest I've setup some *self* variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those *self* variables from decorator? For the sake of simplicity, I'm posting this code: ``` def decorator(func): def ...
Since you're decorating a method, and `self` is a method argument, your decorator has access to `self` at runtime. Obviously not at parsetime, because there are no objects yet, just a class. So you change your decorator to: ``` def decorator(func): def _decorator(self, *args, **kwargs): # access a from Te...
List of unique items in a list of tuples
7,590,950
3
2011-09-28T23:46:15Z
7,590,966
9
2011-09-28T23:48:59Z
[ "python", "list", "tuples" ]
I have a list of tuples like this: `mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]`. If I use the list comprehension `slist = [item for sublist in mylist for item in sublist]`, I could get `slist = [1,2,3,6,1,1,7,8,1,3,4,5]`. How should I modify if I need only unique elements in `slist` like this `[1,2,3,6,7,8,4,5]`?
Use a [set](http://docs.python.org/library/stdtypes.html#set) instead of a list. ``` set(slist) ``` If you *really* need it as a list then you can convert it back to a list: ``` slist = list(set(slist)) ``` Note that this conversion won't preserve the original order of the elements. If you need the same order you c...
Exporting Layout Positions for a Graph Using NetworkX
7,591,154
5
2011-09-29T00:24:17Z
7,592,166
8
2011-09-29T03:36:05Z
[ "python", "graph", "networkx", "graphml" ]
After generating x/y layout coordinates for a graph in NetworkX, how do I export the graph, along with node positions, as part of the node definition using something like GraphML? The layout algorithms don't seem to annotate the graph directly? Or do they?!
The layout algorithms don't set node attributes (but they should). Here is how to set the attributes: ``` In [1]: import networkx as nx In [2]: G=nx.path_graph(4) In [3]: pos=nx.spring_layout(G) In [4]: nx.set_node_attributes(G,'pos',pos) In [5]: G.node Out[5]: {0: {'pos': array([ 0., 0.])}, 1: {'pos': array([ ...
How to display point cloud in vtk in different colors?
7,591,204
3
2011-09-29T00:35:44Z
7,604,478
14
2011-09-29T23:27:55Z
[ "python", "vtk" ]
I have a point cloud which I want to visualize in vtk. I want to see them in different colors depending on some conditions. I am using python. Any suggestions on how to do that? Thanks a lot
Here is an example that sets the point color based on z-axis value. ``` import vtk from numpy import random class VtkPointCloud: def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6): self.maxNumPoints = maxNumPoints self.vtkPolyData = vtk.vtkPolyData() self.clearPoints() ma...
Fast n-gram calculation
7,591,258
13
2011-09-29T00:49:34Z
7,595,897
20
2011-09-29T10:23:06Z
[ "python", "nlp", "nltk", "n-gram" ]
I'm using NLTK to search for n-grams in a corpus but it's taking a very long time in some cases. I've noticed calculating n-grams isn't an uncommon feature in other packages (apparently Haystack has some functionality for it). Does this mean there's a potentially faster way of finding n-grams in my corpus if I abandon ...
Since you didn't indicate whether you want word or character-level n-grams, I'm just going to assume the former, without loss of generality. I also assume you start with a list of tokens, represented by strings. What you can easily do is write n-gram extraction yourself. ``` def ngrams(tokens, MIN_N, MAX_N): n_to...
How to create a self resizing grid of buttons in tkinter?
7,591,294
17
2011-09-29T00:54:48Z
7,591,453
29
2011-09-29T01:23:03Z
[ "python", "button", "grid", "tkinter", "autoresize" ]
I am trying to create a grid of buttons(in order to achieve the clickable cell effect) with Tkinter. My main problem is that I cannot make the `grid` and the buttons autoresize and fit the parent window. For example, when I have a high number of buttons on the grid, instead of shrinking the buttons so that the grid f...
You need to configure the rows and columns to have a **non-zero weight** so that they will take up the extra space: ``` for x in range(60): Grid.columnconfigure(grid, x, weight=1) for y in range(30): Grid.rowconfigure(grid, y, weight=1) ``` You also need to configure your buttons so that they will **expand t...
BeautifulSoup: AttributeError: 'NavigableString' object has no attribute 'name'
7,591,535
6
2011-09-29T01:38:27Z
7,591,578
11
2011-09-29T01:46:26Z
[ "python", "beautifulsoup" ]
Do you know why the first example in BeautifulSoup tutorial <http://www.crummy.com/software/BeautifulSoup/documentation.html#QuickStart> gives `AttributeError: 'NavigableString' object has no attribute 'name'`? According to [this answer](http://groups.google.com/group/beautifulsoup/browse_thread/thread/5359ec13be2347d5...
`name` will refer to the name of the tag if the object is a `Tag` object (ie: `<html>` name = "html") if you have spaces in your markup in between nodes BeautifulSoup will turn those into `NavigableString`'s. So if you use the index of the `contents` to grab nodes, you might grab a `NavigableString` instead of the nex...
Selenium testing without browser
7,593,611
24
2011-09-29T07:01:33Z
23,898,028
18
2014-05-27T20:09:02Z
[ "python", "selenium", "selenium-webdriver", "selenium-rc", "load-testing" ]
I use Selenium RC for testing. Now to perform a load test, I want to run parallel test cases. Is there any way to run them without opening a browser?
Yes. Just [install PhantomJS](http://phantomjs.org/download.html). Then, change this line: ``` driver = webdriver.Firefox() ``` to: ``` driver = webdriver.PhantomJS() ``` The rest of your code won't need to be changed and no browser will open. For debugging purposes, use `driver.save_screenshot('screen.png')` at ...
Django form field label translations
7,595,965
9
2011-09-29T10:29:32Z
7,645,330
8
2011-10-04T08:47:31Z
[ "python", "django", "internationalization", "django-forms" ]
I have a baseform with over 20 fields. Then I have about 15 other forms inheriting from that form, passing in a parameter called fields which the baseform uses to delete all other fields. Best explain via example: ``` class BaseForm(forms.Form): reportid = forms.HiddenInput() fromdate = forms.DateField(label=_...
Django provides \_lazy variants of the translation functions (for example ugettext\_laxy) so you can ark strings for translations at the access time (as opposed to when the translation function is called). It's documented in details at <https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#lazy-translation>
Benchmarking (python vs. c++ using BLAS) and (numpy)
7,596,612
83
2011-09-29T11:23:25Z
7,597,107
9
2011-09-29T12:09:48Z
[ "c++", "python", "numpy", "benchmarking", "blas" ]
I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate. I have, so to speak, three contestants and want to test their performance with a simple matrix-mat...
Given the rigor you've shown with your analysis, I'm surprised by the results thus far. I put this as an 'answer' but only because it's too long for a comment and does provide a possibility (though I expect you've considered it). I would've thought the numpy/python approach wouldn't add much overhead for a matrix of r...
Benchmarking (python vs. c++ using BLAS) and (numpy)
7,596,612
83
2011-09-29T11:23:25Z
7,601,495
20
2011-09-29T18:04:53Z
[ "c++", "python", "numpy", "benchmarking", "blas" ]
I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate. I have, so to speak, three contestants and want to test their performance with a simple matrix-mat...
Here's another benchmark (on Linux, just type `make`): <http://dl.dropbox.com/u/5453551/blas_call_benchmark.zip> ![](http://dl.dropbox.com/u/5453551/blas_call_benchmark.png) I do not see essentially any difference between the different methods for large matrices, between Numpy, Ctypes and Fortran. (Fortran instead of...
Benchmarking (python vs. c++ using BLAS) and (numpy)
7,596,612
83
2011-09-29T11:23:25Z
7,614,252
38
2011-09-30T18:00:19Z
[ "c++", "python", "numpy", "benchmarking", "blas" ]
I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate. I have, so to speak, three contestants and want to test their performance with a simple matrix-mat...
I've run [your benchmark](https://github.com/zed/woltan-benchmark). There is no difference between C++ and numpy on my machine: ![woltan's benchmark](http://i.stack.imgur.com/nGX9d.jpg) > Do you think my approach is fair, or are there some unnecessary overheads I can avoid? It seems fair due to there is no differenc...
Benchmarking (python vs. c++ using BLAS) and (numpy)
7,596,612
83
2011-09-29T11:23:25Z
7,645,872
53
2011-10-04T09:33:50Z
[ "c++", "python", "numpy", "benchmarking", "blas" ]
I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate. I have, so to speak, three contestants and want to test their performance with a simple matrix-mat...
## UPDATE (30.07.2014): I re-run the the benchmark on our new HPC. Both the hardware as well as the software stack changed from the setup in the original answer. I put the results in a [google spreadsheet](https://docs.google.com/spreadsheets/d/1jq0fDv-0ySMCF6qB22A13Aqf0TjAn449c6-TWrfViJ0/edit?usp=sharing) (contains ...
Regex for wrapping digits with curly braces?
7,596,667
2
2011-09-29T11:29:26Z
7,596,713
7
2011-09-29T11:33:56Z
[ "python", "regex", "backreference" ]
I am trying to using Python's `re.sub()` to match a string with an `e` character and insert curly braces immediately after the `e` character and after the lastdigit. For example: ``` 12.34e56 to 12.34e{56} 1e10 to 1e{10} ``` I can't seem to find the correct regex to insert the desired curly braces. For example, I can...
``` re.sub(r'e(\d+)', r'e{\1}', '12.34e56') ``` returns `'12.34e{56}'` or, the same result but different logic (don't replace `e` with `e`): ``` re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56') ```
How to set the line width of error bar caps, in matplotlib?
7,601,334
23
2011-09-29T17:49:54Z
7,627,376
22
2011-10-02T15:50:55Z
[ "python", "matplotlib" ]
How can the line width of the error bar caps in Matplotlib be changed? I tried the following code: ``` (_, caplines, _) = matplotlib.pyplot.errorbar( data['distance'], data['energy'], yerr=data['energy sigma'], capsize=10, elinewidth=3) for capline in caplines: capline.set_linewidth(10) capline.set_c...
EOL, you were very close.., ``` distance = [1,3,7,9] energy = [10,20,30,40] sigma = [1,3,2,5] (_, caps, _) = plt.errorbar(distance, energy, sigma, capsize=20, elinewidth=3) for cap in caps: cap.set_color('red') cap.set_markeredgewidth(10) plt.show ``` ![enter image description here](http://i.stack.imgur.co...
How to improve efficiency in this numpy iterating?
7,601,611
2
2011-09-29T18:13:30Z
7,601,953
7
2011-09-29T18:46:38Z
[ "python", "image-processing", "numpy", "python-imaging-library" ]
I'm working on an assignment about converting a grayscale image to 1-bit binary image by dithering. I'm trying a simple 4x4 matrix that will make the image 16 times larger than original. ``` dithering_matrix = array([[ 0, 8, 2, 10], [12, 4, 14, 6], [ 3, 11, 1, ...
If you use the [Kronecker product](http://en.wikipedia.org/wiki/Kronecker_product) to turn every pixel into a 4x4 submatrix, that'll enable you to get rid of the Python loops: ``` im2 = np.kron(im, np.ones((4,4))) dm2 = np.tile(dithering_matrix,(512,512)) out2 = ((im2 / (256 / split_num)) > dm2) * 255 ``` On my machi...
How do chained assignments work?
7,601,823
15
2011-09-29T18:34:45Z
7,601,847
12
2011-09-29T18:36:50Z
[ "python", "python-3.x" ]
A quote from something: ``` >>> x = y = somefunction() ``` is the same as ``` >>> y = somefunction() >>> x = y ``` Question: Is ``` x = y = somefunction() ``` the same as ``` x = somefunction() y = somefunction() ``` ? Based on my understanding, they should be same because `somefunction` can only return exactl...
What if `somefunction()` returns different values each time it is called? ``` import random x = random.random() y = random.random() ```
How do chained assignments work?
7,601,823
15
2011-09-29T18:34:45Z
7,601,890
23
2011-09-29T18:41:15Z
[ "python", "python-3.x" ]
A quote from something: ``` >>> x = y = somefunction() ``` is the same as ``` >>> y = somefunction() >>> x = y ``` Question: Is ``` x = y = somefunction() ``` the same as ``` x = somefunction() y = somefunction() ``` ? Based on my understanding, they should be same because `somefunction` can only return exactl...
They will not necessarily work the same if `somefunction` returns a mutable value. Consider: ``` >>> def somefunction(): ... return [] ... >>> x = y = somefunction() >>> x.append(4) >>> x [4] >>> y [4] >>> x = somefunction(); y = somefunction() >>> x.append(3) >>> x [3] >>> y [] ```
How do chained assignments work?
7,601,823
15
2011-09-29T18:34:45Z
36,346,517
10
2016-04-01T01:24:12Z
[ "python", "python-3.x" ]
A quote from something: ``` >>> x = y = somefunction() ``` is the same as ``` >>> y = somefunction() >>> x = y ``` Question: Is ``` x = y = somefunction() ``` the same as ``` x = somefunction() y = somefunction() ``` ? Based on my understanding, they should be same because `somefunction` can only return exactl...
Neither. ``` x = y = some_function() ``` is equivalent to ``` temp = some_function() x = temp y = temp ``` Note the order. **The leftmost target in the chain is assigned first**. From the [docs](https://docs.python.org/reference/simple_stmts.html#assignment-statements): > ...assigns the single resulting object to ...