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
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program...
24
2009-04-08T21:44:44Z
732,199
<p>A process has its own memory space. It makes it more difficult to share information, but also makes the program safer (less need for explicit synchronization). That being said, processes can share the same memory in read-only mode. </p> <p>A thread is cheaper to create or kill, but the main difference is that it sh...
10
2009-04-08T22:48:35Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program...
24
2009-04-08T21:44:44Z
732,462
<p>There was a good talk on multiprocessing at Pycon this year. The takeaway message was "Only use multiprocessing unless you're sure you have a problem that it will solve, that cannot be solved with threads; otherwise, use threads." </p> <p>Processes have a lot of overhead, and all data to be shared among processes m...
14
2009-04-09T01:21:33Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program...
24
2009-04-08T21:44:44Z
734,919
<p>It sounds like you'd want threading. </p> <p>The way you described it, it sounded like there was one single thing that actually took a lot of CPU...the actual running of the simulation. </p> <p>What you're trying to get is more responsive displays, by allowing user interaction and graphics updates while the simu...
0
2009-04-09T16:17:00Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program...
24
2009-04-08T21:44:44Z
748,397
<p>If you would like to read a lengthy discussion of multi-threading in Mozilla, consider having a look at <a href="https://bugzilla.mozilla.org/show%5Fbug.cgi?id=40848" rel="nofollow">this discussion</a> which started in 2000. The discussion doesn't necessarily answer your question. However, it's an indepth discussion...
4
2009-04-14T16:35:01Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program...
24
2009-04-08T21:44:44Z
35,972,455
<p>Very puzzled. Bastien Léonard rightly pointed out that the GIL will stop any ability to use threading in any useful way. His reference states:</p> <blockquote> <p>"Use of a global interpreter lock in a language effectively limits the amount of parallelism reachable through concurrency of a single interpreter...
0
2016-03-13T16:01:39Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Serving static files with mod_wsgi and Django
732,190
<p>I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how to create something simple to serve static files....
8
2009-04-08T22:47:16Z
732,692
<p>I run a a dozen or so Django sites on the same server and here's how I configure the media URL's.</p> <p>Each VirtualHost has the following configuration:</p> <pre><code>Alias /media /path/to/media/ &lt;Directory /path/to/media&gt; Include /etc/apache2/vhosts.d/media.include &lt;/Directory&gt; </code></pre> <...
16
2009-04-09T03:42:00Z
[ "python", "django", "mod-wsgi", "mod-python" ]
Serving static files with mod_wsgi and Django
732,190
<p>I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how to create something simple to serve static files....
8
2009-04-08T22:47:16Z
1,037,869
<p>The mod_wsgi documentation explains how to setup static files which appear at a URL underneath that which the WSGI application is mounted at. See:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting%5FOf%5FStatic%5FFiles">http://code.google.com/p/modwsgi/wiki/ConfigurationGuideline...
13
2009-06-24T11:50:44Z
[ "python", "django", "mod-wsgi", "mod-python" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whe...
2
2009-04-08T22:47:25Z
732,229
<p>You should look at the PIL (Python Imaging Library), and in particular the <a href="http://www.pythonware.com/library/pil/handbook/imagedraw.htm" rel="nofollow">ImageDraw module</a>, which support Hex, RGB, HSL and common color names. You should be able to get the information you need there.</p>
0
2009-04-08T23:04:30Z
[ "python", "colors", "tkinter" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whe...
2
2009-04-08T22:47:25Z
732,452
<p>Instantiate Tk(), run the code once, and then stick the information into your source as a dict literal?</p>
0
2009-04-09T01:05:56Z
[ "python", "colors", "tkinter" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whe...
2
2009-04-08T22:47:25Z
12,434,606
<p>Both Tkinter and the Python Imaging Library say they use the X Window colour names, so if you can get Shane's suggestion of the ImageDraw module to work, that sounds best. I wasn't sure I could rely on ImageDraw being available, so I parsed the list from the <a href="http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm" re...
1
2012-09-15T04:50:27Z
[ "python", "colors", "tkinter" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
732,257
<p>I am pretty sure that WSGI compliant servers should support that. Essentially, WSGI applications return iterable chunks, which the webserver returns. I don't have first hand experience with this, but here is a <a href="http://www.wsgi.org/wsgi/Servers" rel="nofollow">list of compliant servers</a>.</p> <p>I should t...
0
2009-04-08T23:18:10Z
[ "python", "http", "chunked-encoding" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
732,266
<p>Twisted supports <a href="http://twistedmatrix.com/documents/current/api/twisted.web.http.%5FChunkedTransferEncoding.html" rel="nofollow">chunked transfer encoding (API link)</a> (see also the API doc for <a href="http://twistedmatrix.com/documents/current/api/twisted.web.http.HTTPChannel.html" rel="nofollow">HTTPCh...
5
2009-04-08T23:22:39Z
[ "python", "http", "chunked-encoding" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
9,326,192
<p>Twisted supports chunked transfer and it does so transparently. i.e., if your request handler does not specify a response length, twisted will automatically switch to chunked transfer and it will generate one chunk per call to Request.write.</p>
2
2012-02-17T10:00:40Z
[ "python", "http", "chunked-encoding" ]
Django Model: Returning username from currently logged in user
732,405
<p>I'm working on a Django app for hosting media (specifically audio and images). I have image galleries and photos separate in my model, and have them linked with a <code>ForeignKey</code> (not sure if that's correct, but still learning). What I need is for the Album class's <code>__unicode__</code> to return the albu...
0
2009-04-09T00:39:06Z
732,683
<p>There should be no problem accessing the user (even as a foreign key) from a model. I just finished testing it out myself, and there doesn't appear to be any significant difference.</p> <pre><code>def __unicode__(self): return self.user.username </code></pre> <p>On a side note, you should also just be able to...
1
2009-04-09T03:36:27Z
[ "python", "django", "django-models", "django-admin" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,439
<p>There are several very mature javascript implementations that are server-framework agnostic:</p> <ul> <li><a href="http://www.fckeditor.net/">http://www.fckeditor.net/</a></li> <li><a href="http://tinymce.moxiecode.com/">TinyMCE</a></li> <li><a href="http://wmd-editor.com/">WMD</a> (used by SO)</li> </ul> <p>The w...
5
2009-04-09T00:59:43Z
[ "javascript", "python", "http", "pylons", "widget" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,441
<p>ExtJS's HtmlEditor was the best I found (license issues aside):</p> <p><a href="http://extjs.com/deploy/dev/docs/?class=Ext.form.HtmlEditor" rel="nofollow">http://extjs.com/deploy/dev/docs/?class=Ext.form.HtmlEditor</a></p> <p>ExtJS is a bit heavy-weight, but that HtmlEditor was the most responsive and best-lookin...
2
2009-04-09T01:02:24Z
[ "javascript", "python", "http", "pylons", "widget" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,453
<p>webkit-gtk is getting very stable, and i believe has python bindings now so technically you could use that (then your text editor merely needs to be <code>&lt;body contenteditable&gt;&lt;/body&gt;</code> and you'd be done. Unfortunately i'm not sure how complete its bindings are at present</p>
1
2009-04-09T01:06:35Z
[ "javascript", "python", "http", "pylons", "widget" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lin...
0
2009-04-09T01:26:22Z
732,477
<p>Using regular expressions to deal with HTML is extremely error-prone; they're simply not the right tool.</p> <p>Instead, use a HTML/XML-aware library (such as <A HREF="http://codespeak.net/lxml/" rel="nofollow">lxml</A>) to build a DOM-style object tree; modify the text segments within the tree in-place, and genera...
5
2009-04-09T01:33:31Z
[ "python", "regex" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lin...
0
2009-04-09T01:26:22Z
732,482
<p>Try this:</p> <pre><code>\r?\n[ \t]* </code></pre> <p>EDIT: The idea is to remove all newlines (either Unix: "\n", or Windows: "\r\n") plus any horizontal whitespace (TABs or spaces) that immediately follow them.</p>
0
2009-04-09T01:36:59Z
[ "python", "regex" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lin...
0
2009-04-09T01:26:22Z
932,863
<p>Alan,</p> <p>I have to agree with Charles that the safest way is to parse the HTML, then work on the Text nodes only. Sounds overkill but that's the safest.</p> <p>On the other hand, there is a way in regex to do that as long as you trust that the HTML code is correct (i.e. does not include invalid &lt; and > in t...
0
2009-05-31T21:04:54Z
[ "python", "regex" ]
How do I make this progress bar close when it is done
732,829
<p>I commonly write Python scipts to do conversion tasks for me and whenever I write one that takes a while I use this little progress bar to check on it</p> <pre><code>import sys import time from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) barra = QtGui.QProgressBar() barra.show() barra.setMinimum(0) barra....
1
2009-04-09T04:42:59Z
734,139
<p>Well, because you set your Maximum to 10, your progress bar shouldn't reach 100% because </p> <pre><code>for a in range(10): time.sleep(1) barra.setValue(a) </code></pre> <p>will only iterate up to 9.</p> <p>Progress bars don't close automatically. You will have to call </p> <pre><code>barra.hide() </code></...
3
2009-04-09T13:06:58Z
[ "python", "pyqt", "progress-bar" ]
Get Primary Key after Saving a ModelForm in Django
732,952
<p>How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. </p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(re...
21
2009-04-09T05:38:47Z
732,973
<p>The <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform">ModelForm</a>'s <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method">save</a> method returns the saved object.</p> <p>Try this:</p> <pre><code>def contact_create(request): if request.method ...
31
2009-04-09T05:50:11Z
[ "python", "django", "django-models", "django-forms" ]
Get Primary Key after Saving a ModelForm in Django
732,952
<p>How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. </p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(re...
21
2009-04-09T05:38:47Z
6,247,910
<p>In the case where you have set form.save(commit=False) because you want to modify data and you have a many-to-many relation, then the answer is a little bit different:</p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): ...
6
2011-06-06T04:58:11Z
[ "python", "django", "django-models", "django-forms" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,461
<p>You most likely just need to format your integer:</p> <pre><code>'%0*d' % (fill, your_int) </code></pre> <p>For example,</p> <pre><code>&gt;&gt;&gt; '%0*d' % (3, 4) '004' </code></pre>
57
2009-04-09T09:16:59Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,478
<p>You can use the <code>zfill()</code> method to pad a string with zeros:</p> <pre><code>In [3]: str(1).zfill(2) Out[3]: '01' </code></pre>
288
2009-04-09T09:23:23Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,512
<p>This is my Python function:</p> <pre><code>def add_nulls(num, cnt=2): cnt = cnt - len(str(num)) nulls = '0' * cnt return '%s%s' % (nulls, num) </code></pre>
0
2009-04-09T09:36:21Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,525
<p>A straightforward conversion would be (again with a function):</p> <pre><code>def add_nulls2(int, cnt): nulls = str(int) for i in range(cnt - len(str(int))): nulls = '0' + nulls return nulls </code></pre>
1
2009-04-09T09:40:57Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,576
<p>Python 2.6 allows this:</p> <pre><code>add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count) &gt;&gt;&gt;add_nulls(2,3) '002' </code></pre>
16
2009-04-09T09:59:49Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,825
<p>You have at least two options:</p> <ul> <li>str.zfill: <code>lambda n, cnt=2: str(n).zfill(cnt)</code></li> <li><code>%</code> formatting: <code>lambda n, cnt=2: "%0*d" % (cnt, n)</code></li> </ul> <p>If on Python >2.5, see a third option in clorz's answer.</p>
4
2009-04-09T11:36:57Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
733,939
<p>Just for the culture, on PHP, you have the function <a href="http://fr3.php.net/str%5Fpad" rel="nofollow" title="str_pad"><code>str_pad</code></a> which makes exactly the job of your function <code>add_nulls</code>.</p> <pre><code>str_pad($int, $cnt, '0', STR_PAD_LEFT); </code></pre>
0
2009-04-09T12:07:24Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
12,098,091
<h3>One-liner alternative to the built-in <code>zfill</code>.</h3> <p>This function takes <code>x</code> and converts it to a string, and adds zeros in the beginning only and only if the length is too short:</p> <pre><code>def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))&lt;len else str...
1
2012-08-23T18:42:00Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
13,919,632
<p>The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.</p> <pre><code>i = random.randint(0,99999) print "%05d" % i </code></pre> <p>which will output an string of len...
104
2012-12-17T18:10:33Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
36,558,670
<p>For Python 3 and beyond: str.zfill() is still the most readable option</p> <p>But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?</p> <pre><code> # if we want to pad 22 with zeros in front, to be 5 digits in length: str_output = '{:0&gt;5}'....
2
2016-04-11T20:30:23Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; ...
113
2009-04-09T09:15:33Z
36,881,673
<p>Initially, find the digits in the number of Cases /Folders. According to the length of the maximum / highest number of Cases / Folder, a format is created and added as suffix. For example. No of Cases = 9. Case_1. Case_2...Case_9 are generated. For No of Cases = 99, Case_01, Case_02...Case_99.. for 999, Case_001, Ca...
-3
2016-04-27T06:12:06Z
[ "python", "string-formatting" ]
Access list of tuples
733,574
<p>I have a list that contains several tuples, like:</p> <pre><code>[('a_key', 'a value'), ('another_key', 'another value')] </code></pre> <p>where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like:</p> <p><code>"mylist.a_key"</code> or <code>"...
3
2009-04-09T09:59:02Z
733,582
<p>You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more importan...
14
2009-04-09T10:03:41Z
[ "python" ]
Access list of tuples
733,574
<p>I have a list that contains several tuples, like:</p> <pre><code>[('a_key', 'a value'), ('another_key', 'another value')] </code></pre> <p>where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like:</p> <p><code>"mylist.a_key"</code> or <code>"...
3
2009-04-09T09:59:02Z
733,596
<p>If you're generating the list yourself, you might be able to create it as a dictionary at source (which allows for key, value pairs).</p> <p>Otherwise, Van Gale's defaultdict is the way to go I would think.</p> <p>Edit:</p> <p>As mentioned in the comments, defaultdict is not required here unless you need to deal ...
3
2009-04-09T10:07:28Z
[ "python" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make ...
1
2009-04-09T12:01:58Z
734,150
<p>I don't know much about Pygame, but I've used SDL (on which Pygame is based).</p> <p>If you use <code>Surface.blit()</code>: <a href="http://www.pygame.org/docs/ref/surface.html#Surface.blit" rel="nofollow">link text</a></p> <p>You can use the optional <code>area</code> argument to select which part of the surface...
0
2009-04-09T13:10:39Z
[ "python", "2d", "pygame", "sprite" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make ...
1
2009-04-09T12:01:58Z
734,772
<p>Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:</p> <pre><code>import pygame quit = False pygame.init() display = pygame.display.set_mode((640,480)) sprite_sheet = pygame.image.load('sprite.bmp').convert() # by default, display the first sprite image_n...
1
2009-04-09T15:38:23Z
[ "python", "2d", "pygame", "sprite" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make ...
1
2009-04-09T12:01:58Z
1,766,294
<p>dude the only thing you have to do is offcourse </p> <p>import pygame and all the other stuff needed type code and stuff..........then when it comes to you making a spri</p> <pre><code>class .your class nam here. (pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.init(self) s...
-1
2009-11-19T20:29:26Z
[ "python", "2d", "pygame", "sprite" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mys...
23
2009-04-09T13:35:00Z
734,271
<p>As you said, you'd have a site called StackOverflow with an auth app, questions app, etc.</p> <p>You should have a look at the <a href="http://pinaxproject.com/" rel="nofollow">Pinax project</a> to see how they lay things out. It's one of the better ways to do it since it will increase the modularity and portabili...
0
2009-04-09T13:38:13Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mys...
23
2009-04-09T13:35:00Z
734,297
<p>From the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Django documentation</a>:</p> <blockquote> <h2>Projects vs. apps</h2> <p>What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a...
8
2009-04-09T13:43:20Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mys...
23
2009-04-09T13:35:00Z
734,321
<p>Django actually has 3 concepts here:</p> <ul> <li><p><strong>Project</strong> (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.</p></li> <li><p><strong>App</strong>: This is a set of views, models, and te...
24
2009-04-09T13:48:52Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mys...
23
2009-04-09T13:35:00Z
2,665,181
<p>The answer to would you have a project with a single app called StackOverflow is an unequivocal no. A site like this might have 20+ apps.</p> <p>See James Bennett's "<a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow" title="DjangoCon 2008: Reusable Apps">DjangoCon 2008: Reusable Apps</a>" video pr...
2
2010-04-19T04:21:29Z
[ "python", "django" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
734,442
<p>In python the <a href="http://docs.python.org/library/pprint.html" rel="nofollow">pprint</a> module is available.</p> <p>Depending on how your data is structured it may not return the result your looking for.</p>
1
2009-04-09T14:14:26Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
734,690
<p>One way would be to just print it and then invoke a code formatter.</p>
-1
2009-04-09T15:17:35Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
739,358
<p>Once you have an AST, this should be very easy. When you walk your AST, all you have to do is keep track of what your current indent level is -- you could use a global for this. The code that's walking the tree simply needs to increment the indent level every time you enter a block, and decrement it when you exit ...
1
2009-04-11T01:50:20Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the foru...
27
2009-04-09T16:11:15Z
734,962
<p>I can talk from experience using HTTP, rather than mechanize, but I think this is probably what you want.</p> <p>When there are two submit buttons in a form, a server can determine which one was pressed, because the client should have added an argument for the submit button. So:</p> <pre><code>&lt;form action="bla...
2
2009-04-09T16:28:42Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the foru...
27
2009-04-09T16:11:15Z
735,031
<p>I would suggest you to use Twill which uses mechanize (mostly monkeypatched). So say you have form with some fields and two submit buttons with <strong>names</strong> "submit_to_preview" and "real_submit". Following code should work.</p> <p>BTW remember this is not threadsafe so you might want to use locks in case...
7
2009-04-09T16:50:55Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the foru...
27
2009-04-09T16:11:15Z
1,263,476
<p>Use the 'click' method. E.g.</p> <pre><code>mybrowser.select_form(nr=0) req = mybrowser.click(type="submit", nr=1) mybrowser.open(req) </code></pre> <p>Should work.</p>
4
2009-08-11T23:10:18Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the foru...
27
2009-04-09T16:11:15Z
1,685,753
<p>I tried using the nr parameter, without any luck.</p> <p>I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML:</p> <p>Here are my two submit buttons:</p> <pre><code>&lt;input type="submit" name="Preview" value="Preview" /&gt...
19
2009-11-06T06:17:16Z
[ "python", "mechanize" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): ...
0
2009-04-09T16:29:49Z
734,984
<p>Your example would work if you called <code>print self.__class__.var</code>. I don't think there's any need to use the name.</p>
1
2009-04-09T16:33:35Z
[ "python" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): ...
0
2009-04-09T16:29:49Z
734,995
<p>Depending on where you get this string, any general method may be insecure (one such method is to simply use <code>eval(string)</code>. The best method is to define a dict mapping names to classes:</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string...
2
2009-04-09T16:36:52Z
[ "python" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): ...
0
2009-04-09T16:29:49Z
735,014
<blockquote> <p>How to use a string containing a class name to reference a class itself?</p> </blockquote> <p>Classes aren't special, they're just values contained in variables. If you've said:</p> <pre><code>class X(object): pass </code></pre> <p>in global scope, then the variable ‘X’ will be a reference to t...
5
2009-04-09T16:46:09Z
[ "python" ]
Propagating application settings
735,337
<p>Probably a very common question, but couldn't find suitable answer yet.. </p> <p>I have a (Python w/ C++ modules) application that makes heavy use of an SQLite database and its path gets supplied by user on application start-up. </p> <p>Every time some part of application needs access to database, I plan to acquir...
4
2009-04-09T18:17:18Z
735,436
<p>Yes, there are others. Your option 3 though is very Pythonic. </p> <p>Use a standard Python module to encapsulate options (this is the way web frameworks like Django do it)</p> <p>Use a factory to emit properly configured sessions.</p> <p>Since SQLite already has a "connection", why not use that? What does you...
2
2009-04-09T18:43:09Z
[ "python", "singleton", "settings", "global" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
735,593
<p>See <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation">http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation</a></p> <blockquote> <p>Secondly, once we have decided that the combined data in the two fields we are considering aren't valid, we must...
17
2009-04-09T19:27:13Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
1,285,554
<p>You access the data from either the field's clean() method, or from the form's clean() method. clean() is the function that determines whether the form is valid or not. It's called when is_valid() is called. In form's clean() you have the <code>cleaned_data</code> list when you can run through custom code to make su...
1
2009-08-16T22:54:20Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
1,440,599
<p>You can use</p> <pre><code>form.data['field_name'] </code></pre> <p>This way you get the raw value assigned to the field.</p>
33
2009-09-17T18:36:49Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
6,152,128
<p>You can use this pattern:</p> <pre><code>class MyForm(forms.Form): ... def clean(self): self.saved_data=self.cleaned_data return self.cleaned_data </code></pre> <p>In your code:</p> <pre><code>if form.is_valid(): form.save() return django.http.HttpResponseRedirect(...) if form.is_b...
5
2011-05-27T12:17:15Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
9,807,131
<p>I ran into a similar problem using a formset. In my example, I wanted the user to select a 1st choice before a 2nd choice, but if the 1st choice hit another error, the 'select 1st choice before 2nd' error was also displayed. </p> <p>To grab the 1st field's uncleaned data, I used this within the form field's clean...
3
2012-03-21T14:57:22Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
11,005,988
<p>I was struggling with a similar issue, and came across a great discussion here: <a href="https://code.djangoproject.com/ticket/10427">https://code.djangoproject.com/ticket/10427</a></p> <p>It's not at all well documented, but for a live form, you can view a field's value -- as seen by widgets/users -- with the foll...
12
2012-06-12T22:51:06Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
31,262,753
<p>I have many methods. All you can pick.</p> <p>I suppose the form is like as below:</p> <pre><code>class SignupForm(forms.Form): email = forms.CharField(label='email') password = forms.CharField(label='password', widget=forms.PasswordInput) </code></pre> <p>1-1. Get from <cod...
2
2015-07-07T07:50:33Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,784
<p>It seems like you are talking about permutations of character combinations. This has been a fairly well <a href="http://code.activestate.com/recipes/190465/" rel="nofollow">published recipe</a>. That link should get you started.</p> <p>One additional note, ping will not tell you if a server 'exists' or if the name ...
0
2009-04-09T20:16:17Z
[ "python", "ping" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,801
<p>Just because a site fails a ping doesn't mean the domain is available. The domain could be reserved but not pointing anywhere, or the machine may not respond to pings, or it may just be down.</p>
3
2009-04-09T20:21:14Z
[ "python", "ping" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,810
<p>You don't want to use the ping command, but you can use Python's <a href="http://docs.python.org/library/socket.html#socket.gethostbyname" rel="nofollow"><code>socket.gethostbyname()</code> function</a> to determine whether a host exists.</p> <pre><code>def is_valid_host(hostname): try: addr = socket.ge...
7
2009-04-09T20:24:52Z
[ "python", "ping" ]
Pass to python method based on length of a list
735,878
<p>I have a list called 'optionlist' which may change length from day to day, but I want a tkinter dropdown box to be able to select something from it. </p> <p>Here's an example of how to define a tkinter optionmenu:</p> <pre><code>opt1 = OptionMenu(root, var1, 'A', 'B', 'C') </code></pre> <p>A, B, and C are the opt...
1
2009-04-09T20:51:18Z
735,889
<p>You want the <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists"><code>*</code> operator</a>:</p> <pre><code>opt1 = OptionMenu(root, var1, *optionlist) </code></pre>
11
2009-04-09T20:53:59Z
[ "python", "parameters" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
735,976
<p>Yes, check out the <a href="http://docs.python.org/library/functions.html#staticmethod">staticmethod</a> decorator:</p> <pre><code>&gt;&gt;&gt; class C: ... @staticmethod ... def hello(): ... print "Hello World" ... &gt;&gt;&gt; C.hello() Hello World </code></pre>
58
2009-04-09T21:24:15Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
735,978
<p>Yep, using the <a href="https://docs.python.org/2/library/functions.html#staticmethod">staticmethod</a> decorator</p> <pre><code>class MyClass(object): @staticmethod def the_static_method(x): print x MyClass.the_static_method(2) # outputs 2 </code></pre> <p>Note that some code might use the old me...
1,215
2009-04-09T21:24:36Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
738,102
<p>You don't really need to use the <code>@staticmethod</code> decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)</p> <p>Mostly, you jus...
20
2009-04-10T16:00:50Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
10,206,355
<p>I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.</p> <p>(Note that this answer refers to Python 3.x. In Python...
127
2012-04-18T09:16:03Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
14,085,311
<p>Aside from the particularities of how <a href="http://docs.python.org/2/reference/datamodel.html#types" rel="nofollow">static method objects</a> behave, there is a certain kind of beauty you can strike with them when it comes to organizing your module-level code.</p> <pre><code># garden.py def trim(a): pass de...
6
2012-12-29T19:47:13Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
25,041,766
<p>Perhaps the simplest option is just to put those functions outside of the class:</p> <pre><code>class Dog(object): def __init__(self, name): self.name = name def bark(self): if self.name == "Doggy": return barking_sound() else: return "yip yip" def barking_s...
2
2014-07-30T16:10:48Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
28,122,324
<blockquote> <p><strong>Static methods in Python?</strong></p> <p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod() </code></pre> </blockquote> <p>Yes, static methods can be created like this (although it's a bit mor...
18
2015-01-24T04:34:35Z
[ "python", "static-methods" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
736,050
<p>I would just use..</p> <pre><code>try: float(element) except ValueError: print "Not a float" </code></pre> <p>..it's simple, and it works</p> <p>Another option would be a regular expression:</p> <pre><code>import re if re.match("^\d+?\.\d+?$", element) is None: print "Not float" </code></pre>
101
2009-04-09T21:55:39Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
736,117
<p>This regex will check for scientific floating point numbers:</p> <pre><code>^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$ </code></pre> <p>However, I believe that your best bet is to use the parser in a try.</p>
2
2009-04-09T22:30:52Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
736,179
<p>If you cared about performance (and I'm not suggesting you should), the try-based approach is the clear winner (compared with your partition-based approach or the regexp approach), as long as you don't expect a lot of invalid strings, in which case it's potentially slower (presumably due to the cost of exception han...
5
2009-04-09T22:56:46Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
738,944
<p>Strictly, these regexp-style solutions should be checking the locale. Not all locales use dots as the separator.</p>
3
2009-04-10T21:34:47Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
20,929,881
<h2>Python method to check for float:</h2> <pre><code>def isfloat(value): try: float(value) return True except ValueError: return False </code></pre> <h2>Don't get bit by the goblins hiding in the float boat! DO UNIT TESTING!</h2> <p>What is, and is not a float may surprise you:</p> <pre><code>Comm...
51
2014-01-05T03:56:52Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
25,299,441
<p>There is another method available via a third-party module called <a href="https://pypi.python.org/pypi/fastnumbers" rel="nofollow">fastnumbers</a> (disclosure, I am the author); it provides a function called <a href="http://pythonhosted.org//fastnumbers/checks.html#isfloat" rel="nofollow">isfloat</a>. I have taken...
2
2014-08-14T03:13:05Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
33,012,298
<p>If you don't need to worry about scientific or other expressions of numbers and are only working with strings that could be numbers with or without a period:</p> <p><strong>Function</strong></p> <pre><code>def is_float(s): result = False if s.count(".") == 1: if s.replace(".", "").isdigit(): ...
1
2015-10-08T09:50:32Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
38,329,481
<pre><code>'1.43'.replace('.','',1).isdigit() </code></pre> <p>which will return <code>true</code> only if there is one or no '.' in the string of digits. <br><br></p> <pre><code>'1.4.3'.replace('.','',1).isdigit() </code></pre> <p>will return <code>false</code> <br><br></p> <pre><code>'1.ww'.replace('.','',1).isdi...
2
2016-07-12T12:52:46Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
39,671,880
<p>str(strval).isdigit() seems to be simple. Handles values stored in as a string or int or float</p>
0
2016-09-24T02:20:47Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm usin...
55
2009-04-09T21:52:33Z
40,064,302
<p>I used the function already mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of the function, that will return false on those type of input and will not fail "1e3" variants:</p> <pre><code>def is_float(text): try: fl...
0
2016-10-15T21:15:58Z
[ "python", "string", "type-conversion" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
736,359
<p>In theory yes, you can start spewing crud into __builtin__:</p> <pre><code>&gt;&gt;&gt; import __builtin__ &gt;&gt;&gt; __builtin__.rubbish= 3 &gt;&gt;&gt; rubbish 3 </code></pre> <p>But, don't do this; it's horrible evilness that will give your applications programming-cancer.</p> <blockquote> <p>classes and f...
15
2009-04-10T00:35:38Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
736,378
<p>Even if there are, you should not use such a construct EVER. Consider using a borg pattern to hold this kind of stuff.</p> <pre><code>class Config: """ Borg singlton config object """ __we_are_one = {} __myvalue = "" def __init__(self): #implement the borg patter (we are one) ...
4
2009-04-10T00:41:45Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
737,386
<p>Create empty superglobal.py module.<br/> In your files do:</p> <pre><code>import superglobal superglobal.whatever = loacalWhatever other = superglobal.other </code></pre>
2
2009-04-10T11:40:21Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
4,898,617
<p>The reason it wasn't obvious to you is that Python intentionally doesn't try to support such a thing. Namespaces are a <em>feature</em>, and using them is to your advantage. If you want something you defined in another file, import it. This means from reading your source code you can figure out where everything came...
1
2011-02-04T13:43:41Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
4,900,210
<p>in years of practice, i've grown quite disappointed with python's import system: it is complicated and difficult to handle correctly. also, i have to maintain scores of imports in each and every module i write, which is a pita. </p> <p>namespaces are a very good idea, and they're indispensable---php doesn't have pr...
3
2011-02-04T16:14:51Z
[ "python", "python-3.x" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way ...
4
2009-04-10T01:00:55Z
736,576
<p>maybe sth like that:</p> <pre><code>import xmlrpclib j = xmlrpclib.Server('http://feedburnerrpc') reply = j.weblogUpdates.ping('website title','http://urltothenewpost') </code></pre>
1
2009-04-10T02:51:02Z
[ "python", "django", "xml-rpc" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way ...
4
2009-04-10T01:00:55Z
736,617
<p>You can use Django's <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow"><code>signals</code></a> feature to get a callback after a model is saved:</p> <pre><code>import xmlrpclib from django.db.models.signals import post_save from app.models import MyModel def ping_handler(sender, instan...
12
2009-04-10T03:14:49Z
[ "python", "django", "xml-rpc" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way ...
4
2009-04-10T01:00:55Z
736,821
<p>Use pluggable apps, Luke!</p> <p><a href="http://github.com/svetlyak40wt/django-pingback/" rel="nofollow">http://github.com/svetlyak40wt/django-pingback/</a></p>
2
2009-04-10T05:48:24Z
[ "python", "django", "xml-rpc" ]
PyQt connect method bug when used in a for loop which creates widgets from a list
736,651
<p>I have a GUI program, </p> <p>It auto create buttons from a name list, and connect to a function prints its name.</p> <p>but when I run this program, I press all the buttons, </p> <p>they all return the last button's name.</p> <p>I wonder why this thing happens. can any one help?</p> <pre><code>import sys from...
1
2009-04-10T03:48:22Z
736,738
<p>I see at least one bug in your code.</p> <p>Replace: </p> <pre><code> lambda :logging.debug(name) </code></pre> <p>By:</p> <pre><code> lambda name=name: logging.debug(name) </code></pre> <p>See <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why result...
3
2009-04-10T04:51:10Z
[ "python", "pyqt" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,818
<p>A quick google showed up <a href="http://id3-py.sourceforge.net/" rel="nofollow">http://id3-py.sourceforge.net/</a></p> <p>Maybe this works for you ?</p>
2
2009-04-10T05:48:03Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,823
<p>Mutagen <a href="https://bitbucket.org/lazka/mutagen" rel="nofollow">https://bitbucket.org/lazka/mutagen</a> <em>Edited 14/09/23 with current code host location</em></p> <p>eyeD3 <a href="http://eyed3.nicfit.net/" rel="nofollow">http://eyed3.nicfit.net/</a></p>
12
2009-04-10T05:48:51Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,869
<p><a href="http://diveintopython.net/object_oriented_framework/index.html">Dive into Python</a> uses MP3 ID3 tags as an example.</p>
15
2009-04-10T06:20:26Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
737,144
<p>Try <a href="http://eyed3.nicfit.net/" rel="nofollow">eyeD3</a>, it's a program and a module.</p>
2
2009-04-10T09:24:35Z
[ "python", "tags", "mp3", "music", "id3" ]
Pygame: Sprite animation Theory - Need Feedback
737,303
<p>After some tweaking of some code I got from someone to cause a characters images to move in regards to its direction and up down left right input I've put this together: (hope the code isn't too messy)</p> <p><a href="http://animania1.ca/ShowFriends/dev/dirmove.rar" rel="nofollow">Character Move Code + IMG</a></p> ...
3
2009-04-10T10:53:05Z
737,379
<p>It should be easy.</p> <p>If you record the frame number in a variable, you can modulo this with the number of frames you have to get an animation frame number to display.</p> <pre><code>frame_count = 0 animation_frames = 4 while quit == False: # ... # snip # ... area = pygame.Rect( image_n...
4
2009-04-10T11:35:13Z
[ "python", "2d", "pygame", "sprite" ]
How can I make a Python extension module packaged as an egg loadable without installing it?
737,383
<p>I'm in the middle of reworking our build scripts to be based upon <a href="http://code.google.com/p/waf/" rel="nofollow">the wonderful Waf tool</a> (I did use SCons for ages but its just <em>way</em> too slow). </p> <p>Anyway, I've hit the following situation and I cannot find a resolution to it:</p> <ul> <li>I h...
0
2009-04-10T11:37:52Z
737,493
<p>Heh, I think this was my bad. The issue appear to have been that the <code>zipsafe</code> flag in setup.py for the extension package was set to False, which appears to affect your ability to treat it as such at all.</p> <p>Now that I've set that to True I can import the egg files, simply by adding each one to the ...
3
2009-04-10T12:32:33Z
[ "python", "setuptools", "egg", "waf", "build-tools" ]
How can I make a Python extension module packaged as an egg loadable without installing it?
737,383
<p>I'm in the middle of reworking our build scripts to be based upon <a href="http://code.google.com/p/waf/" rel="nofollow">the wonderful Waf tool</a> (I did use SCons for ages but its just <em>way</em> too slow). </p> <p>Anyway, I've hit the following situation and I cannot find a resolution to it:</p> <ul> <li>I h...
0
2009-04-10T11:37:52Z
738,470
<p>Although you have a solution, you could always try "virtualenv" that creates a virtual environment of python where you can install and test Python Packages without messing with the core system python:</p> <p><a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">http://pypi.python.org/pypi/virtualenv</a></...
1
2009-04-10T18:32:32Z
[ "python", "setuptools", "egg", "waf", "build-tools" ]
SQLite in Python 2.2.3
737,511
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/> Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tr...
1
2009-04-10T12:40:39Z
737,606
<p>Look here: <a href="http://oss.itsystementwicklung.de/download/pysqlite/" rel="nofollow">http://oss.itsystementwicklung.de/download/pysqlite/</a></p> <p>From the release notes (<a href="http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt" rel="nofollow">http://oss.itsystementwicklung.de/t...
1
2009-04-10T13:21:35Z
[ "python", "sql", "linux", "sqlite", "hosting" ]
SQLite in Python 2.2.3
737,511
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/> Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tr...
1
2009-04-10T12:40:39Z
737,617
<p>There is no out-of-the-box solution; you either have to backport the SQLlite module from Python 2.5 to Python 2.2 or ask your web hoster to upgrade to the latest Python version. </p> <p>Python 2.2 is really ancient! At least for security reasons, they should upgrade (no more security fixes for 2.2 since May 30, 200...
2
2009-04-10T13:26:57Z
[ "python", "sql", "linux", "sqlite", "hosting" ]