title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Map two lists into a dictionary in Python
209,840
<p>Imagine that you have:</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') </code></pre> <p>What is the simplest way to produce the following dictionary ?</p> <pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} </code></pre> <p>This code works, but I'm not really proud of i...
435
2008-10-16T19:05:47Z
16,750,190
<p>with Python 3.x, goes for dict comprehensions</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') dic = {k:v for k,v in zip(keys, values)} print(dic) </code></pre> <p>More on <a href="http://www.python.org/dev/peps/pep-0274/">dict comprehensions here</a>, an example is there:</p> <pre><...
7
2013-05-25T13:47:03Z
[ "python", "dictionary" ]
Map two lists into a dictionary in Python
209,840
<p>Imagine that you have:</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') </code></pre> <p>What is the simplest way to produce the following dictionary ?</p> <pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} </code></pre> <p>This code works, but I'm not really proud of i...
435
2008-10-16T19:05:47Z
33,728,822
<p>A more natural way is to use dictionary comprehension </p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') dict = {keys[i]: values[i] for i in range(len(keys))} </code></pre>
3
2015-11-16T05:03:26Z
[ "python", "dictionary" ]
Map two lists into a dictionary in Python
209,840
<p>Imagine that you have:</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') </code></pre> <p>What is the simplest way to produce the following dictionary ?</p> <pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} </code></pre> <p>This code works, but I'm not really proud of i...
435
2008-10-16T19:05:47Z
33,737,067
<blockquote> <p>Imagine that you have:</p> <pre><code>keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') </code></pre> <p><strong>What is the simplest way to produce the following dictionary ?</strong></p> <pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} </code></pre> </blockquote> ...
21
2015-11-16T13:54:24Z
[ "python", "dictionary" ]
Advanced Python FTP - can I control how ftplib talks to a server?
210,067
<p>I need to send a very specific (non-standard) string to an FTP server:</p> <pre><code>dir "SYS:\IC.ICAMA." </code></pre> <p>The case is critical, as are the style of quotes and their content.</p> <p>Unfortunately, ftplib.dir() seems to use the 'LIST' command rather than 'dir' (and it uses the wrong case for this ...
1
2008-10-16T20:03:39Z
210,158
<p>Try the following. It is a modification of the original <code>FTP.dir</code> command which uses "dir" instead of "LIST". It gives a "DIR not understood" error with the ftp server I tested it on, but it does send the command you're after. (You will want to remove the print command I used to check that.)</p> <pre>...
4
2008-10-16T20:28:12Z
[ "python", "ftp" ]
py3k RC-1: "LookupError: unknown encoding: uft-8"
210,344
<p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p> <pre><code>&gt;&gt;&gt; help('modules foo') </code></pre> <pre>[...] LookupError: unknown encoding: uft-8</pre> <p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p> <p>Is this a py3k specif...
1
2008-10-16T21:13:29Z
210,395
<p>Looks like a typo in a config file somewhere, whether in the Py3k package or on your machine. You might try installing the stable final Python 2.6 (which supports 3.0 syntax changes with imports from <code>__future__</code>), and if that works you should probably file a bug report.</p>
0
2008-10-16T21:34:16Z
[ "python", "python-3.x" ]
py3k RC-1: "LookupError: unknown encoding: uft-8"
210,344
<p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p> <pre><code>&gt;&gt;&gt; help('modules foo') </code></pre> <pre>[...] LookupError: unknown encoding: uft-8</pre> <p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p> <p>Is this a py3k specif...
1
2008-10-16T21:13:29Z
210,417
<p>It's not a typo, it's a deliberate error in a test module.</p> <pre><code>met% pwd /home/coventry/src/Python-3.0rc1 met% rgrep uft-8 . ./Lib/test/bad_coding.py:# -*- coding: uft-8 -*- ./py3k/Lib/test/bad_coding.py:# -*- coding: uft-8 -*- </code></pre> <p>Removing this module causes the <code>help</code> command to...
5
2008-10-16T21:43:43Z
[ "python", "python-3.x" ]
Distributing a stand-alone Python web-based application to non-technical users
210,461
<p>I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if they want more performance or they simply won't have an Internet connection availabl...
5
2008-10-16T22:00:41Z
210,510
<p>Using NSIS is great (i use it too) but i would suggest using a "packager" like pyinstaller (my personal fav, alternatives bb_freeze, py2exe) to create an exe before the using NSIS</p> <p>The primary benefit you get by doing this is; Your download is smaller as you're not bundling the whole Python Standard Lib and e...
4
2008-10-16T22:23:47Z
[ "python", "installer", "installation" ]
Distributing a stand-alone Python web-based application to non-technical users
210,461
<p>I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if they want more performance or they simply won't have an Internet connection availabl...
5
2008-10-16T22:00:41Z
463,428
<p>You can try the <a href="http://bitnami.org/stack/djangostack" rel="nofollow">Bitnami Stack for Django</a> that includes Apache, MySQL,Python, etc in an all-in-one installer. It is free/open source</p>
0
2009-01-20T22:42:13Z
[ "python", "installer", "installation" ]
I need some help with cursor event handling in python+Tkinter
210,522
<p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p> <p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the En...
0
2008-10-16T22:29:13Z
211,283
<p>This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:</p> <p><a href="http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python">http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python</a></p> <p>I h...
0
2008-10-17T07:12:44Z
[ "python", "events", "cursor", "tkinter" ]
I need some help with cursor event handling in python+Tkinter
210,522
<p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p> <p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the En...
0
2008-10-16T22:29:13Z
225,834
<p>The events &lt;FocusIn&gt; and &lt;FocusOut&gt; are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.</p> <pre><code>from Tkinter import * def main(): global text root=Tk() ...
4
2008-10-22T13:56:48Z
[ "python", "events", "cursor", "tkinter" ]
Python: unsigned 32 bit bitwise arithmetic
210,629
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p> <p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result m...
24
2008-10-16T23:25:31Z
210,707
<pre><code>from numpy import uint32 </code></pre>
8
2008-10-17T00:04:03Z
[ "python", "math" ]
Python: unsigned 32 bit bitwise arithmetic
210,629
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p> <p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result m...
24
2008-10-16T23:25:31Z
210,740
<p>You can use <a href="http://docs.python.org/lib/module-ctypes.html">ctypes</a> and its <code>c_uint32</code>:</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; m = 0xFFFFFF00 &gt;&gt;&gt; ctypes.c_uint32(~m).value 255L </code></pre> <p>So what I did here was casting <code>~m</code> to a C 32-bit unsigned inte...
47
2008-10-17T00:27:26Z
[ "python", "math" ]
Python: unsigned 32 bit bitwise arithmetic
210,629
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p> <p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result m...
24
2008-10-16T23:25:31Z
210,747
<p>You can mask everything by <code>0xFFFFFFFF</code>:</p> <pre><code>&gt;&gt;&gt; m = 0xFFFFFF00 &gt;&gt;&gt; allf = 0xFFFFFFFF &gt;&gt;&gt; ~m &amp; allf 255L </code></pre>
32
2008-10-17T00:28:43Z
[ "python", "math" ]
Python: unsigned 32 bit bitwise arithmetic
210,629
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p> <p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result m...
24
2008-10-16T23:25:31Z
211,342
<p>This is a module that I created a long time ago, and it might be of help to you:</p> <p><a href="http://pypi.python.org/pypi/IPv4_Utils/0.35" rel="nofollow">IPv4Utils</a></p> <p>It provides at least a <code>CIDR</code> class with subnet arithmetic. Check the test cases at the end of the module for examples.</p>
1
2008-10-17T07:45:07Z
[ "python", "math" ]
Python: unsigned 32 bit bitwise arithmetic
210,629
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p> <p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result m...
24
2008-10-16T23:25:31Z
34,951,075
<p>You could also xor with 0xFFFFFFFF, which is equivalent to the "unsigned complement".</p> <pre><code>&gt;&gt;&gt; 0xFFFFFF00 ^ 0xFFFFFFFF 255 </code></pre>
0
2016-01-22T16:10:58Z
[ "python", "math" ]
Using os.execvp in Python
210,978
<p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p> <pre> args = [ "java" , classpath , "-Djava.library.path=" + lib_path() , ea , "-Xmx1000m" , "-server" , "code_swarm" , par...
6
2008-10-17T03:04:38Z
210,982
<p>If your "classpath" variable contains for instance "-classpath foo.jar", it will not work, since it is thinking the option name is "-classpath foo.jar". Split it in two arguments: [..., "-classpath", classpath, ...].</p> <p>The other ways (copy and paste and system()) work because the shell splits the command line ...
11
2008-10-17T03:07:53Z
[ "python", "shell", "exec" ]
Using os.execvp in Python
210,978
<p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p> <pre> args = [ "java" , classpath , "-Djava.library.path=" + lib_path() , ea , "-Xmx1000m" , "-server" , "code_swarm" , par...
6
2008-10-17T03:04:38Z
211,898
<p>Make sure you aren't relying on shell expansion in your classpath. E.g. "~/my.jar" will get expanded by the shell in an os.system call, but not, I believe in an os.execvp call.</p>
0
2008-10-17T12:11:04Z
[ "python", "shell", "exec" ]
Create an icon in memory with win32 in python
211,046
<p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p> <p>Something like this:</p> <pre><code> if os.path.isfile(self.icon): icon_flags = win32con.LR_LO...
0
2008-10-17T04:07:42Z
211,110
<p>You can probably create a object that mimics the python file-object interface.</p> <p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects" rel="nofollow">http://docs.python.org/library/stdtypes.html#bltin-file-objects</a></p>
0
2008-10-17T04:49:23Z
[ "python", "windows", "winapi", "icons" ]
Create an icon in memory with win32 in python
211,046
<p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p> <p>Something like this:</p> <pre><code> if os.path.isfile(self.icon): icon_flags = win32con.LR_LO...
0
2008-10-17T04:07:42Z
211,304
<p>You can use <a href="http://wxpython.org/" rel="nofollow">wxPython</a> for this.</p> <pre><code>from wx import EmptyIcon icon = EmptyIcon() icon.CopyFromBitmap(your_wxBitmap) </code></pre> <p>The <a href="http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap" rel="nofollow">wxBitmap</a> can be generated in me...
2
2008-10-17T07:22:12Z
[ "python", "windows", "winapi", "icons" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
211,101
<p>From the python docs on <code>__import__</code>:</p> <blockquote> <pre><code>__import__( name[, globals[, locals[, fromlist[, level]]]]) </code></pre> <p>...</p> <p>When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not...
51
2008-10-17T04:46:20Z
[ "python", "python-import" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
214,682
<p>There is something that works as you want it to: <code>twisted.python.reflect.namedAny</code>:</p> <pre><code>&gt;&gt;&gt; from twisted.python.reflect import namedAny &gt;&gt;&gt; namedAny("operator.eq") &lt;built-in function eq&gt; &gt;&gt;&gt; namedAny("pysqlite2.dbapi2.connect") &lt;built-in function connect&gt;...
7
2008-10-18T06:37:19Z
[ "python", "python-import" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
5,138,775
<p>python 2.7 has importlib, dotted paths resolve as expected</p> <pre><code>import importlib foo = importlib.import_module('a.dotted.path') instance = foo.SomeClass() </code></pre>
32
2011-02-28T06:08:46Z
[ "python", "python-import" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
5,489,623
<p>For python 2.6, I wrote this snippet:</p> <pre><code>def import_and_get_mod(str, parent_mod=None): """Attempts to import the supplied string as a module. Returns the module that was imported.""" mods = str.split('.') child_mod_str = '.'.join(mods[1:]) if parent_mod is None: if len(mods) ...
1
2011-03-30T17:07:40Z
[ "python", "python-import" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
6,957,437
<p>There is a simpler solution, as explained in the documentation:</p> <p>If you simply want to import a module (potentially within a package) by name, you can call __import__() and then look it up in sys.modules:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; name = 'foo.bar.baz' &gt;&gt;&gt; __import__(name) &...
16
2011-08-05T13:54:49Z
[ "python", "python-import" ]
Python's __import__ doesn't work as expected
211,100
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
40
2008-10-17T04:46:08Z
25,381,926
<p>The way I did is </p> <pre><code>foo = __import__('foo', globals(), locals(), ["bar"], -1) foobar = eval("foo.bar") </code></pre> <p>then i can access any content from by </p> <pre><code>foobar.functionName() </code></pre>
0
2014-08-19T11:11:58Z
[ "python", "python-import" ]
How to build "Tagging" support using CouchDB?
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { ...
4
2008-10-17T04:57:22Z
211,144
<p>You are very much on the right track with the view. A list of thoughts though:</p> <p>View generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should ...
1
2008-10-17T05:15:36Z
[ "python", "couchdb", "tagging", "document-oriented-db" ]
How to build "Tagging" support using CouchDB?
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { ...
4
2008-10-17T04:57:22Z
213,138
<p><em>Disclaimer: I didn't test this and don't know if it can perform better.</em> </p> <p>Create a single perm view:</p> <pre><code>function(doc) { for (var tag in doc.tags) { emit([tag, doc.published], doc) } }; </code></pre> <p>And query with _view/your_view/all?startkey=['your_tag_here']&amp;endkey=['...
7
2008-10-17T17:48:37Z
[ "python", "couchdb", "tagging", "document-oriented-db" ]
How to build "Tagging" support using CouchDB?
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { ...
4
2008-10-17T04:57:22Z
216,543
<p>You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, <em>don't</em> output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying ...
3
2008-10-19T15:34:37Z
[ "python", "couchdb", "tagging", "document-oriented-db" ]
How to build "Tagging" support using CouchDB?
211,118
<p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large. Any other approach?</p> <pre><code>def by_tag(tag): return ''' function(doc) { if (doc.tags.length &gt; 0) { ...
4
2008-10-17T04:57:22Z
312,181
<pre><code># Works on CouchDB 0.8.0 from couchdb import Server # http://code.google.com/p/couchdb-python/ byTag = """ function(doc) { if (doc.type == 'post' &amp;&amp; doc.tags) { doc.tags.forEach(function(tag) { emit(tag, doc); }); } } """ def findPostsByTag(self, tag): server = Server("http://lo...
0
2008-11-23T05:53:49Z
[ "python", "couchdb", "tagging", "document-oriented-db" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
211,174
<p>You should have a look at <a href="http://www.scipy.org/Tentative_NumPy_Tutorial">numpy</a> if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.</p> <pre><code>f...
93
2008-10-17T05:41:42Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
213,717
<p>If you hate numpy, get out RPy and your local copy of R, and use it instead.</p> <p>(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)</p>
1
2008-10-17T20:25:42Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
215,523
<p>Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equati...
44
2008-10-18T20:12:27Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
605,460
<p>You could calculate the determinant of the matrix which is recursive and then form the adjoined matrix</p> <p><a href="http://www.easycalculation.com/matrix/inverse-matrix-tutorial.php">Here is a short tutorial</a></p> <p>I think this only works for square matrices</p> <p>Another way of computing these involves g...
6
2009-03-03T07:46:49Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
3,128,931
<p>It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:</p> <pre><code>A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) </code></pre> <p>By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanati...
9
2010-06-27T21:19:14Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
Python Inverse of a Matrix
211,160
<p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
50
2008-10-17T05:30:49Z
21,126,480
<p>Numpy will be suitable for most people, but you can also do <a href="http://docs.sympy.org/latest/tutorial/matrices.html" rel="nofollow">matrices in Sympy</a></p> <p>Try running these commands at <a href="http://live.sympy.org/" rel="nofollow">http://live.sympy.org/</a></p> <pre><code>M = Matrix([[1, 3], [-2, 3]])...
5
2014-01-14T23:49:57Z
[ "python", "algorithm", "matrix", "linear-algebra", "matrix-inverse" ]
arguments to cryptographic functions
211,483
<p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p> <pre><code>hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) </code></pre> <p>(ignore for the moment that random.randbits() might not be cryptographica...
0
2008-10-17T08:55:21Z
211,503
<p>You can.</p> <p>However, for the HMAC, you actually want to store the key somewhere. Without the key, there is no way for you to verify the hash value later. :-)</p>
1
2008-10-17T09:03:11Z
[ "python", "cryptography" ]
arguments to cryptographic functions
211,483
<p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p> <pre><code>hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) </code></pre> <p>(ignore for the moment that random.randbits() might not be cryptographica...
0
2008-10-17T08:55:21Z
211,506
<p>Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is cor...
6
2008-10-17T09:06:02Z
[ "python", "cryptography" ]
arguments to cryptographic functions
211,483
<p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p> <pre><code>hashlib.sha256(str(user_id)+str(expiry_time)) hmac.new(str(random.randbits(256))) </code></pre> <p>(ignore for the moment that random.randbits() might not be cryptographica...
0
2008-10-17T08:55:21Z
211,509
<p>Oh and Sha256 isn't really an industrial strength cryptographic function (although unfortunately it's used quite commonly on many sites). It's not a real way to protect passwords or other critical data, but more than good enough for generating temporal tokens</p> <p>Edit: As mentioned Sha256 needs at least some sal...
-1
2008-10-17T09:07:01Z
[ "python", "cryptography" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,534
<p>AFAIK an SQLITE database is just a file. To check if the database exists, check for file existence.</p> <p>When you open a SQLITE database it will automatically create one if the file that backs it up is not in place.</p> <p>If you try and open a file as a sqlite3 database that is NOT a database, you will get this...
12
2008-10-17T09:23:01Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,539
<p>Doing SQL in overall is horrible in any language I've picked up. SQLalchemy has shown to be easiest from them to use because actual query and committing with it is so clean and absent from troubles.</p> <p>Here's some basic steps on actually using sqlalchemy in your app, better details can be found from the documen...
3
2008-10-17T09:24:13Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,541
<ul> <li>Sqlite doesn't throw an exception if you create a new database with the same name, it will just connect to it. Since sqlite is a file based database, I suggest you just check for the existence of the file.</li> <li>About your second problem, to check if a table has been already created, just catch the exceptio...
4
2008-10-17T09:26:07Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,562
<p>As @diciu pointed out, the database file will be created by <a href="http://docs.python.org/library/sqlite3.html#module-sqlite3">sqlite3.connect</a>. If you want to take a special action when the file is not there, you'll have to explicitly check for existance:</p> <pre><code>import os import sqlite3 if not os.path...
5
2008-10-17T09:40:12Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,573
<p>SQLite automatically creates the database file the first time you try to use it. The SQL statements for creating tables can use <code>IF NOT EXISTS</code> to make the commands only take effect if the table has not been created This way you don't need to check for the database's existence beforehand: SQLite can take ...
7
2008-10-17T09:44:53Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
211,660
<p>Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler.</p> <p>Do the following.</p> <ol> <li><p>Add a table to your database for "Components" or "Versions" or "Configuration"...
28
2008-10-17T10:30:02Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
214,623
<p>Yes, I was nuking out the problem. All I needed to do was check for the file and catch the IOError if it didn't exist.</p> <p>Thanks for all the other answers. They may come in handy in the future.</p>
0
2008-10-18T05:19:05Z
[ "python", "exception", "sqlite" ]
Using SQLite in a Python program
211,501
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in pro...
13
2008-10-17T09:02:12Z
1,416,903
<p>See this solution at SourceForge which covers your question in a tutorial manner, with instructive source code :</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve the...
2
2009-09-13T05:07:20Z
[ "python", "exception", "sqlite" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
211,774
<p>The <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections module</a> has grown a <em>namedtuple</em> function in 2.6:</p> <pre><code>import collections opt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS') myoptions=opt(True, False) &gt;&gt;&gt; myoptions options(VERBOSE=Tr...
14
2008-10-17T11:17:06Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
211,918
<p>I use <a href="http://code.activestate.com/recipes/361668/">attrdict</a>:</p> <pre><code>class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self </code></pre> <p>Depending on your point of view, you probably think it's either a big kl...
5
2008-10-17T12:19:07Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
211,970
<p>Simplifying <a href="http://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#211918">davraamides's suggestion</a>, one could use the following:</p> <pre><code>class attrdict2(object): def __init__(self, *args, **kwargs): self.__dict__.update(*args, **kwarg...
2
2008-10-17T12:44:22Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,010
<p>One can use</p> <pre><code>class options(object): VERBOSE = True IGNORE_WARNINGS = False options.VERBOSE = False if options.VERBOSE: ... </code></pre> <p>, using the class object itself (not an instance of the class!) as the place to store individual options. This is terse and satisfies all of the r...
1
2008-10-17T12:58:34Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,144
<p>The absolutely simplest class to do the job is:</p> <pre><code>class Struct: def __init__(self, **entries): self.__dict__.update(entries) </code></pre> <p>It can be later used as:</p> <pre><code>john = Struct(name='john doe', salary=34000) print john.salary </code></pre> <p><code>namedtuple</code> (...
1
2008-10-17T13:37:37Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,187
<p>If you insist on not having to define a class, you can abuse some existing classes. Most objects belong to "new-style" classes which don't have a dict, but functions can have arbitrary attributes:</p> <pre><code>&gt;&gt;&gt; x = lambda: 0 # any function will do &gt;&gt;&gt; x.foo = 'bar' &gt;&gt;&gt; x.bar = 0 &g...
6
2008-10-17T13:46:37Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,299
<p>Given your requirements, I'd say the custom class is your best bet:</p> <pre><code>class options(object): VERBOSE = True IGNORE_WARNINGS = True if options.VERBOSE: # ... </code></pre> <p>To be complete, another approach would be using a separate module, i.e. <code>options.py</code> to encapsulate your...
8
2008-10-17T14:10:03Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,357
<p>Just make a module called Options.py, and import it. Put your default options values in there as global variables.</p>
3
2008-10-17T14:23:15Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
212,959
<p>Why not just use <a href="http://docs.python.org/library/optparse.html#module-optparse" rel="nofollow">optparse</a>:</p> <pre><code>from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add...
7
2008-10-17T16:56:19Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
216,453
<p>As best practices go, you're really better off with one of the options in <a href="http://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#212299">David Eyk's answer</a>. </p> <p>However, to answer your question, you can create a one-off class using the <code>type</co...
4
2008-10-19T13:54:18Z
[ "python" ]
What is an easy way to create a trivial one-off Python object?
211,695
<p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p> <pre><code>options = ?????? options.VERBOSE = True options.IGNORE_WARNINGS = False # Then, elsewhere in the code... if options.VERBOSE: ... </code></pre> <p>Of course I could ...
9
2008-10-17T10:47:49Z
6,465,039
<p>simple object and named tuples are the way to go</p>
-2
2011-06-24T08:09:38Z
[ "python" ]
Turning a GqlQuery result set into a python dictionary
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the re...
3
2008-10-17T13:34:03Z
212,351
<p>I can't do too much better than that, but here are a couple of ideas:</p> <pre><code>class Foo: id = db.StringProperty() # etc. json_attrs = 'id bar baz'.split() # Depending on how easy it is to identify string properties, there # might also be a way to assign json_attrs programmatically after the # defini...
1
2008-10-17T14:21:25Z
[ "python", "google-app-engine", "gqlquery" ]
Turning a GqlQuery result set into a python dictionary
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the re...
3
2008-10-17T13:34:03Z
212,682
<p>Take a look at <a href="http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py" rel="nofollow">google.appengine.api.datastore</a>. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it us...
2
2008-10-17T15:37:18Z
[ "python", "google-app-engine", "gqlquery" ]
Turning a GqlQuery result set into a python dictionary
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the re...
3
2008-10-17T13:34:03Z
214,766
<p><a href="http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55" rel="nofollow">http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55</a></p> <p>The encoder method will solve your GQL-to-JSON needs nicely. I'd recommend getting rid of some o...
0
2008-10-18T08:41:26Z
[ "python", "google-app-engine", "gqlquery" ]
Turning a GqlQuery result set into a python dictionary
212,125
<p>Let's say I have a model like this</p> <pre><code>class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() </code></pre> <p>And I'm going a GqlQuery like this</p> <pre><code>foos = db.GqlQuery("SELECT * FROM Foo") </code></pre> <p><strong>I want to take the re...
3
2008-10-17T13:34:03Z
259,334
<p>You can use web2py on GAE and do:</p> <pre><code>db.define_table('foo',SQLField('bar'),SQLField('baz')) rows=db(db.foo.id&gt;0).select() ### rows is a list, rows.response is a list of tuples for row in rows: print dict(row) </code></pre> <p>Runs on Oracle, Postgresql, Mssql, mysql, etc... too.</p>
-1
2008-11-03T17:15:14Z
[ "python", "google-app-engine", "gqlquery" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
212,413
<p>Why not look at the code for bisect_left/right and adapt it to suit your purpose.</p> <p>like this:</p> <pre class="lang-py prettyprint-override"><code>def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) while lo &lt; hi: mid = (lo+hi)//2 midval = a[mid] if mi...
51
2008-10-17T14:36:49Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
212,541
<p>If you just want to see if it's present, try turning the list into a dict:</p> <pre><code># Generate a list l = [n*n for n in range(1000)] # Convert to dict - doesn't matter what you map values to d = dict((x, 1) for x in l) count = 0 for n in range(1000000): # Compare with "if n in l" if n in d: ...
3
2008-10-17T15:03:30Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
212,971
<p>This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring...
32
2008-10-17T16:59:57Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
213,834
<p>Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:</p> <pre><code>&gt;&gt;&gt; a = 'foo' &gt;&gt;&gt; b = [a] &gt;&gt;&gt; c = [a] &gt;&gt;&gt; b[0] is c[0] True </code></pre> <p>In that example, 'foo' is ...
1
2008-10-17T21:01:17Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
530,397
<p>Simplest is to use <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> and check one position back to see if the item is there:</p> <pre><code>def binary_search(a,x,lo=0,hi=-1): i = bisect(a,x,lo,hi) if i == 0: return -1 elif a[i-1] == x: return i-1 else: ...
10
2009-02-09T22:41:14Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
2,233,940
<pre><code>from bisect import bisect_left def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi hi = hi if hi is not None else len(a) # hi defaults to len(a) pos = bisect_left(a,x,lo,hi) # find insertion position return (pos if pos != hi and a[pos] == x else -1) # do...
170
2010-02-10T02:05:27Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
5,763,198
<p>It might be worth mentioning that the bisect docs now provide searching examples: <a href="http://docs.python.org/library/bisect.html#searching-sorted-lists">http://docs.python.org/library/bisect.html#searching-sorted-lists</a></p> <p>(Raising ValueError instead of returning -1 or None is more pythonic – list.ind...
10
2011-04-23T08:36:45Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
10,390,802
<p><p>This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer. If not, a middle value is set and tested to be the correct, if not bisection is performed b...
1
2012-04-30T21:25:18Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
10,555,553
<pre><code>''' Only used if set your position as global ''' position #set global def bst(array,taget): # just pass the array and target global position low = 0 high = len(array) while low &lt;= high: mid = (lo+hi)//2 if a[mid] == target: position = mid ...
0
2012-05-11T16:54:56Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
10,578,346
<p>Check out the examples on Wikipedia <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Binary_search_algorithm</a></p> <pre><code>def binary_search(a, key, imin=0, imax=None): if imax is None: # if max amount not set, get the total imax = l...
1
2012-05-14T06:26:24Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
18,678,361
<p>Dave Abrahams' solution is good. Although I have would have done it minimalistic:</p> <pre><code>def binary_search(L, x): i = bisect.bisect_left(L, x) if i == len(L) or L[i] != x: return -1 return i </code></pre>
1
2013-09-07T22:08:09Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
18,681,876
<p>I agree that <a href="http://stackoverflow.com/a/2233940/2484194">@DaveAbrahams's answer</a> using the bisect module is the correct approach. He did not mention one important detail in his answer.</p> <p>From the <a href="http://docs.python.org/2/library/bisect.html#searching-sorted-lists">docs</a> <code>bisect.b...
6
2013-09-08T08:28:55Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
20,007,672
<p>While there's no explicit binary search algorithm in Python, there is a module - <code>bisect</code> - designed to find the insertion point for an element in a sorted list using a binary search. This can be "tricked" into performing a binary search. The biggest advantage of this is the same advantage most library co...
2
2013-11-15T18:03:48Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
20,827,948
<p>This is right from the manual:</p> <p><a href="http://docs.python.org/2/library/bisect.html">http://docs.python.org/2/library/bisect.html</a></p> <p>8.5.1. Searching Sorted Lists</p> <p>The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching ta...
5
2013-12-29T17:20:44Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
27,843,077
<ul> <li><code>s</code> is a list. </li> <li><code>binary(s, 0, len(s) - 1, find)</code> is the initial call.</li> <li><p>Function returns an index of the queried item. If there is no such item it returns <code>-1</code>.</p> <pre><code>def binary(s,p,q,find): if find==s[(p+q)/2]: return (p+q)/2 elif ...
0
2015-01-08T15:01:25Z
[ "python", "binary-search", "bisection" ]
Binary search (bisection) in Python
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position eve...
129
2008-10-17T14:23:17Z
30,385,777
<p>This one is:</p> <ul> <li>not recursive (which makes it more <strong>memory-efficient</strong> than most recursive approaches)</li> <li>actually <strong>working</strong></li> <li>fast since it <strong>runs without any unnecessary <em>if's</em> and conditions</strong></li> <li><strong>based on a mathematical asserti...
2
2015-05-21T23:02:52Z
[ "python", "binary-search", "bisection" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
214,066
<p>You're question is very confusing to say the least. </p> <p>1> The code you pasted is using a trick to communicate with the driver using its 'DOSNAME' i.e.</p> <pre><code>\\.\DRIVERNAME </code></pre> <p>2> Have you created &amp; loaded the 'giveio' driver ?</p> <p>The reason the driver handles this calls is beca...
2
2008-10-17T22:38:41Z
[ "python", "windows", "device" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
214,727
<p>I'm not sure if that's possible. As an alternative, you could write a C/C++ program that does all that kernel space work for you and interface with it in Python via <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html" rel="nofollow">the subprocess module</a> or <a href="http://www.language-binding.ne...
1
2008-10-18T07:54:21Z
[ "python", "windows", "device" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
214,867
<p>I don't know anything about Python, but I do know a bit about drivers. You're not trying to 'open a file in kernel space' at all - you're just trying to open a handle to a device which happens to be made to look a bit like opening a file.</p> <p>CreateFile is a user-mode function, and everything you're doing here ...
3
2008-10-18T10:32:02Z
[ "python", "windows", "device" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
218,562
<p>Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!</p>
5
2008-10-20T14:07:25Z
[ "python", "windows", "device" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
5,870,770
<p>There are 2 ways to do this.</p> <p>The first way is using the win32 python bindings</p> <pre><code>h = win32file.CreateFile </code></pre> <p>Or using ctypes</p>
2
2011-05-03T14:11:26Z
[ "python", "windows", "device" ]
Opening a handle to a device in Python on Windows
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
12
2008-10-17T15:47:40Z
5,891,868
<p>It sounds to me like you're asking why os.open is not magically equal to calling CreateFile with a very specific set of parameters. Kostya's answer is practical in that it tells you that you can use the Win32 python bindings to call CreateFile which is a Win32 API, directly.</p> <p>Anything other than doing direct ...
2
2011-05-05T01:59:00Z
[ "python", "windows", "device" ]
Keyboard interruptable blocking queue in Python
212,797
<p>It seems</p> <pre><code>import Queue Queue.Queue().get(timeout=10) </code></pre> <p>is keyboard interruptible (ctrl-c) whereas</p> <pre><code>import Queue Queue.Queue().get() </code></pre> <p>is not. I could always create a loop;</p> <pre><code>import Queue q = Queue() while True: try: q.get(time...
11
2008-10-17T16:10:51Z
212,975
<p><code>Queue</code> objects have this behavior because they lock using <code>Condition</code> objects form the <code>threading</code> module. So your solution is really the only way to go.</p> <p>However, if you really want a <code>Queue</code> method that does this, you can monkeypatch the <code>Queue</code> class...
5
2008-10-17T17:01:03Z
[ "python", "multithreading", "concurrency", "python-2.x" ]
Keyboard interruptable blocking queue in Python
212,797
<p>It seems</p> <pre><code>import Queue Queue.Queue().get(timeout=10) </code></pre> <p>is keyboard interruptible (ctrl-c) whereas</p> <pre><code>import Queue Queue.Queue().get() </code></pre> <p>is not. I could always create a loop;</p> <pre><code>import Queue q = Queue() while True: try: q.get(time...
11
2008-10-17T16:10:51Z
216,719
<p>This may not apply to your use case at all. But I've successfully used this pattern in several cases: (sketchy and likely buggy, but you get the point).</p> <pre><code>STOP = object() def consumer(q): while True: x = q.get() if x is STOP: return consume(x) def main() q ...
4
2008-10-19T17:40:36Z
[ "python", "multithreading", "concurrency", "python-2.x" ]
Using django-rest-interface
212,941
<p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go a...
20
2008-10-17T16:53:23Z
214,383
<p>Well, from the look of things, there's an <code>authentication</code> parameter to <code>Collection</code>. (see this example: <a href="http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/authentication.py" rel="nofollow">authentication.py</a>)</p> <p>Second, (even if Django doesn't ...
3
2008-10-18T01:52:44Z
[ "python", "django", "rest" ]
Using django-rest-interface
212,941
<p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go a...
20
2008-10-17T16:53:23Z
214,946
<p>Even with the Authentication parameter, you don't have fine-grained control over what people can do. The current implementation of the Django-REST interface doesn't track the user information, so you don't have this information available for doing fine-grained authorization checks.</p> <p>See <a href="http://code....
3
2008-10-18T11:49:51Z
[ "python", "django", "rest" ]
Using django-rest-interface
212,941
<p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go a...
20
2008-10-17T16:53:23Z
996,423
<p>I would look into using django-piston <a href="http://bitbucket.org/jespern/django-piston/wiki/Home">http://bitbucket.org/jespern/django-piston/wiki/Home</a> application if security is your main concern. </p> <p>I have used django-rest-interface in the past, its reliable and though simple can be quite powerful, how...
12
2009-06-15T14:28:37Z
[ "python", "django", "rest" ]
Using django-rest-interface
212,941
<p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go a...
20
2008-10-17T16:53:23Z
11,989,130
<p>Please do have a look at django-rest-framework, I just stepped over from tastypie to this new framework, works great!</p> <p><a href="http://django-rest-framework.org/" rel="nofollow">http://django-rest-framework.org/</a></p> <p>Especially the class based views and the browsable api! and many other advantages (e.....
2
2012-08-16T14:16:34Z
[ "python", "django", "rest" ]
In Django, how could one use Django's update_object generic view to edit forms of inherited models?
213,237
<p>In Django, given excerpts from an application <em>animals</em> likeso:</p> <p>A <em>animals/models.py</em> with: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType class Animal(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=Tr...
0
2008-10-17T18:16:07Z
213,393
<p>AFAICT, cats and dogs are on different DB tables, and maybe there's no Animal table. but you're using one URL pattern for all. somewhere you need to choose between each.</p> <p>I'd use a different URL patter for cats and dogs, both would call <code>'create_update.update_object'</code>; but using a different <code...
0
2008-10-17T18:51:06Z
[ "python", "django", "forms", "inheritance", "decorator" ]
In Django, how could one use Django's update_object generic view to edit forms of inherited models?
213,237
<p>In Django, given excerpts from an application <em>animals</em> likeso:</p> <p>A <em>animals/models.py</em> with: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType class Animal(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=Tr...
0
2008-10-17T18:16:07Z
215,488
<p>Alright, here's what I've done, and it seems to work and be a sensible design (though I stand to be corrected!).</p> <p>In a core library (e.g. mysite.core.views.create_update), I've written a decorator:</p> <pre><code>from django.contrib.contenttypes.models import ContentType from django.views.generic import crea...
1
2008-10-18T19:40:12Z
[ "python", "django", "forms", "inheritance", "decorator" ]
python threadsafe object cache
213,455
<p>I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p> <p><a href="http://fres...
9
2008-10-17T19:05:20Z
213,695
<p>You probably want to use memcached instead. It's very fast, very stable, very popular, has good python libraries, and will allow you to grow to a distributed cache should you need to:</p> <p><a href="http://www.danga.com/memcached/" rel="nofollow">http://www.danga.com/memcached/</a></p>
4
2008-10-17T20:18:25Z
[ "python", "multithreading", "caching" ]
python threadsafe object cache
213,455
<p>I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p> <p><a href="http://fres...
9
2008-10-17T19:05:20Z
213,768
<p>Thread per request is often a bad idea. If your server experiences huge spikes in load it will take the box to its knees. Consider using a thread pool that can grow to a limited size during peak usage and shrink to a smaller size when load is light.</p>
8
2008-10-17T20:39:48Z
[ "python", "multithreading", "caching" ]
python threadsafe object cache
213,455
<p>I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p> <p><a href="http://fres...
9
2008-10-17T19:05:20Z
215,329
<p>Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues.</p> <p>There's a list here: <a href="http://coreygoldberg.blogspot.com/2008/09/python...
7
2008-10-18T17:48:05Z
[ "python", "multithreading", "caching" ]
python threadsafe object cache
213,455
<p>I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p> <p><a href="http://fres...
9
2008-10-17T19:05:20Z
17,433,852
<p>For a thread safe object you want threading.local:</p> <pre><code>from threading import local safe = local() safe.cache = {} </code></pre> <p>You can then put and retrieve objects in <code>safe.cache</code> with thread safety.</p>
2
2013-07-02T19:09:51Z
[ "python", "multithreading", "caching" ]
A good multithreaded python webserver?
213,483
<p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large...
13
2008-10-17T19:12:38Z
213,515
<p>Not multithreaded, but <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> might serve your needs.</p>
2
2008-10-17T19:22:28Z
[ "python", "apache", "webserver", "mod-python" ]
A good multithreaded python webserver?
213,483
<p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large...
13
2008-10-17T19:12:38Z
213,539
<p>Perhaps you have a problem with your implementation in Python using <code>BaseHttpServer</code>. There's no reason for it to "get stuck", and implementing a simple threaded server using <code>BaseHttpServer</code> and <code>threading</code> shouldn't be difficult.</p> <p>Also, see <a href="http://pymotw.com/2/BaseH...
2
2008-10-17T19:27:36Z
[ "python", "apache", "webserver", "mod-python" ]
A good multithreaded python webserver?
213,483
<p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large...
13
2008-10-17T19:12:38Z
213,549
<p>I use CherryPy both personally and professionally, and I'm extremely happy with it. I even do the kinds of thing you're describing, such as having global object caches, running other threads in the background, etc. And it integrates well with Apache; simply run CherryPy as a standalone server bound to localhost, t...
0
2008-10-17T19:30:57Z
[ "python", "apache", "webserver", "mod-python" ]
A good multithreaded python webserver?
213,483
<p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large...
13
2008-10-17T19:12:38Z
213,551
<p>You could instead use a distributed cache that is accessible from each process, <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a> being the example that springs to mind.</p>
2
2008-10-17T19:31:15Z
[ "python", "apache", "webserver", "mod-python" ]
A good multithreaded python webserver?
213,483
<p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large...
13
2008-10-17T19:12:38Z
213,563
<p><a href="http://cherrypy.org/">CherryPy</a>. Features, as listed from the website:</p> <ul> <li>A fast, HTTP/1.1-compliant, WSGI thread-pooled webserver. Typically, CherryPy itself takes only 1-2ms per page!</li> <li>Support for any other WSGI-enabled webserver or adapter, including Apache, IIS, lighttpd, mod_pytho...
16
2008-10-17T19:33:25Z
[ "python", "apache", "webserver", "mod-python" ]