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
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
1,398,649
<pre><code> s = 'abcdefgh' for e in (s[i:i+2] for i in range(0,len(s),2)): print(e) </code></pre>
1
2009-09-09T09:52:09Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
24,007,145
<p>The <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow">itertools doc</a> has a recipe for this:</p> <pre><code>from itertools import izip_longest def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gx...
0
2014-06-03T04:28:50Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
32,863,281
<p>Except for two answers I saw a lot of premature materialization on the batches, and subscripting (which does not work for all iterators). Hence I came up with this alternative:</p> <pre class="lang-py prettyprint-override"><code>def iter_x_and_n(iterable, x, n): yield x try: for _ in range(n): ...
0
2015-09-30T10:03:23Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
34,114,803
<p>From the docs of more_itertools:</p> <pre><code>more_itertools.chunked(iterable, n) </code></pre> <p>Break an iterable into lists of a given length:</p> <pre><code>&gt;&gt;&gt; list(chunked([1, 2, 3, 4, 5, 6, 7], 3)) [[1, 2, 3], [4, 5, 6], [7]] </code></pre> <p>If the length of iterable is not evenly divisible b...
0
2015-12-06T06:38:02Z
[ "iteration", "python" ]
Is there a fini routine for a python module written in C?
760,937
<p>I have a python module written in C, and I would like to add a function that is called when the module is unloaded. I obviously have an <code>initfoo</code> function to initialize the module -- is there a way to tell python to call a <code>finifoo</code> function when it's uninitializing the module?</p> <p>Is <code...
3
2009-04-17T15:40:25Z
760,981
<p>Not in Python 2, but <a href="http://www.python.org/dev/peps/pep-3121/" rel="nofollow">Python 3 seems to</a>. If you need to manage some resource, I would advise putting it in a module-level object -- I'm pretty sure those will be garbage-collected when the module is unloaded.</p> <p><hr /></p> <p>From the link:</...
4
2009-04-17T15:52:00Z
[ "python", "c", "python-module" ]
Long-running ssh commands in python paramiko module (and how to end them)
760,978
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p> <pre><code>interface = paramiko.SSHClient() #snip the connection setup portion stdin, stdout, stderr = interface.exec_command("tail -f logfile") #sni...
17
2009-04-17T15:51:20Z
762,686
<p>To close the process simply run:</p> <pre><code>interface.close() </code></pre> <p>In terms of nonblocking, you can't get a non-blocking read. The best you would be able to to would be to parse over it one "block" at a time, "stdout.read(1)" will only block when there are no characters left in the buffer. </p>
0
2009-04-18T00:58:10Z
[ "python", "ssh", "paramiko" ]
Long-running ssh commands in python paramiko module (and how to end them)
760,978
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p> <pre><code>interface = paramiko.SSHClient() #snip the connection setup portion stdin, stdout, stderr = interface.exec_command("tail -f logfile") #sni...
17
2009-04-17T15:51:20Z
766,255
<p>Instead of calling exec_command on the client, get hold of the transport and generate your own channel. The <a href="http://www.lag.net/paramiko/docs/paramiko.Channel-class.html" rel="nofollow">channel</a> can be used to execute a command, and you can use it in a select statement to find out when data can be read:<...
20
2009-04-19T22:27:05Z
[ "python", "ssh", "paramiko" ]
Long-running ssh commands in python paramiko module (and how to end them)
760,978
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p> <pre><code>interface = paramiko.SSHClient() #snip the connection setup portion stdin, stdout, stderr = interface.exec_command("tail -f logfile") #sni...
17
2009-04-17T15:51:20Z
836,069
<p>1) You can just close the client if you wish. The server on the other end will kill the tail process. </p> <p>2) If you need to do this in a non-blocking way, you will have to use the channel object directly. You can then watch for both stdout and stderr with channel.recv_ready() and channel.recv_stderr_ready(), or...
12
2009-05-07T17:43:22Z
[ "python", "ssh", "paramiko" ]
Long-running ssh commands in python paramiko module (and how to end them)
760,978
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p> <pre><code>interface = paramiko.SSHClient() #snip the connection setup portion stdin, stdout, stderr = interface.exec_command("tail -f logfile") #sni...
17
2009-04-17T15:51:20Z
11,190,794
<p>Just for information, there is a solution to do this using channel.get_pty(). Fore more details have a look at: <a href="http://stackoverflow.com/a/11190727/1480181">http://stackoverflow.com/a/11190727/1480181</a></p>
0
2012-06-25T14:02:15Z
[ "python", "ssh", "paramiko" ]
Long-running ssh commands in python paramiko module (and how to end them)
760,978
<p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p> <pre><code>interface = paramiko.SSHClient() #snip the connection setup portion stdin, stdout, stderr = interface.exec_command("tail -f logfile") #sni...
17
2009-04-17T15:51:20Z
14,888,341
<p>Just a small update to the solution by Andrew Aylett. The following code actually breaks the loop and quits when the external process finishes:</p> <pre><code>import paramiko import select client = paramiko.SSHClient() client.load_system_host_keys() client.connect('host.example.com') channel = client.get_transport...
6
2013-02-15T04:40:38Z
[ "python", "ssh", "paramiko" ]
pyQT QNetworkManager and ProgressBars
761,286
<p>I'm trying to code something that downloads a file from a webserver and saves it, showing the download progress in a QProgressBar. Now, there are ways to do this in regular Python and it's easy. Problem is that it locks the refresh of the progressBar. Solution is to use PyQT's QNetworkManager class. I can download ...
1
2009-04-17T17:03:51Z
762,680
<p>Well you haven't connected any of the signals to your updateBar() method.</p> <p>change</p> <pre><code>def replyFinished(self, reply): self.connect(reply,SIGNAL("downloadProgress(int,int)"),self.progressBar, SLOT("setValue(int)")) </code></pre> <p>to </p> <pre><code>def replyFinished(self, reply): ...
4
2009-04-18T00:53:34Z
[ "python", "pyqt" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
761,459
<p>You could use Python 3.0.. The default string type is unicode, so the <code>u''</code> prefix is no longer required..</p> <p>In short, no. You cannot turn this off.</p> <p>The <code>u</code> comes from the <code>unicode.__repr__</code> method, which is used to display stuff in REPL:</p> <pre><code>&gt;&gt;&gt; pr...
30
2009-04-17T17:42:38Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
1,146,258
<p>I know this isn't a global option, but you can also suppress the Unicode u by placing the string in a str() function.</p> <p>So a Unicode derived list that would look like:</p> <pre><code>&gt;&gt;&gt; myList=[unicode('a'),unicode('b'),unicode('c')] &gt;&gt;&gt; myList [u'a', u'b', u'c'] </code></pre> <p>would bec...
4
2009-07-18T00:19:01Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
5,822,478
<p>Try the following</p> <blockquote> <p>print str(result.url)</p> </blockquote> <p>It could be that your default encoding has been changed.</p> <p>You can check your default encoding with the following:-</p> <pre><code>&gt; import sys &gt; print sys.getdefaultencoding() &gt; ascii </code></pre> <p>The default s...
1
2011-04-28T17:14:03Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
5,822,501
<p>Not sure with unicode, but generally you can call <code>str.encode()</code> to convert it to a more suitable form. For instance, subprocess output captured in Python 3.0+ captures it as a byte stream (prefix 'b'), and encode() fixes to a regular string form.</p>
3
2011-04-28T17:16:02Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
5,839,420
<p>You have to use <code>print str(your_Variable)</code></p>
1
2011-04-30T04:06:41Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
5,839,729
<p>using <code>str( text )</code> is a somewhat bad idea in fact whenever you cannot be 100% sure about both your python's default encoding and the exact content of the string---the latter would be typical for a text fetched from the internet. also, depending on what you want to do, using <code>print text.encode( 'utf-...
6
2011-04-30T05:15:38Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
8,627,204
<p>In the case that you do not want to update to Python 3, you could make use of substrings. For example, say the original output was (u'mystring',). Let us assume for the sake of the example that the variable row contains the "mystring" string without the unicode prefix. Then you would want to do something like this:<...
1
2011-12-24T22:29:10Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
13,246,056
<p>I had a case where I needed drop the u prefix because I was setting up some javascript with python as part of an html template. A simple output left the u prefix in for the dict keys e.g.</p> <pre><code>var turns = [{u'armies':2...]; </code></pre> <p>which breaks javascript.</p> <p>In order to get the output java...
13
2012-11-06T07:05:49Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
30,167,034
<pre><code>from __future__ import unicode_literals </code></pre> <p>is available since Python 2.6 (released on October 1, 2008). It is default in Python 3.</p> <p>It allows to omit <code>u''</code> prefix in the source code though it does not change <code>repr(unicode_string)</code> that would be misleading.</p> <p>...
2
2015-05-11T11:54:37Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
35,850,273
<p>Just in case you are getting something like this <code>u['hello']</code> then you must be printing an array. print <code>str(arr[0])</code> and you are good to go. </p>
1
2016-03-07T17:37:57Z
[ "python", "string", "unicode", "printing" ]
Suppress the u'prefix indicating unicode' in python strings
761,361
<p>Is there a way to globally suppress the unicode string indicator in python? I'm working exclusively with unicode in an application, and do a lot of interactive stuff. Having the u'prefix' show up in all of my debug output is unnecessary and obnoxious. Can it be turned off?</p>
30
2009-04-17T17:22:04Z
38,702,735
<p>What seems to be working for me:</p> <pre><code>import ast import json j = json.loads('{"one" : "two"}') j dd = {u'one': u'two'} dd # to get double quotes json.dumps(j, encoding='ascii') json.dumps(dd, encoding='ascii') # to get single quotes str(ast.literal_eval(json.dumps(j, encoding='ascii'))) str(ast.literal_...
0
2016-08-01T15:31:56Z
[ "python", "string", "unicode", "printing" ]
Why csv.reader is not pythonic?
761,430
<p>I started to use the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv.reader</a> in Python 2.6 but you can't use <code>len</code> on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.</p> <p>Or is this just an abandoned module in later versions?<...
7
2009-04-17T17:35:38Z
761,449
<p>I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.</p> <pre><code>import csv r = csv.reader(...) lines = [line for line in r] print len(lines) #number of lines for odd in lines[1::2]: print odd # print odd lines </code></pre>
14
2009-04-17T17:40:42Z
[ "python", "csv" ]
Is it ok to use dashes in Python files when trying to import them?
761,519
<p>Basically when I have a python file like:</p> <pre><code>python-code.py </code></pre> <p>and use:</p> <pre><code>import (python-code) </code></pre> <p>the interpreter gives me syntax error.</p> <p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
65
2009-04-17T17:58:59Z
761,529
<p>The problem is that <code>python-code</code> is not an identifier. The parser sees this as <code>python</code> minus <code>code</code>. Of course this won't do what you're asking. You will need to use a filename that is also a valid python identifier. Try replacing the <code>-</code> with an underscore.</p>
19
2009-04-17T18:01:05Z
[ "python", "naming" ]
Is it ok to use dashes in Python files when trying to import them?
761,519
<p>Basically when I have a python file like:</p> <pre><code>python-code.py </code></pre> <p>and use:</p> <pre><code>import (python-code) </code></pre> <p>the interpreter gives me syntax error.</p> <p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
65
2009-04-17T17:58:59Z
761,531
<p>You should check out <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, the Style Guide for Python Code:</p> <blockquote> <p>Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have s...
84
2009-04-17T18:01:46Z
[ "python", "naming" ]
Is it ok to use dashes in Python files when trying to import them?
761,519
<p>Basically when I have a python file like:</p> <pre><code>python-code.py </code></pre> <p>and use:</p> <pre><code>import (python-code) </code></pre> <p>the interpreter gives me syntax error.</p> <p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
65
2009-04-17T17:58:59Z
761,534
<p>You could probably import it through some <code>__import__</code> hack, but if you don't already know how, you shouldn't. Python module names should be valid variable names ("identifiers") -- that means if you have a module <code>foo_bar</code>, you can use it from within Python (<code>print foo_bar</code>). You wou...
3
2009-04-17T18:03:29Z
[ "python", "naming" ]
Is it ok to use dashes in Python files when trying to import them?
761,519
<p>Basically when I have a python file like:</p> <pre><code>python-code.py </code></pre> <p>and use:</p> <pre><code>import (python-code) </code></pre> <p>the interpreter gives me syntax error.</p> <p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
65
2009-04-17T17:58:59Z
762,693
<p>One other thing to note in your code is that import is not a function. So <code>import(python-code)</code> should be <code>import python-code</code> which, as some have already mentioned, is interpreted as "import python minus code", not what you intended. If you really need to import a file with a dash in its nam...
74
2009-04-18T01:06:18Z
[ "python", "naming" ]
Is it ok to use dashes in Python files when trying to import them?
761,519
<p>Basically when I have a python file like:</p> <pre><code>python-code.py </code></pre> <p>and use:</p> <pre><code>import (python-code) </code></pre> <p>the interpreter gives me syntax error.</p> <p>Any ideas on how to fix it? Are dashes illegal in python file names?</p>
65
2009-04-17T17:58:59Z
37,831,973
<p>Dashes are <em>not</em> illegal but you should not use them for 3 reasons:</p> <ol> <li>You need special syntax to import files with dashes</li> <li>Nobody expects a module name with a dash</li> <li>It's against the recommendations of the <a href="https://www.python.org/dev/peps/pep-0008/#id38" rel="nofollow">Pytho...
4
2016-06-15T09:52:47Z
[ "python", "naming" ]
Overriding 'to boolean' operator in python?
761,586
<p>I'm using a class that is inherited from list as a data structure:</p> <pre><code>class CItem( list ) : pass oItem = CItem() oItem.m_something = 10 oItem += [ 1, 2, 3 ] </code></pre> <p>All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has n...
19
2009-04-17T18:15:27Z
761,605
<p>In 2.x: override <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__"><code>__nonzero__()</code></a>. In 3.x, override <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__bool__#object.__bool__"><code>__bool__()</code></a>.</p>
33
2009-04-17T18:21:14Z
[ "python" ]
If you were to clone Monopoly Tycoon in Python, what libraries would you use?
761,652
<p>Ever played the game Monopoly Tycoon? I think it's great. I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff, figuring out what is being clicked on and so on...</p> <p>If you were to unde...
3
2009-04-17T18:30:52Z
761,668
<p><a href="http://www.pygame.org/news.html" rel="nofollow">pyGame</a> seems quite mature and builds on top of the proven SDL library. </p>
6
2009-04-17T18:36:22Z
[ "python", "opengl" ]
If you were to clone Monopoly Tycoon in Python, what libraries would you use?
761,652
<p>Ever played the game Monopoly Tycoon? I think it's great. I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff, figuring out what is being clicked on and so on...</p> <p>If you were to unde...
3
2009-04-17T18:30:52Z
763,147
<p>I'd use pyglet. It's all opengl from the start, doesn't build on top of ugly SDL library and has better interfaces than what I've seen on other python's multimedia libraries.</p> <pre><code>import pyglet from pyglet.gl import * class Application(object): def __init__(self): self.window = window = pygle...
4
2009-04-18T08:40:11Z
[ "python", "opengl" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
762,002
<p>Here is a way I came up with. There may be an easier way. I tested it using <code>python manage.py shell</code>:</p> <pre><code>&gt;&gt;&gt; cf = ContactForm({'reason': 'feature'}) &gt;&gt;&gt; cf.is_valid() True &gt;&gt;&gt; cf.fields['reason'].choices [('feature', 'A feature')] &gt;&gt;&gt; for val in cf.fields...
3
2009-04-17T20:06:40Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
762,830
<p>See the docs on <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get%5FFOO%5Fdisplay">Model.get_FOO_display()</a>. So, should be something like :</p> <pre><code>ContactForm.get_reason_display() </code></pre> <p>In a template, use like this:</p> <pre><code>{{ OBJNAME.get_F...
90
2009-04-18T03:28:26Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
4,019,532
<p>I think maybe @webjunkie is right.</p> <p>If you're reading from the form from a POST then you would do </p> <pre><code>def contact_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact = form.save() contact.reason = for...
0
2010-10-25T22:57:07Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
7,600,927
<p>This may help:</p> <pre><code>reason = form.cleaned_data['reason'] reason = dict(form.fields['reason'].choices)[reason] </code></pre>
51
2011-09-29T17:14:51Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
9,574,425
<p>This the easiest way to do this: <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display">Model instance reference: Model.get_FOO_display()</a></p> <p>You can use this function which will return the display name: <code>ObjectName.get_FieldName_display()</code></p>...
11
2012-03-05T21:40:16Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
10,051,191
<p>If the form instance is bound, you can use</p> <pre><code>chosen_label = form.instance.get_FOO_display() </code></pre>
5
2012-04-07T02:18:21Z
[ "python", "django", "choicefield" ]
How to get the label of a choice in a Django forms ChoiceField?
761,698
<p>I have a ChoiceField, now how do I get the "label" when I need it?</p> <pre><code>class ContactForm(forms.Form): reason = forms.ChoiceField(choices=[("feature", "A feature"), ("order", "An order")], widget=forms.RadioSelect) </code></pre>...
41
2009-04-17T18:43:52Z
10,515,057
<p>You can have your form like this:</p> <pre><code>#forms.py CHOICES = [('feature', "A feature"), (order", "An order")] class ContactForm(forms.Form): reason = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) </code></pre> <p>Then this would give you what you want:</p...
2
2012-05-09T11:20:24Z
[ "python", "django", "choicefield" ]
Trimming a string in Python
761,804
<p>How do I remove leading and trailing whitespace from a string in Python?</p> <p>For example:</p> <pre><code>" Hello " --&gt; "Hello" " Hello" --&gt; "Hello" "Hello " --&gt; "Hello" "Bob has a cat" --&gt; "Bob has a cat" </code></pre>
610
2009-04-17T19:16:06Z
761,816
<pre><code>myString.strip() </code></pre>
33
2009-04-17T19:19:12Z
[ "python", "string", "trim" ]
Trimming a string in Python
761,804
<p>How do I remove leading and trailing whitespace from a string in Python?</p> <p>For example:</p> <pre><code>" Hello " --&gt; "Hello" " Hello" --&gt; "Hello" "Hello " --&gt; "Hello" "Bob has a cat" --&gt; "Bob has a cat" </code></pre>
610
2009-04-17T19:16:06Z
761,822
<p>You want strip():</p> <pre><code>myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ] for phrase in myphrases: print phrase.strip() </code></pre>
18
2009-04-17T19:21:14Z
[ "python", "string", "trim" ]
Trimming a string in Python
761,804
<p>How do I remove leading and trailing whitespace from a string in Python?</p> <p>For example:</p> <pre><code>" Hello " --&gt; "Hello" " Hello" --&gt; "Hello" "Hello " --&gt; "Hello" "Bob has a cat" --&gt; "Bob has a cat" </code></pre>
610
2009-04-17T19:16:06Z
761,825
<p>Just one space, or all such spaces? If the second, then strings already have a <code>.strip()</code> method:</p> <pre><code>&gt;&gt;&gt; ' Hello '.strip() 'Hello' &gt;&gt;&gt; ' Hello'.strip() 'Hello' &gt;&gt;&gt; 'Bob has a cat'.strip() 'Bob has a cat' &gt;&gt;&gt; ' Hello '.strip() # ALL spaces ...
932
2009-04-17T19:21:29Z
[ "python", "string", "trim" ]
Trimming a string in Python
761,804
<p>How do I remove leading and trailing whitespace from a string in Python?</p> <p>For example:</p> <pre><code>" Hello " --&gt; "Hello" " Hello" --&gt; "Hello" "Hello " --&gt; "Hello" "Bob has a cat" --&gt; "Bob has a cat" </code></pre>
610
2009-04-17T19:16:06Z
6,039,813
<p>As pointed out in answers above </p> <pre><code>myString.strip() </code></pre> <p>will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space.</p> <p>For more flexibility use the following</p> <ul> <li>Removes only <strong>leading</strong> whitespace chars: <code>myString.lstrip(...
163
2011-05-18T04:16:47Z
[ "python", "string", "trim" ]
Trimming a string in Python
761,804
<p>How do I remove leading and trailing whitespace from a string in Python?</p> <p>For example:</p> <pre><code>" Hello " --&gt; "Hello" " Hello" --&gt; "Hello" "Hello " --&gt; "Hello" "Bob has a cat" --&gt; "Bob has a cat" </code></pre>
610
2009-04-17T19:16:06Z
10,192,113
<p><code>strip</code> is not limited to whitespace characters either:</p> <pre><code># remove all leading/trailing commas, periods and hyphens title = title.strip(',.-') </code></pre>
68
2012-04-17T13:22:23Z
[ "python", "string", "trim" ]
Active Directory - Django/Rails
761,820
<p>I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?</p> <p>(The app will be hosted on Linux)</p> <p>I have lots of reasons for the re-write, one them is to make myself more marketable...
3
2009-04-17T19:20:28Z
761,857
<p>A quick google to give you some pointers on using Active Directory in these environments.</p> <ul> <li><a href="http://www.djangosnippets.org/snippets/501/" rel="nofollow">http://www.djangosnippets.org/snippets/501/</a></li> <li><a href="http://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-...
3
2009-04-17T19:32:41Z
[ "python", "ruby-on-rails", "ruby", "django", "active-directory" ]
Active Directory - Django/Rails
761,820
<p>I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?</p> <p>(The app will be hosted on Linux)</p> <p>I have lots of reasons for the re-write, one them is to make myself more marketable...
3
2009-04-17T19:20:28Z
763,921
<p>I did Active Directory auth in Rails about a year ago. I did it similarly to the article Daniel linked to. It felt hacky, but it was an internal app, so it was acceptable.</p> <p>Since then <a href="http://www.modrails.org/" rel="nofollow">Passenger</a> (<code>mod_rails</code>) has come out which could be a better ...
0
2009-04-18T18:33:31Z
[ "python", "ruby-on-rails", "ruby", "django", "active-directory" ]
Python : How to convert markdown formatted text to text
761,824
<p>I need to convert markdown text to plain text format to display summary in my website. I want the code in python. </p>
16
2009-04-17T19:21:18Z
761,847
<p>This module will help do what you describe:</p> <p><a href="http://www.freewisdom.org/projects/python-markdown/Using%5Fas%5Fa%5FModule">http://www.freewisdom.org/projects/python-markdown/Using_as_a_Module</a></p> <p>Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text...
25
2009-04-17T19:27:32Z
[ "python", "parsing", "markdown" ]
Python : How to convert markdown formatted text to text
761,824
<p>I need to convert markdown text to plain text format to display summary in my website. I want the code in python. </p>
16
2009-04-17T19:21:18Z
761,901
<p>Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.</p>
1
2009-04-17T19:42:56Z
[ "python", "parsing", "markdown" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,120
<p>You can edit your <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">PYTHONPATH</a> to add or remove locations that python will search whenever you attempt an import.</p>
3
2009-04-17T20:39:58Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,122
<ul> <li><p>python will import from the current directory by default.</p></li> <li><p><strong>sys.path</strong> is the variable that controls where python searches for imports.</p></li> </ul>
3
2009-04-17T20:40:13Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,125
<p>You can extend the path at runtime like this:</p> <pre><code>sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/'])) </code></pre>
9
2009-04-17T20:41:04Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,135
<p>You can import module that are in the same path the module you are importing to. For example:</p> <p>Directory contains: <code>mod1.py, mod2.py</code></p> <pre><code>mod2.py -------- import mod1 </code></pre> <p>Or you can add any directory to your PYTHON_PATH variable:</p> <pre><code>import sys sys.path.extend...
0
2009-04-17T20:43:14Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,142
<p>It searches in ./lib by default.</p>
0
2009-04-17T20:46:45Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
762,709
<p>For low-level control over the import process, the <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp</a> module lets you import modules from arbitrary open files under arbitrary names.</p> <p>For example, if this is <code>foo.py</code>:</p> <pre><code>def x(): print 'hello, world' </code></p...
0
2009-04-18T01:27:44Z
[ "python", "import" ]
Importing In Python
762,111
<p>Is it possible to import modules based on location? </p> <p>(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)</p> <p>I'd like to import a module that's local to the current script.</p>
3
2009-04-17T20:37:07Z
763,809
<h2>Use <strong>init</strong>.py</h2> <p>The only problem with doing dynamic modification of sys.path is that you need to repeat it in every script and hard-code the pathnames. That gets messy and non DRY if you have even two or three files. </p> <p>Instead, if your file structure looks like this: </p> <pre><code>~/...
0
2009-04-18T17:34:48Z
[ "python", "import" ]
Django Template: Comparing Dictionary Length in IF Statement
762,118
<p>I am trying to compare the length of a dictionary inside a django template</p> <p>For example, I would like to know the correct syntax to do the following:</p> <pre><code> {% if error_messages %} &lt;div class="error"&gt; {% if length(error_messages) &gt; 1 %} Please fix the following errors: &lt;div ...
1
2009-04-17T20:38:44Z
762,134
<p>You could do this, using the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#length">length</a> filter and the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal">ifequal</a> tag:</p> <pre><code>{% if error_messages %} &lt;div class="error"&gt; {% ifequal...
8
2009-04-17T20:42:35Z
[ "python", "django" ]
Django Template: Comparing Dictionary Length in IF Statement
762,118
<p>I am trying to compare the length of a dictionary inside a django template</p> <p>For example, I would like to know the correct syntax to do the following:</p> <pre><code> {% if error_messages %} &lt;div class="error"&gt; {% if length(error_messages) &gt; 1 %} Please fix the following errors: &lt;div ...
1
2009-04-17T20:38:44Z
2,194,667
<p>use the smart_if template tag: </p> <p><a href="http://www.djangosnippets.org/snippets/1350/" rel="nofollow">http://www.djangosnippets.org/snippets/1350/</a></p> <p>its super cool :)</p> <p>can do all the obvious stuff like: </p> <p>{% if articles|length >= 5 %}...{% endif %}</p> <p>{% if "ifnotequal tag" != "b...
1
2010-02-03T19:06:38Z
[ "python", "django" ]
Django Template: Comparing Dictionary Length in IF Statement
762,118
<p>I am trying to compare the length of a dictionary inside a django template</p> <p>For example, I would like to know the correct syntax to do the following:</p> <pre><code> {% if error_messages %} &lt;div class="error"&gt; {% if length(error_messages) &gt; 1 %} Please fix the following errors: &lt;div ...
1
2009-04-17T20:38:44Z
29,987,079
<p>You can actually use both the <code>if</code> tag and the <code>length</code> filter</p> <pre><code>{% if page_detail.page_content|length &gt; 2 %} &lt;strong&gt;&lt;a class="see-more" href="#" data-prevent-default=""&gt; Learn More&lt;/a&gt;&lt;/strong&gt;{% endif %} </code></pre> <p><strong>NB</strong> Ensure n...
2
2015-05-01T12:44:52Z
[ "python", "django" ]
Overriding class member variables in Python (Django/Satchmo)
762,165
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p> <pre><code>class Product(models.Model...
1
2009-04-17T20:54:10Z
762,352
<p>For two reasons, firstly the way you are trying to override a class variable just isn't how it works in Python. You just define it in the class as normal, the same way that <code>def __init__(self):</code> is overriding the super-class initializer. But, Django model inheritance simply doesn't support this. If you wa...
1
2009-04-17T21:55:30Z
[ "python", "django", "satchmo" ]
Overriding class member variables in Python (Django/Satchmo)
762,165
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p> <pre><code>class Product(models.Model...
1
2009-04-17T20:54:10Z
762,579
<p>You can't change the superclass from a subclass. </p> <p>You have the source. Use subversion. Make the change. When Satchmo is updated merge the updates around your change. </p>
-2
2009-04-17T23:43:16Z
[ "python", "django", "satchmo" ]
Overriding class member variables in Python (Django/Satchmo)
762,165
<p>I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:</p> <pre><code>class Product(models.Model...
1
2009-04-17T20:54:10Z
768,882
<p>You could probably monkeypatch it if you really wanted to:</p> <pre><code>site_field = Product._meta.get_field('site') site_field.editable = False site_field.default = 1 </code></pre> <p>But this is a nasty habit and could cause problems; arguably less maintainable than just patching Satchmo's source directly.</p>...
1
2009-04-20T15:52:20Z
[ "python", "django", "satchmo" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
762,957
<p>Have you installed freetype properly? If you have, there should be a file named <code>ft2build.h</code> somewhere under the installation directory, and the directory where that file is found is the one that you should specify with <code>-I</code>. The string "GnuWin32" does not appear anywhere in the output of your ...
13
2009-04-18T05:27:41Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
4,767,910
<p>For those who might have the same issue but on a Mac OS 10.6 (snow leopard) and Python 2.7. , the easiest solution I found was to get a make file which downloads Numpy, scipy and matplotlib and compile them for you. You can customize the make file to get you matplotlib only. Here is the <a href="http://stefan.sofa-r...
3
2011-01-22T12:55:35Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
5,206,094
<p>This error comes about when building matplotlib on Ubuntu 10.10 also. The solution is to do:</p> <pre><code>sudo apt-get install python-dev libfreetype6-dev </code></pre>
57
2011-03-05T19:02:47Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
12,326,339
<p>I had the same error in red hat 6. Turns out that I needed to install <code>freetype-devel</code>, not <code>freetype</code> (using <code>sudo yum install freetype-devel</code>)</p>
3
2012-09-07T22:42:44Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
13,188,340
<p>Another solution for Mac OS X is to install Freetype with Homebrew.</p> <pre><code>brew install freetype </code></pre>
6
2012-11-02T02:13:29Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
18,308,136
<p>I also fixed this problem by installing freetype using homebrew on Mac OS X. However, that was not sufficient, as the libraries were not linked properly under Mac OS X 10.7. So I had to manually add them to <code>pip</code> command as follows:</p> <pre><code>brew install freetype brew install libpng LDFLAGS="-L/usr...
2
2013-08-19T07:04:16Z
[ "python", "build", "matplotlib", "freetype" ]
Matplotlib Build Problem: Error C1083: Cannot open include file: 'ft2build.h'
762,292
<p><strong>ft2build.h</strong> is located here:</p> <p><strong>C:\Program Files\GnuWin32\include</strong></p> <p>Initially, I made the same mistake as here:</p> <p><a href="http://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffio-h-no-such-file-or-director">http://stackoverflow.com...
23
2009-04-17T21:36:22Z
24,534,246
<p>I was able to solve this on Windows by doing the following:</p> <pre><code> set INCLUDE=%INCLUDE%;C:\tmp\msvcr90-x32 set LIB=%LIB%;C:\tmp\msvcr90-x32 pip.exe install matplotlib </code></pre> <p>The link libraries for Freetype on windows can be found here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/...
1
2014-07-02T14:48:43Z
[ "python", "build", "matplotlib", "freetype" ]
Is this Python code thread safe?
762,448
<pre><code>import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count&lt;9: self.work() def skip(self): self.doSkip = True def work(self): ...
2
2009-04-17T22:33:40Z
762,463
<p>Thread-safe in which way? I don't see any part you might want to protect here.</p> <p>skip may reset the <code>doSkip</code> at any time, so there's not much point in locking it. You don't have any resources that are accessed at the same time - so IMHO nothing can be corrupted / unsafe in this code.</p> <p>The onl...
2
2009-04-17T22:42:54Z
[ "python", "multithreading" ]
Is this Python code thread safe?
762,448
<pre><code>import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count&lt;9: self.work() def skip(self): self.doSkip = True def work(self): ...
2
2009-04-17T22:33:40Z
762,470
<p>Apparently there isn't any critical resource, so I'd say it's thread-safe.</p> <p>But as usual you can't predict in which order the two threads will be blocked/run by the scheduler.</p>
0
2009-04-17T22:44:50Z
[ "python", "multithreading" ]
Is this Python code thread safe?
762,448
<pre><code>import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count&lt;9: self.work() def skip(self): self.doSkip = True def work(self): ...
2
2009-04-17T22:33:40Z
762,481
<p>This is and will thread safe as long as you don't share data between threads.</p> <p>If an other thread needs to read/write data to your thread class, then this won't be thread safe unless you protect data with some synchronization mechanism (like locks).</p>
0
2009-04-17T22:46:59Z
[ "python", "multithreading" ]
Is this Python code thread safe?
762,448
<pre><code>import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count&lt;9: self.work() def skip(self): self.doSkip = True def work(self): ...
2
2009-04-17T22:33:40Z
764,584
<p>Whenever the test of a mutex boolean ( e.g. if(self.doSkip) ) is separate from the set of the mutex boolean you will probably have threading problems.</p> <p>The rule is that your thread will get swapped out at the most inconvenient time. That is, after the test and before the set. Moving them closer together reduc...
1
2009-04-19T00:53:39Z
[ "python", "multithreading" ]
Is this Python code thread safe?
762,448
<pre><code>import time import threading class test(threading.Thread): def __init__ (self): threading.Thread.__init__(self) self.doSkip = False self.count = 0 def run(self): while self.count&lt;9: self.work() def skip(self): self.doSkip = True def work(self): ...
2
2009-04-17T22:33:40Z
766,280
<p>To elaborate on DanM's answer, conceivably this could happen:</p> <ol> <li>Thread 1: <code>t.skip()</code></li> <li>Thread 2: <code>if self.doSkip: print 'skipped'</code></li> <li>Thread 1: <code>t.skip()</code></li> <li>Thread 2: <code>self.doSkip = False</code></li> <li>etc.</li> </ol> <p>In other words, while y...
0
2009-04-19T22:40:55Z
[ "python", "multithreading" ]
Python Regexp problem
762,482
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p> <pre><code>&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;random Value&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt; </code></pre> <p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contain...
0
2009-04-17T22:47:53Z
762,496
<p>This</p> <pre><code>import re htmlbody = "&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;random Value&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt;" reg = re.compile("&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;([^&lt;]*)&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt;") value = r...
1
2009-04-17T22:56:45Z
[ "python", "html", "regex" ]
Python Regexp problem
762,482
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p> <pre><code>&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;random Value&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt; </code></pre> <p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contain...
0
2009-04-17T22:47:53Z
762,556
<p>There is no surefire way to do this with a regex. See <a href="http://stackoverflow.com/questions/701166">Can you provide some examples of why it is hard to parse XML and HTML with a regex?</a> for why. What you need is an HTML parser like <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTM...
4
2009-04-17T23:22:47Z
[ "python", "html", "regex" ]
Python Regexp problem
762,482
<p>I'm trying to regexp a line from a webpage. The line is as follows:</p> <pre><code>&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;random Value&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt; </code></pre> <p>This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contain...
0
2009-04-17T22:47:53Z
762,559
<p>It sounds like you may want to use <code>findall</code> rather than <code>search</code>:</p> <pre><code>reg = re.compile("&lt;tr&gt;&lt;td width=60 bgcolor='#ffffcc'&gt;&lt;b&gt;([^&lt;]*)&lt;/b&gt;&lt;/td&gt;&lt;td align=center width=80&gt;") value = reg.findall(htmlbody) print 'Found %i match(es)' % len(value) <...
1
2009-04-17T23:26:50Z
[ "python", "html", "regex" ]
Defining a table with sqlalchemy with a mysql unix timestamp
762,750
<p>Background, there are several ways to store dates in MySQ.</p> <ol> <li>As a string e.g. "09/09/2009".</li> <li>As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap seconds).</li> <li>As a MySQL TIMESTAMP, a mysq...
3
2009-04-18T02:22:58Z
763,195
<p>So yeah, this approach works. And I ended up answering my own question :/, hope somebody finds this useful.</p> <pre><code>import datetime, time from sqlalchemy.types import TypeDecorator, DateTime class IntegerDateTime(TypeDecorator): """a type that decorates DateTime, converts to unix time on the way in a...
2
2009-04-18T09:19:18Z
[ "python", "mysql", "sqlalchemy" ]
Defining a table with sqlalchemy with a mysql unix timestamp
762,750
<p>Background, there are several ways to store dates in MySQ.</p> <ol> <li>As a string e.g. "09/09/2009".</li> <li>As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap seconds).</li> <li>As a MySQL TIMESTAMP, a mysq...
3
2009-04-18T02:22:58Z
866,566
<p>I think there is a couple of issues with the type decorator you showed.</p> <ol> <li><code>impl</code> should be <code>sqlalchemy.types.Integer</code> instead of <code>DateTime</code>.</li> <li>The decorator should allow nullable columns.</li> </ol> <p>Here's the what I have in mind:</p> <pre><code> import dateti...
5
2009-05-15T00:44:41Z
[ "python", "mysql", "sqlalchemy" ]
How do you store an app engine Image object in the db?
762,764
<p>I'm a bit stuck with my code:</p> <pre><code>def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj = Venue(images = [img]) ...
1
2009-04-18T02:36:47Z
762,777
<p><a href="http://code.google.com/appengine/docs/python/images/usingimages.html" rel="nofollow">http://code.google.com/appengine/docs/python/images/usingimages.html</a></p> <p>I think that link should help. Good luck.</p>
0
2009-04-18T02:45:09Z
[ "python", "google-app-engine", "image" ]
How do you store an app engine Image object in the db?
762,764
<p>I'm a bit stuck with my code:</p> <pre><code>def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj = Venue(images = [img]) ...
1
2009-04-18T02:36:47Z
762,860
<p>I'm not happy with this solution as it doesn't convert an Image object to a blob, but it will do for the time being:</p> <pre><code>def setVenueImage(img): original = img.read() img = images.Image(original) x, y = photo_utils.getIdealResolution(img.width, img.height) img = images.resize(original, x, y) ve...
2
2009-04-18T04:09:34Z
[ "python", "google-app-engine", "image" ]
How do you store an app engine Image object in the db?
762,764
<p>I'm a bit stuck with my code:</p> <pre><code>def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj = Venue(images = [img]) ...
1
2009-04-18T02:36:47Z
773,127
<p><a href="http://aralbalkan.com/1333" rel="nofollow">http://aralbalkan.com/1333</a></p> <p>try this link, it is about a GAW SWF project and sources are inclued.</p>
0
2009-04-21T15:20:44Z
[ "python", "google-app-engine", "image" ]
How do you store an app engine Image object in the db?
762,764
<p>I'm a bit stuck with my code:</p> <pre><code>def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj = Venue(images = [img]) ...
1
2009-04-18T02:36:47Z
899,950
<p>This will probably work:</p> <pre><code>def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img_bytes = img.execute_transforms() # Converts to PNG venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj ...
2
2009-05-22T20:54:28Z
[ "python", "google-app-engine", "image" ]
How do i convert WMD markdown syntax to HTML on my site?
763,087
<p>Am using django and am implementing WMD on my site, am just wondering how do i convert the markdown syntax to HTML for display purposes, is there some sort of function i should call to do this conversion?</p> <p>What is the best way to handle markdown ie. do i save the markdown as is to the database then parse it w...
3
2009-04-18T07:21:39Z
763,102
<p>Check out the <a href="http://docs.djangoproject.com/en/1.0/ref/contrib/#markup" rel="nofollow">markup</a> add-on which comes with Django. That is what you are looking for.</p> <blockquote> <p>To activate these filters, add 'django.contrib.markup' to your INSTALLED_APPS setting. Once you’ve done that, use {% lo...
7
2009-04-18T07:47:21Z
[ "python", "html", "django", "markdown", "wmd" ]
Auto GET to argument of view
763,103
<pre><code>some_view?param1=10&amp;param2=20 def some_view(request, param1, param2): </code></pre> <p>Is such possible in Django?</p>
0
2009-04-18T07:48:08Z
763,107
<p>I'm not sure it's possible to get it to pass them as <em>arguments</em> to the view function, but why can't you access the <code>GET </code> variables from <code>request.GET</code>? Given that URL, Django would have <code>request.GET['param1']</code> be 10 and <code>request.GET['param2']</code> be 20. Otherwise, you...
1
2009-04-18T07:54:09Z
[ "python", "django", "django-urls", "django-views" ]
Auto GET to argument of view
763,103
<pre><code>some_view?param1=10&amp;param2=20 def some_view(request, param1, param2): </code></pre> <p>Is such possible in Django?</p>
0
2009-04-18T07:48:08Z
763,133
<p>I agree with Paolo... the stuff after the '?' are GET parameters and should probably be treated as such. That said, if you really want to keep the definition of some_view() as you've stated in the question, you could do something like:</p> <pre><code>from django.http import Http404 def some_view_proxy(request): ...
1
2009-04-18T08:27:15Z
[ "python", "django", "django-urls", "django-views" ]
Auto GET to argument of view
763,103
<pre><code>some_view?param1=10&amp;param2=20 def some_view(request, param1, param2): </code></pre> <p>Is such possible in Django?</p>
0
2009-04-18T07:48:08Z
763,357
<p>Instead of fighting Django, why not just request some_view/10/20 and then set up urls.py to extract the arguments?</p>
1
2009-04-18T12:26:15Z
[ "python", "django", "django-urls", "django-views" ]
Auto GET to argument of view
763,103
<pre><code>some_view?param1=10&amp;param2=20 def some_view(request, param1, param2): </code></pre> <p>Is such possible in Django?</p>
0
2009-04-18T07:48:08Z
763,387
<p>You could always write a decorator. Eg. something like (untested):</p> <pre><code>def map_params(func): def decorated(request): return func(request, **request.GET) return decorated @map_params def some_view(request, param1, param2): ... </code></pre>
3
2009-04-18T12:47:22Z
[ "python", "django", "django-urls", "django-views" ]
How to interact through vim?
763,372
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those...
1
2009-04-18T12:34:43Z
763,381
<p>Check out <a href="https://addons.mozilla.org/en-US/firefox/addon/4125" rel="nofollow">It's All Text!</a>. It's a Firefox add-in that does something similar for <code>textarea</code>s on web pages, except the editor in question is configurable.</p>
2
2009-04-18T12:43:28Z
[ "python", "linux", "vim" ]
How to interact through vim?
763,372
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those...
1
2009-04-18T12:34:43Z
763,426
<p>Write your intermediate results (what you want the user to edit) to a temp file. Then use the <code>$EDITOR</code> environment variable in a system call to make the user edit the temp file, and read the results when the process finishes.</p> <p>This lets users configure which editor they want to use in a pseudo-st...
6
2009-04-18T13:19:31Z
[ "python", "linux", "vim" ]
How to interact through vim?
763,372
<p>I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those...
1
2009-04-18T12:34:43Z
763,983
<p>You can also think about integrating VIM in to your app. <a href="http://pida.co.uk/" rel="nofollow">Pida</a> does this</p>
1
2009-04-18T19:14:10Z
[ "python", "linux", "vim" ]
Python Beginner: How to Prevent 'finally' from executing?
763,480
<p>The function code:</p> <pre><code># Connect to the DB try: dbi = MySQLdb.connect(host='localhost', \ user='user', \ passwd='pass', \ db='dbname', \ port=3309) print "Connected to DB ..." except MySQLdb....
3
2009-04-18T14:01:21Z
763,484
<p>Don't use finally. If you don't want the code to always be executed then you should find another flow control structure that meets your needs.</p> <p>One way to accomplish this behavior is to move the statements in your 'finally' block to the bottom of your 'try' block. That way they won't get executed when an exce...
4
2009-04-18T14:05:34Z
[ "python" ]
Python Beginner: How to Prevent 'finally' from executing?
763,480
<p>The function code:</p> <pre><code># Connect to the DB try: dbi = MySQLdb.connect(host='localhost', \ user='user', \ passwd='pass', \ db='dbname', \ port=3309) print "Connected to DB ..." except MySQLdb....
3
2009-04-18T14:01:21Z
763,499
<p>I think in this case you do want to use finally, because you want to close those connections. </p> <p>I disagree with the notion that you should have two try blocks in the same method.</p> <p>I think the flaw in the design is acquiring the connection and performing the query in the same method. I would recommend...
5
2009-04-18T14:14:58Z
[ "python" ]
Python Beginner: How to Prevent 'finally' from executing?
763,480
<p>The function code:</p> <pre><code># Connect to the DB try: dbi = MySQLdb.connect(host='localhost', \ user='user', \ passwd='pass', \ db='dbname', \ port=3309) print "Connected to DB ..." except MySQLdb....
3
2009-04-18T14:01:21Z
763,550
<p>Use <code>else:</code> instead of <code>finally:</code>. See the <a href="http://docs.python.org/tutorial/errors.html#handling-exceptions">Exception Handling</a> part of the docs:</p> <blockquote> <p>The <code>try ... except</code> statement has an optional else clause, which, when present, must follow all except...
6
2009-04-18T14:47:59Z
[ "python" ]
Priority issue in Sitemaps
763,485
<p>I am trying to use Django sitemaps. </p> <pre><code>class BlogSiteMap(Sitemap): """A simple class to get sitemaps for blog""" changefreq = 'hourly' priority = 0.5 def items(self): return Blog.objects.order_by('-pubDate') def lastmod(self, obj): return obj.pubDate </code></pre>...
1
2009-04-18T14:05:41Z
763,571
<p>I think you can alter each object with its priority. Like that for example:</p> <pre><code>def items(self): for i, obj in enumerate(Blog.objects.order_by('-pubDate')): obj.priority = i &lt; 3 and 1 or 0.5 yield obj def priority(self, obj): return obj.priority </code></pre>
1
2009-04-18T15:02:47Z
[ "python", "django", "sitemap" ]
Priority issue in Sitemaps
763,485
<p>I am trying to use Django sitemaps. </p> <pre><code>class BlogSiteMap(Sitemap): """A simple class to get sitemaps for blog""" changefreq = 'hourly' priority = 0.5 def items(self): return Blog.objects.order_by('-pubDate') def lastmod(self, obj): return obj.pubDate </code></pre>...
1
2009-04-18T14:05:41Z
898,447
<p>Something like that might work:</p> <pre><code>def priority(self, obj): if obj.id in list(Blog.objects.all()[:3].values_list('id')) return 1.0 else: return 0.5 </code></pre>
0
2009-05-22T15:23:40Z
[ "python", "django", "sitemap" ]
How do I store a string with a `"` in it?
763,654
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>. For example:</p> <pre><code>{ "Dimensions" : " 12.0" x 9.6" " } </code></pre> <p>Obviously this is not possible. How do I do this? With Python.</p>
1
2009-04-18T15:57:00Z
763,660
<p>JSON.stringify, if using Javascript, will escape it for you.<br /> If not, you can escape them like \" (put a \ in front)<br /> Edit: in Python, try <a href="http://ayaz.wordpress.com/2007/04/22/reescape-pythons-equivalent-of-phps-addslashes/" rel="nofollow">re.escape()</a> or just replace all " with \":</p> <pre><...
1
2009-04-18T15:59:25Z
[ "python", "json" ]
How do I store a string with a `"` in it?
763,654
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>. For example:</p> <pre><code>{ "Dimensions" : " 12.0" x 9.6" " } </code></pre> <p>Obviously this is not possible. How do I do this? With Python.</p>
1
2009-04-18T15:57:00Z
763,688
<p>Isaac is correct.</p> <p>As for how to do it in python, you need to provide a more detailed explanation of how you are building your <code>JSON</code> object. For example, let's say you're using no external libraries and are doing it manually (ridiculous, I know), you would do this:</p> <pre><code>&gt;&gt;&gt; st...
7
2009-04-18T16:12:10Z
[ "python", "json" ]
How do I store a string with a `"` in it?
763,654
<p>I want to have a JSON object with the value of an attribute as a string with the character <code>"</code>. For example:</p> <pre><code>{ "Dimensions" : " 12.0" x 9.6" " } </code></pre> <p>Obviously this is not possible. How do I do this? With Python.</p>
1
2009-04-18T15:57:00Z
765,258
<p>Python has two symbols you can use to specify string literals, the single quote and the double quote. </p> <p>For example: my_string = "I'm home!"</p> <p>Or, more relevant to you, </p> <pre><code>&gt;&gt;&gt; string = '{ "Dimensions" : " 12.0\\\" x 9.6\\\" " }' &gt;&gt;&gt; print string { "Dimensions" : " 12....
3
2009-04-19T11:29:19Z
[ "python", "json" ]
python, "a in b" keyword, how about multiple a's?
763,944
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p> <pre><code>if "a" in "abrakadabra" : print "it is definitely here" </code></pre> <p>But is it possible to test if more than one ite...
15
2009-04-18T18:53:11Z
763,947
<p><code>any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))</code></p>
7
2009-04-18T18:57:12Z
[ "python" ]
python, "a in b" keyword, how about multiple a's?
763,944
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p> <pre><code>if "a" in "abrakadabra" : print "it is definitely here" </code></pre> <p>But is it possible to test if more than one ite...
15
2009-04-18T18:53:11Z
763,951
<pre><code>alternatives = ("// @in ", "// @out ", "// @ret ") if any(a in sTxT for a in alternatives): print "found" if all(a in sTxT for a in alternatives): print "found all" </code></pre> <p><a href="http://docs.python.org/library/functions.html#any"><code>any()</code></a> and <a href="http://docs.python.org...
45
2009-04-18T18:58:14Z
[ "python" ]
python, "a in b" keyword, how about multiple a's?
763,944
<p>My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:</p> <pre><code>if "a" in "abrakadabra" : print "it is definitely here" </code></pre> <p>But is it possible to test if more than one ite...
15
2009-04-18T18:53:11Z
763,957
<p>There's no built in way in the syntax to do it. However you can use the 'any' function to make it easier as @MizardX and @Benjamin Peterson showed.</p>
0
2009-04-18T19:00:01Z
[ "python" ]