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
drop table in python with sqlite3
2,060,032
7
2010-01-13T20:33:44Z
2,060,099
7
2010-01-13T20:43:49Z
[ "python", "sqlite" ]
I have question about python and sqlite3. I want to drop a table from within Python. The command ``` cur.execute('drop table if exists tab1') ``` Does not work. ``` cur.executescript('drop table if exists tab1;') ``` does the job. The execute method allows the creation of tables. However, it won't drop them? Is th...
The `cur.executescript` command issues a `COMMIT` before running the provided script. Additionally a `CREATE` executes a `COMMIT` intrinsically. Perhaps you have an open transaction that needs committed before your changes take place.
Draw a colored sphere from cartesian coordinates in pymol
2,060,582
5
2010-01-13T21:57:19Z
2,075,684
7
2010-01-16T00:35:25Z
[ "python", "visualization", "bioinformatics" ]
I was looking in the wiki how to convert the following information about beads, cartesian coordinates + energy : 23.4 54.6 12.3 -123.5 54.5 23.1 9.45 -56.7 ....... to a draw in pymol that contains for each atom a sphere of radius R, centered on its coordinates, and with color, in a rainbow gradient. Thanks
Does what you're rendering actually have anything to do with molecular structure (i.e. what is the motivation for using PyMol)? If you are drawing some molecular structure, I would recommend just outputting a custom PDB file with the sphere coordinates (you can use the B-factor field per ATOM line as a way of controll...
Reading *.wav files in Python
2,060,628
32
2010-01-13T22:03:28Z
2,061,184
36
2010-01-13T23:44:48Z
[ "python", "audio", "wav", "wave" ]
I need to analyze sound written in a .wav file. For that I need to transform this file into set of numbers (arrays, for example). I think I need to use the wave package. However, I do not know how exactly it works. For example I did the following: ``` import wave w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', ...
Per [the sources](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.read.html), `scipy.io.wavfile.read(somefile)` returns a tuple of two items: the first is the sampling rate in samples per second, the second is a `numpy` array with all the data read from the file. Looks pretty easy to use!
Reading *.wav files in Python
2,060,628
32
2010-01-13T22:03:28Z
5,281,240
36
2011-03-12T07:21:08Z
[ "python", "audio", "wav", "wave" ]
I need to analyze sound written in a .wav file. For that I need to transform this file into set of numbers (arrays, for example). I think I need to use the wave package. However, I do not know how exactly it works. For example I did the following: ``` import wave w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', ...
I did some research this evening and figured this out: ``` import wave, struct waveFile = wave.open('sine.wav', 'r') length = waveFile.getnframes() for i in range(0,length): waveData = waveFile.readframes(1) data = struct.unpack("<h", waveData) print(int(data[0])) ``` Hopefully this snippet helps someon...
Subclassing Python dictionary to override __setitem__
2,060,972
31
2010-01-13T23:01:58Z
2,588,648
36
2010-04-06T21:57:52Z
[ "python", "dictionary", "subclass" ]
I am building a class which subclasses `dict`, and overrides `__setitem__`. I would like to be certain that my method will be called in all instances where dictionary items could possibly be set. I have discovered three situations where Python (in this case, 2.6.4) does not call my overridden `__setitem__` method when...
I'm answering my own question, since I eventually decided that I really *do* want to subclass Dict, rather than creating a new mapping class, and UserDict still defers to the underlying Dict object in some cases, rather than using the provided `__setitem__`. After reading and re-reading the Python 2.6.4 source (mostly...
What is the true difference between a dictionary and a hash table?
2,061,222
21
2010-01-13T23:53:47Z
2,061,248
20
2010-01-13T23:57:27Z
[ "python", "data-structures", "hash", "dictionary", "hashtable" ]
I've always used dictionaries. I write in Python.
A dictionary is a data structure that maps keys to values. A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values are stored. IMO this is analogous to asking the difference between a lis...
What is the true difference between a dictionary and a hash table?
2,061,222
21
2010-01-13T23:53:47Z
2,061,273
12
2010-01-14T00:01:41Z
[ "python", "data-structures", "hash", "dictionary", "hashtable" ]
I've always used dictionaries. I write in Python.
"A dictionary" has a few different meanings in programming, as [wikipedia](http://en.wikipedia.org/wiki/Dictionary_%28disambiguation%29) will tell you -- "associative array", the sense in which Python uses the term (also known as "a mapping"), is one of those meanings (but "data dictionary", and "dictionary attacks" in...
What is the true difference between a dictionary and a hash table?
2,061,222
21
2010-01-13T23:53:47Z
2,061,406
87
2010-01-14T00:29:15Z
[ "python", "data-structures", "hash", "dictionary", "hashtable" ]
I've always used dictionaries. I write in Python.
A dictionary is a general concept that maps keys to values. There are many ways to implement such a mapping. A hashtable is a specific way to implement a dictionary. Besides hashtables, another common way to implement dictionaries is [red-black trees](http://en.wikipedia.org/wiki/Red-black_tree). Each method has it'...
Filter array to show rows with a specific value in a specific column
2,062,368
5
2010-01-14T05:32:43Z
2,062,399
10
2010-01-14T05:39:19Z
[ "python", "list" ]
Let's say i have a multidimensional list l: ``` l = [['a', 1],['b', 2],['c', 3],['a', 4]] ``` and I want to return another list consisting only of the rows that has 'a' in their first list element: ``` m = [['a', 1],['a', 4]] ``` What's a good and efficient way of doing this?
Definitely a case for a list comprehension: ``` m = [row for row in l if 'a' in row[0]] ``` Here I'm taking your "having 'a' **in** the first element" literally, whence the use of the `in` operator. If you want to restrict this to "having 'a' **as** the first element" (a very different thing from what you actually wr...
How to use "class" the word as parameter function calls in python
2,062,683
3
2010-01-14T07:08:01Z
2,062,746
7
2010-01-14T07:29:09Z
[ "python", "elementtree" ]
I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer. The result XML require attributes named "class". e.g. ``` <Node class="oops"></Node> ``` As the official tutorial suggested, to write an XML node just use this method: ...
I guess SimpleXMLWriter developers meant this solution: ``` w.element("Node", None, {'class': 'oops'}) ``` or ``` w.element("Node", attrib={'class': 'oops'}) ```
Comments (#) go to start of line in the insert mode in Vim
2,063,175
44
2010-01-14T09:24:05Z
2,064,155
7
2010-01-14T12:58:32Z
[ "python", "vim", "comments", "indentation" ]
Whenever I want to add a comment to an indented line in vim, I hit `Shift`-`o` (open a new row above the current, switch to insert mode) and start typing a Python comment (using `#`). That hash is then magically moved to the start of the line (no indentation) and I have to click tab a few times. Anyone know how to wor...
try putting that in your .vimrc: ``` autocmd BufRead *.py inoremap # X<c-h># ``` This will make that the insertion of the hash (pound) sign is always indented in Python source files.
Comments (#) go to start of line in the insert mode in Vim
2,063,175
44
2010-01-14T09:24:05Z
2,064,318
43
2010-01-14T13:26:45Z
[ "python", "vim", "comments", "indentation" ]
Whenever I want to add a comment to an indented line in vim, I hit `Shift`-`o` (open a new row above the current, switch to insert mode) and start typing a Python comment (using `#`). That hash is then magically moved to the start of the line (no indentation) and I have to click tab a few times. Anyone know how to wor...
I suppose you have `set smartindent` in your .vimrc See `:h smartindent` ``` When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this mapping: ":inoremap # X^H#", where ^H...
Trying to open a serial port with pyserial on WinXP -> "Access denied"
2,063,257
3
2010-01-14T09:44:51Z
2,063,271
9
2010-01-14T09:49:00Z
[ "python", "serial-port", "access-denied", "windows-xp", "pyserial" ]
I'm trying to send data to an hplc pump via the serial port using python and pyserial. I tested the cable and the pump under linux (a gentoo derivative), where it worked perfectly, albeit as root. Now i have to use the code on a WinXP machine, where i always get an "Access denied" error when trying to open the port (i ...
Try opening the port as `\\.\COMxx` Also make sure that the port isn't already open from another application. I recommend that you use Hyperterminal to see if the port is open.
Trying to open a serial port with pyserial on WinXP -> "Access denied"
2,063,257
3
2010-01-14T09:44:51Z
2,256,136
7
2010-02-13T01:28:42Z
[ "python", "serial-port", "access-denied", "windows-xp", "pyserial" ]
I'm trying to send data to an hplc pump via the serial port using python and pyserial. I tested the cable and the pump under linux (a gentoo derivative), where it worked perfectly, albeit as root. Now i have to use the code on a WinXP machine, where i always get an "Access denied" error when trying to open the port (i ...
.close() before I called the .open() worked for me as well
XML parsing with lxml and Python
2,063,274
6
2010-01-14T09:49:56Z
2,063,673
12
2010-01-14T11:17:20Z
[ "python", "lxml" ]
Please help me to resolve my problem with lxml (I'm a newbie to lxml). How can I get "Comment 1" from the next file: ``` <?xml version="1.0" encoding="windows-1251" standalone="yes" ?> <!--Comment 1--> <a> <!--Comment 2--> </a> ```
Docs: [the lxml tutorial](http://lxml.de/tutorial.html), and search for "Comments" Code: ``` import lxml.etree as et text = """\ <?xml version="1.0" encoding="windows-1251" standalone="yes" ?> <!--Comment 1a--> <!--Comment 1b--> <a> waffle <!--Comment 2--> blah blah </a> <!--Comment 3a--> <!--Comment 3b--> """...
What is the easiest way to read wav-files using Python [summary]?
2,063,284
7
2010-01-14T09:51:35Z
2,602,334
8
2010-04-08T18:05:21Z
[ "python", "audio", "wav", "scipy", "wave" ]
I want to use Python to access a wav-file and write its content in a form which allows me to analyze it (let's say arrays). 1. I heard that "audiolab" is a suitable tool for that (it transforms numpy arrays into wav and vica versa). 2. I have installed the "audiolab" but I had a problem with the version of numpy (I co...
Have you tried the wave module? It has fewer dependencies: <http://docs.python.org/library/wave.html> ``` def everyOther (v, offset=0): return [v[i] for i in range(offset, len(v), 2)] def wavLoad (fname): wav = wave.open (fname, "r") (nchannels, sampwidth, framerate, nframes, comptype, compname) = wav.getpa...
Python elegant inverse function of int(string,base)
2,063,425
32
2010-01-14T10:28:03Z
2,063,535
9
2010-01-14T10:48:34Z
[ "python" ]
python allows conversions from string to integer using any base in the range [2,36] using: ``` int(string,base) ``` im looking for an elegant inverse function that takes an integer and a base and returns a string for example ``` >>> str_base(224,15) 'ee' ``` i have the following solution: ``` def digit_to_char(di...
[This thread](http://code.activestate.com/recipes/65212/) has some example implementations. Actually I think your solution looks rather nice, it's even recursive which is somehow pleasing here. I'd still simplify it to remove the `else`, but that's probably a personal style thing. I think `if foo: return` is very cle...
Python elegant inverse function of int(string,base)
2,063,425
32
2010-01-14T10:28:03Z
15,140,779
16
2013-02-28T16:35:07Z
[ "python" ]
python allows conversions from string to integer using any base in the range [2,36] using: ``` int(string,base) ``` im looking for an elegant inverse function that takes an integer and a base and returns a string for example ``` >>> str_base(224,15) 'ee' ``` i have the following solution: ``` def digit_to_char(di...
Maybe this shouldn't be an answer, but it could be helpful for some: the built-in [`format`](http://docs.python.org/2/library/string.html#format-specification-mini-language) function does convert numbers to string in a few bases: ``` >>> format(255, 'b') # base 2 '11111111' >>> format(255, 'd') # base 10 '255' >>> for...
Python elegant inverse function of int(string,base)
2,063,425
32
2010-01-14T10:28:03Z
23,926,613
8
2014-05-29T05:54:59Z
[ "python" ]
python allows conversions from string to integer using any base in the range [2,36] using: ``` int(string,base) ``` im looking for an elegant inverse function that takes an integer and a base and returns a string for example ``` >>> str_base(224,15) 'ee' ``` i have the following solution: ``` def digit_to_char(di...
If you use Numpy, there is `numpy.base_repr`. You can read the code under `numpy/core/numeric.py`. Short and elegant
Find system folder locations in Python
2,063,508
8
2010-01-14T10:44:07Z
2,063,795
8
2010-01-14T11:46:33Z
[ "python", "windows", "path", "special-folders" ]
I am trying to find out the location of system folders with Python 3.1. For example "My Documents" = "C:\Documents and Settings\User\My Documents", "Program Files" = "C:\Program Files" etc etc.
I found [a slightly different way of doing it](http://mail.python.org/pipermail/python-win32/2005-September/003738.html). This way will give you the location of various system folders and uses real words instead of CLSIDs. ``` import win32com.client objShell = win32com.client.Dispatch("WScript.Shell") allUserDocs = ob...
What is returned by wave.readframes?
2,063,565
9
2010-01-14T10:54:25Z
2,063,590
7
2010-01-14T10:58:07Z
[ "python", "wave" ]
I assign a value to a variable `x` in the following way: ``` import wave w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', 'r') x = w.readframes(1) ``` When I type x I get: ``` '\x1e\x00' ``` So `x` got a value. But what is that? Is it hexadecimal? `type(x)` and `type(x[0])` tell me that `x` and `x[0]` a strin...
The interactive interpreter echoes unprintable characters like that. The string contains two bytes, 0x1E and 0x00. You can convert it to an (WORD-size) integer with `struct.unpack("<H", x)` (little endian!).
Using SUDS to test WSDL
2,063,720
5
2010-01-14T11:27:58Z
2,063,758
14
2010-01-14T11:36:40Z
[ "python", "soap", "suds" ]
Does anyone know about a good SUDS tutorial. I am trying to run tests on WSDL files and I am having trouble finding any imformation on how to do this. Is SUDS much different to SOAPy and would anyone recommend it to run smoke tests on functions stored in WSDL files. I have read that SOAPAy is no longer supported in Py...
Suds is very simple to use. ``` from suds.client import Client client = Client("http://example.com/foo.wsdl") client.service.someMethod(someParameter) ``` `someMethod` is the name of a method as described in the WSDL.
How should Django Apps bundle static media?
2,063,923
13
2010-01-14T12:15:55Z
2,065,389
9
2010-01-14T15:49:56Z
[ "python", "django", "web-applications" ]
**Background:** I'm starting to use Django for the first time, which is also my first foray into web development. I just got stuck on the whole "serving static media" problem. After spending a while looking at all the documentation and StackOverflow questions, I think I understand how it's supposed to work (i.e. MEDIA...
Convention is to put static media in either media/appname/ or static/appname/ within the app (similar to templates). For using apps in your project that come with media, I strongly recommend using [django-staticfiles](http://pypi.python.org/pypi/django-staticfiles). It will automatically serve media (including media w...
Remove lines from textfile with python
2,064,184
10
2010-01-14T13:04:03Z
2,064,238
27
2010-01-14T13:11:48Z
[ "python" ]
I have a textfile.txt like this: ``` First Line Second Line Third Line Fourth Line Fifth Line Sixth Line ``` How can I remove the first three lines and the last line most comfortable? Thanks!
``` lines = open('textfile.txt').readlines() open('newfile.txt', 'w').writelines(lines[3:-1]) ```
Remove lines from textfile with python
2,064,184
10
2010-01-14T13:04:03Z
2,064,437
7
2010-01-14T13:44:47Z
[ "python" ]
I have a textfile.txt like this: ``` First Line Second Line Third Line Fourth Line Fifth Line Sixth Line ``` How can I remove the first three lines and the last line most comfortable? Thanks!
This one doesn't use readlines() so it is ideal for bigger sized files. ``` numline=3 #3 lines to skip p="" o=open("output.txt","a") f=open("file") for i in range(numline): f.next() for line in f: if p: o.write(p) p=line f.close() o.close() ``` Since there's a sed answer, here's an awk one ``` $ ...
private members in python
2,064,202
32
2010-01-14T13:06:19Z
2,064,212
38
2010-01-14T13:08:13Z
[ "python", "oop", "class" ]
How can I make methods and data members private in Python? Or doesn't python support private members?
> [**9.6. Private Variables**](http://docs.python.org/tutorial/classes.html#private-variables-and-class-local-references) > > “Private” instance variables that > cannot be accessed except from inside > an object, don’t exist in Python. > However, there is a convention that is > followed by most Python code: a nam...
private members in python
2,064,202
32
2010-01-14T13:06:19Z
2,064,400
23
2010-01-14T13:39:09Z
[ "python", "oop", "class" ]
How can I make methods and data members private in Python? Or doesn't python support private members?
The other answers provide the technical details. I'd like to emphasise the difference in philosophy between Python on one hand and languages like C++/Java (which I presume you're familiar with based on your question). The general attitude in Python (and Perl for that matter) is that the 'privacy' of an attribute is a ...
Why python does not allow hyphens
2,064,329
10
2010-01-14T13:27:44Z
2,064,358
29
2010-01-14T13:32:14Z
[ "python" ]
I have always wondered why can't we use hyphens in between function names and variable names in python Having tried functional programming languages like Lisp and Clojure, where hyphens are allowed. Why python doesn't do that. ``` # This won't work -- SyntaxError def is-even(num): return num % 2 # This will work...
Because hyphen is used as the subtraction operator. Imagine that you *could* have an `is-even` function, and then you had code like this: ``` my_var = is-even(another_var) ``` Is `is-even(another_var)` a call to the function `is-even`, or is it subtracting the result of the function `even` from a variable named `is`?...
Why python does not allow hyphens
2,064,329
10
2010-01-14T13:27:44Z
2,064,376
8
2010-01-14T13:35:08Z
[ "python" ]
I have always wondered why can't we use hyphens in between function names and variable names in python Having tried functional programming languages like Lisp and Clojure, where hyphens are allowed. Why python doesn't do that. ``` # This won't work -- SyntaxError def is-even(num): return num % 2 # This will work...
Because Python uses infix notation to represent calculations and a hyphen and a minus has the exact same ascii code. You can have ambiguous cases such as: ``` a-b = 10 a = 1 b = 1 c = a-b ``` What is the answer? 0 or 10?
Python not all in operation
2,064,389
3
2010-01-14T13:37:39Z
2,064,404
12
2010-01-14T13:39:46Z
[ "python", "set" ]
How do I check if a list is a subset of a bigger list. i.e. `a = [1,2,3]` is a subset of `b = [1,2,3,4,5,6]` Can I do something like ``` if a all in b ```
<http://docs.python.org/library/stdtypes.html#set.issubset> ``` set(a).issubset(set(b)) ```
Jinja-like for Pdf in Python
2,064,936
11
2010-01-14T14:56:04Z
2,066,042
9
2010-01-14T17:16:59Z
[ "python", "pdf-generation", "jinja2" ]
I am looking for the best accurate tool for PDF in Python that works like Jinja does for HTML. What are your suggestions?
As answered by jbochi, ReportLab is the foundation for almost all Python projects that generate PDF. But for your needs you might want to check out [Pisa / xhtml2pdf](http://www.xhtml2pdf.com/). You would generate your HTML with a Jinja template and then use Pisa to convert the HTML to PDF. Pisa is built on top of Rep...
Get all numbers that add up to a number
2,065,553
11
2010-01-14T16:12:49Z
2,065,576
14
2010-01-14T16:15:42Z
[ "python", "math" ]
I'm trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have: ``` 1, 4 2, 3 ``` Or for 3 integers that make 6: ``` 1, 1, 4 1, 2, 3 2, 2, 2 ``` I only need whole numbers not including 0 and it only needs to work...
<http://en.wikipedia.org/wiki/Partition_(number_theory)> <http://mathworld.wolfram.com/Partition.html> <http://code.activestate.com/recipes/218332/>
Get all numbers that add up to a number
2,065,553
11
2010-01-14T16:12:49Z
2,074,693
8
2010-01-15T20:49:59Z
[ "python", "math" ]
I'm trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have: ``` 1, 4 2, 3 ``` Or for 3 integers that make 6: ``` 1, 1, 4 1, 2, 3 2, 2, 2 ``` I only need whole numbers not including 0 and it only needs to work...
Here is one way to solve this problem: ``` def sum_to_n(n, size, limit=None): """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = n start = (n + size - 1) // size stop = min(...
A clean algorithm for sorting a objects according to defined dependencies?
2,065,897
5
2010-01-14T16:58:01Z
2,065,910
8
2010-01-14T16:59:19Z
[ "python", "algorithm", "order" ]
Given a list of classes inheriting from this base: ``` class Plugin(object): run_after_plugins = () run_before_plugins = () ``` ...and the following rules: * Plugins can provide a list of plugins that they must run after. * Plugins can provide a list of plugins that they must run before. * The list of plugin...
This is called [topological sorting](http://en.wikipedia.org/wiki/Topological_sorting). > The canonical application of > topological sorting (topological > order) is in scheduling a sequence of > jobs or tasks; topological sorting > algorithms were first studied in the > early 1960s in the context of the PERT > techni...
What permissions are required for subprocess.Popen?
2,066,068
8
2010-01-14T17:20:14Z
2,088,273
11
2010-01-18T18:30:47Z
[ "python", "osx", "subprocess", "popen" ]
The following code: ``` gb = self.request.form['groupby'] typ = self.request.form['type'] tbl = self.request.form['table'] primary = self.request.form.get('primary', None) if primary is not None: create = False else: create = True mdb = tempfile.NamedTemporaryFile() mdb.write(self.request.form['mdb'].read()) md...
Assuming that permissions on parent folders are correct (i.e. all parent folders should have +x permission), try adding: ``` shell=True ``` to the Popen command such as: ``` subprocess.Popen(("/Users/jondoe/development/mdb-export", mdb.name, tbl,), stdout=csv, shell=True) ```
Python - test a property throws exception
2,066,179
8
2010-01-14T17:38:10Z
2,066,214
11
2010-01-14T17:43:43Z
[ "python", "unit-testing", "properties", "ironpython" ]
Given: ``` def test_to_check_exception_is_thrown(self): # Arrange c = Class() # Act and Assert self.assertRaises(NameError, c.do_something) ``` If `do_something` throws an exception the test passes. But I have a property, and when I replace `c.do_something` with `c.name = "Name"` I get an error about...
`assertRaises` expects a callable object. You can create a function and pass it: ``` obj = Class() def setNameTest(): obj.name = "Name" self.assertRaises(NameError, setNameTest) ``` Another possibility is to use `setattr`: ``` self.assertRaises(NameError, setattr, obj, "name", "Name") ``` Your original ...
Python - test a property throws exception
2,066,179
8
2010-01-14T17:38:10Z
2,066,236
8
2010-01-14T17:46:57Z
[ "python", "unit-testing", "properties", "ironpython" ]
Given: ``` def test_to_check_exception_is_thrown(self): # Arrange c = Class() # Act and Assert self.assertRaises(NameError, c.do_something) ``` If `do_something` throws an exception the test passes. But I have a property, and when I replace `c.do_something` with `c.name = "Name"` I get an error about...
[The second argument to `assertRaises` should be a callable](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises). An assignment statement (ie. `class.name = "Name"`) is not a callable so it will not work. Use `setattr` to perform the assignment like so ``` self.assertRaises(NameError, setattr...
Python - test a property throws exception
2,066,179
8
2010-01-14T17:38:10Z
23,650,764
7
2014-05-14T09:32:30Z
[ "python", "unit-testing", "properties", "ironpython" ]
Given: ``` def test_to_check_exception_is_thrown(self): # Arrange c = Class() # Act and Assert self.assertRaises(NameError, c.do_something) ``` If `do_something` throws an exception the test passes. But I have a property, and when I replace `c.do_something` with `c.name = "Name"` I get an error about...
Since Python 2.7 `assertRaises()` can be used as a context manager. [see here](https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertRaises) So you can write your test with the `with` instruction like this: ``` def test_to_check_exception_is_thrown(self): c = Class() with self.assertRaises...
how to concatenate lists in python?
2,066,213
2
2010-01-14T17:43:41Z
2,066,227
9
2010-01-14T17:45:47Z
[ "python" ]
I'm trying to insert a String into a list. I got this error: ``` TypeError: can only concatenate list (not "tuple") to list ``` because I tried this: ``` var1 = 'ThisIsAString' # My string I want to insert in the following list file_content = open('myfile.txt').readlines() new_line_insert = file_content[:10] + list...
try ``` file_content[:10] + [var1] + rss_xml[11:] ```
How to disable individual tests temporarily using unittest module in python?
2,066,508
18
2010-01-14T18:26:25Z
2,066,544
9
2010-01-14T18:30:47Z
[ "python", "unit-testing" ]
How to disable individual tests temporarily using unittest module in python? [Like googletest does.](https://code.google.com/p/googletest/wiki/AdvancedGuide#Temporarily_Disabling_Tests) Thanks.
[The latest version (2.7 - unreleased) supports test skipping/disabling like so](http://docs.python.org/dev/library/unittest.html#unittest-skipping). You could just get this module and use it on your existing Python install. It will probably work. Before this, I used to rename the tests I wanted skipped to `xtest_test...
How to disable individual tests temporarily using unittest module in python?
2,066,508
18
2010-01-14T18:26:25Z
2,066,729
19
2010-01-14T18:59:11Z
[ "python", "unit-testing" ]
How to disable individual tests temporarily using unittest module in python? [Like googletest does.](https://code.google.com/p/googletest/wiki/AdvancedGuide#Temporarily_Disabling_Tests) Thanks.
You can use decorators to disable the test that can wrap the function and prevent the googletest or python unit test to run the testcase. ``` def disabled(f): def _decorator(): print f.__name__ + ' has been disabled' return _decorator @disabled def testFoo(): '''Foo test case''' print 'this is...
How to disable individual tests temporarily using unittest module in python?
2,066,508
18
2010-01-14T18:26:25Z
16,138,561
40
2013-04-22T02:30:23Z
[ "python", "unit-testing" ]
How to disable individual tests temporarily using unittest module in python? [Like googletest does.](https://code.google.com/p/googletest/wiki/AdvancedGuide#Temporarily_Disabling_Tests) Thanks.
``` @unittest.skip("demonstrating skipping") def testFoo(): """Foo test case""" print 'this is foo test case' ``` For more details, see the `unittest` documentation: <http://docs.python.org/2/library/unittest.html#skipping-tests-and-expected-failures>
TDD - beginner problems and stumbling blocks
2,066,593
21
2010-01-14T18:38:28Z
2,066,689
8
2010-01-14T18:55:00Z
[ "python", "tdd", "testdrivendesign" ]
While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the book and while some of it looks alien, I felt that I...
> 1. Kent Beck uses a list ... finally now, it's just something like "client should be able to connect to server" (which subsumed server startup etc.). Often a bad practice. Separate tests for each separate layer of the architecture are good. Consolidated tests tend to obscure architectural issues. However, only te...
TDD - beginner problems and stumbling blocks
2,066,593
21
2010-01-14T18:38:28Z
2,080,013
10
2010-01-17T05:01:14Z
[ "python", "tdd", "testdrivendesign" ]
While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the book and while some of it looks alien, I felt that I...
As a preliminary comment, TDD takes practice. When I look back at the tests I wrote when I began TDD, I see lots of issues, just like when I look at code I wrote a few year ago. Keep doing it, and just like you begin to recognize good code from bad, the same things will happen with your tests - with patience. > How do...
GUI not updated from another thread when using PyGtk
2,066,767
4
2010-01-14T19:04:40Z
2,067,868
10
2010-01-14T21:58:29Z
[ "python", "multithreading", "pygtk" ]
I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
GTK+ is not thread-safe, so you should not simply call GUI update methods from other threads. [glib.idle\_add](http://pygtk.org/docs/pygobject/glib-functions.html#function-glib--idle-add) (or gobject.idle\_add in older PyGTK versions) can be used for this purpose. Instead of writing: ``` label.set_text("foo") ``` yo...
Accessing a dict by variable in Django templates?
2,067,006
25
2010-01-14T19:37:43Z
2,067,093
14
2010-01-14T19:48:43Z
[ "python", "django", "django-templates" ]
My view code looks basically like this: ``` context = Context() context['my_dict'] = {'a': 4, 'b': 8, 'c': 15, 'd': 16, 'e': 23, 'f': 42 } context['my_list'] = ['d', 'f', 'e', 'b', 'c', 'a'] ``` And what I'd like to do in my Django template is this: ``` <ul> {% for item in my_list %} <li>{{ item }} : {{ my_dict....
There's no builtin way to do that, you'd need to write a simple template filter to do this: <http://code.djangoproject.com/ticket/3371>
Accessing parallel arrays in Django templates?
2,067,036
4
2010-01-14T19:42:16Z
2,067,071
8
2010-01-14T19:46:30Z
[ "python", "django", "django-templates" ]
My view code looks basically like this: ``` context = Context() context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f'] context['other_values'] = [4, 8, 15, 16, 23, 42] ``` I would like my template code to look like this: ``` {% for some in some_values %} {% with index as forloop.counter0 %} {{ some }} : {{...
`zip(some_values, other_values)`, then use it in template ``` from itertools import izip some_values = ['a', 'b', 'c', 'd', 'e', 'f'] other_values = [4, 8, 15, 16, 23, 42] context['zipped_values'] = izip(some_values, other_values) {% for some, other in zipped_values %} {{ some }}: {{ other }} <br/> {% endfor %} ...
python list of dicts how to merge key:value where values are same?
2,067,627
9
2010-01-14T21:15:38Z
2,068,064
9
2010-01-14T22:35:54Z
[ "python", "list", "merge", "dictionary" ]
Python newb here looking for some assistance... For a variable number of dicts in a python list like: ``` list_dicts = [ {'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'}, {'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'}, {'id':'002', 'name':'mary', 'item':'tape', 'price':'7.99'}, {'id':'003', 'n...
Try to avoid complex nested data structures. I believe people tend to grok them only while they are intensively using the data structure. After the program is finished, or is set aside for a while, the data structure quickly becomes mystifying. Objects can be used to retain or even add richness to the data structure i...
Efficient method to store Python dictionary on disk?
2,067,749
2
2010-01-14T21:35:20Z
2,067,757
8
2010-01-14T21:36:03Z
[ "python", "dictionary", "disk", "pickle" ]
What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the `pickle` module. **Edit:** Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain mutable objects that will hold information to be p...
[shelve](http://docs.python.org/library/shelve.html) is pretty nice as well or [this persistent dictionary recipe](http://code.activestate.com/recipes/576642/) for a convenient method that keeps your objects synchronized with storage, there's the ORM [SQLAlchemy](http://www.sqlalchemy.org/) for python if you just ne...
Music Recognition and Signal Processing
2,068,286
12
2010-01-14T23:21:37Z
2,068,311
10
2010-01-14T23:27:41Z
[ "php", "python", "audio", "signal-processing", "audio-processing" ]
I want to **build something similar to [Tunatic](http://www.wildbits.com/tunatic/) or [Midomi](http://www.midomi.com/)** (try them out if you're not sure what they do) and I'm wondering what algorithms I'd have to use; The idea I have about the workings of such applications is something like this: 1. have a big databa...
I worked on the periphery of a cool framework that implements several Music Information Retrieval techniques. I'm hardly an expert (edit: actually i'm nowhere close to an expert, just to clarify), but I can tell that that the Fast Fourier Transform is used all over the place with this stuff. Fourier analysis is wacky b...
Music Recognition and Signal Processing
2,068,286
12
2010-01-14T23:21:37Z
2,072,606
11
2010-01-15T15:20:28Z
[ "php", "python", "audio", "signal-processing", "audio-processing" ]
I want to **build something similar to [Tunatic](http://www.wildbits.com/tunatic/) or [Midomi](http://www.midomi.com/)** (try them out if you're not sure what they do) and I'm wondering what algorithms I'd have to use; The idea I have about the workings of such applications is something like this: 1. have a big databa...
I do research in music information retrieval (MIR). The seminal paper on music fingerprinting is the one by Haitsma and Kalker around 2002-03. Google should get you it. I read an early (really early; before 2000) white paper about Shazam's method. At that point, they just basically detected spectrotemporal peaks, and ...
Understanding .get() method in Python
2,068,349
38
2010-01-14T23:35:11Z
2,068,360
8
2010-01-14T23:37:18Z
[ "python" ]
``` sentence = "The quick brown fox jumped over the lazy dog." characters = {} for character in sentence: characters[character] = characters.get(character, 0) + 1 print(characters) ``` I don't understand what `characters.get(character, 0) + 1` is doing, rest all seems pretty straightforward.
Start here <http://docs.python.org/tutorial/datastructures.html#dictionaries> Then here <http://docs.python.org/library/stdtypes.html#mapping-types-dict> Then here <http://docs.python.org/library/stdtypes.html#dict.get> ``` characters.get( key, default ) key is a character default is 0 ``` If the character is in ...
Understanding .get() method in Python
2,068,349
38
2010-01-14T23:35:11Z
2,068,377
52
2010-01-14T23:41:22Z
[ "python" ]
``` sentence = "The quick brown fox jumped over the lazy dog." characters = {} for character in sentence: characters[character] = characters.get(character, 0) + 1 print(characters) ``` I don't understand what `characters.get(character, 0) + 1` is doing, rest all seems pretty straightforward.
The `get` method of a dict (like for example `characters` works just like indexing the dict, except that, if the key is missing, instead of raising a `KeyError` it returns the default value (if you call `.get` with just one argument, the key, the default value is `None`). So an equivalent Python function (where callin...
Understanding .get() method in Python
2,068,349
38
2010-01-14T23:35:11Z
20,326,912
9
2013-12-02T11:13:29Z
[ "python" ]
``` sentence = "The quick brown fox jumped over the lazy dog." characters = {} for character in sentence: characters[character] = characters.get(character, 0) + 1 print(characters) ``` I don't understand what `characters.get(character, 0) + 1` is doing, rest all seems pretty straightforward.
To understand what is going on, let's take one letter(repeated more than once) in the **sentence** string and follow what happens when it goes through the loop. Remember that we start off with an empty **characters** dictionary ``` characters = {} ``` I will pick the letter 'e'. Let's pass the character 'e' (found i...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
2,068,412
36
2010-01-14T23:52:06Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
There's a pretty neat sample from the Python Cookbook [here](http://oreilly.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=last) -- the fastest version proposed on that URL is: ``` import itertools def erat2( ): D = { } yield 2 for q in itertools.islice(itertools.count(3), 0, None, 2): ...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
2,068,522
17
2010-01-15T00:14:04Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
The algorithm is fast, but it has a serious flaw: ``` >>> sorted(get_primes(530)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, ...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
2,068,548
249
2010-01-15T00:19:09Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
**Warning:** `timeit` results may vary due to differences in hardware or version of Python. Below is a script which compares a number of implementations: * ambi\_sieve\_plain,* [rwh\_primes](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188),* [rwh\_primes1](h...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
2,070,175
13
2010-01-15T07:58:18Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
For **truly** fastest solution with sufficiently large N would be to download a [pre-calculated list of primes](http://primes.utm.edu/lists/small/millions/), store it as a tuple and do something like: ``` for pos,i in enumerate(primes): if i > N: print primes[:pos] ``` If `N > primes[-1]` *only* then calc...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
2,073,279
25
2010-01-15T16:50:02Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
Using [Sundaram's Sieve](http://plus.maths.org/issue50/features/havil/index.html), I think I broke pure-Python's record: ``` def sundaram3(max_n): numbers = range(3, max_n+1, 2) half = (max_n)//2 initial = 4 for step in xrange(3, max_n+1, 2): for i in xrange(initial, half, step): n...
Fastest way to list all primes below N
2,068,372
251
2010-01-14T23:40:27Z
3,035,188
80
2010-06-14T05:49:40Z
[ "python", "math", "optimization", "primes" ]
This is the best algorithm I could come up. ``` def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)...
Related question(dealing with primes generators & including benchmarks): [Speed up bitstring/bit operations in Python?](http://stackoverflow.com/questions/2897297/speed-up-bitstring-bit-operations-in-python) Faster & more memory-wise pure Python code: ``` def primes(n): """ Returns a list of primes < n """ ...
Example for using Python Twisted with File Descriptors
2,069,262
3
2010-01-15T03:20:02Z
2,071,881
12
2010-01-15T13:42:33Z
[ "python", "pipe", "twisted", "file-descriptor", "mkfifo" ]
I'm looking to use twisted to control communication across Linux pipes (os.pipe()) and fifos (os.mkfifo()) between a master process and a set of slave processes. While I'm positive tat it's possible to use twisted for these types of file descriptors (after all, twisted is great for tcp sockets which \*nix abstracts awa...
You can use `reactor.spawnProcess` to set up arbitrary file descriptor mappings between a parent process and a child process it spawns. For example, to run a program and give it two extra output descriptors (in addition to stdin, stdout, and stderr) with which it can send bytes back to the parent process, you would do ...
How to exit an if clause
2,069,662
39
2010-01-15T05:20:54Z
2,069,670
38
2010-01-15T05:24:07Z
[ "python", "control-flow" ]
What sorts of methods exist for prematurely exiting an `if` clause? There are times when I'm writing code and want to put a `break` statement inside of an `if` clause, only to remember that those can only be used for loops. Lets take the following code as an example: ``` if some_condition: ... if condition_a: ...
This method works for `if`s, multiple nested loops and other constructs that you can't `break` from easily. Wrap the code in its own function. Instead of `break`, `return`.
How to exit an if clause
2,069,662
39
2010-01-15T05:20:54Z
2,069,687
24
2010-01-15T05:29:47Z
[ "python", "control-flow" ]
What sorts of methods exist for prematurely exiting an `if` clause? There are times when I'm writing code and want to put a `break` statement inside of an `if` clause, only to remember that those can only be used for loops. Lets take the following code as an example: ``` if some_condition: ... if condition_a: ...
``` from goto import goto, label if some_condition: ... if condition_a: # do something # and then exit the outer if block goto .end ... if condition_b: # do something # and then exit the outer if block goto .end # more code here label .end ``` (Don't actually ...
Where can I find source or algorithm of Python's hash() function?
2,070,276
13
2010-01-15T08:26:46Z
2,070,320
16
2010-01-15T08:37:53Z
[ "python", "c", "algorithm", "hash" ]
``` >>> hash("\x01") 128000384 >>> hash("\x02") 256000771 >>> hash("\x03") 384001154 >>> hash("\x04") 512001541 ``` Interesting part is `128000384 x 2` is not `256000771`, and also others I am just wondering how that algorithm works and want to learn something on it.
If you download the source code of Python, you will find it for sure! But bear in mind the hash function is implemented for each kind of objects differently. For example, you will find the unicode hash function in `Objects/unicodeobject.c` in the function `unicode_hash`. You might have to look a bit more to find the s...
Subtracting two lists in Python
2,070,643
25
2010-01-15T09:53:17Z
2,070,734
41
2010-01-15T10:11:40Z
[ "python", "list", "collections" ]
In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I'd like to do something like c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b. **Note this is different from sets!**...
I know "for" is not what you want, but it's simple and clear: ``` for x in b: a.remove(x) ``` Or if members of `b` might not be in `a` then use: ``` for x in b: if x in a: a.remove(x) ```
Subtracting two lists in Python
2,070,643
25
2010-01-15T09:53:17Z
2,071,172
24
2010-01-15T11:44:40Z
[ "python", "list", "collections" ]
In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I'd like to do something like c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b. **Note this is different from sets!**...
Python 2.7 and 3.2 will add the [collections.Counter](http://docs.python.org/dev/library/collections.html#collections.Counter) class which is a dictionary that maps elements to the number of occurrences of the element. This can be used as a multiset. According to the docs you should be able to do something like this (...
Subtracting two lists in Python
2,070,643
25
2010-01-15T09:53:17Z
2,794,615
17
2010-05-08T15:26:36Z
[ "python", "list", "collections" ]
In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I'd like to do something like c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b. **Note this is different from sets!**...
I would do it in an easier way: ``` a_b = [e for e in a if not e in b ] ``` ..as wich wrote, this is wrong - it works only if the items are unique in the lists. And if they are, it's better to use ``` a_b = list(set(a) - set(b)) ```
Python conversion from binary string to hexadecimal
2,072,351
21
2010-01-15T14:47:57Z
2,072,366
29
2010-01-15T14:51:07Z
[ "python", "binary", "hex" ]
How can I perform a conversion of a binary string to the corresponding hex value in Python? I have `0000 0100 1000 1101` and I want to get `048D` I'm using Python 2.6.
Welcome to StackOverflow! `int` given base 2 and then `hex`: ``` >>> int('010110', 2) 22 >>> hex(int('010110', 2)) '0x16' >>> >>> hex(int('0000010010001101', 2)) '0x48d' ``` The doc of `int`: > ``` > int(x[, base]) -> integer > > Convert a string or number to an integer, if possible. A floating > ``` > > point >...
Python conversion from binary string to hexadecimal
2,072,351
21
2010-01-15T14:47:57Z
2,072,384
11
2010-01-15T14:53:14Z
[ "python", "binary", "hex" ]
How can I perform a conversion of a binary string to the corresponding hex value in Python? I have `0000 0100 1000 1101` and I want to get `048D` I'm using Python 2.6.
``` bstr = '0000 0100 1000 1101'.replace(' ', '') hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2)) ```
How to get list index and element simultaneously in Python?
2,072,407
11
2010-01-15T14:56:29Z
2,072,427
31
2010-01-15T14:58:45Z
[ "python" ]
I find myself frequently writing code like this: ``` k = 0 for i in mylist: # y[k] = some function of i k += 1 ``` Instead, I could do ``` for k in range(K): # y[k] = some function of mylist[k] ``` but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extr...
You can use `enumerate`: ``` for k,i in enumerate(mylist): #do something with index k #do something with element i ``` More information about [looping techniques](http://docs.python.org/tutorial/datastructures.html#looping-techniques). **Edit:** As pointed out in the comments, using other variable names li...
How to get list index and element simultaneously in Python?
2,072,407
11
2010-01-15T14:56:29Z
2,072,431
13
2010-01-15T14:58:59Z
[ "python" ]
I find myself frequently writing code like this: ``` k = 0 for i in mylist: # y[k] = some function of i k += 1 ``` Instead, I could do ``` for k in range(K): # y[k] = some function of mylist[k] ``` but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extr...
[`enumerate`](http://docs.python.org/library/functions.html#enumerate) is the answer: ``` for index, element in enumerate(iterable): #work with index and element ```
Search and Replace in HTML with BeautifulSoup
2,073,541
7
2010-01-15T17:29:56Z
2,073,697
13
2010-01-15T17:56:09Z
[ "python", "beautifulsoup" ]
I want to use BeautfulSoup to search and replace `<\a>` with `<\a><br>`. I know how to open with `urllib2` and then parse to extract all the `<a>` tags. What I want to do is search and replace the closing tag with the closing tag plus the break. Any help, much appreciated. **EDIT** I would assume it would be somethin...
This will insert a `<br>` tag after the end of each `<a>...</a>` element: ``` from BeautifulSoup import BeautifulSoup, Tag # .... soup = BeautifulSoup(data) for a in soup.findAll('a'): a.parent.insert(a.parent.index(a)+1, Tag(soup, 'br')) ``` You can't use `soup.findAll(tag = '</a>')` because BeautifulSoup does...
How get get more search results than the server's sizelimit with Python LDAP?
2,073,574
9
2010-01-15T17:34:52Z
2,086,982
12
2010-01-18T15:19:12Z
[ "python", "ldap" ]
I am using the [python LDAP](http://www.python-ldap.org/) module to (amongst other things) search for groups, and am running into the server's size limit and getting a SIZELIMIT\_EXCEEDED exception. I have tried both synchronous and asynchronous searches and hit the problem both ways. You are supposed to be able to wo...
Here are some links related to paging in python-ldap. * Documentation: <http://www.python-ldap.org/doc/html/ldap-controls.html#ldap.controls.SimplePagedResultsControl> * Example code using paging: <http://www.novell.com/coolsolutions/tip/18274.html> * More example code: <http://google-apps-for-your-domain-ldap-sync.go...
multiprocessing problem [pyqt, py2exe]
2,073,942
14
2010-01-15T18:49:23Z
2,196,650
24
2010-02-04T00:52:34Z
[ "python", "pyqt", "multiprocessing", "py2exe" ]
I am writing a GUI program using PyQt4. There is a button in my main window and by clicking this button. I hope to launch a background process which is an instance of a class derived from processing.Process. ``` class BackgroundTask(processing.Process): def __init__(self, input): processing.Process.__init_...
I think your actual problem has to do with this: > The program works as expected under the python intepreter, i.e. if it is started from the command line "python myapp.py". > > However, after I package the program using py2exe, every time when I click that button, > instead of starting the background task, a copy of t...
max size in BlobProperty (appengine)
2,074,154
7
2010-01-15T19:20:42Z
2,074,245
10
2010-01-15T19:33:21Z
[ "python", "google-app-engine" ]
What is the maximum size of one BlobProperty in appengine? I'm not talking about of the Blobstore API, i'm referring to the property class [BlobProperty](http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#BlobProperty) Please add a link who support your answers
The limit is 1 megabyte. [Docs here](http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#Properties_and_Types). > Like db.Text, a db.Blob value can be > as large as 1 megabyte, but is not > indexed, and cannot be used in query > filters or sort orders. The db.Blob > class takes a str value as...
Django Query That Get Most Recent Objects From Different Categories
2,074,514
41
2010-01-15T20:21:01Z
2,076,665
24
2010-01-16T08:12:43Z
[ "python", "django", "django-queryset", "greatest-n-per-group" ]
I have two models `A` and `B`. All `B` objects have a foreign key to an `A` object. Given a set of `A` objects, is there anyway to use the ORM to get a set of `B` objects containing the most recent object created for each `A` object Here's an simplified example: ``` Class Bakery(models.Model): town = models.CharF...
As far as I know, there is no one-step way of doing this in Django ORM. But you can split it in two queries: ``` bakeries = Bakery.objects.annotate(hottest_cake_baked_at=Max('cake__baked_at')) hottest_cakes = Cake.objects.filter(baked_at__in=[b.hottest_cake_baked_at for b in bakeries]) ``` If id's of cakes are prog...
Django Query That Get Most Recent Objects From Different Categories
2,074,514
41
2010-01-15T20:21:01Z
20,129,229
12
2013-11-21T18:35:42Z
[ "python", "django", "django-queryset", "greatest-n-per-group" ]
I have two models `A` and `B`. All `B` objects have a foreign key to an `A` object. Given a set of `A` objects, is there anyway to use the ORM to get a set of `B` objects containing the most recent object created for each `A` object Here's an simplified example: ``` Class Bakery(models.Model): town = models.CharF...
If you happen to be using PostGreSQL, you can use [Django's interface to DISTINCT ON](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct): ``` recent_cakes = Cake.objects.order_by('bakery__id', '-baked_at').distinct('bakery__id') ``` As [the docs](https://docs.djangop...
Python, print all floats to 2 decimal places in output
2,075,128
25
2010-01-15T22:15:31Z
2,075,141
32
2010-01-15T22:18:30Z
[ "python", "floating-point", "string-formatting" ]
I need to output 4 different floats to two decimal places. This is what I have: ``` print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l' ``` Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'? Note: Using Python 2.6.
Well I would atleast clean it up as follows: ``` print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4) ```
Python, print all floats to 2 decimal places in output
2,075,128
25
2010-01-15T22:15:31Z
2,075,633
13
2010-01-16T00:25:12Z
[ "python", "floating-point", "string-formatting" ]
I need to output 4 different floats to two decimal places. This is what I have: ``` print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l' ``` Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'? Note: Using Python 2.6.
If you just want to convert the values to nice looking strings do the following: ``` twodecimals = ["%.2f" % v for v in vars] ``` Alternatively, you could also print out the units like you have in your question: ``` vars = [0, 1, 2, 3] # just some example values units = ['kg', 'lb', 'gal', 'l'] delimiter = ', ' # or...
Accessing related object key without fetching object in App Engine
2,075,951
7
2010-01-16T02:10:19Z
2,076,012
9
2010-01-16T02:48:12Z
[ "python", "google-app-engine", "gae-datastore" ]
In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects: ``` sons = Son.all() ``` Then, I'd like to get all the fathers for that group of sons. I do: ``` father_keys = {} for son in sons: father_...
You can find the answer by studying the sources of [appengine.ext.db](http://google_appengine/google/appengine/ext/db/__init__.py) in your download of the App Engine SDK sources -- and the answer is, no, there's no special-casing as you require: the `__get__` method (line 2887 in the sources for the 1.3.0 SDK) of the `...
Extract string from between quotations
2,076,343
13
2010-01-16T05:53:07Z
2,076,356
16
2010-01-16T05:58:24Z
[ "python", "string", "extraction", "quotations" ]
I want to extract information from user-inputted text. Imagine I input the following: ``` SetVariables "a" "b" "c" ``` How would I extract information between the first set of quotations? Then the second? Then the third?
``` >>> import re >>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ') ['a', 'b', 'c'] ```
Extract string from between quotations
2,076,343
13
2010-01-16T05:53:07Z
2,076,399
16
2010-01-16T06:16:45Z
[ "python", "string", "extraction", "quotations" ]
I want to extract information from user-inputted text. Imagine I input the following: ``` SetVariables "a" "b" "c" ``` How would I extract information between the first set of quotations? Then the second? Then the third?
You could do a string.split() on it. If the string is formatted properly with the quotation marks (i.e. even number of quotation marks), every odd value in the list will contain an element that is between quotation marks. ``` >>> s = 'SetVariables "a" "b" "c"'; >>> l = s.split('"')[1::2]; # the [1::2] is a slicing whi...
Making an android Python service to run in suspend state
2,076,381
13
2010-01-16T06:08:11Z
2,208,326
10
2010-02-05T15:41:56Z
[ "python", "android", "android-scripting" ]
Here's my Python script written using [android-scripting](http://code.google.com/p/android-scripting/wiki/PythonAndroidAPI): ``` import android, time droid = android.Android() interval = 1 # every 1 minute while True: # define your own vibrate pattern here droid.vibrate(200) time.sleep(0.3) droid.vib...
The scripting environment is definitely a second-class citizen. What you want is called the AlarmManager, using ELAPSED\_REALTIME. If that's not available for the scripting environment, you're stuck. The scripting environment is not, at least currently, intended to be a full replacement for the development kit environ...
How does wordpress password hash work?
2,076,507
4
2010-01-16T07:07:59Z
2,076,586
7
2010-01-16T07:40:41Z
[ "php", "python", "django", "wordpress" ]
I need to integrate a Django system with a Wordpress site, as in wordpress users should be able to log in the DJnago part and vice versa, For this I need to understand how the password hashing works in Wordpress. I can see the `wp_users` table which stores the username and password hashes. Looking through the wordpre...
There is a comment in the implementation saying: ``` 28 /** 29 * Portable PHP password hashing framework. 30 * 31 * @package phpass 32 * @version 0.1 / genuine 33 * @link http://www.openwall.com/phpass/ 34 * @since 2.5 35 */ ``` The hashing framework used is [phpass](http://www.openwall...
Python os.stat and unicode file names
2,076,708
11
2010-01-16T08:30:46Z
2,076,884
7
2010-01-16T09:42:43Z
[ "python", "unicode", "operating-system" ]
In my Django application, a user has uploaded a file with a unicode character in the name. When I'm downloading files, I'm calling : ``` os.path.exists(media) ``` to test that the file is there. This, in turn, seems to call ``` st = os.stat(path) ``` Which then blows up with the error : UnicodeEncodeError: 'ascii...
I'm assuming you're in Unix. If not, please remember to say which OS you're in. Make sure your locale is set to UTF-8. All modern Linux systems do this by default, usually by setting the environment variable LANG to "en\_US.UTF-8", or another language. Also, make sure your filenames are encoded in UTF-8. With that se...
Generating non-repeating random numbers in Python
2,076,838
39
2010-01-16T09:27:22Z
2,076,937
9
2010-01-16T10:07:57Z
[ "python", "random", "numbers" ]
Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell...
With some modular arithmic and prime numbers, you can create all numbers between 0 and a big prime, out of order. If you choose your numbers carefully, the next number is hard to guess. ``` modulo = 87178291199 # prime incrementor = 17180131327 # relative prime current = 433494437 # some start value for i in xrange(1...
Generating non-repeating random numbers in Python
2,076,838
39
2010-01-16T09:27:22Z
2,077,036
25
2010-01-16T10:45:42Z
[ "python", "random", "numbers" ]
Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell...
This is a neat problem, and I've been thinking about it for a while (with solutions similar to [Sjoerd's](http://stackoverflow.com/questions/2076838/generating-non-repeating-random-numbers-in-python/2076937#2076937)), but in the end, here's what I think: Use your point 1) and stop worrying. Assuming real randomness, ...
Generating non-repeating random numbers in Python
2,076,838
39
2010-01-16T09:27:22Z
2,077,264
11
2010-01-16T12:10:10Z
[ "python", "random", "numbers" ]
Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell...
You could use [Format-Preserving Encryption](http://en.wikipedia.org/wiki/Format-Preserving_Encryption) to encrypt a counter. Your counter just goes from 0 upwards, and the encryption uses a key of your choice to turn it into a seemingly random value of whatever radix and width you want. Block ciphers normally have a ...
Escape special HTML characters in Python
2,077,283
11
2010-01-16T12:18:33Z
2,077,321
23
2010-01-16T12:30:29Z
[ "python" ]
I have a string where special characters like `'` or `"` or `&` (...) can appear. In the string: ``` string = " Hello "XYZ" this 'is' a test & so on " ``` how can I automatically escape every special character, so that I get this: ``` string = " Hello &quot;XYZ&quot; this &#39;is&#39; a test &amp; so on " ```
In Python 3.2, you could use the [`html.escape` function](http://docs.python.org/3/library/html.html#html.escape), e.g. ``` >>> string = """ Hello "XYZ" this 'is' a test & so on """ >>> import html >>> html.escape(string) ' Hello &quot;XYZ&quot; this &#x27;is&#x27; a test &amp; so on ' ``` For earlier versions of Pyt...
How to load a C# dll in python?
2,077,870
10
2010-01-16T15:38:22Z
20,263,498
11
2013-11-28T10:26:47Z
[ "c#", "python", ".net", "cpython", "python.net" ]
how can I load a c# dll in python? Do I have to put some extra code in the c# files? (like export in c++ files) I don't want to use IronPython. I want to import a module to Python!
The package [Python for.NET](http://pythonnet.sourceforge.net/) and the Python Implementation [IronPython](http://ironpython.net/) now work the same way. Example for a C# DLL `MyDll.dll`: ``` import clr clr.AddReference('MyDll') from MyNamespace import MyClass my_instance = MyClass() ``` See [this post](http://stack...
'proper' & reliable way to get all installed windows programs in Python?
2,077,902
7
2010-01-16T15:45:11Z
2,081,549
7
2010-01-17T15:56:19Z
[ "python", "windows", "registry", "wmi", "win32com" ]
I've seen numerous ways of retrieving installed programs on WinXP+ in python. What is the *proper* and *most robust* way of doing this? Currently I'm accessing `HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall` and reading each of the keys from there to get a list. (I've been told this isn't the *proper* ...
The technet script you refer to perfectly works under Win 7 (with Python 2.5 32bits), and I really cannot see why it shouldn't. Actually, the real weakness of the WMI approach is that it only lists products installed through the Windows Installer. So it's will not give you the full list. Many programs use different in...
Python/Django shell won't start
2,078,059
5
2010-01-16T16:23:44Z
2,078,129
11
2010-01-16T16:43:08Z
[ "python", "django", "shell" ]
One of the great features of Django is that you can open a python interpreter set-up for use with your project. This can be used to analyse objects in a database and allows any python commands to be executed on your project. I find it essential for Django development. It is invoked in the project directory using this c...
It seems like IPython is installed wrongly somehow. Try starting the shell with: ``` ./manage.py shell --plain ``` to start the standard Python shell, rather than IPython. If that works, then trying removing IPython completely and reinstalling it.
static file with mod_wsgi in django
2,078,160
6
2010-01-16T16:52:55Z
2,080,001
7
2010-01-17T04:55:18Z
[ "python", "django", "apache", "mod-wsgi" ]
I've searched a lot but I still have a problem with the static files (css, image,...) with my django website. I'm using mod\_wsgi with apache on archlinux 64bits I've added it in my http.conf : ``` LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost *:80> WSGIDaemonProcess mart.localhost user=mart group=use...
It is not sufficient for just the directory '/home/mart/programmation/python/django/martfiles/media' containing static files to be readable and searchable. The user that Apache runs as must have read and potentially search access, to all parent directories of it back up to root directory. Since home directories on many...
Python class that inherits from itself? How does this work?
2,078,634
3
2010-01-16T19:19:31Z
2,078,650
11
2010-01-16T19:24:53Z
[ "python", "eclipse", "facebook" ]
Relatively new to Python, and I saw the following construct in the PyFacebook library (source here: [http://github.com/sciyoshi/pyfacebook/blob/master/facebook/**init**.py#L660](http://github.com/sciyoshi/pyfacebook/blob/master/facebook/__init__.py#L660)). I'm curious what this does because it appears to be a class tha...
The class statement there doesn't make the class inherit from itself, it creates a class object with the current value of AuthProxy as a superclass, and then assigns the class object to the variable 'AuthProxy', presumably overwriting the previously assigned AuthProxy that it inherited from. Essentially, it's about th...
Pythonic way to sort list of objects by a dict value (by key) contained within the object
2,078,986
2
2010-01-16T21:38:23Z
2,078,998
9
2010-01-16T21:41:05Z
[ "python", "sorting" ]
I'm seeking advice on doing the following in a more pythonic way. Consider: ``` class MyObj(object): def __init__(self): self.dict_properties = {} ``` Suppose I've got a list which contains multiple MyObj instances: ``` mylist = [<__main__.MyObj object at 0x1005e3b90, ...] ``` Now i want to sort `mylis...
``` mylist.sort(key=lambda x: x.dict_properties['mykey']) ``` is way simpler, and faster. You could reach for `operator` and try to compose an `attrgetter` and an `itemgetter`, but a straightforward `lambda` (or `def`) seems simplest here.
Which methods implement the buffer interface in Python?
2,079,272
13
2010-01-16T23:08:40Z
2,079,345
11
2010-01-16T23:23:57Z
[ "python", "buffer" ]
I have a custom class with a `serialize` method, and I want to be able to write this class directly to files and have the return value of the `serialize` method get written, in Python 2.6. (I'm not trying to [pickle](http://docs.python.org/library/pickle.html) my objects, this is something totally different.) For examp...
Peculiarly, there are no special methods that a pure-Python coded class can directly implement to support the `buffer` interface -- that would have been [PEP 298](http://www.python.org/dev/peps/pep-0298/), but it was withdrawn. I'm afraid you'll have to use some explicit attribute or method (or a built-in like `str` w...
String matching in Python
2,079,676
3
2010-01-17T01:44:02Z
2,079,685
9
2010-01-17T01:50:31Z
[ "python", "string-matching" ]
does anyone know which string matching algorithm is implemented in Python?
Per [the sources](http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=77470&view=markup), it's a > fast search/count implementation, > based on a mix between boyer-moore and > horspool, with a few more bells and > whistles on the top. for some more > background, see: > <http://effbot.org/zo...
Caching sitemaps in django
2,079,786
8
2010-01-17T02:46:37Z
2,499,180
13
2010-03-23T10:45:19Z
[ "python", "django", "caching", "sitemap" ]
I implemented a simple sitemap class using django's default sitemap app. As it was taking a long time to execute, I added manual caching: ``` class ShortReviewsSitemap(Sitemap): changefreq = "hourly" priority = 0.7 def items(self): # try to retrieve from cache result = get_cache(CACHE_SITE...
50k it's not a hardcore parameter. :) You can use this class instead django.contrib.sitemaps.GenericSitemap ``` class LimitGenericSitemap(GenericSitemap): limit = 2000 ```
Python web hosting: Numpy, Matplotlib, Scientific Computing
2,080,110
39
2010-01-17T05:51:56Z
2,080,138
11
2010-01-17T06:04:59Z
[ "python", "numpy", "matplotlib", "scipy" ]
I write scientific software in Numpy/Scipy/Matplotlib. Having developed applications on my home computer, I am now interested in writing simple web applications. Example: user uploads image or audio file, my program processes it using Numpy/Scipy, and output is displayed on the browser using Matplotlib, or perhaps the ...
App Engine does not support any of numpy, scipy, or matplotlib, alas. If you know exactly what OS and CPU your host is using, you could make an identical installation for yourself, download and install the same version of Python they're using, download the sources of packages you require and build them into `.so` (or ...
Python web hosting: Numpy, Matplotlib, Scientific Computing
2,080,110
39
2010-01-17T05:51:56Z
2,080,261
14
2010-01-17T07:10:09Z
[ "python", "numpy", "matplotlib", "scipy" ]
I write scientific software in Numpy/Scipy/Matplotlib. Having developed applications on my home computer, I am now interested in writing simple web applications. Example: user uploads image or audio file, my program processes it using Numpy/Scipy, and output is displayed on the browser using Matplotlib, or perhaps the ...
**1: Installing third party packages to hosted spaces** You can indeed install third party packages to your hosted space. If it's a pure python package, all that's needed is to unpack it to a directory and then add that directory to your PYTHONPATH environment variable or `sys.path`. This can be tiring to do often, a...