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
listlengths
1
5
datetime.now() in Django application goes bad
883,823
<p>I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:</p> <pre><code>def servertime(): return HttpResponse( datetime.now() ) <...
5
2009-05-19T16:34:03Z
16,958,086
<p>Try to set your time zone (TIME_ZONE variable) in settings.py</p> <p>That worked for me.</p>
0
2013-06-06T09:11:41Z
[ "python", "django", "apache", "datetime", "mod-wsgi" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" si...
3
2009-05-19T17:28:52Z
884,073
<p>What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to:</p> <pre><code>def func(n): x, y = n ... </code></pre> <p>Both functions require a single argument (list or tuple) that contains two elements.</p>
6
2009-05-19T17:31:20Z
[ "python" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" si...
3
2009-05-19T17:28:52Z
884,114
<p>More information about tuple parameter unpacking (and why it is removed) here: <a href="http://www.python.org/dev/peps/pep-3113/">http://www.python.org/dev/peps/pep-3113/</a></p>
6
2009-05-19T17:41:57Z
[ "python" ]
What is an exotic function signature in Python?
884,068
<p>I recently saw a <a href="http://pypi.python.org/pypi/decorator/" rel="nofollow">reference to "exotic signatures"</a> and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is</p> <pre><code>def exotic_signature((x, y)=(1,2)): return x+y </code></pre> <p>What makes this an "exotic" si...
3
2009-05-19T17:28:52Z
885,290
<p>Here's a slightly more complex example. Let's say you're doing some kind of graphics programming and you've got a list of points.</p> <pre><code>points = [(1,2), (-3,1), (4,-2), (-1,5), (3,3)] </code></pre> <p>and you want to know how far away they are from the origin. You might define a function like this:</p> ...
1
2009-05-19T22:11:11Z
[ "python" ]
How can I create a RSA public key in PEM format from an RSA modulus?
884,207
<p>I have the modulus of an RSA public key. I want to use this public key with the <a href="http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto" rel="nofollow">Python library "M2Crypto",</a> but it requires a public key in PEM format. </p> <p>Thus, I have to convert the RSA modulus to a PEM file.</p> <p>The m...
2
2009-05-19T17:58:14Z
884,562
<p>The M2Crypto library has <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA-module.html#new%5Fpub%5Fkey" rel="nofollow">a way to reconstruct a public key.</a> You need to know the public exponent, <code>e</code> (often 65337 for RSA keys, but other numbers such as 3 or 17 have been used), and the modul...
4
2009-05-19T19:21:54Z
[ "python", "cryptography", "rsa", "m2crypto" ]
How to return a function value with decorator and thread
884,410
<p>have this code</p> <pre><code>import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): ret...
2
2009-05-19T18:46:54Z
884,415
<p>That's because you never return a value in your "decorator"-function.</p> <p>You have to include a shared variable in your thread and move the return value of your threaded function back into the "decorator"-function.</p>
2
2009-05-19T18:49:31Z
[ "python", "multithreading", "decorator" ]
How to return a function value with decorator and thread
884,410
<p>have this code</p> <pre><code>import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): ret...
2
2009-05-19T18:46:54Z
884,425
<p>The reason <code>None</code> is returned, is because there is nothing to return (besides the fact that <code>decorator</code> doesn't have a return statement). <code>join()</code> always returns <code>None</code>, as per the <a href="http://docs.python.org/3.0/library/threading.html#threading.Thread.join" rel="nofol...
4
2009-05-19T18:53:41Z
[ "python", "multithreading", "decorator" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def wr...
1
2009-05-19T19:27:00Z
884,634
<blockquote> <p>But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object.</p> </blockquote> <p>That's why the manual suggests that you do this for all "real" attribute accesses.</p> <pre><code>theobj = ...
2
2009-05-19T19:36:15Z
[ "python" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def wr...
1
2009-05-19T19:27:00Z
884,655
<p>Unless I'm missing something, this will work just fine:</p> <pre><code>def __getattr__(self, name): return getattr(self.theObject, name) </code></pre> <p><hr /></p> <p><strong>Edit:</strong> for those thinking that the lookup of <code>self.theObject</code> will result in an infinite recursive call to <code>__...
3
2009-05-19T19:41:07Z
[ "python" ]
Wrapping a Python Object
884,594
<p>I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects:</p> <pre><code>def __init__(self, anObject): self.theObject = anObject </code></pre> <p>and provides a "write" method: </p> <pre><code>def wr...
1
2009-05-19T19:27:00Z
885,340
<p>I'm glad to see others have been able to help you with the recursive call to <code>__getattr__</code>. Since you've asked for comments on the general approach of serializing to plist, I just wanted to chime in with a few thoughts.</p> <p>Python's plist implementation handles basic types only, and provides no extens...
1
2009-05-19T22:30:14Z
[ "python" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something l...
33
2009-05-19T19:39:42Z
884,751
<p>I would definitely use <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> rather than rolling my own solution using subprocess.</p>
1
2009-05-19T20:04:01Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something l...
33
2009-05-19T19:39:42Z
884,753
<p>I don't think you need queue unless you intend to get data out of the applications (Which if you do want data, I think it may be easier to add it to a database anyway)</p> <p>but try this on for size:</p> <p>put the contents of your create_graphs.py script all into a function called "create_graphs"</p> <pre><code...
2
2009-05-19T20:04:26Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something l...
33
2009-05-19T19:39:42Z
884,846
<p>What you are looking for is the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool">process pool</a> class in multiprocessing.</p> <pre><code>import multiprocessing import subprocess def work(cmd): return subprocess.call(cmd, shell=False) if __name__ == '__main__': co...
44
2009-05-19T20:26:13Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to spawn parallel child processes on a multi-processor system?
884,650
<p>I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called:</p> <pre><code>$ python create_graphs.py --name=NAME </code></pre> <p>where NAME is something l...
33
2009-05-19T19:39:42Z
1,008,113
<p>Here is the solution I came up, based on Nadia and Jim's comments. I am not sure if it is the best way, but it works. The original child script being called needs to be a shell script because I need to use some 3rd party apps including Matlab. So I had to take it out of Python and code it in bash.</p> <pre><code>im...
2
2009-06-17T16:16:38Z
[ "python", "exec", "subprocess", "multiprocessing" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
885,048
<p>There is a parsedate function in <a href="http://docs.python.org/library/email.util.html" rel="nofollow">email.util</a>. It parses all valid RFC 2822 dates and some special cases.</p>
8
2009-05-19T21:10:19Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
885,049
<pre><code>from email.utils import parsedate print parsedate('Fri, 15 May 2009 17:58:28 +0000') </code></pre> <p><a href="http://docs.python.org/library/email.util.html#email.utils.parsedate">Documentation</a>.</p>
12
2009-05-19T21:11:14Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
1,258,623
<p>The problem is that parsedate will ignore the offset.</p> <p>Do this instead:</p> <pre><code>from email.utils import parsedate_tz print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700') </code></pre>
26
2009-08-11T05:50:00Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
17,155,727
<p>I'd like to elaborate on previous answers. <code>email.utils.parsedate</code> and <code>email.utils.parsedate_tz</code> both return tuples, since the OP needs a <code>datetime.datetime</code> object, I'm adding these examples for completeness:</p> <pre><code>from email.utils import parsedate from datetime import da...
7
2013-06-17T19:58:42Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
How to parse a RFC 2822 date/time into a Python datetime?
885,015
<p>I have a date of the form specified by RFC 2822 -- say <code>Fri, 15 May 2009 17:58:28 +0000</code>, as a string. Is there a quick and/or standard way to get it as a <code>datetime</code> object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.</p>
21
2009-05-19T21:03:05Z
22,486,403
<p>It looks like Python 3.3 going forward has a new method <code>parsedate_to_datetime</code> in email.utils that takes care of the intermediate steps:</p> <blockquote> <p><strong>email.utils.parsedate_to_datetime(date)</strong> </p> <p>The inverse of format_datetime(). Performs the same function as parsedate()...
4
2014-03-18T17:14:44Z
[ "python", "parsing", "datetime", "time", "python-2.5" ]
Django Admin & Model Deletion
885,103
<p>I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its <code>delete</code> method.</p> <pre><code>class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, sel...
2
2009-05-19T21:26:03Z
885,222
<p>According to <a href="http://code.djangoproject.com/ticket/11022" rel="nofollow">this</a> documentation bug report (<a href="http://code.djangoproject.com/ticket/11022" rel="nofollow">Document that the admin bulk delete doesn't call Model.delete()</a>), the admin's <em>bulk</em> delete does NOT call the model's dele...
9
2009-05-19T21:54:56Z
[ "python", "django", "django-admin" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conv...
2
2009-05-19T21:41:11Z
885,203
<p>The Django book covers this issue in <a href="http://www.djangobook.com/en/1.0/chapter05/" rel="nofollow">Chapter 5</a>, near the end of the chapter (or bottom of the page, in the web edition). Basically, the rules are:</p> <ul> <li>When <em>adding</em> a field, first add it to the database manually (using, e.g., <...
4
2009-05-19T21:50:00Z
[ "python", "database", "django", "django-models" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conv...
2
2009-05-19T21:41:11Z
885,513
<p>As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic "schema migration". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself.</p> <p>There are some tools on the horizon for Django schema migration. (I'm w...
5
2009-05-19T23:19:06Z
[ "python", "database", "django", "django-models" ]
python orm
885,172
<p>This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conv...
2
2009-05-19T21:41:11Z
885,738
<p>We include a 'version' number in the application name.</p> <p>Our directories look like this</p> <pre><code>project settings.py appA_1 __init__.py models.py tests.py appB_1 __init__.py models.py tests.py appB_2 __init__.py models.p...
0
2009-05-20T01:05:59Z
[ "python", "database", "django", "django-models" ]
Problems eagerloading a set of object using SQLAlchemy
885,235
<p>I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's.</p> <p>Unfortunately the query below fails because table O2 is aliased in the query and the column referenced by the or...
2
2009-05-19T21:57:26Z
885,282
<p>Use a lambda of clause elements to achieve late binding of the order by, like this:</p> <pre><code>ones = relation('O1', order_by=lambda:[O1.value]) </code></pre> <p>Or as an another option, make the whole order_by a string, like this:</p> <pre><code>ones = relation('O1', order_by='O1.value, O1.something_else') <...
3
2009-05-19T22:08:02Z
[ "python", "orm", "sqlalchemy" ]
wxPython dialogs: "Enter" keyboard button would not "ok" the dialog
885,294
<p>I am creating a custom wxPython dialog by subclassing <code>wx.Dialog</code>. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button.</p> <p>How do I solve this?</p>
2
2009-05-19T22:13:28Z
885,307
<p>That should happen automatically if the button has the <em>wx.ID&#95;OK</em> id. If that's impossible then the <em>wx.StdDialogButtonSizer.SetAffirmativeButton()</em> method could be a solution (using the <em>StdDialogButtonSizer</em> class will help with correct button placement and positioning on the different pla...
5
2009-05-19T22:18:02Z
[ "python", "keyboard", "wxpython" ]
Closing and Opening Frames in wxPython
885,453
<p>I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. </p> <p>The login frame is a subclass of wx.Frame, and basically I just want to close it...
0
2009-05-19T23:02:13Z
885,654
<p>I would make your main frame appear, then show a modal login dialog over top instead.</p> <p>If you don't want to do that, I suggest you create two separate Frames and have your application listen for a close event on the login frame. Handle the login in that event handler, then have it show the main window. Basi...
1
2009-05-20T00:18:19Z
[ "python", "user-interface", "network-programming", "wxpython" ]
Closing and Opening Frames in wxPython
885,453
<p>I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. </p> <p>The login frame is a subclass of wx.Frame, and basically I just want to close it...
0
2009-05-19T23:02:13Z
889,899
<p><code>mainWindow</code> is a local variable of <code>handleServerSignon</code>. This is a guess, but I think it may be garbage collected as soon as the <code>handleServerSignon</code> method returns.</p>
0
2009-05-20T19:52:13Z
[ "python", "user-interface", "network-programming", "wxpython" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
885,551
<p>This code seems to work:</p> <pre><code>l = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] previous = None # value/repetition pair greatest = (-1, -1) reps = 1 for e in l: if e == previous: reps += 1 else: if reps &gt; greatest[1]: greatest = (previous, reps) previous = e ...
0
2009-05-19T23:30:22Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
885,554
<p>I'd use a hashmap of item to counter.</p> <p>Every time you see a 'key' succession, increment its counter value. If you hit a new element, set the counter to 1 and keep going. At the end of this linear search, you should have the maximum succession count for each number. </p>
0
2009-05-19T23:31:23Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
885,566
<p>Loop through the list, keep track of the current number, how many times it has been repeated, and compare that to the most times youve seen that number repeated.</p> <pre><code>Counts={} Current=0 Current_Count=0 LIST = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] for i in LIST: if Current == i: Current_Count++...
3
2009-05-19T23:37:19Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
885,584
<p>Use <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">groupby</a>, it group elements by value:</p> <pre><code>from itertools import groupby group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]) print max(group, key=lambda k: len(list(k[1]))) </code></pre> <p>And here is the c...
42
2009-05-19T23:43:39Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
885,595
<p>If you want it for just <em>any</em> element (i.e. the element with the most repetitions), you could use:</p> <pre><code>def f((v, l, m), x): nl = l+1 if x==v else 1 return (x, nl, max(m,nl)) maxrep = reduce(f, l, (0,0,0))[2]; </code></pre> <p>This only counts continuous repetitions (Result for <code>[1,2...
1
2009-05-19T23:48:49Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
12,696,788
<p>This is my solution:</p> <pre class="lang-py prettyprint-override"><code>def longest_repetition(l): if l == []: return None element = l[0] new = [] lar = [] for e in l: if e == element: new.append(e) else: if len(new) &gt; len(lar): ...
1
2012-10-02T19:17:42Z
[ "python", "list" ]
How do you calculate the greatest number of repetitions in a list?
885,546
<p>If I have a list in Python like</p> <pre><code>[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1] </code></pre> <p>How do I calculate the greatest number of repeats for any element? In this case <code>2</code> is repeated a maximum of 4 times and <code>1</code> is repeated a maximum of 3 times.</p> <p>Is there a way to do this...
10
2009-05-19T23:27:17Z
15,770,461
<p>-You can make new copy of the list but with unique values and a corresponding hits list.</p> <p>-Then get the Max of hits list and get from it's index your most repeated item.</p> <pre><code>oldlist = ["A", "B", "E", "C","A", "C","D","A", "E"] newlist=[] hits=[] for i in range(len(oldlist)): if oldlist[i] in n...
1
2013-04-02T17:31:02Z
[ "python", "list" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pick...
0
2009-05-20T00:03:05Z
885,643
<p>Here are three things you can try:</p> <ol> <li>Compress the pickled dictionary with zlib. pickle.dumps(dict).encode("zlib")</li> <li>Make your own serializing format (shouldn't be too hard).</li> <li>Load the data in a sqlite database.</li> </ol>
0
2009-05-20T00:11:09Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pick...
0
2009-05-20T00:03:05Z
885,657
<p>To get fast lookups, use the standard Python <code>dbm</code> module (see <a href="http://docs.python.org/library/dbm.html" rel="nofollow">http://docs.python.org/library/dbm.html</a>) to build your database file, and do lookups in it. The dbm file format may not be cross-platform, so you may want to to distrubute yo...
2
2009-05-20T00:19:02Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pick...
0
2009-05-20T00:03:05Z
885,684
<p>The standard <code>shelve</code> module will give you a persistent dictionary that is stored in a dbm style database. Providing that your keys are strings and your values are picklable (since you're using pickle already, this must be true), this could be a better solution that simply storing the entire dictionary in...
6
2009-05-20T00:33:29Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pick...
0
2009-05-20T00:03:05Z
885,813
<p>How much memory can your application reasonably use? Is this going to be running on each user's desktop, or will there just be one deployment somewhere?</p> <p>A python dictionary in memory can certainly cope with two million keys. You say that you've got a subset of the data; do you have the whole lot? Maybe yo...
2
2009-05-20T01:46:25Z
[ "python", "database", "dictionary" ]
What is the least resource intense data structure to distribute with a Python Application
885,625
<p>I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pick...
0
2009-05-20T00:03:05Z
1,416,881
<p>See this solution at SourceForge, esp. the "endnotes" documentation:</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 them chronologically by keywords without any SQ...
1
2009-09-13T04:52:36Z
[ "python", "database", "dictionary" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', ...
2
2009-05-20T00:07:31Z
885,640
<p>In the example code, <code>answers</code> is an iterable object containing zero or more items, which are each assigned to <code>rdata</code> in turn. To see the properties of the individual responses, try:</p> <pre><code>dir(answers[0]) </code></pre>
1
2009-05-20T00:10:38Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', ...
2
2009-05-20T00:07:31Z
885,648
<p>answers is an iterable as indicated by its "__iter__" method. Think of answers as a list of rdatas.</p> <p>You can try doing this to get 1 rdata from answers:</p> <pre><code>answers.__iter__().next() </code></pre>
1
2009-05-20T00:14:56Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', ...
2
2009-05-20T00:07:31Z
885,796
<p>If you're on Python 2.6, the "proper" way to get the first item of any iterable (such as <code>answers</code> here) is <code>next(iter(answers))</code>; if you want to avoid an exception when <code>answers</code> is an empty iterable, then <code>next(iter(answers), somevalue)</code> will return <code>somevalue</code...
0
2009-05-20T01:38:01Z
[ "python", "dns", "dnspython" ]
dnspython and python objects
885,634
<p>I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:</p> <pre><code>import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', ...
2
2009-05-20T00:07:31Z
886,171
<p>I haven't looked at <code>dns.resolver</code> as of yet - I just added it to the ever-growing list of things to check out. I would guess that <code>rdata</code> refers to the resource record type specific data as described in <a href="http://tools.ietf.org/html/rfc1035#section-4.1.3" rel="nofollow">Section 4.1.3 of ...
1
2009-05-20T04:45:08Z
[ "python", "dns", "dnspython" ]
How does MySQL's RENAME TABLE statment work/perform?
885,771
<p>MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. </p> <p>The manual mentions </p> <blockquote> <p>The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running</p> </blockquote> <p>The manual does not (...
3
2009-05-20T01:22:36Z
885,783
<p>I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant.</p>
5
2009-05-20T01:29:27Z
[ "php", "python", "mysql", "ruby", "migration" ]
How does MySQL's RENAME TABLE statment work/perform?
885,771
<p>MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. </p> <p>The manual mentions </p> <blockquote> <p>The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running</p> </blockquote> <p>The manual does not (...
3
2009-05-20T01:22:36Z
885,848
<p>In addition to altering the metadata, it also renames the associated .FRM file. While they can claim it being an "atomic" operation, this is an actual comment in the code for the mysql_rename_tables function...</p> <pre><code>/* Lets hope this doesn't fail as the result will be messy */ </code></pre> <p>=)</p>
1
2009-05-20T02:03:22Z
[ "php", "python", "mysql", "ruby", "migration" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;ud...
0
2009-05-20T04:20:04Z
886,129
<p>not sure i'd do it that way, but the quickest way would be to shift the captures:</p> <p>([\w\W]<em>[\w\W]</em>&lt;%s>)[\w\W]<em>([\w\W]</em>)' and replace with group1 +mode+group2</p>
0
2009-05-20T04:30:00Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;ud...
0
2009-05-20T04:20:04Z
886,175
<p>Supposing that your link_regex is correct, you can add parenthesis like this:</p> <pre><code>(&lt;link [\w\W]+ %s&gt;[\w\W]*[\w\W]*&lt;%s&gt;)([\w\W]*)(&lt;/%s&gt;[\w\W]*&lt;/link&gt;) </code></pre> <p>and then you could do:</p> <pre><code>p = re.compile(link_regex) replacement = 'foo' print p.sub(r'\g&lt;1&gt;' ...
1
2009-05-20T04:47:16Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;ud...
0
2009-05-20T04:20:04Z
886,195
<p>I have to give you the obligatory: "don't use regular expressions to do this."</p> <p>Check out how very easily awesome it is to do this with <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML" rel="nofollow">BeautifulSoup</a>, for example:</p> <pre><code>&gt;&gt;&gt; from Beaut...
6
2009-05-20T04:58:12Z
[ "python", "regex", "groups" ]
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
886,111
<p>I need to parse a configuration file which looks like this (simplified):</p> <pre><code>&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="1"&gt; &lt;encapsulation&gt; &lt;mode&gt;ipsec&lt;/mode&gt; &lt;/encapsulation&gt; &lt;/link&gt; &lt;link name="Link2" id="2"&gt; &lt;encapsulation&gt; &lt;mode&gt;ud...
0
2009-05-20T04:20:04Z
886,273
<p>This looks like valid XML, in that case you don't need BeautifulSoup, definitely not the regex, just load XML using any good XML library, edit it and print it out, here is a approach using ElementTree:</p> <pre><code>import xml.etree.cElementTree as ET s = """&lt;config&gt; &lt;links&gt; &lt;link name="Link1" id="...
2
2009-05-20T05:23:36Z
[ "python", "regex", "groups" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
886,274
<p>The <code>a</code> is superfluous. <code>wua</code> is the same as <code>wu</code> since <code>w</code> comes first and will thus truncate the file. If you would reverse the order, that is, <code>auw</code>, that would be the same as <code>au</code>. Visualized:</p> <pre><code>&gt;&gt;&gt; f = open('test.txt', 'r')...
5
2009-05-20T05:24:07Z
[ "python", "file" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
886,280
<p>I did not notice that you knew what the modifiers did. Combined they will do the following:</p> <p>A and W together is superfluous since both will open for writing. When using W, the file will be overwritten. When using A, all new text is appended after the existing content.</p> <p>U means "open file XXX for inpu...
3
2009-05-20T05:24:55Z
[ "python", "file" ]
What is "wua" mode when opening a file in python?
886,238
<p>I have recently been going through some of our windows python 2.4 code and come across this:</p> <pre><code>self.logfile = open(self.logfile_name, "wua") </code></pre> <p>I know what <code>w</code>, <code>u</code> and <code>a</code> do on their own, but what happens when you combine them?</p>
4
2009-05-20T05:13:13Z
890,542
<p>Underneath the hood Python 2.4 passes the the builtin <code>open</code>'s arguments on to the operating system's <code>fopen</code> function. Python does do some mangling of the mode string under certain conditions.</p> <pre><code>if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0) mode = "rb"; </code></pre>...
1
2009-05-20T22:17:53Z
[ "python", "file" ]
Beautiful Soup and uTidy
886,381
<p>I want to pass the results of <a href="http://utidylib.berlios.de/" rel="nofollow">utidy</a> to Beautiful Soup, ala:</p> <pre><code>page = urllib2.urlopen(url) options = dict(output_xhtml=1,add_xml_decl=0,indent=1,tidy_mark=0) cleaned_html = tidy.parseString(page.read(), **options) soup = BeautifulSoup(cleaned_html...
3
2009-05-20T06:05:38Z
886,400
<p>Just wrap <a href="http://docs.python.org/library/functions.html#str"><code>str()</code></a> around <code>cleaned_html</code> when passing it to BeautifulSoup. </p>
9
2009-05-20T06:11:05Z
[ "python", "screen-scraping", "beautifulsoup", "tidy" ]
Beautiful Soup and uTidy
886,381
<p>I want to pass the results of <a href="http://utidylib.berlios.de/" rel="nofollow">utidy</a> to Beautiful Soup, ala:</p> <pre><code>page = urllib2.urlopen(url) options = dict(output_xhtml=1,add_xml_decl=0,indent=1,tidy_mark=0) cleaned_html = tidy.parseString(page.read(), **options) soup = BeautifulSoup(cleaned_html...
3
2009-05-20T06:05:38Z
32,613,070
<p>Convert the value passed to BeautifulSoup into a string. In your case, do the following edit to the last line:</p> <pre><code>soup = BeautifulSoup(str(cleaned_html)) </code></pre>
2
2015-09-16T15:39:29Z
[ "python", "screen-scraping", "beautifulsoup", "tidy" ]
Django without shell access
886,526
<p>Is it possible to run django without shell access? My hoster supports the following for 5€/month:</p> <ul> <li>python (I assume via mod_python)</li> <li>mysql </li> </ul> <p>There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it.</p> <p>I know that Google Apps also ...
0
2009-05-20T07:07:41Z
886,561
<p>It is possible.</p> <p>Usually you will develop your application locally (where shell access is nice to have) and publish your work to your server. All you need for this is FTP access and some way to import a database dump from your development database (often hosters provide an installation of phpMyAdmin for this)...
1
2009-05-20T07:17:38Z
[ "python", "django", "shell" ]
Django without shell access
886,526
<p>Is it possible to run django without shell access? My hoster supports the following for 5€/month:</p> <ul> <li>python (I assume via mod_python)</li> <li>mysql </li> </ul> <p>There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it.</p> <p>I know that Google Apps also ...
0
2009-05-20T07:07:41Z
886,581
<p>It's possible but not desirable. Having shell access makes it possible to centralise things properly using symlinks. </p> <p>Get a better host would be my first suggestion. <a href="http://www.webfaction.com/" rel="nofollow">WebFaction</a> is the most recommended shared host for using with Django.</p> <p>If that's...
4
2009-05-20T07:22:44Z
[ "python", "django", "shell" ]
How to perform a query in django that selects all projects where I am a team member of?
886,624
<p>I have the concept of a team in my django app.</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) </code></pre> <p>I would like to fetch all teams the currently logged in user is member of. Something along the lines of </p>...
0
2009-05-20T07:33:36Z
886,891
<p>You don't need <code>in</code> here, Django handles that automatically in a ManyToMany lookup.</p> <p>Also, you need to understand that the database fields must always be on the <em>left</em> of the lookup, as they are actually handled as parameters to a function.</p> <p>What you actually want is very simple:</p> ...
4
2009-05-20T08:48:11Z
[ "python", "django", "pinax" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,643
<p>counter += 1</p> <p>but that isn't the problem. What's the error? Indentation error maybe?</p>
1
2009-05-20T07:40:27Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,644
<p>The error you're seeing is because you're indexing out of range on the <code>str_date_list</code> list, not because you're incrementing the variable.</p> <p>Compare the largest value of <code>counter</code> that the loop prints (<code>30</code>) to the length of the list (<code>len(str_date_list)</code>). Since ind...
2
2009-05-20T07:40:51Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,670
<p>You don't need to duplicate the loop iteration variable and the counter:</p> <pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_dat...
2
2009-05-20T07:52:14Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,694
<ol> <li><p>you do not need to create a iterator for going thru 0-31 you can use enumerate e.g.</p> <p>for i, sdate in enumerate(str_date_list): print i, sdate</p></li> <li><p>if you are using iter isn't item and counter same?</p></li> </ol>
2
2009-05-20T07:58:42Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,787
<p>Better written:</p> <pre><code>str_date_list=[] for n in xrange(1,32): str_date_list.append(str(n).zfill(2)+'-'+'05' + '-' +'09') for i in xrange(len(str_date_list)): daily_user_status_list=[] print i val_time1 = str_date_list[i] val_time2 = str_date_list[i + 1] </code></pre> <ul> <li>xrange g...
0
2009-05-20T08:20:00Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,879
<p>The counter is getting out of step with the sequences you're iterating over. But more than that, the counter is totally unnecessary.</p> <p>You've got several manual iterations of things that could be automated, and they're causing you to trip over. Especially, you hardly ever need to manually track a counter while...
8
2009-05-20T08:44:37Z
[ "python", "iterator" ]
How to use counter in for loop python
886,629
<pre><code>my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item...
1
2009-05-20T07:36:04Z
886,882
<p>Just for kicks, here's the super-compact Pythonic way to write this:</p> <pre><code>from itertools import izip, islice str_date_list = ['%02d-05-09' % i for i in xrange(1, 32)] for val_time1, val_time2 in izip(islice(str_date_list, 0, None), islice(str_date_list, 1, None)): daily_user_status_list = [ &lt;whatev...
4
2009-05-20T08:45:17Z
[ "python", "iterator" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,672
<p>You appear to be asking for the sum of the differences between the paired components of the two arrays:</p> <pre><code>&gt;&gt;&gt; A=[1,2,3,4] &gt;&gt;&gt; B=[2,3,4,5] &gt;&gt;&gt; sum(abs(a - b) for a, b in zip(A, B)) 4 </code></pre>
6
2009-05-20T07:52:53Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,675
<p>It is not clear what exactly is required here, but here is my guess</p> <pre><code>a=[1,2,3,4] b=[2,3,4,5] def a_b(a,b): return sum(map(lambda a:abs(a[0]-a[1]), zip(a,b))) print a_b(a,b) </code></pre>
2
2009-05-20T07:54:17Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,762
<p>Python has powerful built-in types, but <strong>Python lists are not mathematical vectors or matrices</strong>. You <em>could</em> do this with lists, but it will likely be cumbersome for anything more than trivial operations.</p> <p>If you find yourself needing vector or matrix arithmetic often, the <strong>standa...
15
2009-05-20T08:15:52Z
[ "python", "vector", "norm" ]
Get the 1-norm of a vector in Python
886,633
<p>How can I calculate the 1-norm of the difference of two vectors, <code>||a - b||_1 = sum(|a_i - b_i|)</code> in Python?</p> <pre><code>a = [1,2,3,4] b = [2,3,4,5] ||a - b||_1 = 4 </code></pre>
10
2009-05-20T07:37:49Z
886,791
<p>In NumPy, for two vectors <code>a</code> and <code>b</code>, this is just</p> <pre><code>numpy.linalg.norm(a - b, ord=1) </code></pre>
8
2009-05-20T08:20:33Z
[ "python", "vector", "norm" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, an...
2
2009-05-20T07:44:14Z
886,671
<p>You can trap the exit signal with the <strong>signal</strong> module. Haven't tried this with mod_python though.</p> <p><a href="http://docs.python.org/library/signal.html" rel="nofollow">http://docs.python.org/library/signal.html</a></p> <p>Note in the docs:</p> <blockquote> <p>When a signal arrives during an ...
1
2009-05-20T07:52:44Z
[ "python", "cgi" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, an...
2
2009-05-20T07:44:14Z
886,956
<p>The script is probably not killed silently; you just don't see the exception which python throws. I suggest to wrap the whole script in <code>try-except</code> and write any exception to a log file.</p> <p>This way, you can see what really happens. The <code>logging</code> module is your friend.</p>
1
2009-05-20T09:08:04Z
[ "python", "cgi" ]
Making a python cgi script to finish gracefully
886,653
<p>I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, an...
2
2009-05-20T07:44:14Z
887,004
<p>You may be able to use the atexit module.</p> <p><a href="http://docs.python.org/library/atexit.html" rel="nofollow">http://docs.python.org/library/atexit.html</a></p> <p>From the documentation:</p> <blockquote> <p>The atexit module defines a single function to register cleanup functions. Functions thus registe...
0
2009-05-20T09:18:45Z
[ "python", "cgi" ]
Controling bars width in matplotlib with per-month data
886,716
<p>When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month.</p> <p>I tried to set the minor ticks locator to MonthLocator() without effect.</p> <p><strong>[edit]</s...
6
2009-05-20T08:03:25Z
888,141
<p>Just use the <code>width</code> keyword argument:</p> <pre><code>bar(x, y, width=30) </code></pre> <p>Or, since different months have different numbers of days, to make it look good you can use a sequence:</p> <pre><code>bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30]) </code></pre>
12
2009-05-20T14:10:31Z
[ "python", "matplotlib" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch ...
2
2009-05-20T08:50:11Z
886,914
<p>Try searching for "sandboxing python", e.g.:</p> <p><a href="http://wiki.python.org/moin/SandboxedPython" rel="nofollow">http://wiki.python.org/moin/SandboxedPython</a></p> <p><a href="http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29" rel="nofollow"...
1
2009-05-20T08:54:45Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch ...
2
2009-05-20T08:50:11Z
886,945
<p>Consider using a chroot jail. Not only is this very secure, well-supported and tested but it also applies to external applications you run from python.</p>
4
2009-05-20T09:05:05Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch ...
2
2009-05-20T08:50:11Z
887,091
<p>You could run jython and use the sandboxing mechanism from the JVM. The sandboxing in the JVM is very strong very well understood and more or less well documented. It will take some time to define exactly what you want to allow and what you dnt want to allow, but you should be able to get a very strong security from...
2
2009-05-20T09:44:35Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch ...
2
2009-05-20T08:50:11Z
887,104
<p>There are 4 things you may try:</p> <ul> <li>As you already mentioned, using a virtual machine or some other form of virtualisation (perhaps solaris zones are lightweight enough?). If the script breaks the OS there then you don't care.</li> <li>Using chroot, which puts a shell session into a virtual root directory,...
4
2009-05-20T09:48:15Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Safe Python Environment in Linux
886,895
<p>Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually.</p> <p>A very brute-force solution is to create a virtual machine and restore its initial state after every launch ...
2
2009-05-20T08:50:11Z
5,289,924
<p>could you not just run as a user which has no access to anything but the scripts in that directory?</p>
1
2011-03-13T14:18:06Z
[ "python", "linux", "runtime", "sandbox", "restriction" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
887,405
<p>I don't know much about this package <a href="http://code.astraw.com/projects/motmot/" rel="nofollow">Motmot</a> or how it compares to OpenCV, but I have imported and used a class or two from it. Much of the image processing is done via numpy arrays and might be similar enough to how you've used Matlab to meet your...
0
2009-05-20T11:33:41Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
889,535
<p>You probably would be well served by <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>. Here is the <a href="http://www.scipy.org/Getting%5FStarted" rel="nofollow">introductory tutorial</a> for SciPy. It has a lot of similarities to Matlab. Especially the included matplotlib package, which is explicitly made ...
2
2009-05-20T18:39:16Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
930,145
<p>I've acquired image from FW camera using .NET and IronPython. On CPython I would checkout ctypes library, unless you find any library support for grabbing.</p>
0
2009-05-30T17:20:31Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
930,299
<p>documentation: A few years ago I used OpenCV wrapped for Python quite a lot. OpenCV is extensively documented, ships with many examples, and there's even a <a href="http://oreilly.com/catalog/9780596516130/" rel="nofollow">book</a>. The Python wrappers I was using were thin enough so that very little wrapper speci...
7
2009-05-30T18:34:25Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
930,318
<p>OpenCV is probably your best bet for a library; you have your choice of wrappers for them. I looked at the SWIG wrapper that comes with the standard OpenCV install, but ended up using <a href="http://code.google.com/p/ctypes-opencv/">ctypes-opencv</a> because the memory management seemed cleaner.</p> <p>They are bo...
13
2009-05-30T18:48:31Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
3,696,260
<p>I've started a website on this subject: <a href="http://pythonvision.org" rel="nofollow" title="pythonvision.org">pythonvision.org</a>. It has some tutorials, &amp;c and some links to software. There are more links and tutorials there.</p>
4
2010-09-12T19:33:17Z
[ "python", "matlab", "computer-vision" ]
Machine vision in Python
887,252
<p>I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started.</p> <p>As far as I know, the only free library for Python that does machine vision is <a href="http://pycv.sharkdolphin.com/" rel="nofollow">PyCV</a> (which is a wrapper fo...
19
2009-05-20T10:45:29Z
10,910,941
<p>Foreword: This book is more for people who want a good hands on introduction into computer or machine vision, even though it covers what the original question asked.</p> <h2>[BOOK]: <a href="http://programmingcomputervision.com/" rel="nofollow"><strong>Programming Computer Vision with Python</strong></a></h2> <p>A...
0
2012-06-06T08:45:48Z
[ "python", "matlab", "computer-vision" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count ...
6
2009-05-20T11:12:34Z
887,432
<p>The functionality you want is called a "<a href="http://en.wikipedia.org/wiki/Barrier%5F%28computer%5Fscience%29" rel="nofollow">barrier</a>". (Unfortunately that term has 2 meanings when talking about threading. So if you <a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-GB%...
2
2009-05-20T11:40:53Z
[ "python", "multithreading", "synchronize" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count ...
6
2009-05-20T11:12:34Z
887,538
<p>There are many ways to synchronize threads. Many.</p> <p>In addition to synchronize, you can do things like the following.</p> <ol> <li><p>Break your tasks into two steps around the synchronization point. Start threads doing the pre-sync step. Then use "join" to wait until all threads finish step 1. Start new ...
1
2009-05-20T12:05:05Z
[ "python", "multithreading", "synchronize" ]
Synchronising multiple threads in python
887,346
<p>I have a problem where I need <code>x</code> threads to wait until they have all reached a synchronization point. My solution uses the <code>synchronise</code> method below which is called by each threaded function when they need to synchronise.</p> <p>Is there a better way to do this?</p> <pre><code>thread_count ...
6
2009-05-20T11:12:34Z
25,559,884
<p>Note that Barrier has been implemented <a href="https://docs.python.org/3/whatsnew/3.2.html#threading" rel="nofollow">as of Python 3.2</a></p> <p>Example of using barriers:</p> <pre><code>from threading import Barrier, Thread def get_votes(site): ballots = conduct_election(site) all_polls_closed.wait() ...
2
2014-08-29T00:17:02Z
[ "python", "multithreading", "synchronize" ]
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
887,388
<p>Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy?</p> <pre><code>SELECT * FROM foo WHERE foo.bar IN (1,2,3)</code></pre> <p>I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that ...
11
2009-05-20T11:27:26Z
887,402
<pre><code>select([foo], foo.c.bar.in_([1, 2, 3])) </code></pre> <p>You can use the <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement.in_" rel="nofollow"><code>.in_()</code></a> method with Columns or with Instrumented attributes. Both work.</p> <p><a href="htt...
14
2009-05-20T11:32:30Z
[ "python", "sqlalchemy" ]
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
887,388
<p>Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy?</p> <pre><code>SELECT * FROM foo WHERE foo.bar IN (1,2,3)</code></pre> <p>I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that ...
11
2009-05-20T11:27:26Z
27,309,357
<p>The .in_() operator now lives in the <strong>ColumnOperators</strong> class, documented @ <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperator...
4
2014-12-05T05:27:37Z
[ "python", "sqlalchemy" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,564
<p>You can use <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a> to change access and modify time but not the creation date.</p>
13
2009-05-20T12:15:28Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,652
<p>I am not a UNIX expert, so maybe I'm wrong, but I think that UNIX (or Linux) don't store file creation time.</p>
2
2009-05-20T12:34:29Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
887,688
<p>Linux and Unix file system stores :</p> <blockquote> <p>File access, change and modification time (remember UNIX or Linux never stores file creation time, this is favorite question asked in UNIX/Linux sys admin job interview)</p> </blockquote> <p><a href="http://www.cyberciti.biz/tips/understanding-unixlinux-fil...
13
2009-05-20T12:44:51Z
[ "python", "linux", "file", "date" ]
Change file creation date
887,557
<p>Can I change creation date of some file using Python in Linux?</p>
10
2009-05-20T12:12:13Z
32,943,250
<p>Check out <a href="http://docs.python.org/2/library/os.html#os.utime" rel="nofollow">os.utime</a></p> <pre><code>os.utime(file_path,(new_atime,new_mtime)) </code></pre>
1
2015-10-05T07:25:15Z
[ "python", "linux", "file", "date" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,116
<p>Because interpretting from bytecode directly is faster. It avoids the need to do lexing, for one thing.</p>
7
2009-05-20T14:07:17Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,117
<p>Because you can compile to a <code>.pyc</code> once and interpret from it many times.</p> <p>So if you're running a script many times you only have the overhead of parsing the source code once.</p>
8
2009-05-20T14:07:35Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,119
<p>Nearly no interpreter really interprets code <em>directly</em>, line by line – it's simply too inefficient. Almost all interpreters use some intermediate representation which can be executed easily. Also, small optimizations can be performed on this intermediate code.</p> <p>Python furthermore stores this code wh...
31
2009-05-20T14:07:45Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
888,159
<p>Re-lexing and parsing the source code over and over, rather than doing it just once (most often on the first <code>import</code>), would obviously be a silly and pointless waste of effort.</p>
6
2009-05-20T14:12:39Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
1,184,282
<p>I doubt very much that the reason is performance, albeit be it a nice side effect. I would say that it's only natural to think a VM built around some high-level assembly language would be more practical than to find and replace text in some source code string.</p> <p>Edit:</p> <p>Okay, clearly, who ever put a -1 v...
-1
2009-07-26T11:03:26Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Why python compile the source to bytecode before interpreting?
888,100
<p>Why python compile the source to bytecode before interpreting?</p> <p>Why not interpret from the source directly?</p>
8
2009-05-20T14:04:26Z
1,189,344
<p>Although there is a small efficiency aspect to it (you can store the bytecode on disk or in memory), its mostly engineering: it allows you separate parsing from interpreting. Parsers can often be nasty creatures, full of edge-cases and having to conform to esoteric rules like using just the right amount of lookahead...
2
2009-07-27T16:55:51Z
[ "python", "compiler-construction", "interpreter", "bytecode" ]
Make Emacs use UTF-8 with Python Interactive Mode
888,406
<p>When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8:</p> <pre><code>$ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&g...
7
2009-05-20T14:50:56Z
888,464
<p>check your environment variables:</p> <pre><code>$ LANG="en_US.UTF8" python -c "import sys; print sys.stdout.encoding" UTF-8 $ LANG="en_US" python -c "import sys; print sys.stdout.encoding" ANSI_X3.4-1968 </code></pre> <p>in your python hook, try:</p> <pre><code>(setenv "LANG" "en_US.UTF8") </code></pre>
7
2009-05-20T15:00:14Z
[ "python", "emacs", "encoding", "utf-8", "terminal" ]