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
Can you apply an operation directly to arguments within map/reduce/filter?
11,402,607
6
2012-07-09T20:28:13Z
11,402,642
11
2012-07-09T20:30:36Z
[ "python", "syntax", "iteration", "readability" ]
`map` and `filter` are often interchangeable with list comprehensions, but `reduce` is not so easily swapped out as `map` and `filter` (and besides, in some cases I still prefer the functional syntax anyway). When you need to operate on the arguments themselves, though, I find myself going through syntactical gymnastic...
Check out [itertools](http://docs.python.org/library/itertools.html) for tools that will make your life easier. For example, the code you posted is already available as [`itertools.starmap`](http://docs.python.org/library/itertools.html#itertools.starmap). ``` itertools.starmap(afunc, aniter) ``` From the documentat...
No JSON object could be decoded - tastypie - curl
11,402,756
4
2012-07-09T20:39:33Z
11,413,586
12
2012-07-10T12:43:50Z
[ "python", "django", "json", "curl", "tastypie" ]
I was following the tastypie tutorial word for word until i reached the post part: <http://django-tastypie.readthedocs.org/en/latest/interacting.html#creating-a-new-resource-post> When i run this command i keep getting the following error: `No JSON object could be decoded` I checked and I am certain that I am followi...
Turned out to be a windows thing with cURL. 1. The JSON data should be quoted with double quotes ("") instead of single quotes. 2. All the double quotes in the json packet must be escaped with a backslash (\) Eg: So, this: `curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"body": "This will ...
Confusion about Python list slice results
11,403,132
2
2012-07-09T21:04:56Z
11,403,149
9
2012-07-09T21:05:53Z
[ "python", "list" ]
I'm new to Python, the following output I'm getting from a simple list slice operation confused the jebuse out of me. Here is the code. ``` >>> a = [1,2,3,4]; >>> a[1:3] [2, 3] >>> a[3] 4 ``` shouldn't `a[1:3]` returns `[2,3,4]` instead of `[2,3]`?
`a[1:3]` specifies a *half-closed interval*, which means it includes the values starting at the *1st* specified index up to, *but not including*, at the *2nd* index. So in this case `a[1:3]` means the slice includes `a[1]` and `a[2]`, but *not* `a[3]` You see the same in the use of the [range()](http://docs.python.or...
Python: How can I check whether a object is a module?
11,403,436
2
2012-07-09T21:27:33Z
11,403,492
7
2012-07-09T21:31:05Z
[ "python", "object", "module" ]
How can I check in Python whether a given object is a module or not? Here is what I tried: ``` >>> import sys >>> sys.modules["sys"].__class__ <class 'module'> >>> isinstance(sys.modules["sys"], module) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'module' is not defined >>...
``` >>> import sys, types >>> isinstance(sys, types.ModuleType) True ``` the `types` module also provides many other types: ``` >>> dir(types) ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType'...
Python Regex - Remove special characters but preserve apostraphes
11,403,474
3
2012-07-09T21:30:14Z
11,403,663
10
2012-07-09T21:44:01Z
[ "python", "regex" ]
I am attempting to remove all special characters from some text, here is my regex: ``` pattern = re.compile('[\W_]+', re.UNICODE) words = str(pattern.sub(' ', words)) ``` Super simple, but unfortunately it is causing problems when using apostrophes (single quotes). For example, if I had the word "doesn't", this code ...
Like this? ``` >>> pattern=re.compile("[^\w']") >>> pattern.sub(' ', "doesn't it rain today?") "doesn't it rain today " ``` If underscores also should be filtered away: ``` >>> re.compile("[^\w']|_").sub(" ","doesn't this _technically_ means it works? naïve I am ...") "doesn't this technically means it works naÃ...
Convert rows into columns
11,403,733
5
2012-07-09T21:50:07Z
11,404,092
7
2012-07-09T22:25:56Z
[ "python", "ruby", "perl", "unix" ]
I have a file in rows as below and would like to convert into two column format. ``` >00000_x1688514 TGCTTGGACTACATATGGTTGAGGGTTGTA >00001_x238968 TGCTTGGACTACATATTGTTGAGGGTTGTA ... ``` Desired output is ``` >00000_x1688514 TGCTTGGACTACATATGGTTGAGGGTTGTA >00001_x238968 TGCTTGGACTACATATTGTTGAGGGTTGTA ... ``` I would...
I don't know if you are aware of the BioPerl modules for reading/writing and other genetic functions. Your problem can be written like this. ``` #!/usr/bin/perl use strict; use warnings; use Bio::SeqIO; my $file = 'o33.txt'; my $in = Bio::SeqIO->new( -file => $file, -format => 'fasta');...
Python AttributeError: 'module' object has no attribute 'Serial'
11,403,932
52
2012-07-09T22:09:25Z
11,404,052
47
2012-07-09T22:21:46Z
[ "python", "serial-port", "raspberry-pi" ]
I'm trying to access a serial port with Python 2.6 on my Raspberry Pi running Debian. My script named `serial.py` tries to import pySerial: ``` import serial ser = serial.Serial('/dev/ttyAMA0', 9600) ser.write("hello world!") ``` For some reason it refuses to establish the serial connection with this error: ``` Attr...
You're importing the module, not the class. So, you must write: `from serial import serial`
Python AttributeError: 'module' object has no attribute 'Serial'
11,403,932
52
2012-07-09T22:09:25Z
11,873,344
93
2012-08-08T21:19:10Z
[ "python", "serial-port", "raspberry-pi" ]
I'm trying to access a serial port with Python 2.6 on my Raspberry Pi running Debian. My script named `serial.py` tries to import pySerial: ``` import serial ser = serial.Serial('/dev/ttyAMA0', 9600) ser.write("hello world!") ``` For some reason it refuses to establish the serial connection with this error: ``` Attr...
I'm adding this solution for people who make the same mistake as I did. In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error. Problem occurs when you import 'something' when your python file name is 'something.py'.
NumPy ImportError in python - Dll load failed
11,404,269
12
2012-07-09T22:41:29Z
11,404,318
22
2012-07-09T22:45:40Z
[ "python", "numpy", "matplotlib" ]
I've installed the latest version of numpy from [here](http://sourceforge.net/projects/numpy/files/NumPy/1.6.2/) for python 3.2 on 64-bit Windows Vista for use with matplotlib. However, when I try to import matplotlib, I get the following error: ``` ImportError: DLL load failed: %1 is not a valid Win32 application. ``...
You are most likely using a 64bit Python with a 32bit numpy or vice versa. Make sure both have the same bitness. Unless you need 64bit python for some reason it's usually a good idea to stay with 32bit as you might have to compile some binary python packages manually since 32bit binary packages are much more common.
accepting multiple user inputs seperated by a space in python and append them to a list
11,404,946
5
2012-07-10T00:04:43Z
11,404,958
20
2012-07-10T00:06:19Z
[ "python", "list" ]
How can I accept multiple user inputs separated by a space? I don't know the number of inputs, but I do know they are all ints. Here's some example inputs: ``` 13213 412 8143 12 312 1321 142 9421 9 29 319 ``` I know can do this if I know the number of inputs beforehand, but I'm having trouble making this generic. I ...
``` s = raw_input("Please enter your numbers: ") mynums = [int(i) for i in s.split()] # OR mynums = map(int, s.split()) ```
accepting multiple user inputs seperated by a space in python and append them to a list
11,404,946
5
2012-07-10T00:04:43Z
11,404,961
11
2012-07-10T00:06:46Z
[ "python", "list" ]
How can I accept multiple user inputs separated by a space? I don't know the number of inputs, but I do know they are all ints. Here's some example inputs: ``` 13213 412 8143 12 312 1321 142 9421 9 29 319 ``` I know can do this if I know the number of inputs beforehand, but I'm having trouble making this generic. I ...
Try this: ``` nums = [int(i) for i in raw_input("Enter space separated inputs: ").split()] ```
How to get the file modification date in UTC from Python
11,405,049
13
2012-07-10T00:21:31Z
11,405,092
17
2012-07-10T00:28:19Z
[ "python" ]
I want to get the modification date of a file in UTC from Python. The following code returns dates in my Linux configured time zone (GMT-5). I want it in UTC. Or how do I get the os configured time zone to convert it with pytz ? ``` $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type ...
Try [datetime.datetime.utcfromtimestamp](http://docs.python.org/library/datetime.html#datetime.datetime.utcfromtimestamp) ``` import datetime import os dt=os.path.getmtime('/home/me/.bashrc') print (datetime.datetime.fromtimestamp(dt)) print (datetime.datetime.utcfromtimestamp(dt)) ```
How do I install PyCrypto on Windows?
11,405,549
100
2012-07-10T01:44:52Z
11,405,614
17
2012-07-10T01:54:32Z
[ "python", "windows", "python-2.7", "pycrypto" ]
I've read every other google source and SO thread, with nothing working. `Python 2.7.3 32bit` installed on `Windows 7 64bit`. Download, extracting, and then trying to install PyCrypto results in `"Unable to find vcvarsall.bat".` So I install MinGW and tack that on the install line as the compiler of choice. But then ...
### In general `vcvarsall.bat` is part of the Visual C++ compiler, you need that to install what you are trying to install. Don't even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the **version** of the Microsoft tool chain is important. Python compiled with VS ...
How do I install PyCrypto on Windows?
11,405,549
100
2012-07-10T01:44:52Z
11,405,769
135
2012-07-10T02:19:54Z
[ "python", "windows", "python-2.7", "pycrypto" ]
I've read every other google source and SO thread, with nothing working. `Python 2.7.3 32bit` installed on `Windows 7 64bit`. Download, extracting, and then trying to install PyCrypto results in `"Unable to find vcvarsall.bat".` So I install MinGW and tack that on the install line as the compiler of choice. But then ...
If you don't already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available. Fortunately, there are PyCrypto binaries available for Win...
How do I install PyCrypto on Windows?
11,405,549
100
2012-07-10T01:44:52Z
16,955,818
13
2013-06-06T07:09:41Z
[ "python", "windows", "python-2.7", "pycrypto" ]
I've read every other google source and SO thread, with nothing working. `Python 2.7.3 32bit` installed on `Windows 7 64bit`. Download, extracting, and then trying to install PyCrypto results in `"Unable to find vcvarsall.bat".` So I install MinGW and tack that on the install line as the compiler of choice. But then ...
For VS2010: ``` SET VS90COMNTOOLS=%VS100COMNTOOLS% ``` For VS2012: ``` SET VS90COMNTOOLS=%VS110COMNTOOLS% ``` then Call: ``` pip install pyCrypto ```
How do I install PyCrypto on Windows?
11,405,549
100
2012-07-10T01:44:52Z
27,327,236
23
2014-12-06T01:22:05Z
[ "python", "windows", "python-2.7", "pycrypto" ]
I've read every other google source and SO thread, with nothing working. `Python 2.7.3 32bit` installed on `Windows 7 64bit`. Download, extracting, and then trying to install PyCrypto results in `"Unable to find vcvarsall.bat".` So I install MinGW and tack that on the install line as the compiler of choice. But then ...
Microsoft has recently recently released a standalone, dedicated [Microsoft Visual C++ Compiler for Python 2.7](http://www.microsoft.com/en-us/download/details.aspx?id=44266). If you're using Python 2.7, simply install that compiler and Setuptools 6.0 or later, and most packages with C extensions will now compile readi...
How do I install PyCrypto on Windows?
11,405,549
100
2012-07-10T01:44:52Z
32,676,880
7
2015-09-20T07:25:00Z
[ "python", "windows", "python-2.7", "pycrypto" ]
I've read every other google source and SO thread, with nothing working. `Python 2.7.3 32bit` installed on `Windows 7 64bit`. Download, extracting, and then trying to install PyCrypto results in `"Unable to find vcvarsall.bat".` So I install MinGW and tack that on the install line as the compiler of choice. But then ...
[PyCryptodome](http://www.pycryptodome.org/) is an almost-compatible fork of PyCrypto with Windows wheels available on [pypi](https://pypi.python.org/pypi/pycryptodome). You can install it with a simple: ``` pip install pycryptodome ``` The website includes instructions to build it from sources with the Microsoft co...
ListField without duplicates in Python mongoengine
11,406,380
9
2012-07-10T03:57:07Z
11,416,698
11
2012-07-10T15:26:38Z
[ "python", "mongodb", "unique", "mongoengine" ]
I must be missing something really obvious. But I can't seem to find a way to represent a set using mongoengine. ``` class Item(Document): name = StringField(required=True) description = StringField(max_length=50) parents = ListField(ReferenceField('self')) i = Item.objects.get_or_create(name='test item')...
Instead of using `append` then using `save` and letting MongoEngine convert that to updates, you could use atomic updates and the $addToSet method - see [the updating mongoDB docs](http://www.mongodb.org/display/DOCS/Updating) So in your case you could do: ``` i.update(add_to_set__parents=i2) i.update(add_to_set__par...
how to get derived class name from base class
11,408,148
13
2012-07-10T06:59:51Z
11,408,458
14
2012-07-10T07:23:33Z
[ "python", "plone", "derived-class", "base-class" ]
I have a base class `Person` and derived classes `Manager` and `Employee`. Now, what I would like to know is the object created is `Manager` or the `Employee`. The person is given as belows: ``` from Project.CMFCore.utils import getToolByName schema = getattr(Person, 'schema', Schema(())).copy() + Schema((TextField('...
I don't know if this is what you want, and the way you'd like it implemented, but here's a try: ``` >>> class Person(object): def _type(self): return self.__class__.__name__ >>> p = Person() >>> p._type() 'Person' >>> class Manager(Person): pass >>> m = Manager() >>> m._type() 'Manager' >>> ``` Pro...
About python closure
11,408,515
6
2012-07-10T07:28:03Z
11,408,601
14
2012-07-10T07:33:45Z
[ "python", "closures" ]
Below is an example I got from someone's blog about python closure. I run it in python 2.7 and get a output different from my expect. ``` flist = [] for i in xrange(3): def func(x): return x*i flist.append(func) for f in flist: print f(2) ``` My expected output is: 0, 2, 4 But the output is: 4...
Loops do not introduce scope in Python, so all three functions close over the same `i` variable, and will refer to its final value after the loop finishes, which is 2. It seems as though nearly everyone I talk to who uses closures in Python has been bitten by this. The corollary is that the outer function can change `...
Is it worth closing files in small functions?
11,409,345
8
2012-07-10T08:24:30Z
11,409,388
12
2012-07-10T08:27:20Z
[ "python", "file", "garbage-collection" ]
Say you have: ``` def my_func(): fh = open(...) try: print fh.read() finally: fh.close() ``` My first question is: Is it worth having the try/finally (or with) statement? Isn't the file closed anyway when the function terminates (via garbage collection)? I came across this after reading a...
It is good practice to close the file yourself. Using the `with` statement leads to clean code and it automatically closes the file (which is a Good Thing). Even though Python is a high-level programming language, you still need to be in control of what you're doing. As a rule of thumb: if you open a file, it also nee...
Python prints result as '7\xe6\x9c\x8810\xe6\x97\xa5', but I want '7月10日'
11,409,486
5
2012-07-10T08:33:54Z
11,409,647
7
2012-07-10T08:44:32Z
[ "python", "unicode", "printing" ]
I fetched a web page, which contains Japanese, but when I print it to the console I didn't get the output as **`7月10日`**. Instead, it prints: `7\xe6\x9c\x8810\xe6\x97\xa5` What should I do?
The output you get is correct. That is the UTF-8 representation of the japanese string. The problem is the console itself that it doesn't understand UTF-8. If you write that string in a file and open it with an editor that does understand UTF-8 you'll see the content as you would expect. You could also try to change th...
Plotting a 2d Array with mplot3d
11,409,690
5
2012-07-10T08:47:43Z
11,409,882
7
2012-07-10T08:58:11Z
[ "python", "arrays", "2d", "mplot3d" ]
I have a 2D numpy array and I want to plot it in 3D. I heard about mplot3d but I cant get to work properly Here's an example of what I want to do. I have an array with the dimensions (256,1024). It should plot a 3D graph where the x axis is from 0 to 256 the y axis from 0 to 1024 and the z axis of the graph displays t...
It sounds like you are trying to create a [surface](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#surface-plots) plot (alternatively you could draw a [wireframe](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots) plot or a [filled countour plot](http://matplotli...
Turn off the the upper/right axis tick marks
11,410,796
11
2012-07-10T09:56:20Z
11,411,617
8
2012-07-10T10:43:17Z
[ "python", "matplotlib" ]
I want to make the ticks on the right and upper axis invisible and am not sure what the third line should be: ``` import matplotlib.pyplot as plt plt.plot(X,Y) #plt.upper_right_axis_ticks_off() ```
Have a look at <http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html> ``` import pylab as p t = p.arange(0.0, 2.0, 0.01) ax=p.subplot(111) s = p.sin(2*p.pi*t) ax.plot(t, s, color='r',linewidth=1.0) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') p.show() ```
Turn off the the upper/right axis tick marks
11,410,796
11
2012-07-10T09:56:20Z
11,417,222
12
2012-07-10T15:55:37Z
[ "python", "matplotlib" ]
I want to make the ticks on the right and upper axis invisible and am not sure what the third line should be: ``` import matplotlib.pyplot as plt plt.plot(X,Y) #plt.upper_right_axis_ticks_off() ```
As pointed by @imsc, You can tweak the visibility of the tick marks by setting the position of the ticks to the bottom and left (if you don't want them on top and right) using the `ax.xaxis.set_ticks_position` and `ax.yaxis.set_ticks_position` methods. If you also want to set the axis itself invisible, check out the [...
Python: How json dumps None to empty string
11,410,896
5
2012-07-10T10:02:21Z
11,410,935
7
2012-07-10T10:04:32Z
[ "python", "json" ]
I want Python's `None` to be encoded in json as empty string how? Below is the default behavior of `json.dumps`. ``` >>> import json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' ``` Should I overwrite the json encoder method or is there any other way? Thanks! **E...
In the object you're encoding, use an empty string instead of a `None`. Here's an untested function that walks through a series of nested dictionaries to change all `None` values to `''`. Adding support for lists and tuples is left as an exercise to the reader. :) ``` import copy def scrub(x): ret = copy.deepcop...
Sending e-mail after scrape in scrapy
11,411,033
3
2012-07-10T10:09:34Z
11,411,162
9
2012-07-10T10:16:31Z
[ "python", "email", "scrapy" ]
**pipeline.py code** ``` class Examplepipeline(object): def __init__(self): dispatcher.connect(self.spider_opened, signal=signals.spider_opened) dispatcher.connect(self.spider_closed, signal=signals.spider_closed) def spider_opened(self, spider): log.msg("opened spider %s at time %s" % (spider.name,date...
Have you looked into documentation: <http://doc.scrapy.org/en/latest/topics/email.html> Basic usage from documentation ``` from scrapy.mail import MailSender mailer = MailSender() mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"]) ``` Also you could implem...
Quick way to know if a file is open on Linux?
11,411,428
2
2012-07-10T10:31:54Z
11,411,493
8
2012-07-10T10:35:53Z
[ "python", "linux" ]
Is there a quick way (i.e. that minimizes time-to-answer) to find out if a file is open on Linux? Let's say I have a process that writes a ton a files in a directory and another process which reads those files **once** they are finished writing, can the latter process know if a file is still being written to by the fo...
You can of course use INOTIFY feature of Linux, but it is safer to avoid the situation: let the writing process create the files (say data.tmp) which the reading process will definitely ignore. When the writer finishes, it should just rename the file for the reader (into say .dat). The rename operation guarantees that ...
dropping a row in pandas with dates indexes, python
11,414,596
5
2012-07-10T13:40:36Z
11,414,827
10
2012-07-10T13:51:12Z
[ "python", "pandas" ]
I'm trying to drop the last row in a dataframe created by pandas in python and seem to be having trouble. ``` index = DateRange('1/1/2000', periods=8) df = DataFrame(randn(8, 3), index=index, columns=['A', 'B', 'C']) ``` I tried the drop method like this: ``` df.drop([shape(df)[0]-1], axis = 0) ``` but it keeps say...
``` df.ix[:-1] ``` returns the original DataFrame with the last row removed.
Translate output to Japanese
11,414,839
2
2012-07-10T13:51:57Z
11,414,864
7
2012-07-10T13:53:20Z
[ "python", "internationalization", "gettext", "cjk", "machine-translation" ]
I'm planning to use Python Bottle framework for a simple website. Except for the numerics (eg., data shown in a table), all output has to be in Japanese. So instead of outputing "345.65 meters", I need to output "345.65 ". Is there anyway I could create a text file containing (english) key = (japanese) value pairs ......
What you just described already exists and it is called [gettext](https://www.gnu.org/software/gettext/) (**edit**: also see Python's [`gettext`](http://docs.python.org/library/gettext.html#module-gettext) module). It does exactly that and I'm not sure if it the Bottle framework supports it but I do know that the [Djan...
Extract traceback info from an exception object
11,414,894
37
2012-07-10T13:54:59Z
11,415,140
38
2012-07-10T14:08:57Z
[ "python", "debugging", "exception-handling" ]
Given an Exception object (of unknown origin) is there way to obtain its traceback? I have code like this: ``` def stuff(): try: ..... return useful except Exception as e: return e result = stuff() if isinstance(result, Exception): result.traceback <-- How? ``` How can I extract the tr...
The traceback is not stored in the exception. (Not, that is, in Python 2; see [Vyktor](http://stackoverflow.com/a/14564261/577088)'s answer for more about the situation in Python 3). Within an `except` clause, you can retrieve it using [`sys.exc_info()`](http://docs.python.org/library/sys.html#sys.exc_info). See also t...
Extract traceback info from an exception object
11,414,894
37
2012-07-10T13:54:59Z
14,564,261
17
2013-01-28T14:31:59Z
[ "python", "debugging", "exception-handling" ]
Given an Exception object (of unknown origin) is there way to obtain its traceback? I have code like this: ``` def stuff(): try: ..... return useful except Exception as e: return e result = stuff() if isinstance(result, Exception): result.traceback <-- How? ``` How can I extract the tr...
Since [Python 3.0[PEP 3109]](http://www.python.org/dev/peps/pep-3109/) the built in class [`Exception`](http://docs.python.org/3.2/tutorial/errors.html#exceptions) has a `__traceback__` attribute which contains a `traceback object` (with Python 3.2.3): ``` >>> try: ... raise Exception() ... except Exception as e: ...
directory path types with argparse
11,415,570
24
2012-07-10T14:29:50Z
11,415,816
22
2012-07-10T14:41:19Z
[ "python", "argparse" ]
My python script needs to read files from a directory passed on the command line. I have defined a readable\_dir type as below to be used with argparse for validating that the directory passed on the command line is existent and readable. Additionally, a default value (/tmp/non\_existent\_dir in the example below) has ...
You can create a custom action instead of a type: ``` import argparse import os import tempfile import shutil import atexit class readable_dir(argparse.Action): def __call__(self,parser, namespace, values, option_string=None): prospective_dir=values if not os.path.isdir(prospective_dir): ...
directory path types with argparse
11,415,570
24
2012-07-10T14:29:50Z
11,416,062
9
2012-07-10T14:54:21Z
[ "python", "argparse" ]
My python script needs to read files from a directory passed on the command line. I have defined a readable\_dir type as below to be used with argparse for validating that the directory passed on the command line is existent and readable. Additionally, a default value (/tmp/non\_existent\_dir in the example below) has ...
If your script can't work without a valid `launch_directory` then it should be made a mandatory argument: ``` parser.add_argument('launch_directory', type=readable_dir) ``` btw, you should use `argparse.ArgumentTypeError` instead of `Exception` in `readable_dir()`.
Efficiently construct Pandas DataFrame from large list of tuples/rows
11,415,701
11
2012-07-10T14:36:11Z
11,415,882
16
2012-07-10T14:44:48Z
[ "python", "tuples", "pandas", "dta" ]
I've inherited a data file saved in the Stata .dta format. I can load it in with scikits.statsmodels `genfromdta()` function. This puts my data into a 1-dimensional NumPy array, where each entry is a row of data, stored in a 24-tuple. ``` In [2]: st_time = time.time(); initialload = sm.iolib.genfromdta("/home/myfile.d...
If my comment answered your question, my answer does not have to comment on it any more… ;-) ``` pandas.DataFrame(initialload, columns=list_of_column_names) ```
Error installing python-snappy: snappy-c.h: No such file or directory
11,416,024
9
2012-07-10T14:52:07Z
11,416,828
9
2012-07-10T15:33:27Z
[ "python", "gcc" ]
I am using amazon ec2 ubuntu 11.04 server ``` sudo pip install python-snappy ``` also I tried to downloaded package and entered "sudo python setup.py install" I got the error: ``` running build running build_ext building 'snappy' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Ws...
You need Snappy C [library](http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CFYQFjAA&url=http://code.google.com/p/snappy/&ei=L0v8T8HlHMXOrQez2_DTBg&usg=AFQjCNEQTGy3Q9f9_RhG9h04N1ikI6tyiQ) Then you have to install python-snappy wrapper. It seems you didn't install Snappy-C library Try it ..as al...
Error installing python-snappy: snappy-c.h: No such file or directory
11,416,024
9
2012-07-10T14:52:07Z
20,678,150
18
2013-12-19T09:45:38Z
[ "python", "gcc" ]
I am using amazon ec2 ubuntu 11.04 server ``` sudo pip install python-snappy ``` also I tried to downloaded package and entered "sudo python setup.py install" I got the error: ``` running build running build_ext building 'snappy' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Ws...
You can install Snappy C library with following commands: **DEB-based:** `sudo apt-get install libsnappy-dev` **RPM-based:** `sudo yum install libsnappy-devel` **Brew:** `brew install snappy`
Find all words in a string that start with the $ sign in Python
11,416,772
6
2012-07-10T15:30:10Z
11,416,842
19
2012-07-10T15:34:01Z
[ "python", "regex", "dollar-sign" ]
How can I extract all words in a string that start with the $ sign? For example in the string ``` This $string is an $example ``` I want to extract the words `$string` and `$example`. I tried with this regex `\b[$]\S*` but it works fine only if I use a normal character rather than dollar.
``` >>> [word for word in mystring.split() if word.startswith('$')] ['$string', '$example'] ```
PyCharm can not resolve PyGObject 3.0, but code runs fine
11,417,921
13
2012-07-10T16:39:58Z
11,418,828
17
2012-07-10T17:37:43Z
[ "python", "ubuntu", "python-3.x", "pycharm", "pygobject" ]
I'm using PyCharm 2.5 on Ubuntu 11.10, trying to develop an application using PyGObject 3.0 on Python 3.2.2. I've installed the Ubuntu package python3-gobject, and when I run my code, it works exactly as expected. However, PyCharm can not seem to find any of the PyGObject modules. It says `Unresolved refrence: 'Gtk'` ...
In Gtk+ 3 Python bindings to binary modules are generated dynamically using `*.typelib` databases. The dynamic importer for accessing all the modules is located in `gi.repository`. PyCharm cannot detect these modules using its code insight, because they require special handling. I've filed a feature request for this i...
PyCharm can not resolve PyGObject 3.0, but code runs fine
11,417,921
13
2012-07-10T16:39:58Z
33,646,560
13
2015-11-11T08:17:05Z
[ "python", "ubuntu", "python-3.x", "pycharm", "pygobject" ]
I'm using PyCharm 2.5 on Ubuntu 11.10, trying to develop an application using PyGObject 3.0 on Python 3.2.2. I've installed the Ubuntu package python3-gobject, and when I run my code, it works exactly as expected. However, PyCharm can not seem to find any of the PyGObject modules. It says `Unresolved refrence: 'Gtk'` ...
Position the text cursor inside the redlined 'Gtk' in: ``` from gi.repository import Gtk ``` hit Alt + Enter and choose "Generate stubs for binary module"
Django: how to annotate queryset with count of filtered ForeignKey field?
11,418,522
20
2012-07-10T17:19:02Z
11,424,891
27
2012-07-11T02:54:10Z
[ "python", "django", "django-models" ]
Django novice question :) I have the following models - each review is for a product, and each product has a department: ``` class Department(models.Model): code = models.CharField(max_length=16) class Product(models.Model): id = models.CharField(max_length=40, primary_key=True, db_index=True) dept = mode...
Avoid `extra` and `raw` whenever possible. The [aggregation docs](https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet) have nearly this use case: Straight from the docs: ``` # Each publisher, each with a count of books as a "num_books" attribute. >>> from django.db.models import Count >>> pubs = ...
How do I truncate a string at the last letter before the first occurrence of a digit?
11,419,065
2
2012-07-10T17:53:50Z
11,419,108
7
2012-07-10T17:56:50Z
[ "python", "string", "parsing", "indexing" ]
I am trying to find things in a string - all of them are before a number, for example: ``` "Diablo Lord Of Destruction 9.2" ``` This is an index from a file such that `file[2] = "Diablo Lord Of Destruction 9.2"` how can I write code that will select only the text and leave out the numbers and any white space before ...
This removes any digits and full stops from your string: ``` import re >>> filtered = re.sub('[0-9.]*','',"Diablo Lord Of Destruction 9.2 111" ) >>> filtered 'Diablo Lord Of Destruction ' >>> filtered.strip() # you might want to get rid of the trailing space too! 'Diablo Lord Of Destruction' ```
Python: catch exceptions inside a class
11,420,464
10
2012-07-10T19:26:41Z
11,420,680
11
2012-07-10T19:40:18Z
[ "python" ]
Is it possible to write an exception handler to catch the run-time errors generated by ALL the methods in class? I can do it by surrounding each one with try/except: ``` class MyError(Exception): def __init__(self, obj, method): print 'Debug info:', repr(obj.data), method.__name__ raise class MyCl...
**Warning: if you want something like this, it's likely you don't... but if you really want to...** Something like: ``` import functools def catch_exception(f): @functools.wraps(f) def func(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: print '...
Python: catch exceptions inside a class
11,420,464
10
2012-07-10T19:26:41Z
11,420,895
8
2012-07-10T19:55:19Z
[ "python" ]
Is it possible to write an exception handler to catch the run-time errors generated by ALL the methods in class? I can do it by surrounding each one with try/except: ``` class MyError(Exception): def __init__(self, obj, method): print 'Debug info:', repr(obj.data), method.__name__ raise class MyCl...
Assuming you've got a decorator `catch_exception` as in @Jon Clement's answer... ``` class ErrorCatcher(type): def __new__(cls, name, bases, dct): for m in dct: if hasattr(dct[m], '__call__'): dct[m] = catch_exception(dct[m]) return type.__new__(cls, name, bases, dct) c...
How to get long file system path from python on Windows
11,420,689
6
2012-07-10T19:40:48Z
11,421,053
8
2012-07-10T20:03:44Z
[ "python", "windows", "path" ]
This returns me a short path (DOS convention) (on Windows): ``` import tempfile tempDir = tempfile.mkdtemp() print tempDir Output >>> c:\users\admini~1\appdata\local\temp\tmpf76unv ``` Notice the `admini~1`. How can I get/convert this to a full path? e.g. C:\users\administrator\appdata...
Please try the following code (updated): ``` from ctypes import create_unicode_buffer, windll BUFFER_SIZE = 500 buffer = create_unicode_buffer(BUFFER_SIZE) get_long_path_name = windll.kernel32.GetLongPathNameW get_long_path_name(unicode(short_path_name), buffer, BUFFER_SIZE) long_path_name = buffer.value ``` Hope thi...
Setting Camera Parameters in OpenCV/Python
11,420,748
27
2012-07-10T19:45:04Z
11,433,221
18
2012-07-11T13:00:19Z
[ "python", "opencv", "camera", "python-2.7" ]
I am using OpenCV (2.4) and Python (2.7.3) with a USB camera from Thorlabs (DC1545M). I am doing some image analysis on a video stream and I would like to be able to change some of the camera parameters from my video stream. The confusing thing is that I am able to change some of the camera properties but not all of t...
Not all the parameters are supported by all the cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to usb cameras to proffesional ones offer a different interface to set its parameters. And there are many branches in OpenCV code to support as man...
Setting Camera Parameters in OpenCV/Python
11,420,748
27
2012-07-10T19:45:04Z
14,510,607
12
2013-01-24T20:57:06Z
[ "python", "opencv", "camera", "python-2.7" ]
I am using OpenCV (2.4) and Python (2.7.3) with a USB camera from Thorlabs (DC1545M). I am doing some image analysis on a video stream and I would like to be able to change some of the camera parameters from my video stream. The confusing thing is that I am able to change some of the camera properties but not all of t...
I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was ``` import time import cv2 cap = cv2.VideoCapture(0) cap.set(3,1280) cap.set(4,1024) time.sleep(2) cap.set(15, -8.0) ``` the time you have to use can be different
Setting Camera Parameters in OpenCV/Python
11,420,748
27
2012-07-10T19:45:04Z
14,776,701
15
2013-02-08T16:09:21Z
[ "python", "opencv", "camera", "python-2.7" ]
I am using OpenCV (2.4) and Python (2.7.3) with a USB camera from Thorlabs (DC1545M). I am doing some image analysis on a video stream and I would like to be able to change some of the camera parameters from my video stream. The confusing thing is that I am able to change some of the camera properties but not all of t...
To avoid using integer values to identify the `VideoCapture` properties, one can use, e.g., `cv2.cv.CV_CAP_PROP_FPS` in OpenCV 2.4 and `cv2.CAP_PROP_FPS` in OpenCV 3.0. (See also Stefan's comment below.) Here a utility function that works for both OpenCV 2.4 and 3.0: ``` # returns OpenCV VideoCapture property id give...
Controlling scheduling priority of python threads?
11,421,651
10
2012-07-10T20:44:32Z
11,422,119
9
2012-07-10T21:18:02Z
[ "python", "multithreading", "threadpool", "scheduling", "nice" ]
I've written a script that uses two thread pools of ten threads each to pull in data from an API. The thread pool implements [this code on ActiveState](http://code.activestate.com/recipes/577187-python-thread-pool/). Each thread pool is monitoring a Redis database via [PubSub](http://redis-py.readthedocs.org/en/latest/...
I believe that threading priority is not controllable in python due to how they are implemented using a global interpreter lock (GIL). Having said that, even if you could give one thread more CPU processing priority, the python implementation that hands around the GIL would not be aware of this as it handed around the ...
Passing variables, creating instances, self, The mechanics and usage of classes: need explanation
11,421,659
13
2012-07-10T20:45:45Z
11,421,962
29
2012-07-10T21:07:50Z
[ "python", "class", "call", "parameter-passing", "instance-variables" ]
I've been sitting over this the whole day and Im a little tired already so please excuse me being brief. Im new to python. I just rewrote a working program, into a bunch of functions in a class and everything messed up. I dont know if it's me but I'm very surprised I couldn't find a beginner's tutorial on how to hand...
``` class Foo (object): # ^class name #^ inherits from object bar = "Bar" #Class attribute. def __init__(self): # #^ The first variable is the class instance in methods. # # This is called "self" by convention, but could be any name you want. #^ double un...
Passing variables, creating instances, self, The mechanics and usage of classes: need explanation
11,421,659
13
2012-07-10T20:45:45Z
11,422,350
12
2012-07-10T21:33:28Z
[ "python", "class", "call", "parameter-passing", "instance-variables" ]
I've been sitting over this the whole day and Im a little tired already so please excuse me being brief. Im new to python. I just rewrote a working program, into a bunch of functions in a class and everything messed up. I dont know if it's me but I'm very surprised I couldn't find a beginner's tutorial on how to hand...
So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customers accounts to be managed by a computer. So you need to model those accounts. Thats where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in...
In python, what the underline parameter mean in function
11,421,997
10
2012-07-10T21:10:20Z
11,422,019
32
2012-07-10T21:11:49Z
[ "python" ]
For example, I read a code: ``` def parse_doc(self, _, doc): ``` What does the underline "\_" mean?
It usually is a place holder for a variable we don't care about. For instance if you have a `for`-loop and you don't care about the value of the index, you can do something like ``` for _ in xrange(10): print "hello World." # just want the message 10 times, no need for index val ``` another example, if a function ...
Django can't find template
11,422,469
4
2012-07-10T21:41:57Z
11,426,082
7
2012-07-11T05:28:16Z
[ "python", "django", "django-templates" ]
I know many people have asked, this question, but despite hardcoding the path to my template directory I can't seem to get Django to find my template. Here is settings.py ``` TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', #django.template.loaders.eg...
I had added in an extra TEMPLATE\_DIR in the settings.py :(
pycharm find where Python function is called
11,422,766
6
2012-07-10T22:07:23Z
11,422,878
8
2012-07-10T22:18:46Z
[ "python", "pycharm" ]
Is there a way for PyCharm to show where a given Python function is called from? I currently rely on simply searching for the function name across the project and this often works fine, but if a function name is vague there are a lot of incorrect hits. I'm wondering if I'm missing a feature somewhere, e.g. perhaps the...
In PyCharm you can select a function and press `Alt`+`Shift`+`F7` to run a usage search. It's also available under "Edit → Find → Find Usages". It looks like it's more intelligent than a text search. Using static analysis to find where a function is called from is difficult in general in Python because it uses dyn...
How to transform a dictionary of strings to lists to a list of dictionaries?
11,423,101
3
2012-07-10T22:43:29Z
11,423,189
8
2012-07-10T22:53:21Z
[ "python", "combinations", "itertools" ]
How can I transform a dictionary of strings to lists to a list of dictionaries that map strings to values in those lists? For example, the following dictionary ``` {'a': [1,2], 'b': ['x', 'y', 'z']} ``` would be transformed into the following list ``` [{'a': 1, 'b': 'x'}, {'a': 1, 'b': 'y'}, {'a': 1, 'b': 'z'}, {'...
The main thing you want here is the product of the values, and then to recreate the dictionaries. We can actually do this easily with the help of [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` >>> from itertools import product >>> test = {'a': [1, 2], 'b': ['x', 'y', 'z']...
Why does my Python3 script balk at piping its output to head or tail (sys module)?
11,423,225
10
2012-07-10T22:57:05Z
11,423,332
8
2012-07-10T23:10:40Z
[ "python", "python-3.x", "pipe" ]
I have a Python3 script that writes its output to stdout, but it complains when I pipe that output into head or tail. Note in the sample output below that it sort of works, in that `head` is returning the first two lines of output as requested. ``` > ./script.py '../Testdata/*indels.ss' -m 5 | head -2 ...
I'll cite from [here](http://www.unixguide.net/unix/bash/E2.shtml): > If a sequence of commands appears in a pipeline, and one of the > > reading commands finishes before the writer has finished, the > > writer receives a SIGPIPE signal. That's what `head` does. Your script hasn't finished writing, but `head` is alre...
Why does my Python3 script balk at piping its output to head or tail (sys module)?
11,423,225
10
2012-07-10T22:57:05Z
11,423,337
12
2012-07-10T23:11:21Z
[ "python", "python-3.x", "pipe" ]
I have a Python3 script that writes its output to stdout, but it complains when I pipe that output into head or tail. Note in the sample output below that it sort of works, in that `head` is returning the first two lines of output as requested. ``` > ./script.py '../Testdata/*indels.ss' -m 5 | head -2 ...
``` ./script.py '../Testdata/*indels.ss' -m 5 | awk 'NR >= 3 {exit} 1' ``` would show the same behavior as `head -2`. You can turn set the `SIGPIPE` handler to one which quietly kills your program instead: ``` import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) ```
Easy way to keep counting up infinitely
11,424,808
4
2012-07-11T02:43:49Z
11,424,819
16
2012-07-11T02:45:14Z
[ "python" ]
What's a good way to keep counting up infinitely? I'm trying to write a condition that will keep going until there's no value in a database, so it's going to iterate from 0, up to theoretically infinity (inside a try block, of course). How would I count upwards infinitely? Or should I use something else? I am looking...
Take a look at [itertools.count()](http://docs.python.org/library/itertools.html#itertools.count). From the docs: > `count(start=0, step=1)` --> count object > > Make an iterator that returns evenly spaced values starting with `n`. > Equivalent to: ``` def count(start=0, step=1): # count(10) --> 10 11 12 13 14 ....
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
11,425,830
261
2012-07-11T05:01:16Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
~~Install [distribute](http://pypi.python.org/pypi/distribute/0.6#installation-instructions), which comes with `egg_info`.~~ Should be as simple as `pip install Distribute`. Distribute has been merged into Setuptools as of version 0.7. If you are using a version <=0.6, upgrade using `pip install --upgrade setuptools`...
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
17,718,187
22
2013-07-18T08:18:28Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
Bear in mind you may have to do `pip install --upgrade Distribute` if you have it installed already and your `pip` may be called `pip2` for Python2 on some systems (it is on mine).
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
18,081,193
47
2013-08-06T13:11:08Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
As distribute has been merged back into setuptools, it is now recommended to install/upgrade setuptools instead: ``` [sudo] pip install --upgrade setuptools ```
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
21,175,750
8
2014-01-17T00:36:37Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
I had this issue, as well as some other issues with Brewed Python on [OS X v10.9](http://en.wikipedia.org/wiki/OS_X_Mavericks) (Mavericks). ``` sudo pip install --upgrade setuptools ``` didn't work for me, and I think my setuptools/distribute setup was botched. I finally got it to work by running ``` sudo easy_inst...
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
23,657,474
11
2014-05-14T14:25:46Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
None of the above worked for me on [Ubuntu 12.04](http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_12.04_LTS_.28Precise_Pangolin.29) LTS (Precise Pangolin), and here's how I fixed it in the end: Download **ez\_setup.py** from <https://pypi.python.org/pypi/setuptools> (see "Installation Instructions" section...
Python pip install fails: invalid command egg_info
11,425,106
160
2012-07-11T03:25:46Z
30,590,000
7
2015-06-02T07:31:53Z
[ "python", "pip" ]
I find that recently often when I try to install a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) package using *[pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29)*, I get the error(s) below. I found a reference online that one has to use "*python2 setup.py install*" from the down...
This error can occur when you trying to install `pycurl`. In this case you should do ``` sudo apt-get install libcurl4-gnutls-dev librtmp-dev ``` (founded here: <https://gist.github.com/lxneng/1031014> )
Django development server reload takes too long
11,426,006
14
2012-07-11T05:22:05Z
27,997,903
8
2015-01-17T09:08:14Z
[ "python", "django" ]
This has been my problem since I've upgraded to OSX Lion: Whenever the runserver reloads when I change a file in my Django project, it takes quite a while before it starts serving again. This happens even in a newly created Django 1.4 project. Didn't have this problem though on Snow Leopard. I used cProfile and this ...
(for guys still googling the answer) I had similar problem using Vagrant (on Windows host machine). Solution for me was move `virtualenv` folder away from synced `/vagrant`. Default settings of synced folders uses VirtualBox provider and that's the problem. We can read about this in another sync methods from [Vagrant ...
Python - match letters of words in a list
11,426,314
2
2012-07-11T05:49:47Z
11,426,343
9
2012-07-11T05:53:06Z
[ "python" ]
I'm trying to create a simple program where a user enters a few letters Enter letters: abc I then want to run through a list of words I have in list and match and words that contain 'a','b', and 'c'. This is what I've tried so far with no luck ``` for word in good_words: #For all words in good words list for le...
If you want `all` the letters inside the word: ``` [word for word in good_words if all(letter in word for letter in letters)] ``` The problem with your code is the `break` inside the inner loop. Python doesn't have a construction to allow breaking more than one loop at once (and you wanted that)
Converting regular expression to finite state machine
11,426,486
3
2012-07-11T06:05:44Z
11,434,134
7
2012-07-11T13:49:20Z
[ "python", "regex", "finite-state-machine", "fsm" ]
would you have a hint at algorithm to convert any regular expression to a finite state machine. For instance, an algorithm parsing a regexp and adding states to the fsm appropriately? Any reference or deeper idea? I am writting this with Python Thanks and regards
Use Michael Sipser's [Introduction to the Theory of Computation](http://rads.stackoverflow.com/amzn/click/053494728X). Chapter 1 gives detailed algorithms for converting a regular expression to a deterministic or non-deterministic finite-state automaton (DFA or NFA), in the context of proving their equivalence (a DFA, ...
Amazon S3 boto - how to delete folder?
11,426,560
16
2012-07-11T06:10:53Z
11,427,712
22
2012-07-11T07:31:21Z
[ "python", "amazon-s3", "boto" ]
I have create a folder in s3, named "test" and I push "test\_1.jpg", "test\_2.jpg" into "test". Now I want to use boto to delete folder "test". What should I do?
There are **no** folders in S3. Instead, the keys form a flat namespace. However a key with slashes in its name shows specially in some programs, including the AWS console (see for example [[Amazon S3 boto - how to create a folder?](http://stackoverflow.com/questions/1939743/amazon-s3-boto-how-to-create-folder][1)]). ...
Amazon S3 boto - how to delete folder?
11,426,560
16
2012-07-11T06:10:53Z
15,949,749
12
2013-04-11T13:13:38Z
[ "python", "amazon-s3", "boto" ]
I have create a folder in s3, named "test" and I push "test\_1.jpg", "test\_2.jpg" into "test". Now I want to use boto to delete folder "test". What should I do?
You can use [bucket.delete\_keys()](http://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.bucket.Bucket.delete_keys) with a list of keys (with a large number of keys I found this to be an order of magnitude faster than using key.delete). Something like this: ``` delete_key_list = [] for key in bucket.list(prefix=...
Python wildcard search in string
11,427,138
24
2012-07-11T06:54:58Z
11,427,183
53
2012-07-11T06:57:55Z
[ "python" ]
Lets say that I have a list ``` list = ['this','is','just','a','test'] ``` how can I have a user do a wildcard search? Search Word: 'th\_s' Would return 'this'
Use [`fnmatch`](http://docs.python.org/library/fnmatch.html): ``` import fnmatch lst = ['this','is','just','a','test'] filtered = fnmatch.filter(lst, 'th?s') ``` If you want to allow `_` as a wildcard, just [replace](http://docs.python.org/library/stdtypes.html#str.replace) all underscores with `'?'` (for one charact...
Python wildcard search in string
11,427,138
24
2012-07-11T06:54:58Z
11,427,220
25
2012-07-11T07:00:59Z
[ "python" ]
Lets say that I have a list ``` list = ['this','is','just','a','test'] ``` how can I have a user do a wildcard search? Search Word: 'th\_s' Would return 'this'
Regular expressions are probably the easiest solution to this problem: ``` import re regex = re.compile('th.s') l = ['this', 'is', 'just', 'a', 'test'] matches = [string for string in l if re.match(regex, string)] ```
Produce a summary ("pivot"?) table
11,428,271
5
2012-07-11T08:10:27Z
11,429,042
8
2012-07-11T08:59:57Z
[ "python", "sqlite" ]
I'd like a way to summarise a database table so that rows sharing a common ID are summarised into one row of output. My tools are SQLite and Python 2.x. For example, given the following table of fruit prices at my local supermarkets... ``` +--------------------+--------------------+--------------------+ |Fruit ...
On python side, you could use some itertools magic for rearranging your data: ``` data = [('Apple', 'Coles', 1.50), ('Apple', 'Woolworths', 1.60), ('Apple', 'IGA', 1.70), ('Banana', 'Coles', 0.50), ('Banana', 'Woolworths', 0.60), ('Banana'...
Produce a summary ("pivot"?) table
11,428,271
5
2012-07-11T08:10:27Z
18,765,503
10
2013-09-12T13:20:15Z
[ "python", "sqlite" ]
I'd like a way to summarise a database table so that rows sharing a common ID are summarised into one row of output. My tools are SQLite and Python 2.x. For example, given the following table of fruit prices at my local supermarkets... ``` +--------------------+--------------------+--------------------+ |Fruit ...
The pandas package can handle this very nicely. ``` >>> import pandas >>> df=pandas.DataFrame(data, columns=['Fruit', 'Shop', 'Price']) >>> df.pivot(index='Fruit', columns='Shop', values='Price') Shop Coles IGA Woolworths Fruit Apple 1.5 1.7 1.6 Banana 0...
Compare values of two arrays in python
11,430,850
4
2012-07-11T10:38:21Z
11,430,994
8
2012-07-11T10:47:12Z
[ "python" ]
How can i check if item in `b` is in `a` and the found match item in `a` should not be use in the next matching? Currently this code will match both 2 in `b`. ``` a = [3,2,5,4] b = [2,4,2] for i in b: if i in a: print "%d is in a" % i ``` This is the required output: ``` 2 => 2 is in a 4 => 4 is in a 2 => ``...
(long post but read it entirely, solution is at the end). Remove the found value or register it in another dict. Better though is to count the number of apparitions inside each array and test how many are common. For the second case, you'd have * for `a`: 3 appears 1 times 2 appears 1 times 5 appears 1 times...
How to find overlapping matches with a regexp?
11,430,863
27
2012-07-11T10:39:16Z
11,430,936
50
2012-07-11T10:44:05Z
[ "python", "regex", "overlapping" ]
``` >>> match = re.findall(r'\w\w', 'hello') >>> print match ['he', 'll'] ``` Since \w\w means two characters, 'he' and 'll' are expected. But why do 'el' and 'lo' **not** match the regex? ``` >>> match1 = re.findall(r'el', 'hello') >>> print match1 ['el'] >>> ```
`findall` doesn't yield overlapping matches by default. This expression does however: ``` >>> re.findall(r'(?=(\w\w))', 'hello') ['he', 'el', 'll', 'lo'] ``` Here `(?=...)` is a [**lookahead assertion**](http://docs.python.org/library/re.html): > `(?=...)` > > Matches if `...` matches next, but doesn’t consume any...
How to find overlapping matches with a regexp?
11,430,863
27
2012-07-11T10:39:16Z
18,966,698
9
2013-09-23T18:54:12Z
[ "python", "regex", "overlapping" ]
``` >>> match = re.findall(r'\w\w', 'hello') >>> print match ['he', 'll'] ``` Since \w\w means two characters, 'he' and 'll' are expected. But why do 'el' and 'lo' **not** match the regex? ``` >>> match1 = re.findall(r'el', 'hello') >>> print match1 ['el'] >>> ```
You can use the [new Python regex module](https://pypi.python.org/pypi/regex), which supports overlapping matches. ``` >>> import regex as re >>> match = re.findall(r'\w\w', 'hello', overlapped=True) >>> print match ['he', 'el', 'll', 'lo'] ```
How can I kill a thread in python
11,431,637
4
2012-07-11T11:27:01Z
11,431,956
8
2012-07-11T11:46:18Z
[ "python", "multithreading" ]
I start a thread using the following code. ``` t = thread.start_new_thread(myfunction) ``` How can I kill the thread `t` from another thread. So basically speaking in terms of code, I want to be able to do something like this. ``` t.kill() ``` Note that I'm using Python 2.4.
If your thread is busy executing Python code, you have a bigger problem than the inability to kill it. The GIL will prevent any other thread from even running whatever instructions you would use to do the killing. (After a bit of research, I've learned that the interpreter periodically releases the GIL, so the precedin...
How can I kill a thread in python
11,431,637
4
2012-07-11T11:27:01Z
15,185,812
8
2013-03-03T12:47:25Z
[ "python", "multithreading" ]
I start a thread using the following code. ``` t = thread.start_new_thread(myfunction) ``` How can I kill the thread `t` from another thread. So basically speaking in terms of code, I want to be able to do something like this. ``` t.kill() ``` Note that I'm using Python 2.4.
In Python, you simply cannot kill a Thread. If you do NOT really need to have a Thread (!), what you can do, instead of using the *threading* package (<http://docs.python.org/2/library/threading.html>), is to use the *multiprocessing* package (<http://docs.python.org/2/library/multiprocessing.html>). Here, to kill a p...
unsupported hash type when installing plone
11,433,108
2
2012-07-11T12:53:24Z
11,434,078
7
2012-07-11T13:46:33Z
[ "python", "plone", "hashlib" ]
I tried to install [plone](http://plone.org/) but I have a problem when I run the script install.sh. Here are the errors details: ``` raise ValueError('unsupported hash type %s' % name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found ValueError: unsupported hash type sha512 ``` ...
This is not a Plone-only problem. Python uses OpenSSL for the [`hashlib` module](http://docs.python.org/library/hashlib.html), and the OpenSSL libraries on your system do not provide functions that it needs. *Normally* the sha256, sha384 and sha512 algorithms are supposed to be present by default but they are not on y...
OpenCV: setting all pixels of specific BGR value to another BGR value
11,433,604
3
2012-07-11T13:20:26Z
11,434,617
9
2012-07-11T14:15:00Z
[ "python", "opencv", "numpy" ]
I am using OpenCV with Python. I have an image, and what I want to do is set all pixels of BGR value [0, 0, 255] to [0, 255, 255]. I asked a [previous question](http://stackoverflow.com/questions/11064454/adobe-photoshop-style-posterization-and-opencv) on how to posterize an image, and from the answer I learned about ...
Consider an image like array as below : ``` >>> red array([[[ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255]], [[ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255], [ 0, 0, 255]]]) ``` Its all ...
Sorting A List Comprehension In One Statement
11,433,886
9
2012-07-11T13:36:50Z
11,433,911
17
2012-07-11T13:38:23Z
[ "python", "list-comprehension" ]
I noticed something I didn't expect when writing a script this morning. I tried to use a list comprehension and sort it all in one statement and got a surprising result. The following code summarizes my general use case, but is simplified for this question: ``` Transaction = namedtuple('Transaction', ['code', 'type'])...
The method `list.sort()` is sorting the list in place, and as all mutating methods it returns `None`. Use the built-in function [`sorted()`](http://docs.python.org/library/functions.html#sorted) to return a new sorted list. ``` result = sorted((trans for trans in my_list if trans.type in types), key=la...
How can I transform a tuple subclass made by namedtuple to tuple itself?
11,434,026
2
2012-07-11T13:44:26Z
11,434,151
7
2012-07-11T13:50:10Z
[ "python", "tuples", "namedtuple" ]
I'm using python while some method requires tuple as its argument. Although instance created by namedtuple is tuple subclass, but it seems that I still need to transform it to tuple. Is there any way to transform the tuple subclass made by namedtuple to tuple quickly? Thanks!
A `namedtuple` instance `x` can be converted to a tuple using `tuple(x)`, but you shouldn't need to do so. If some code only accepts tuples, but no `namedtuple`s, I consider that code broken. (There *may* be special cases that require such a behaviour, but I can't think of any right now.)
Django admin page doesn't show tables of database (djangobook chapter 06)
11,434,239
6
2012-07-11T13:54:24Z
11,434,337
15
2012-07-11T13:59:15Z
[ "python", "mysql", "database", "django", "django-admin" ]
I am doing the [`Activating the Admin Interface`](http://django-book.readthedocs.org/en/latest/chapter06.html#activating-the-admin-interface) part in djangobook chapter 06. At the end of that part one has to run the development server and go to `http://127.0.0.1:8000/admin/`. However I see this: ![My Django admin page...
You need to keep reading <http://django-book.readthedocs.org/en/latest/chapter06.html#adding-your-models-to-the-admin-site> > There’s one crucial part we haven’t done yet... > Within the books directory (mysite/books), create a file called > admin.py, and type in the following lines of code: ``` from django.con...
Tick-labels to span over multiple lines
11,434,389
6
2012-07-11T14:02:17Z
11,434,552
7
2012-07-11T14:11:29Z
[ "python", "matplotlib" ]
Is it possible to make the x-tick labels span over two lines? Say, if my x-tick labels are ``` January 2008, February 2008, March 2008 ``` I want them as ``` January February March 2008 2008 2008 ``` I don't want to rotate them.
After a quick test using the code I found [here](http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo2.html), it appears that it does indeed work if you just add a newline in your tick label. e.g. ``` mytics=['January\n2008', 'February\n2008', 'March\n2008'] ```
Is there a good way to produce documentation for swig interfaces?
11,435,102
6
2012-07-11T14:38:19Z
26,035,360
7
2014-09-25T09:43:24Z
[ "python", "swig" ]
I'd like to know if there are any good techniques for constructing/maintaining documentation on the interface. I'm building an interface from c++ code to python using swig; mostly I'm just %including the c++ header files. I'm dealing with at least dozens of classes and 100's of functions, so automated tools are prefer...
To get your doxygen comments into the python files there exists a python tool called doxy2swig.py on the web as described [here](http://www.enricozini.org/2007/tips/swig-doxygen-docstring/). Create xml documentation from your code. Then use the tool: > doxy2swig.py index.xml documentation.i and import documentation....
python operator, no operator for "not in"
11,435,206
15
2012-07-11T14:43:49Z
11,435,319
12
2012-07-11T14:48:53Z
[ "python", "performance", "indexing" ]
This is a possibly silly question, but looking at [the mapping of operators to functions](http://docs.python.org/library/operator.html#mapping-operators-to-functions) I noticed that there is no function to express the `not in` operator. At first I thought this was probably because the interpreter just reorders this to ...
Another function is not necessary here. `not in` is the inverse of `in`, so you have the following mappings: ``` obj in seq => contains(seq, obj) obj not in seq => not contains(seq, obj) ``` You are right this is not consistent with `is`/`is not`, since identity tests should be symmetrical. This might be a design ar...
Python Requests and Unicode
11,435,331
14
2012-07-11T14:49:50Z
11,435,633
9
2012-07-11T15:04:39Z
[ "python", "unicode", "python-requests" ]
I am using the requests library to query the Diffbot API to get contents of an article from a web page url. When I visit a request URL that I create in my browser, it returns a JSON object with the text in Unicode (right?) for example (I shortended the text somewhat): > {"icon":"http://mexico.cnn.com/images/ico\_mobil...
Concerning the "I don't quite understand unicode", there's an [entertaining primer](http://www.joelonsoftware.com/articles/Unicode.html) on Unicode by Joel Spolsky and the official [Python Unicode HowTo](http://docs.python.org/howto/unicode.html) which is a 10 minute read and covers everything Python specific. The [re...
Python Requests and Unicode
11,435,331
14
2012-07-11T14:49:50Z
12,843,406
21
2012-10-11T15:39:45Z
[ "python", "unicode", "python-requests" ]
I am using the requests library to query the Diffbot API to get contents of an article from a web page url. When I visit a request URL that I create in my browser, it returns a JSON object with the text in Unicode (right?) for example (I shortended the text somewhat): > {"icon":"http://mexico.cnn.com/images/ico\_mobil...
You can use `req.text` instead of `req.content` to ensure that you get Unicode. The methods are described in: <http://docs.python-requests.org/en/latest/api/#main-interface>
How can I associate dictionary keys with functions?
11,435,720
3
2012-07-11T15:09:10Z
11,435,741
12
2012-07-11T15:10:18Z
[ "python", "dictionary" ]
My application has a class full of functions that perform various operations. These operations are related to 1 and only 1 dictionary key. How can I associate the dictionary key with its respective function? The goal of the tool will be for it to use the appropriate set of functions when given a set of keys. This is h...
``` myDict["Objective A"] = MyClass.FuncA() ``` associates the return value of `MyClass.FuncA`. If you want to associate the function itself: ``` myDict["Objective A"] = MyClass.FuncA myDict["Objective B"] = MyClass.FuncB ``` Then you can call it directly: ``` myDict["Objective A"]() ```
Compute divergence of vector field using python
11,435,809
5
2012-07-11T15:14:02Z
19,025,147
9
2013-09-26T10:00:22Z
[ "python", "numpy", "scipy" ]
Is there a function that could be used for calculation of the divergence of the vectorial field? (in [matlab](http://www.mathworks.ch/help/techdoc/ref/divergence.html)) I would expect it exists in numpy/scipy but I can not find it using Google. I need to calculate `div[A * grad(F)]`, where ``` F = np.array([[1,2,3,4]...
``` import numpy as np def divergence(field): "return the divergence of a n-D field" return np.sum(np.gradient(field),axis=0) ```
Compute divergence of vector field using python
11,435,809
5
2012-07-11T15:14:02Z
21,134,289
10
2014-01-15T10:01:59Z
[ "python", "numpy", "scipy" ]
Is there a function that could be used for calculation of the divergence of the vectorial field? (in [matlab](http://www.mathworks.ch/help/techdoc/ref/divergence.html)) I would expect it exists in numpy/scipy but I can not find it using Google. I need to calculate `div[A * grad(F)]`, where ``` F = np.array([[1,2,3,4]...
The answer of @user2818943 is good, but it can be optimized a little: ``` def divergence(F): """ compute the divergence of n-D scalar field `F` """ return reduce(np.add,np.gradient(F)) ``` --- Timeit: ``` F = np.random.rand(100,100) timeit reduce(np.add,np.gradient(F)) # 1000 loops, best of 3: 318 us per lo...
Closing all threads with a keyboard interrupt
11,436,502
21
2012-07-11T15:49:25Z
11,436,603
32
2012-07-11T15:54:45Z
[ "python", "multithreading" ]
What I'm trying to do here is use a keyboard interrupt to exit all ongoing threads in the program. This is a pared down version of my code where the thread is created: ``` for i in taskDictionary: try: sleep(60) thread = Thread(target = mainModule.executeThread) thread.start() except Ke...
A similar question is "How do you kill a thread?" You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thre...
Is there a way to embed dependencies within a python script?
11,436,777
14
2012-07-11T16:05:25Z
11,437,413
7
2012-07-11T16:43:53Z
[ "python" ]
I have a simple script that has a dependency on [dnspython](http://pypi.python.org/pypi/dnspython/) for parsing zone files. I would like to distribute this script as a single .py that users can run just so long as they have 2.6/2.7 installed. I don't want to have the user install dependencies site-wide as there might b...
You can package multiple Python files up into a .egg. Egg files are essentially just zip archives with well defined metadata - look at the setuptools documentation to see how to do this. Per the [docs](http://peak.telecommunity.com/DevCenter/setuptools#eggsecutable-scripts) you can make egg files directly executable by...
Python: replace nonbreaking space in Unicode
11,436,897
4
2012-07-11T16:12:49Z
11,436,976
10
2012-07-11T16:17:16Z
[ "python", "unicode" ]
In Python, I have a text that is Unicode-encoded. This text contains non-breaking spaces, which I want to convert to 'x'. Non-breaking spaces are equal to `chr(160)`. I have the following code, which works great when I run it as Django via Eclipse using Localhost. No errors and any non-breaking spaces are converted. `...
1. In Python 2, `chr(160)` is a byte string of length one whose only byte has value 160, or hex a0. There's no meaning attached to it except in the context of a specific encoding. 2. I'm not familiar with Eclipse, but it may be playing encoding tricks of its own. 3. If you want the Unicode character `NO-BREAK SPACE`, i...
Use method other than __unicode__ in ModelChoiceField Django
11,437,060
6
2012-07-11T16:22:25Z
11,437,294
10
2012-07-11T16:36:37Z
[ "python", "django", "forms", "django-forms", "django-queryset" ]
I'm working on some forms in Django. One field is a `ForeignKey` in the model, so represented as a `ModelChoiceField` in the form. The `ModelChoiceField` currently uses the `__unicode__` method of the model to populate the list, which isn't my desired behavior. I'd like to be able to use another method of the model. Fr...
You can override `label_from_instance` to specify a different method: ``` from django.forms.models import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.my_custom_method() ``` You can then use this field in your form instead. This method is in...
python sterling's approximation program
11,437,700
3
2012-07-11T17:00:15Z
11,437,772
9
2012-07-11T17:05:18Z
[ "python", "python-2.7" ]
I'm trying to write a simple program that prints the first [Stirling's approximation](http://en.wikipedia.org/wiki/Stirling%27s_approximation) for the integers 1:10 alongside the actual value of 1:10 factorial. This is my code: ``` import math nf =1 def stirling(n): return math.sqrt(2*math.pi*n)*(n/math.e)**n ...
(1) You need to reset `nf=1` each time you compute the factorial (or, alternatively, only multiply by one new number each time, which would be more efficient); (2) `range(1,x)` doesn't include x, so your factorials won't include the right upper bound. The following should work: ``` nf = 1 for x in range (1,11): n...
Many-to-many multi-database join with Flask-SQLAlchemy
11,438,352
4
2012-07-11T17:41:56Z
11,439,453
9
2012-07-11T18:52:58Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I'm trying to make this many-to-many join work with Flask-SQLAlchemy and two MySQL databases, and it's very close except it's using the wrong database for the join table. Here's the basics... I've got `main_db` and `vendor_db`. The tables are setup as `main_db.users`, `main_db.user_products` (the relation table), and ...
Turns out what I needed to do here was specify the schema in my `user_products_tbl` table definition. So, ``` user_products_tbl = db.Table('user_products', db.metadata, db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('product_id', db.Integer, db.ForeignKey('products.product_...
Django - Import views from separate apps
11,439,447
4
2012-07-11T18:52:13Z
11,439,505
9
2012-07-11T18:56:03Z
[ "python", "django" ]
I'm new to Django and working my way through "The Django Book" by Holovaty and Kaplan-Moss. I have a project called "mysite" that contains two applications called "books" and "contact." Each has its own view.py file. In my urls.py file I have the following: ``` from books import views from contact import views ... url...
**Disclaimer:** Not a Django answer The problem is with these two lines: ``` from books import views from contact import views ``` The second import is shadowing the first one, so when you use `views` later you're only using the `views` from `contact`. One solution might be to just: ``` import books import contact...
Geany unable to execute Python
11,439,607
3
2012-07-11T19:01:31Z
11,439,651
10
2012-07-11T19:04:38Z
[ "python", "windows-7", "geany" ]
I'm not a great coder, in fact I'm just trying to learn, but I can't get Geany to regonise Python in my system (Windows 7) when I try to execute the program. When I click Execute, it opens a command prompt saying: > 'python' is not recognized as an internal or external command, operable program or batch file How can ...
Add the Python executable to your PATH. For example, I have Python installed at: ``` C:\Program Files\Python 3.2 ``` So press `Win` + `Pause/Break`, and go to "Advanced System Settings": ![System settings](https://i.stack.imgur.com/e23jt.png) Click "Environment Variables" at the bottom, add a new user variable call...
How can I save a LibSVM python object instance?
11,440,970
3
2012-07-11T20:29:43Z
11,483,921
9
2012-07-14T12:54:04Z
[ "python", "svm", "libsvm", "pickle" ]
I wanted to use this classifier in other computer without had to train it again. I used to save some classifiers from scikit with cPickle. Doing the same with LIBSVM it gives me a " ValueError: ctypes objects containing pointers cannot be pickled ". I'm using LibSVM 3.1 and Python 2.7.3. Thanks ``` from libsvm.svm i...
Just use libsvm's load and save functions ``` svm_save_model('libsvm.model', m) m = svm_load_model('libsvm.model') ``` This is from the README file included in the python directory of the libsvm package. It seems to have a much better description of features than the website.