title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python: avoiding if condition? | 2,422,905 | <p>Which is better?
<pre><code>if not var:
var = get_var()</pre></code>
(or)<br/></p>
<blockquote>
<p>var = var or get_var()</p>
</blockquote>
<p>Also, How do I know the better of the two?<br/>
<b>edit:</b><br/>One more option from steve,</p>
<pre><code>var = var if var else get_var()</code></pre>
| 4 | 2010-03-11T06:00:17Z | 2,422,930 | <p>Both will eventually compile to the same code, given that or is a short-circuit operator (it doesn't evaluate the right hand argument if left hand is true).</p>
<p>I'd prefer the first one as it expresses your intent more clearly. The second one is probably more compact.</p>
| 1 | 2010-03-11T06:04:53Z | [
"python",
"variable-assignment",
"condition"
] |
Python: avoiding if condition? | 2,422,905 | <p>Which is better?
<pre><code>if not var:
var = get_var()</pre></code>
(or)<br/></p>
<blockquote>
<p>var = var or get_var()</p>
</blockquote>
<p>Also, How do I know the better of the two?<br/>
<b>edit:</b><br/>One more option from steve,</p>
<pre><code>var = var if var else get_var()</code></pre>
| 4 | 2010-03-11T06:00:17Z | 2,422,937 | <p>The interpreter will likely execute them both the way. There are tradeoffs regarding code readability. Which statement is easier to recognize what it does? Certainly, the first is much clearer. For me, reading this post, I had to think more about the second one. I would use the first due to increased readability, ev... | 1 | 2010-03-11T06:07:48Z | [
"python",
"variable-assignment",
"condition"
] |
Python: avoiding if condition? | 2,422,905 | <p>Which is better?
<pre><code>if not var:
var = get_var()</pre></code>
(or)<br/></p>
<blockquote>
<p>var = var or get_var()</p>
</blockquote>
<p>Also, How do I know the better of the two?<br/>
<b>edit:</b><br/>One more option from steve,</p>
<pre><code>var = var if var else get_var()</code></pre>
| 4 | 2010-03-11T06:00:17Z | 2,422,952 | <p>When two style variations are so close stylistically, I use <code>timeit</code> as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:</p>
<pre><code>$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of... | 7 | 2010-03-11T06:12:22Z | [
"python",
"variable-assignment",
"condition"
] |
Python: avoiding if condition? | 2,422,905 | <p>Which is better?
<pre><code>if not var:
var = get_var()</pre></code>
(or)<br/></p>
<blockquote>
<p>var = var or get_var()</p>
</blockquote>
<p>Also, How do I know the better of the two?<br/>
<b>edit:</b><br/>One more option from steve,</p>
<pre><code>var = var if var else get_var()</code></pre>
| 4 | 2010-03-11T06:00:17Z | 2,422,973 | <p>Actually, if you are trying to determine if var has been previously set using a call to get_var, then I would contend that <strong><em>both forms are wrong</em></strong>. Python treats a number of perfectly ordinary values as evaluating to a boolean 'false': 0, None, [], (,), set(), and {}. So let's say var is goin... | 4 | 2010-03-11T06:16:24Z | [
"python",
"variable-assignment",
"condition"
] |
Python urllib3 and how to handle cookie support? | 2,422,922 | <p>So I'm looking into <a href="http://code.google.com/p/urllib3/">urllib3</a> because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build_opener so something like:</p>
<pre><code>#!/usr/bin/python
imp... | 6 | 2010-03-11T06:03:10Z | 2,422,938 | <p>You need to set <code>'Cookie'</code> not <code>'Set-Cookie'</code>, <code>'Set-Cookie'</code> set by web server.</p>
<p>And Cookies are one of headers, so its nothing wrong with doing that way.</p>
| 1 | 2010-03-11T06:07:54Z | [
"python",
"urllib3"
] |
Python urllib3 and how to handle cookie support? | 2,422,922 | <p>So I'm looking into <a href="http://code.google.com/p/urllib3/">urllib3</a> because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build_opener so something like:</p>
<pre><code>#!/usr/bin/python
imp... | 6 | 2010-03-11T06:03:10Z | 2,423,176 | <p>You're correct, there's no immediately better way to do this right now. I would be more than happy to accept a patch if you have a congruent improvement.</p>
<p>One thing to keep in mind, urllib3's HTTPConnectionPool is intended to be a "pool of connections" to a specific host, as opposed to a stateful client. In t... | 8 | 2010-03-11T07:07:21Z | [
"python",
"urllib3"
] |
Python urllib3 and how to handle cookie support? | 2,422,922 | <p>So I'm looking into <a href="http://code.google.com/p/urllib3/">urllib3</a> because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build_opener so something like:</p>
<pre><code>#!/usr/bin/python
imp... | 6 | 2010-03-11T06:03:10Z | 2,854,172 | <p>Is there not a problem with multiple cookies?</p>
<p>Some servers return multiple Set-Cookie headers, but urllib3 stores the headers in a dict and a dict does not allow multiple entries with the same key.</p>
<p>httplib2 has a similar problem.</p>
<p>Or maybe not: it turns out that the readheaders method of the H... | 2 | 2010-05-18T02:04:48Z | [
"python",
"urllib3"
] |
Python urllib3 and how to handle cookie support? | 2,422,922 | <p>So I'm looking into <a href="http://code.google.com/p/urllib3/">urllib3</a> because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build_opener so something like:</p>
<pre><code>#!/usr/bin/python
imp... | 6 | 2010-03-11T06:03:10Z | 9,762,706 | <p>You should use the requests library. It uses urllib3 but makes things like adding cookies trivial.</p>
<p><a href="https://github.com/kennethreitz/requests" rel="nofollow">https://github.com/kennethreitz/requests</a></p>
<pre><code>import requests
r1 = requests.get(url, cookies={'somename':'somevalue'})
print(r1.c... | 2 | 2012-03-18T22:00:48Z | [
"python",
"urllib3"
] |
Python urllib3 and how to handle cookie support? | 2,422,922 | <p>So I'm looking into <a href="http://code.google.com/p/urllib3/">urllib3</a> because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build_opener so something like:</p>
<pre><code>#!/usr/bin/python
imp... | 6 | 2010-03-11T06:03:10Z | 20,456,965 | <p>You can use a code like this:</p>
<pre><code>def getHtml(url):
http = urllib3.PoolManager()
r = http.request('GET', url, headers={'User-agent':'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36','Cookie':'cookie_name=cookie_value'})
return r.data #HTML... | 1 | 2013-12-08T18:07:13Z | [
"python",
"urllib3"
] |
Best practices for logging in django project | 2,423,005 | <p>It is always good to utilize existing patterns for solving the given problem rather then reinventing the wheel. This time it is about doing logging stuffs in django based project.</p>
<p>Can you please share your ideas with me and other about how do you prefer to implement logging in django based project in the fol... | 7 | 2010-03-11T06:24:36Z | 2,423,034 | <p>In Django, like in any other Python application, I'd use the standard library's <a href="http://docs.python.org/library/logging.html?highlight=logging#module-logging"><code>logging</code></a> module and call <code>logging.debug</code>, <code>logging.info</code> etc as appropriate to each message. Most of the seven q... | 5 | 2010-03-11T06:30:49Z | [
"python",
"django",
"logging"
] |
how to call python code in javascript to display bar chart | 2,423,102 | <p>i have written python code which gives me i/p to chart(json data) but i am not getting how to get these data in my javascript.</p>
<p>i want to display it in google app engine</p>
<p>i want to do it in same way as we can do it with PHP.</p>
| -1 | 2010-03-11T06:51:31Z | 4,975,368 | <p>As I've posted a few times already, if you want Python to be PHP-like, try <a href="http://flask.pocoo.org/" rel="nofollow">Flask</a></p>
<p>Flask is dead-simple, extremely powerful, and intuitive. I prefer it over PHP for <em>soo</em> many reasons, but mainly because PHP is not Python.</p>
<p>Here's what I mean b... | 0 | 2011-02-12T00:18:52Z | [
"javascript",
"python"
] |
how to call python code in javascript to display bar chart | 2,423,102 | <p>i have written python code which gives me i/p to chart(json data) but i am not getting how to get these data in my javascript.</p>
<p>i want to display it in google app engine</p>
<p>i want to do it in same way as we can do it with PHP.</p>
| -1 | 2010-03-11T06:51:31Z | 4,975,617 | <p>Have you tried the <a href="http://code.google.com/apis/chart/" rel="nofollow">Google charts API</a>?</p>
| 0 | 2011-02-12T01:07:03Z | [
"javascript",
"python"
] |
In Python, is this a good practice? | 2,423,145 | <pre><code>try:
spam.foo
except AttributeError:
do_somthing()
</code></pre>
<p>(Is it wise to check an attribute like that without using it?)</p>
| 2 | 2010-03-11T06:59:34Z | 2,423,164 | <p><strong>Update</strong>:</p>
<p>If you are really only interested in whether the attribute <code>foo</code> exists (and not doing something with the attribute) than of course <code>hasattr()</code> might be better way to check for the attribute.<br>
From a <em>developer/user</em> point of view I have to confess tha... | 12 | 2010-03-11T07:05:04Z | [
"python"
] |
In Python, is this a good practice? | 2,423,145 | <pre><code>try:
spam.foo
except AttributeError:
do_somthing()
</code></pre>
<p>(Is it wise to check an attribute like that without using it?)</p>
| 2 | 2010-03-11T06:59:34Z | 2,423,166 | <p>Better use </p>
<pre><code>if hasattr(spam,"foo"):
#dosomthing with spam.foo
else:
do_somthing()
</code></pre>
<p>Python docs:</p>
<blockquote>
<p>hasattr(object, name)<br />
The arguments are an object and a string. The result is True if the
string is the name of one of the
objectâs attribute... | 2 | 2010-03-11T07:05:38Z | [
"python"
] |
The data format for post in urllib2.Request | 2,423,146 | <p>What should data look like before data encoding in:
<code>urllib2.Request(someurl,data)</code> I tried <code>[('name1','value1'),('name2','value2'),...]</code>but not work.:(</p>
<p>EDIT:
I made a log in the program and recorded the value of <code>urllib.urlencode(data)</code>:</p>
<pre><code>content=%E5%8F%91%E5... | 0 | 2010-03-11T06:59:54Z | 2,423,184 | <p><em>data</em> may be a <strong>string</strong> specifying additional data to send to the server, or <code>None</code> if no such data is needed. Currently HTTP requests are the only ones that use <em>data</em>; the HTTP request will be a POST instead of a GET when the <em>data</em> parameter is provided. <em>data</e... | 2 | 2010-03-11T07:09:25Z | [
"python"
] |
creating a frame to put pictures in it and saving back to database | 2,423,162 | <p>I'm working on a mobile site and what I have to do is 1.create a picture frame 2.add to it pictures posted by users individually, then save each picture back to the database. Does anyone know how to go about this</p>
| -3 | 2010-03-11T07:03:52Z | 2,424,626 | <p>Start with this: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield</a></p>
<p>If you need to have multiple images for user, you probably need similar model:</p>
<pre><code>class ImageUpload(Model):
user =... | 1 | 2010-03-11T11:52:55Z | [
"python",
"django",
"python-imaging-library"
] |
Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program | 2,423,380 | <p>:) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters... | -4 | 2010-03-11T07:59:48Z | 2,423,797 | <p>(now i can reply, after taking some time editing the post. when posting, please use the preview and read the help !)</p>
<p>There is no problem Python cannot tackle... and this problam can definitely be solved using python.</p>
<p>After modifying a bit your python script (indentation is messed up !), i was able to... | 2 | 2010-03-11T09:27:09Z | [
"c++",
"python",
"perl",
"file"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,423,793 | <p>The brute force approach is to loop over all pixels in the image and keep count of R, G, B values. A more refined approach is to use <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.histogram" rel="nofollow">Python Image Library</a> histogram function and calculate the average of all colors.</p>
| 3 | 2010-03-11T09:26:47Z | [
"python",
"image-processing",
"colors"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,423,888 | <p>Since you will most likely not want a histogram of all the million colors that are possible using a 24-bit color space, I suggest transforming the image into HSV space instead.
Then you can partition the Hue part of that space into a number of bins that describe the hues you want to find ("dark red", "orange red", o... | 5 | 2010-03-11T09:40:32Z | [
"python",
"image-processing",
"colors"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,425,576 | <p>If you are really sure that you will always have only one dominant color (no bags in two colors, e.g.), then a crude histogram on the H&S dimensions of <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" rel="nofollow">HSV</a> should suffice. </p>
<p>Otherwise, you can (and should ) use <a href="http://en.wikipe... | 1 | 2010-03-11T14:13:51Z | [
"python",
"image-processing",
"colors"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,427,864 | <p>Sort the pixels in-place, then loop through the image and find the longest run.</p>
| 0 | 2010-03-11T19:05:30Z | [
"python",
"image-processing",
"colors"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,571,311 | <p>As suggested, it will be handier to convert your image from RGB to HSV. The standard library module <a href="http://docs.python.org/library/colorsys.html" rel="nofollow">colorsys</a> contains the function <code>rgb_to_hsv</code> to that effect. Then, you can map colors on an image, say with H as x and S as y. Select... | 0 | 2010-04-03T13:03:37Z | [
"python",
"image-processing",
"colors"
] |
detect the most used colour in an image using python | 2,423,743 | <p>I want to find the most used colour in an image using python. for example detect the colour of the object in the following image</p>
<p><a href="http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg">http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg</a>.</p>
<p>how to detect... | 6 | 2010-03-11T09:20:36Z | 2,571,560 | <p>I would use the Python Image Library. This is a piece of code that computes the number of white pixels/non-white pixels in an image. </p>
<pre><code>import sys
from PIL import Image
im = Image.open(sys.argv[1])
white = 0
black = 0
for i in im.getdata():
if i == (255,255,255):
white += 1
else:
# we ass... | 2 | 2010-04-03T14:49:53Z | [
"python",
"image-processing",
"colors"
] |
Python decompressing gzip chunk-by-chunk | 2,423,866 | <p>I've a memory- and disk-limited environment where I need to decompress the contents of a gzip file sent to me in string-based chunks (over xmlrpc binary transfer). However, using the zlib.decompress() or zlib.decompressobj()/decompress() both barf over the gzip header. I've tried offsetting past the gzip header (doc... | 26 | 2010-03-11T09:35:35Z | 2,424,549 | <p>gzip and zlib use slightly different headers.</p>
<p>See <a href="http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib">http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib</a></p>
<p>Try <code>d = zlib.decompressobj(16+zlib.MAX_WBITS)</code>.</... | 34 | 2010-03-11T11:40:57Z | [
"python",
"gzip",
"zlib"
] |
Python decompressing gzip chunk-by-chunk | 2,423,866 | <p>I've a memory- and disk-limited environment where I need to decompress the contents of a gzip file sent to me in string-based chunks (over xmlrpc binary transfer). However, using the zlib.decompress() or zlib.decompressobj()/decompress() both barf over the gzip header. I've tried offsetting past the gzip header (doc... | 26 | 2010-03-11T09:35:35Z | 22,312,660 | <p>I've got a more detailed answer here: <a href="http://stackoverflow.com/a/22310760/1733117">http://stackoverflow.com/a/22310760/1733117</a></p>
<pre><code>d = zlib.decompressobj(zlib.MAX_WBITS|32)
</code></pre>
<p><a href="http://www.zlib.net/manual.html#Advanced" rel="nofollow">per documentation this automaticall... | 1 | 2014-03-10T22:25:04Z | [
"python",
"gzip",
"zlib"
] |
Read and overwrite a file in Python | 2,424,000 | <p>Currently I'm using this:</p>
<pre><code>f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
</code></pre>
<p>But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.</... | 51 | 2010-03-11T10:01:43Z | 2,424,018 | <p>Probably it would be easier and neater to close the file after <code>text = re.sub('foobar', 'bar', text)</code>, re-open it for writing (thus clearing old contents), and write your updated text to it.</p>
| 10 | 2010-03-11T10:04:09Z | [
"python",
"file",
"overwrite"
] |
Read and overwrite a file in Python | 2,424,000 | <p>Currently I'm using this:</p>
<pre><code>f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
</code></pre>
<p>But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.</... | 51 | 2010-03-11T10:01:43Z | 2,424,044 | <p>The <a href="https://docs.python.org/2/library/fileinput.html"><code>fileinput</code></a> module has an <code>inline</code> mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via... | 7 | 2010-03-11T10:08:38Z | [
"python",
"file",
"overwrite"
] |
Read and overwrite a file in Python | 2,424,000 | <p>Currently I'm using this:</p>
<pre><code>f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
</code></pre>
<p>But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.</... | 51 | 2010-03-11T10:01:43Z | 2,424,410 | <p>If you don't want to close and reopen the file, to avoid race conditions, you could <a href="https://docs.python.org/3/library/io.html#io.IOBase.truncate"><code>truncate</code></a> it:</p>
<pre><code>f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f... | 96 | 2010-03-11T11:16:18Z | [
"python",
"file",
"overwrite"
] |
Read and overwrite a file in Python | 2,424,000 | <p>Currently I'm using this:</p>
<pre><code>f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
</code></pre>
<p>But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.</... | 51 | 2010-03-11T10:01:43Z | 38,098,904 | <p>Try writing it in a new file..</p>
<pre><code>f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
</code></pre>
| 0 | 2016-06-29T11:59:40Z | [
"python",
"file",
"overwrite"
] |
Python: installing multiprocessing | 2,424,078 | <p>I need to import the multiprocessing module in Python 2.5. </p>
<p>I've followed the instructions here exactly: <a href="http://code.google.com/p/python-multiprocessing/wiki/Install" rel="nofollow">http://code.google.com/p/python-multiprocessing/wiki/Install</a></p>
<p>make and make test run without errors. I've a... | 2 | 2010-03-11T10:17:18Z | 2,424,194 | <p>Navigate to the directory containing the package then type:</p>
<pre><code>python setup.py install
</code></pre>
<p>This info was contained in the INSTALL.txt file.</p>
<p><a href="http://code.google.com/p/python-multiprocessing/source/browse/trunk/INSTALL.txt" rel="nofollow">http://code.google.com/p/python-multi... | 4 | 2010-03-11T10:34:49Z | [
"python",
"module"
] |
Python: installing multiprocessing | 2,424,078 | <p>I need to import the multiprocessing module in Python 2.5. </p>
<p>I've followed the instructions here exactly: <a href="http://code.google.com/p/python-multiprocessing/wiki/Install" rel="nofollow">http://code.google.com/p/python-multiprocessing/wiki/Install</a></p>
<p>make and make test run without errors. I've a... | 2 | 2010-03-11T10:17:18Z | 2,424,201 | <p>perhaps you can try:</p>
<pre><code>import sys
sys.path.append('/path/to/processingdotpylibs/')
import processing
</code></pre>
| -1 | 2010-03-11T10:35:32Z | [
"python",
"module"
] |
manipulating list items python | 2,424,226 | <pre><code>line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
</code></pre>
<p>the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split... | 2 | 2010-03-11T10:39:10Z | 2,424,234 | <p><s>Just <code>line.split()</code> could give you stripped words list.</s></p>
<p>Updating <code>each</code> inside the loop does not make any changes to the <code>words</code> list</p>
<p>Should be done like this</p>
<pre><code>for i in range(len(words)):
words[i]=words[i].rstrip()
</code></pre>
<p>Or</p>
<... | 2 | 2010-03-11T10:40:27Z | [
"python",
"string"
] |
manipulating list items python | 2,424,226 | <pre><code>line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
</code></pre>
<p>the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split... | 2 | 2010-03-11T10:39:10Z | 2,424,260 | <pre><code>words = line.split('\t')
words = [ i.rstrip() for i in words ]
</code></pre>
| 1 | 2010-03-11T10:46:21Z | [
"python",
"string"
] |
manipulating list items python | 2,424,226 | <pre><code>line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
</code></pre>
<p>the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split... | 2 | 2010-03-11T10:39:10Z | 2,424,385 | <p>You can use a regular expression:</p>
<pre><code>import re
words = re.split(r' *\t| +$', line)[:-1]
</code></pre>
<p>With this you define the possible sequence as the delimiter. It also allows more than one space because of the * operator (or no space at all).</p>
<p>EDIT: Fixed after Roger Pate pointed an error... | 0 | 2010-03-11T11:12:19Z | [
"python",
"string"
] |
Append previous lines of a file based on a condition | 2,424,411 | <p>I have a text file with a few 1000 lines of text in it. A sample is given below:</p>
<pre><code>person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
</code></pre>
<p>Each line starts with either "p" or "h" or "-". When "have paid" is encounte... | 0 | 2010-03-11T11:16:39Z | 2,424,441 | <p>Just iterate the file putting every line into a List or a hashtable. Then iterate the collection and for each match grab the two previous entries using the index of match -1 and -2.</p>
| 0 | 2010-03-11T11:20:26Z | [
"python",
"list",
"append"
] |
Append previous lines of a file based on a condition | 2,424,411 | <p>I have a text file with a few 1000 lines of text in it. A sample is given below:</p>
<pre><code>person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
</code></pre>
<p>Each line starts with either "p" or "h" or "-". When "have paid" is encounte... | 0 | 2010-03-11T11:16:39Z | 2,424,491 | <pre><code>data=open("file").read().split("\n\n")
for rec in data:
if "have paid" in rec:
print rec.split("have paid")[0]
</code></pre>
| 1 | 2010-03-11T11:29:03Z | [
"python",
"list",
"append"
] |
Append previous lines of a file based on a condition | 2,424,411 | <p>I have a text file with a few 1000 lines of text in it. A sample is given below:</p>
<pre><code>person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
</code></pre>
<p>Each line starts with either "p" or "h" or "-". When "have paid" is encounte... | 0 | 2010-03-11T11:16:39Z | 2,424,503 | <p>This parses correctly your example file:</p>
<pre><code>with open('yourfile') as f:
result = {'have paid': [], '': []}
current = []
for line in f:
line = line.strip().strip('-')
if line in result:
result[line].extend(current)
current = []
else:
... | 0 | 2010-03-11T11:31:20Z | [
"python",
"list",
"append"
] |
What is the easiest way to convert list with str into list with int? | 2,424,412 | <p>What is the easiest way to convert list with <code>str</code> into list with <code>int</code> in Python?
For example, we have to convert <code>['1', '2', '3']</code> to <code>[1, 2, 3]</code>. Of course, we can use a <code>for</code> loop, but it's too easy.</p>
| 10 | 2010-03-11T11:16:55Z | 2,424,425 | <p>Python 2.x:</p>
<pre><code>map(int, ["1", "2", "3"])
</code></pre>
<p>Python 3.x (in 3.x, <code>map</code> returns an iterator, not a list as in 2.x):</p>
<pre><code>list(map(int, ["1", "2", "3"]))
</code></pre>
<p><code>map</code> documentation: <a href="http://docs.python.org/library/functions.html#map">2.6</a... | 16 | 2010-03-11T11:18:49Z | [
"python",
"string",
"integer"
] |
What is the easiest way to convert list with str into list with int? | 2,424,412 | <p>What is the easiest way to convert list with <code>str</code> into list with <code>int</code> in Python?
For example, we have to convert <code>['1', '2', '3']</code> to <code>[1, 2, 3]</code>. Of course, we can use a <code>for</code> loop, but it's too easy.</p>
| 10 | 2010-03-11T11:16:55Z | 2,424,434 | <pre><code>[int(i) for i in str_list]
</code></pre>
| 17 | 2010-03-11T11:19:35Z | [
"python",
"string",
"integer"
] |
What is the easiest way to convert list with str into list with int? | 2,424,412 | <p>What is the easiest way to convert list with <code>str</code> into list with <code>int</code> in Python?
For example, we have to convert <code>['1', '2', '3']</code> to <code>[1, 2, 3]</code>. Of course, we can use a <code>for</code> loop, but it's too easy.</p>
| 10 | 2010-03-11T11:16:55Z | 2,424,439 | <p>You could also use list comprehensions:</p>
<pre><code>new = [int(i) for i in old]
</code></pre>
<p>Or the <code>map()</code> builtin function:</p>
<pre><code>new = map(int, old)
</code></pre>
<p>Or the <code>itertools.imap()</code> function, which will provide a speedup in some cases but in this case just spits... | 4 | 2010-03-11T11:20:12Z | [
"python",
"string",
"integer"
] |
What is the easiest way to convert list with str into list with int? | 2,424,412 | <p>What is the easiest way to convert list with <code>str</code> into list with <code>int</code> in Python?
For example, we have to convert <code>['1', '2', '3']</code> to <code>[1, 2, 3]</code>. Of course, we can use a <code>for</code> loop, but it's too easy.</p>
| 10 | 2010-03-11T11:16:55Z | 10,206,053 | <p>If your strings are not only numbers (ie. u''), you can use :</p>
<pre><code>new = [int(i) for i in ["1", "2", "3"] if isinstance(i, int) or isinstance(i, (str, unicode)) and i.isnumeric()]
</code></pre>
| 2 | 2012-04-18T08:56:42Z | [
"python",
"string",
"integer"
] |
Compound assignment to Python class and instance variables | 2,424,451 | <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="http://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>... | 5 | 2010-03-11T11:21:52Z | 2,424,496 | <pre><code>bar.num += 1
</code></pre>
<p>creates a new instance variable 'num' on the 'bar' instance because it doesn't yet exist (and then adds 1 to this value)</p>
<p>an example:</p>
<pre><code>class Foo:
def __init__(self):
self.num= 1
bar = Foo()
print bar.num
</code></pre>
<p>this prints 1</p>
<pre><co... | 0 | 2010-03-11T11:30:25Z | [
"python",
"class"
] |
Compound assignment to Python class and instance variables | 2,424,451 | <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="http://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>... | 5 | 2010-03-11T11:21:52Z | 2,424,560 | <p>I think you just found a bug in Python there. bar.num += 1 should be an error, instead, it is creating an attribute num in the object bar, distinct from Foo.num.</p>
<p>It's a really strange behavior.</p>
| -2 | 2010-03-11T11:41:54Z | [
"python",
"class"
] |
Compound assignment to Python class and instance variables | 2,424,451 | <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="http://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>... | 5 | 2010-03-11T11:21:52Z | 2,424,575 | <p>Personally, I've found <a href="http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html" rel="nofollow">these documents</a> by Shalabh Chaturvedi extremely useful and informative regarding this subject matter.</p>
<p><code>bar.num += 1</code> is a shorthand for <code>bar.num = bar.num +... | 4 | 2010-03-11T11:44:12Z | [
"python",
"class"
] |
Compound assignment to Python class and instance variables | 2,424,451 | <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="http://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>... | 5 | 2010-03-11T11:21:52Z | 2,424,621 | <p>In the following code, <code>num</code> is a class member.</p>
<pre><code>class Foo:
num = 0
</code></pre>
<p>A C++ equivalent would be something like</p>
<pre><code>struct Foo {
static int num;
};
int Foo::num = 1;
</code></pre>
<hr>
<pre><code>class Foo:
def __init__(self):
self.num = 0
</c... | 2 | 2010-03-11T11:52:16Z | [
"python",
"class"
] |
Compound assignment to Python class and instance variables | 2,424,451 | <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="http://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>... | 5 | 2010-03-11T11:21:52Z | 10,872,584 | <p>Searching for this very question, both this StackOverflow question and two (rather old, but valid) slides by Guido van Rossum (<a href="http://www.python.org/doc/essays/ppt/acm-ws/sld051.htm" rel="nofollow">1</a>, <a href="http://www.python.org/doc/essays/ppt/acm-ws/sld052.htm" rel="nofollow">2</a>) came up high. Gu... | 1 | 2012-06-03T17:48:55Z | [
"python",
"class"
] |
Regular expression to match C's multiline preprocessor statements | 2,424,458 | <p>what I need is to match multiline preprocessor's statements such as:</p>
<pre><code>#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
</code></pre>
<p>The point is to match everything between <code>#define</code> and last <code>})</code>, but I ... | 2 | 2010-03-11T11:22:58Z | 2,424,778 | <p>I think something like this will work:</p>
<pre><code>m = re.compile(r"^#define[\s\S]+?}\)*$", re.MULTILINE)
matches = m.findall(your_string_here)
</code></pre>
<p>This assumes that your macros all end with '}', with an optional ')' at the end.</p>
| 0 | 2010-03-11T12:20:18Z | [
"python",
"regex"
] |
Regular expression to match C's multiline preprocessor statements | 2,424,458 | <p>what I need is to match multiline preprocessor's statements such as:</p>
<pre><code>#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
</code></pre>
<p>The point is to match everything between <code>#define</code> and last <code>})</code>, but I ... | 2 | 2010-03-11T11:22:58Z | 2,424,939 | <p>This should do it:</p>
<pre><code>r'(?m)^#define (?:.*\\\r?\n)*.*$'
</code></pre>
<p><code>(?:.*\\\r?\n)*</code> matches zero or more lines ending with backslashes, then <code>.*$</code> matches the final line.</p>
| 2 | 2010-03-11T12:44:17Z | [
"python",
"regex"
] |
Getting registry information using Python | 2,424,648 | <p>I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a <code>.bat</code> file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code:</p>
<p>My working bat file:</p>
<p... | 1 | 2010-03-11T11:56:14Z | 2,424,870 | <p>Without knowing much about your setup, this might work for you the way that you want.</p>
<pre><code>import _winreg
################################################################################
class HKEY:
'Hive Constants'
CLASSES_ROOT = -2147483648
CURRENT_USER = -2147483647
LOCAL_MACHINE = -2... | 2 | 2010-03-11T12:33:03Z | [
"python",
"winreg"
] |
Getting registry information using Python | 2,424,648 | <p>I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a <code>.bat</code> file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code:</p>
<p>My working bat file:</p>
<p... | 1 | 2010-03-11T11:56:14Z | 4,242,739 | <p>Have a look at the Python 3rd-party <a href="http://pypi.python.org/pypi/regobj/" rel="nofollow"><code>regobj</code> module</a>. It makes Windows registry access even easier than using <a href="http://docs.python.org/library/_winreg.html" rel="nofollow">Python's built-in <code>_winreg</code> module</a>.</p>
| 0 | 2010-11-22T06:05:58Z | [
"python",
"winreg"
] |
How to get a list with elements that are contained in two other lists? | 2,424,700 | <p>We have two lists:</p>
<pre><code>a=['1','2','3','4']
b=['2','3','4','5']
</code></pre>
<p>How to get a list with elements that are contained in both lists:</p>
<pre><code>a_and_b=['2','3','4']
</code></pre>
<p>and a list with elements that are contained only in one list, but not the other:</p>
<pre><code>only_... | 2 | 2010-03-11T12:03:33Z | 2,424,712 | <p>if order is not important</p>
<pre><code>>>> a=['1','2','3','4']
>>> b=['2','3','4','5']
>>> set(a) & set(b)
set(['3', '2', '4'])
</code></pre>
<p>only a</p>
<pre><code>>>> set(a).difference(b) # or set(a) - set(b)
set(['1'])
</code></pre>
<p>only b</p>
<pre><code>>>... | 8 | 2010-03-11T12:06:03Z | [
"python"
] |
How to get a list with elements that are contained in two other lists? | 2,424,700 | <p>We have two lists:</p>
<pre><code>a=['1','2','3','4']
b=['2','3','4','5']
</code></pre>
<p>How to get a list with elements that are contained in both lists:</p>
<pre><code>a_and_b=['2','3','4']
</code></pre>
<p>and a list with elements that are contained only in one list, but not the other:</p>
<pre><code>only_... | 2 | 2010-03-11T12:03:33Z | 2,424,720 | <p>Simply with the use of sets:</p>
<pre><code>>>> a=['1','2','3','4']; b=['2','3','4','5']
>>> a = set(a)
>>> b = set(b)
>>> a & b
set(['3', '2', '4'])
>>> a - b
set(['1'])
>>> b - a
set(['5'])
>>>
</code></pre>
| 5 | 2010-03-11T12:06:35Z | [
"python"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 2,424,969 | <p>There are 2 scenario's where Bash performance is at least equal I believe:</p>
<ul>
<li>Scripting of command line utilities</li>
<li>Scripts which take only a short time to execute; where starting the Python interpreter takes more time than the operation itself</li>
</ul>
<p>That said, I usually don't really conce... | 5 | 2010-03-11T12:50:49Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 2,424,971 | <p><strong>Developer efficiency</strong> matters much more to me in scenarios where both bash and Python are sensible choices.</p>
<p>Some tasks lend themselves well to bash, and others to Python. It also isn't unusual for me to start something as a bash script and change it to Python as it evolves over several weeks... | 19 | 2010-03-11T12:50:50Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 2,426,281 | <p>Bash is primarily a batch / shell scripting language with far less support for various data types and all sorts of quirks around control structures -- not to mention compatibility issues. </p>
<p>Which is faster? Neither, because you are not comparing apples to apples here. If you had to sort an ascii text file and... | 10 | 2010-03-11T15:37:06Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 2,441,363 | <p>Generally, bash works better than python only in those environments where python is not available. :)</p>
<p>Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, ... | 48 | 2010-03-14T06:09:42Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 10,562,652 | <p>If you are looking to cobble together a quick utility with minimal effort, bash is good. For a wrapper round an application, bash is invaluable.</p>
<p>Anything that may have you coming back over and over to add improvements is probably (though not always) better suited to a language like Python as Bash code compr... | 7 | 2012-05-12T09:49:21Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 14,476,979 | <p><strong>Typical mainframe flow...</strong></p>
<pre><code>Input Disk/Tape/User (runtime) --> Job Control Language (JCL) --> Output Disk/Tape/Screen/Printer
| ^
v |
... | 26 | 2013-01-23T10:05:05Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 25,171,738 | <p>Performance-wise bash outperforms python in the process startup time. </p>
<p>Here are some measurements from my core i7 laptop running Linux Mint:</p>
<pre><code>Starting process Startup time
empty /bin/sh script 1.7 ms
empty /bin/bash script 2.8 ms
empty p... | 8 | 2014-08-06T23:05:54Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 25,171,858 | <p>The instant your bash script needs to do something that bash doesn't support well*, you're going to wish you'd done it in Python in the first place.</p>
<p>* including "be read and understood by someone else".</p>
| 6 | 2014-08-06T23:20:32Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 35,653,422 | <p>I don't know if this is accurate, but I have found that python/ruby works much better for scripts that have a lot of mathematical computations. Otherwise you have to use <code>dc</code> or some other "arbitrary precision calculator". It just becomes a very big pain. With python you have much more control over floats... | 1 | 2016-02-26T13:48:38Z | [
"python",
"performance",
"bash"
] |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | <p>Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found <a href="http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7">this</a> that claims that you can se... | 42 | 2010-03-11T12:42:52Z | 39,927,503 | <p>When you writing scripts performance does not matter (in most cases).<br>
If you care about performance 'Python vs Bash' is a false question. </p>
<p><strong>Python</strong>:<br>
+ easier to write<br>
+ easier to maintain<br>
+ easier code reuse (try to find universal error-proof way to include files with common c... | 0 | 2016-10-08T00:37:09Z | [
"python",
"performance",
"bash"
] |
Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible? | 2,424,945 | <p>I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.</p>
<p>In order to do that it uses the next method:</p>
<pre><code>def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.d... | 6 | 2010-03-11T12:45:52Z | 2,425,078 | <p>Does <code>byte[] input = stringToCompress.getBytes("utf-8");</code> help? In case your platform's default encoding is not UTF-8, this will force the encoding String -> bytes to use UTF-8. Also, the same goes for the last line of your code where you create a <code>new String</code> - you may want to explicitly speci... | 0 | 2010-03-11T13:09:18Z | [
"java",
"python",
"android",
"zlib",
"deflate"
] |
Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible? | 2,424,945 | <p>I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.</p>
<p>In order to do that it uses the next method:</p>
<pre><code>def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.d... | 6 | 2010-03-11T12:45:52Z | 2,426,740 | <p>compress and deflate are different compression algorithms so the answer is they will not be compatible. As an example of the difference here is 'a' compressed using the two algorithms via Tcl:</p>
<pre><code>% binary encode hex [zlib compress a]
789c4b040000620062
% binary encode hex [zlib deflate a]
4b0400</code><... | 7 | 2010-03-11T16:28:29Z | [
"java",
"python",
"android",
"zlib",
"deflate"
] |
Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible? | 2,424,945 | <p>I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.</p>
<p>In order to do that it uses the next method:</p>
<pre><code>def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.d... | 6 | 2010-03-11T12:45:52Z | 8,021,985 | <p>Although they are not exactly the same algorithms, it seems that they are totally compatible (meaning that if you compress, for example, an String using Deflater.deflate you can correctly uncompress it using zlib).</p>
<p>What caused my problem was that all form variables in a POST need to be percent escaped, and t... | 2 | 2011-11-05T17:40:58Z | [
"java",
"python",
"android",
"zlib",
"deflate"
] |
Testing for Inactivity in Python on Mac | 2,425,087 | <p>Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even <em>if</em> the system is currently idle?</p>
<p><strong>Answer</strong></p>
<p>Using the information from the accepted solution, here is an ugly but functional and fairly efficient function for the job:</p>
<pr... | 5 | 2010-03-11T13:10:08Z | 2,425,253 | <p>Untested (for now), but <a href="http://www.dssw.co.uk/sleepcentre/threads/system_idle_time_how_to_retrieve.html" rel="nofollow">according to this thread</a> you could parse the output of </p>
<blockquote>
<p>ioreg -c IOHIDSystem</p>
</blockquote>
| 0 | 2010-03-11T13:32:29Z | [
"python",
"osx"
] |
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python? | 2,425,096 | <p>I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.</p>
<p>How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?</p>
<p>I am thinking I should som... | 4 | 2010-03-11T13:11:18Z | 2,425,108 | <p>First off, is a generator really needed? This sounds like the perfect job for Pythonâs <a href="http://docs.python.org/library/stdtypes.html#typesseq" rel="nofollow">slices syntax</a>:</p>
<pre><code>result = my_range[ : -1]
</code></pre>
<p>I.e.: take a range form the first item to the one before the last.</p>
| 2 | 2010-03-11T13:13:26Z | [
"python"
] |
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python? | 2,425,096 | <p>I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.</p>
<p>How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?</p>
<p>I am thinking I should som... | 4 | 2010-03-11T13:11:18Z | 2,425,143 | <p>This should do the trick:</p>
<pre><code>def allbutlast(iterable):
it = iter(iterable)
current = it.next()
for i in it:
yield current
current = i
>>> list(allbutlast([1,2,3]))
[1, 2]
</code></pre>
<p>This will iterate through the entire list, and return the previous item so t... | 10 | 2010-03-11T13:18:01Z | [
"python"
] |
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python? | 2,425,096 | <p>I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.</p>
<p>How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?</p>
<p>I am thinking I should som... | 4 | 2010-03-11T13:11:18Z | 2,425,207 | <pre><code>gen = (x for x in iterable[:-1])
</code></pre>
| -1 | 2010-03-11T13:25:53Z | [
"python"
] |
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python? | 2,425,096 | <p>I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.</p>
<p>How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?</p>
<p>I am thinking I should som... | 4 | 2010-03-11T13:11:18Z | 2,426,175 | <p>the <code>itertools</code> module shows a <code>pairwise()</code> method in its recipes. adapting from this recipe, you can get your generator:</p>
<pre><code>from itertools import *
def n_apart(iterable, n):
a,b = tee(iterable)
for count in range(n):
next(b)
return zip(a,b)
def all_but_n_last... | 1 | 2010-03-11T15:25:36Z | [
"python"
] |
Determine current Mac Chrome web page using Python | 2,425,098 | <p>Is there a way to determine programmatically, using Python, which web page is currently active in Google Chrome?</p>
| 1 | 2010-03-11T13:11:37Z | 2,426,177 | <p>Not yet, it seems. Such tasks are done, with other browsers, via the Applescript interface, but, as <a href="http://code.google.com/p/chromium/issues/detail?id=27468" rel="nofollow">this thread</a> shows, while hotly requested for Chrome on the Mac this feature is not there yet.</p>
<p>(Once a Mac app does get a g... | 0 | 2010-03-11T15:26:01Z | [
"python",
"osx",
"google-chrome"
] |
Determine current Mac Chrome web page using Python | 2,425,098 | <p>Is there a way to determine programmatically, using Python, which web page is currently active in Google Chrome?</p>
| 1 | 2010-03-11T13:11:37Z | 5,216,306 | <p>Google Chrome for Mac has added the AppleScripting method for getting the URL.</p>
<h2>Here's the Chromium AppleScript SDK</h2>
<p><a href="https://sites.google.com/a/chromium.org/dev/developers/design-documents/applescript" rel="nofollow">https://sites.google.com/a/chromium.org/dev/developers/design-documents/app... | 2 | 2011-03-07T05:50:25Z | [
"python",
"osx",
"google-chrome"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 2,425,347 | <p>The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the <a href="http://docs.python.org/library/itertools.html">itertools module</a> and prepend the element:</p>
<pre><code>import itertools
gen = iter([1,2,3])
peek = gen.next()
print list(itertools... | 31 | 2010-03-11T13:46:09Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 2,425,389 | <p>This will work -- it buffers an item and calls a function with each item and the next item in the sequence.</p>
<p>Your requirements are murky on what happens at the end of the sequence. What does "look ahead" mean when you're at the last one?</p>
<pre><code>def process_with_lookahead( iterable, aFunction ):
... | 2 | 2010-03-11T13:53:19Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 10,576,559 | <p>Ok - two years too late - but I came across this question, and did not find any of the answers to my satisfaction. Came up with this meta generator:</p>
<pre><code>class Peekorator(object):
def __init__(self, generator):
self.empty = False
self.peek = None
self.generator = generator
... | 18 | 2012-05-14T01:18:25Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 12,059,766 | <p>Instead of using items (i, i+1), where 'i' is the current item and i+1 is the 'peek ahead' version, you should be using (i-1, i), where 'i-1' is the previous version from the generator.</p>
<p>Tweaking your algorithm this way will produce something that is identical to what you currently have, apart from the extra ... | 2 | 2012-08-21T17:08:39Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 12,059,829 | <p>You can use itertools.tee to produce a lightweight copy of the generator. Then peeking ahead at one copy will not affect the second copy:</p>
<pre><code>import itertools
copy1, copy2 = itertools.tee(original_generator)
if copy1.next() == "STOP":
stop_application()
process_items(copy2)
</code></pre>
<p>The 'cop... | 14 | 2012-08-21T17:13:24Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 14,557,201 | <pre><code>>>> gen = iter(range(10))
>>> peek = next(gen)
>>> peek
0
>>> gen = (value for g in ([peek], gen) for value in g)
>>> list(gen)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 3 | 2013-01-28T07:16:25Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 20,412,546 | <p>Just for fun, I created an implementation of a lookahead class based on the suggestion by
Aaron:</p>
<pre><code>import itertools
class lookahead_chain(object):
def __init__(self, it):
self._it = iter(it)
def __iter__(self):
return self
def next(self):
return next(self._it)
... | 4 | 2013-12-05T22:57:58Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 27,698,681 | <p>For sake of completeness, the <a href="https://pypi.python.org/pypi/more-itertools"><code>more-itertools</code> package</a> (which should probably be part of any Python programmer's toolbox) includes a <code>peekable</code> wrapper that implements this behavior. As the code example in <a href="https://pythonhosted.o... | 28 | 2014-12-30T01:59:05Z | [
"python",
"generator"
] |
How to look ahead one element in a Python generator? | 2,425,270 | <p>I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.</p>
<p>Here is what I mean:</p>
<pre><code>gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
</code></p... | 33 | 2010-03-11T13:34:58Z | 28,353,557 | <p>Although <code>itertools.chain()</code> is the natural tool for the job here, beware of loops like this:</p>
<pre><code>for elem in gen:
...
peek = next(gen)
gen = itertools.chain([peek], gen)
</code></pre>
<p>...Because this will consume a linearly growing amount of memory, and eventually grind to a h... | 0 | 2015-02-05T20:37:58Z | [
"python",
"generator"
] |
How to dynamically access class properties in Python? | 2,425,272 | <p>Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:</p>
<pre><code>class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
</code></pre>
<p>But, what ... | 11 | 2010-03-11T13:35:10Z | 2,425,281 | <pre><code>setattr(my_class_instance, 'attr_name', attr_value)
</code></pre>
| 27 | 2010-03-11T13:36:50Z | [
"python",
"class"
] |
How to dynamically access class properties in Python? | 2,425,272 | <p>Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:</p>
<pre><code>class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
</code></pre>
<p>But, what ... | 11 | 2010-03-11T13:35:10Z | 2,425,588 | <p>Using <code>dir</code> with <code>setattr</code> should do the job</p>
<pre><code>class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
for prop in dir(myclass):
print '%s:%s'%(prop,getattr(myclass,prop))
print
for prop in dir(myclass):
... | 0 | 2010-03-11T14:15:39Z | [
"python",
"class"
] |
How to dynamically access class properties in Python? | 2,425,272 | <p>Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:</p>
<pre><code>class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
</code></pre>
<p>But, what ... | 11 | 2010-03-11T13:35:10Z | 28,928,411 | <p>After reading rejected <a href="https://www.python.org/dev/peps/pep-0363/" rel="nofollow">Syntax For Dynamic Attribute Access</a> I'm using a mixin class providing dictionary-style access to an object's attributes :
</p>
<pre><code>class MyClass:
def __init__(self):
self.name = None
self.text = ... | 0 | 2015-03-08T15:48:32Z | [
"python",
"class"
] |
How do I find the baseline of a line of text in Reportlab? | 2,425,476 | <p>How do I find the baseline for a line of text in Reportlab so I can align other elements on the page with the baseline of the text? I am using <code>canvas.drawString()</code> for these elements.</p>
| 1 | 2010-03-11T14:02:52Z | 15,404,781 | <p>The canvas should be thought of as a sheet of white paper with points on the sheet identified using Cartesian (X,Y) coordinates which by default have the (0,0) origin point at the lower left corner of the page.</p>
<p>Furthermore the first coordinate x goes to the right and the second coordinate y goes up, by defau... | 0 | 2013-03-14T08:53:45Z | [
"python",
"pdf",
"reportlab"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,425,616 | <p>Either catch <code>IndexError</code> when indexing or check the <code>len()</code> of the list beforehand.</p>
| 3 | 2010-03-11T14:18:53Z | [
"python",
"list",
"error-handling"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,425,622 | <p>First read the file, and then ask user in a loop, until the answer is acceptable:</p>
<pre><code>while True:
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
if get_item >=0 and get_item < len(lines):
break
</code></pre>
<p>That will, of course, break when the file is empty... | 3 | 2010-03-11T14:19:38Z | [
"python",
"list",
"error-handling"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,425,670 | <pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
try:
lines[get_item] = ""
except Exception,err:
... | 0 | 2010-03-11T14:26:42Z | [
"python",
"list",
"error-handling"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,425,687 | <p>Judicious changes to your current code:</p>
<pre><code>def deleteitem():
showlist()
with open("todo.txt") as f:
lines = f.readlines()
if len(lines) == 0: # completely empty file
return # handle appropriately
prompt = "Enter number to delete (1-%d), or 0 to abort: " % len(lines)
while True:
... | 1 | 2010-03-11T14:28:49Z | [
"python",
"list",
"error-handling"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,426,174 | <p>Try something like this:</p>
<pre><code>def deleteitem():
showlist()
f = open('todo.txt')
lines = f.readlines()
f.close()
if len(lines) == 0:
print "File is empty!"
return False
print "File has %d items\n" % len(lines)
item = 0
while item < len(lines):
item = raw_input( "\n Enter number of item to d... | 0 | 2010-03-11T15:25:33Z | [
"python",
"list",
"error-handling"
] |
Python: list assignment out of range | 2,425,543 | <p>This module is part of a simple todo app I made with Python... </p>
<pre><code>def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get... | 0 | 2010-03-11T14:11:05Z | 2,426,451 | <p>For what it's worth.... I'll put the code to my todo.py program here... It's just something I run from a Terminal in OS X to keep control of stuff I need to do at work...I am sure it's horribly un-pythonic,inefficient and everything else...but maybe it'll be of use to some one who stumbles across this thread : </p>
... | 0 | 2010-03-11T15:54:36Z | [
"python",
"list",
"error-handling"
] |
How do I select from multiple tables in one query with Django? | 2,425,603 | <p>I have two tables, one "Company" and one "Employee":</p>
<pre><code>class Company(models.Model):
name = models.CharField(max_length=60)
class Employee(models.Model):
name = models.CharField(max_length=60)
company = models.ForeignField(Company)
</code></pre>
<p>And I want to list every Employee in a ta... | 6 | 2010-03-11T14:17:04Z | 2,425,642 | <p>Using <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4"><code>select_related()</code></a> will pre-populate the appropriate attributes:</p>
<pre><code>Employee.objects.select_related()
</code></pre>
| 19 | 2010-03-11T14:21:50Z | [
"python",
"django",
"join",
"django-queryset"
] |
How do I select from multiple tables in one query with Django? | 2,425,603 | <p>I have two tables, one "Company" and one "Employee":</p>
<pre><code>class Company(models.Model):
name = models.CharField(max_length=60)
class Employee(models.Model):
name = models.CharField(max_length=60)
company = models.ForeignField(Company)
</code></pre>
<p>And I want to list every Employee in a ta... | 6 | 2010-03-11T14:17:04Z | 2,425,655 | <p>I guess what you're looking for is the select_related method of your queryset.
See <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4">the doc</a></p>
<blockquote>
<p>select_related()</p>
<p>Returns a QuerySet that will
automatically "follow" foreign-key
relationships, selecting tha... | 6 | 2010-03-11T14:24:31Z | [
"python",
"django",
"join",
"django-queryset"
] |
How to prevent a function from being overridden in python | 2,425,656 | <p>Is there a way to make a class function unoverriddable? something like java's <code>final</code> keyword. i.e, any overriding class cannot override that method.</p>
| 20 | 2010-03-11T14:24:32Z | 2,425,785 | <p>The issue is you are trying to write in Python using Java philosophies. Some thing carry over, but not all of them. In Python you can do the following and it is perfectly fine, but completely goes against how Java thinks of objects.</p>
<pre><code>class Thing(object):
x = 1
something = Thing()
something.y = som... | 24 | 2010-03-11T14:39:01Z | [
"python",
"override",
"final"
] |
How to prevent a function from being overridden in python | 2,425,656 | <p>Is there a way to make a class function unoverriddable? something like java's <code>final</code> keyword. i.e, any overriding class cannot override that method.</p>
| 20 | 2010-03-11T14:24:32Z | 2,425,818 | <p>You could put a comment in there to the effect of:</p>
<pre><code># We'll fire you if you override this method.
</code></pre>
<p>It's surprising how well low-tech solutions like this work in practice.</p>
| 47 | 2010-03-11T14:42:08Z | [
"python",
"override",
"final"
] |
How to prevent a function from being overridden in python | 2,425,656 | <p>Is there a way to make a class function unoverriddable? something like java's <code>final</code> keyword. i.e, any overriding class cannot override that method.</p>
| 20 | 2010-03-11T14:24:32Z | 2,428,648 | <p>Yes there is, don't do it.</p>
<p>I should add to this after the down-vote. Such protection mechanisms are seen by some to go against the ethos of Python, that "we are all consenting adults here".Who do you want to protect such functions from? And if a comment will not suffice why would something 'stronger'?</p>
<... | -1 | 2010-03-11T21:03:34Z | [
"python",
"override",
"final"
] |
django forms MultipleChoiceField reverts to original value on save | 2,425,668 | <p>I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.</p>
<p>my code looks something like this:</p>
<pre><code>class ProgrammeField(forms.MultipleChoiceField):
widget = widgets.S... | 2 | 2010-03-11T14:26:18Z | 2,425,853 | <p>You're always passing back an unbound instance of the form, try this:</p>
<p>view.py</p>
<pre><code>if request.method == 'POST':
form = ProgrammeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
else: ##this is the changge
form = ProgrammeForm(request.user)
return rende... | 2 | 2010-03-11T14:46:30Z | [
"python",
"django",
"django-forms"
] |
Django deployment. Error loading MySQLdb module. Trouble reading/writing from /tmp directory | 2,425,715 | <p>I'm deploying my Django app to another host/server using mod_wsgi and MySQLdb. Right now, I'm getting a 500 error with the following log:</p>
<p>ImproperlyConfigured: Error loading MySQLdb module: /tmp/MySQL_python-1.2.3c1-py2.4-linux-i686.egg-tmp/_mysql.so: failed to map segment from shared object: Operation not p... | 0 | 2010-03-11T14:31:38Z | 2,425,874 | <p>Point the <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonEggs" rel="nofollow"><code>WSGIPythonEggs</code></a> directive to a writable, executable path.</p>
| 1 | 2010-03-11T14:48:23Z | [
"python",
"django",
"apache",
"mysql"
] |
Python: PSP & HTML tables | 2,425,787 | <p>I have a python psp page code is shown below. Currently it only prints out the characters in single rows of 60, with the character count in the left column.</p>
<pre><code><table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04... | 0 | 2010-03-11T14:39:16Z | 2,425,844 | <pre><code>for k in s[i:i+60]:
req.write('<td>%s</td>' % k)
req.write('</tr>')
</code></pre>
| 0 | 2010-03-11T14:45:36Z | [
"python",
"html",
"table",
"python-server-pages"
] |
Timeout for xmlrpclib client requests | 2,425,799 | <p>I am using Python's xmlrpclib to make requests to an xml-rpc service.</p>
<p>Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?</p>
<p>I know I can globally set a socket timeout with <code>socket.setdefaulttimeout()</code>, but that is not preferable.</p>
| 3 | 2010-03-11T14:40:35Z | 2,426,293 | <p>The clean approach is to define and use a custom transport, e.g.:
! this will work only for python2.7 !</p>
<pre><code>import xmlrpclib, httplib
class TimeoutTransport(xmlrpclib.Transport):
timeout = 10.0
def set_timeout(self, timeout):
self.timeout = timeout
def make_connection(self, host):
... | 9 | 2010-03-11T15:37:48Z | [
"python",
"xmlrpclib"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.