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 |
|---|---|---|---|---|---|---|---|---|---|
ManyToOneField in Django | 888,550 | <p>I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users:</p>
<pre><code>class User(models.Model):
name = models.CharField()
class Group(models.Model):
name = models.CharField(... | 5 | 2009-05-20T15:15:54Z | 888,591 | <p>A <code>ManyToOne</code> field, as you've guessed, is called <code>ForeignKey</code> in Django. You will have to define it on your <code>User</code> class for the logic to work properly, but Django will make a reverse property available on the <code>Groups</code> model automatically:</p>
<pre><code>class Group(mode... | 8 | 2009-05-20T15:21:28Z | [
"python",
"django"
] |
ManyToOneField in Django | 888,550 | <p>I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users:</p>
<pre><code>class User(models.Model):
name = models.CharField()
class Group(models.Model):
name = models.CharField(... | 5 | 2009-05-20T15:15:54Z | 888,660 | <p>Assuming that the Users construct is the built-in authentication system... I would recommend creating a Profile model of some sort and attaching the OneToMany field to it instead. You can then <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">hook ... | 1 | 2009-05-20T15:34:12Z | [
"python",
"django"
] |
ManyToOneField in Django | 888,550 | <p>I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users:</p>
<pre><code>class User(models.Model):
name = models.CharField()
class Group(models.Model):
name = models.CharField(... | 5 | 2009-05-20T15:15:54Z | 888,778 | <p>You should probably be looking at simply using built in reverse lookups:</p>
<pre><code>group = Group.objects.get(id=1)
users_in_group = group.user_set.all()
</code></pre>
<p>Reverse lookup sets are automatically created for any foreign keys or many-to-many relationships to the model in question.</p>
<p>If you wa... | 1 | 2009-05-20T15:53:46Z | [
"python",
"django"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 888,885 | <p>Just use <a href="http://cr.yp.to/daemontools.html" rel="nofollow">daemontools</a> or some other similar script instead of rolling your own daemonizing process. It is much better to keep this off your script.</p>
<p>Also, your best option: Don't use BaseHTTPServer. It is really bad. There are many good HTTP servers... | 0 | 2009-05-20T16:15:36Z | [
"python",
"daemon",
"basehttpserver"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 889,115 | <p>You start by instantiating a HTTPServer. But you don't actually tell it to start serving in any of the supplied code. In your child process try calling <code>server.serve_forever()</code>.</p>
<p><a href="http://snippets.dzone.com/posts/show/654" rel="nofollow">See this</a> for reference </p>
| 2 | 2009-05-20T17:06:00Z | [
"python",
"daemon",
"basehttpserver"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 890,300 | <p>After a bit of googling I <a href="http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer" rel="nofollow">finally stumbled over this BaseHTTPServer documentation</a> and after that I ended up with:</p>
<pre><code>from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import Thr... | 7 | 2009-05-20T21:17:13Z | [
"python",
"daemon",
"basehttpserver"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 2,248,502 | <p>Here's how to do this with the <a href="http://pypi.python.org/pypi/python-daemon" rel="nofollow">python-daemon</a> library:</p>
<pre><code>from BaseHTTPServer import (HTTPServer, BaseHTTPRequestHandler)
import contextlib
import daemon
from my_app_config import config
# Make the HTTP Server instance.
server = HT... | 4 | 2010-02-11T23:13:09Z | [
"python",
"daemon",
"basehttpserver"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 2,256,550 | <p>Since this has solicited answers since I originally posted, I thought that I'd share a little info.</p>
<p>The issue with the output has to do with the fact that the default handler for the logging module uses the StreamHandler. The best way to handle this is to create your own handlers. In the case where you wan... | 0 | 2010-02-13T05:07:24Z | [
"python",
"daemon",
"basehttpserver"
] |
Daemonizing python's BaseHTTPServer | 888,834 | <p>I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not.</p>
<p>I ... | 8 | 2009-05-20T16:04:22Z | 8,578,242 | <p>A simple solution that worked for me was to override the <code>BaseHTTPRequestHandler</code> method <code>log_message()</code>, so we prevent any kind of writing in stdout and avoid problems when demonizing.</p>
<pre><code>class CustomRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_message(self,... | 1 | 2011-12-20T15:58:56Z | [
"python",
"daemon",
"basehttpserver"
] |
isDigit() for rational numbers? | 888,925 | <p>I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is... | 4 | 2009-05-20T16:21:22Z | 888,942 | <p>int() or float() throws ValueError if the literal is not valid </p>
| 0 | 2009-05-20T16:25:17Z | [
"python",
"string"
] |
isDigit() for rational numbers? | 888,925 | <p>I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is... | 4 | 2009-05-20T16:21:22Z | 888,948 | <p><code>float()</code> throws a <code>ValueError</code> if the conversion fails. So try to convert your string to a float, and catch the <code>ValueError</code>.</p>
| 0 | 2009-05-20T16:26:19Z | [
"python",
"string"
] |
isDigit() for rational numbers? | 888,925 | <p>I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is... | 4 | 2009-05-20T16:21:22Z | 888,952 | <p>1.25 is a notation commonly used for <a href="http://en.wikipedia.org/wiki/Real%5Fnumber">reals</a>, less so for <a href="http://en.wikipedia.org/wiki/Rational%5Fnumber">rational numbers</a>. Python's <a href="http://docs.python.org/library/functions.html#float">float</a> will raise a <a href="http://docs.python.org... | 5 | 2009-05-20T16:27:07Z | [
"python",
"string"
] |
isDigit() for rational numbers? | 888,925 | <p>I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is... | 4 | 2009-05-20T16:21:22Z | 888,954 | <p><code>try</code>/<code>catch</code> is very cheap in Python, and attempting to construct a <code>float</code> from a string that's not a number raises an exception:</p>
<pre><code>>>> float('1.45')
1.45
>>> float('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <modu... | 1 | 2009-05-20T16:27:23Z | [
"python",
"string"
] |
isDigit() for rational numbers? | 888,925 | <p>I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is... | 4 | 2009-05-20T16:21:22Z | 7,643,695 | <p>The existing answers are correct in that the more Pythonic way is usually to <code>try...except</code> (i.e. EAFP).</p>
<p>However, if you really want to do the validation, you could remove exactly 1 decimal point before using <code>isdigit()</code>.</p>
<pre><code>>>> "124".replace(".", "", 1).isdigit()
... | 1 | 2011-10-04T05:37:38Z | [
"python",
"string"
] |
Substituting a regex only when it doesn't match another regex (Python) | 889,045 | <p>Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced,... | 3 | 2009-05-20T16:45:00Z | 889,083 | <p>You could replace all the {} instances with your replacement string (which would include the {{}} ones), and then replace the {{}} ones with a back-reference to itself (overwriting the first replace with the original data) -- then only the {} instances would have changed.</p>
| 1 | 2009-05-20T16:54:52Z | [
"python",
"regex"
] |
Substituting a regex only when it doesn't match another regex (Python) | 889,045 | <p>Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced,... | 3 | 2009-05-20T16:45:00Z | 889,103 | <p>You can give replace a function (<a href="http://docs.python.org/howto/regex.html#search-and-replace" rel="nofollow">reference</a>)</p>
<p>But make sure the first regex contain the second one. This is just an example:</p>
<pre><code>regex1 = re.compile('\{.*\}')
regex2 = re.compile('\{\{.*\}\}')
def replace(match... | 3 | 2009-05-20T17:00:49Z | [
"python",
"regex"
] |
Substituting a regex only when it doesn't match another regex (Python) | 889,045 | <p>Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced,... | 3 | 2009-05-20T16:45:00Z | 889,215 | <p>It strikes me as sub-optimal to match against two different regexes when what you're looking for is really one pattern. To illustrate:</p>
<pre><code>import re
foo = "{{this}}"
bar = "{that}"
re.match("\{[^\{].*[^\}]\}", foo) # gives you nothing
re.match("\{[^\{].*[^\}]\}", bar) # gives you a match object
</code>... | 0 | 2009-05-20T17:29:03Z | [
"python",
"regex"
] |
Substituting a regex only when it doesn't match another regex (Python) | 889,045 | <p>Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced,... | 3 | 2009-05-20T16:45:00Z | 890,750 | <p>Using negative look-ahead/behind assertion</p>
<pre><code>pattern = re.compile( "(?<!\{)\{(?!\{).*?(?<!\})\}(?!\})" )
pattern.sub( "hello", input_string )
</code></pre>
<p>Negative look-ahead/behind assertion allows you to compare against more of the string, but is not considered as using up part of the stri... | 5 | 2009-05-20T23:34:57Z | [
"python",
"regex"
] |
Function Decorators | 889,088 | <p>I like being able to measure performance of the python functions I code, so very often I do something similar to this...</p>
<pre><code>import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
#... | 5 | 2009-05-20T16:57:13Z | 889,145 | <p>Though <a href="http://docs.python.org/3.0/library/inspect.html">inspect</a> may get you a bit on the way, what you want is in general <em>not</em> possible:</p>
<pre><code>def f(*args):
pass
</code></pre>
<p>Now how many arguments does <code>f</code> take? Since <code>*args</code> and <code>**kwargs</code> al... | 8 | 2009-05-20T17:12:34Z | [
"python",
"decorator",
"argument-passing"
] |
Function Decorators | 889,088 | <p>I like being able to measure performance of the python functions I code, so very often I do something similar to this...</p>
<pre><code>import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
#... | 5 | 2009-05-20T16:57:13Z | 889,235 | <p>+1 on Stephan202's answer, however (putting this in a separate answer since comments don't format code well!), the following bit of code in that answer:</p>
<pre><code>verbose = False
if 'verbose' in kwargs:
verbose = True
del kwargs['verbose']
</code></pre>
<p>can be expressed much more clearly and conc... | 7 | 2009-05-20T17:34:31Z | [
"python",
"decorator",
"argument-passing"
] |
Function Decorators | 889,088 | <p>I like being able to measure performance of the python functions I code, so very often I do something similar to this...</p>
<pre><code>import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
#... | 5 | 2009-05-20T16:57:13Z | 889,236 | <p>it might be difficult but you can do something on these lines. Code below tries to remove any extra arguments and prints them out.</p>
<pre><code>def mydeco(func):
def wrap(*args, **kwargs):
"""
we want to eat any extra argument, so just count args and kwargs
and if more(>func.func_co... | 0 | 2009-05-20T17:34:34Z | [
"python",
"decorator",
"argument-passing"
] |
Python regular expression to match # followed by 0-7 followed by ## | 889,143 | <p>I would like to intercept string starting with <code>\*#\*</code></p>
<p>followed by a number between 0 and 7</p>
<p>and ending with: <code>##</code></p>
<p>so something like <code>\*#\*0##</code></p>
<p>but I could not find a regex for this</p>
| 2 | 2009-05-20T17:12:09Z | 889,154 | <p><code>r'\#[0-7]\#\#'</code></p>
| 1 | 2009-05-20T17:15:23Z | [
"python",
"regex"
] |
Python regular expression to match # followed by 0-7 followed by ## | 889,143 | <p>I would like to intercept string starting with <code>\*#\*</code></p>
<p>followed by a number between 0 and 7</p>
<p>and ending with: <code>##</code></p>
<p>so something like <code>\*#\*0##</code></p>
<p>but I could not find a regex for this</p>
| 2 | 2009-05-20T17:12:09Z | 889,170 | <p>The regular expression should be like ^#[0-7]##$</p>
| 1 | 2009-05-20T17:18:06Z | [
"python",
"regex"
] |
Python regular expression to match # followed by 0-7 followed by ## | 889,143 | <p>I would like to intercept string starting with <code>\*#\*</code></p>
<p>followed by a number between 0 and 7</p>
<p>and ending with: <code>##</code></p>
<p>so something like <code>\*#\*0##</code></p>
<p>but I could not find a regex for this</p>
| 2 | 2009-05-20T17:12:09Z | 889,188 | <p>Assuming you want to allow <strong>only</strong> one # before and two after, I'd do it like this:</p>
<pre><code>r'^(\#{1}([0-7])\#{2})'
</code></pre>
<p>It's important to note that <a href="http://stackoverflow.com/questions/889143/python-regular-expression/889154#889154">Alex's</a> regex will also match things l... | 7 | 2009-05-20T17:22:34Z | [
"python",
"regex"
] |
Python regular expression to match # followed by 0-7 followed by ## | 889,143 | <p>I would like to intercept string starting with <code>\*#\*</code></p>
<p>followed by a number between 0 and 7</p>
<p>and ending with: <code>##</code></p>
<p>so something like <code>\*#\*0##</code></p>
<p>but I could not find a regex for this</p>
| 2 | 2009-05-20T17:12:09Z | 889,308 | <p>None of the above examples are taking into account the *#*</p>
<pre><code>^\*#\*[0-7]##$
</code></pre>
<p>Pass : *#*7##</p>
<p>Fail : *#*22324324##</p>
<p>Fail : *#3232#</p>
<p>The ^ character will match the start of the string, \* will match a single asterisk, the # characters do not need to be escape in this ... | 4 | 2009-05-20T17:50:09Z | [
"python",
"regex"
] |
Python regular expression to match # followed by 0-7 followed by ## | 889,143 | <p>I would like to intercept string starting with <code>\*#\*</code></p>
<p>followed by a number between 0 and 7</p>
<p>and ending with: <code>##</code></p>
<p>so something like <code>\*#\*0##</code></p>
<p>but I could not find a regex for this</p>
| 2 | 2009-05-20T17:12:09Z | 892,251 | <p>As I understand the question, the simplest regular expression you need is:</p>
<pre><code>rex= re.compile(r'^\*#\*([0-7])##$')
</code></pre>
<p>The <code>{1}</code> constructs are redundant.
After doing <code>rex.match</code> (or <code>rex.search</code>, but it's not necessary here), <code>.group(1)</code> of the ... | 1 | 2009-05-21T10:24:42Z | [
"python",
"regex"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,343 | <p>Would checking the file extensions be acceptable or are you trying to confirm the data itself represents an image file?</p>
<p>If you can check the file extension a regular expression or a simple comparison could satisfy the requirement.</p>
| 1 | 2009-05-20T17:57:22Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,349 | <p>A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above. </p>
| 8 | 2009-05-20T17:58:26Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,372 | <p>Well, I do not know about the insides of psd, but I, sure, know that, as a matter of fact, svg is not an image file per se, -- it is based on xml, so it is, essentially, a plain text file.</p>
| 2 | 2009-05-20T18:03:41Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,379 | <p>On Linux, you could use python-magic (<a href="http://pypi.python.org/pypi/python-magic/0.1" rel="nofollow">http://pypi.python.org/pypi/python-magic/0.1</a>) which uses libmagic to identify file formats.</p>
<p>AFAIK, libmagic looks into the file and tries to tell you more about it than just the format, like bitmap... | 2 | 2009-05-20T18:05:40Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,639 | <p>In addition to what Brian is suggesting you could use PIL's <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.verify">verify</a> method to check if the file is broken.</p>
<blockquote>
<p>im.verify()</p>
<p>Attempts to determine if the file is
broken, without actually decoding the
image da... | 20 | 2009-05-20T19:02:45Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 889,778 | <p>You could use the Python bindings to libmagic, <a href="http://pypi.python.org/pypi/python-magic/" rel="nofollow">python-magic</a> and then check the mime types. This won't tell you if the files are corrupted or intact but it should be able to determine what type of image it is.</p>
| 3 | 2009-05-20T19:29:00Z | [
"python",
"image"
] |
How to check if a file is a valid image file? | 889,333 | <p>I am currently using PIL.</p>
<pre><code>import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
</code></pre>
<p>However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowErr... | 40 | 2009-05-20T17:55:16Z | 902,779 | <p>I have just found the builtin <a href="http://docs.python.org/library/imghdr.html">imghdr</a> module. From python documentation:</p>
<blockquote>
<p>The imghdr module determines the type
of image contained in a file or byte
stream.</p>
</blockquote>
<p>This is how it works:</p>
<pre><code>>>> impor... | 88 | 2009-05-24T00:29:03Z | [
"python",
"image"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,472 | <p>Yes, but.</p>
<p>Please, please, please. Never say <code>if some expression == True</code>. It's redundant and causes many people to wonder what you're thinking.</p>
<p>More importantly. </p>
<p><code>i/3</code> is the quotient.</p>
<p><code>i%3</code> is the remainder. If i is a multiple of 3, <code>i%3 == 0... | 7 | 2009-05-20T18:24:57Z | [
"python"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,490 | <p>Hmm seems you want a weird thing - you divide i by 3 and check if it is equal to 1.
As 4 == True => False.</p>
| 0 | 2009-05-20T18:26:47Z | [
"python"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,563 | <p>Short answer: no. You cannot make assignments in if statements in python.</p>
<p>But really, I don't understand what you are trying to do here. Your sample code will only print out the numbers 3, 4, and 5 because every other value of i divided by 3 evaluates to something other than 1 (and therefore false).</p>
<p... | 0 | 2009-05-20T18:45:11Z | [
"python"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,566 | <p>At the command prompt:</p>
<pre><code>>>> [i for i in range(20) if i%3 == 0]
>>> [0, 3, 6, 9, 12, 15, 18]
</code></pre>
<p>OR</p>
<pre><code>>>> a = [i for i in range(20) if i%3 == 0]
>>> print a
[0, 3, 6, 9, 12, 15, 18]
>>>
</code></pre>
| 2 | 2009-05-20T18:46:49Z | [
"python"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,612 | <p>While working on Project Euler myself, I found "<code>if not x % y</code>" to be the cleanest way to represent "if x is a multiple of y". This is equivalent to "<code>if x % y == 0</code>", seen in other answers. I don't believe there is a significant difference between the two; which you use is simply a matter of... | 0 | 2009-05-20T18:55:35Z | [
"python"
] |
Dividing in an if statement | 889,446 | <p>In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.</p>
<pre><code>a = range(20)
for i in a:
if i / 3 == True:
print i
</code></pre>
| 0 | 2009-05-20T18:20:36Z | 889,733 | <p>Everyone here has done a good job explaining how to do it right. I just want to explain what you are doing wrong.</p>
<pre><code>if i / 3 == True
</code></pre>
<p>Is equivalent to:</p>
<pre><code>if i / 3 == 1
</code></pre>
<p>Because True == 1. So you are basicly checking if i when divided by 3 equals 1. Your c... | 2 | 2009-05-20T19:19:31Z | [
"python"
] |
How can I read()/write() against a python HTTPConnection? | 889,528 | <p>I've got python code of the form: </p>
<pre><code>(o,i) = os.popen2 ("/usr/bin/ssh host executable")
ios = IOSource(i,o)
</code></pre>
<p>Library code then uses this IOSource, doing writes() and read()s against inputstream i and outputstream o.</p>
<p>Yes, there is IPC going on here.. Think RPC.</p>
<p>I wan... | 2 | 2009-05-20T18:37:23Z | 889,550 | <p>for output:</p>
<pre><code>output = response.read()
</code></pre>
<p><a href="http://docs.python.org/library/httplib.html#httpresponse-objects" rel="nofollow">http://docs.python.org/library/httplib.html#httpresponse-objects</a></p>
<p>for input:
pass your data in the POST body of your request</p>
| 1 | 2009-05-20T18:42:41Z | [
"python",
"http",
"rpc"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 889,916 | <p>Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (<code>profile</code> or <code>cProfile</code>, depending on your needs): <a href="http://docs.python.org/library/profile.html">http://docs.python.org/library/profile.html</a></p>
| 29 | 2009-05-20T19:55:39Z | [
"python",
"testing",
"time",
"profiling"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 889,919 | <p>Use the <a href="http://docs.python.org/library/timeit.html"><code>timeit</code> module</a> from the Python standard library.</p>
<p>Basic usage:</p>
<pre><code>from timeit import Timer
# first argument is the code to be run, the second "setup" argument is only run once,
# and it not included in the execution tim... | 58 | 2009-05-20T19:55:45Z | [
"python",
"testing",
"time",
"profiling"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 890,030 | <p>This code is very inaccurate</p>
<pre><code>total= 0
for i in range(1000):
start= time.clock()
function()
end= time.clock()
total += end-start
time= total/1000
</code></pre>
<p>This code is less inaccurate</p>
<pre><code>start= time.clock()
for i in range(1000):
function()
end= time.clock()
ti... | 19 | 2009-05-20T20:21:00Z | [
"python",
"testing",
"time",
"profiling"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 18,527,364 | <p>If you want to time a python method even if block you measure may throw, one good approach is to use <code>with</code> statement. Define some <code>Timer</code> class as</p>
<pre><code>import time
class Timer:
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self... | 9 | 2013-08-30T07:33:17Z | [
"python",
"testing",
"time",
"profiling"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 18,528,044 | <p>You can create a "timeme" decorator like so</p>
<pre class="lang-py prettyprint-override"><code>import time
def timeme(method):
def wrapper(*args, **kw):
startTime = int(round(time.time() * 1000))
result = method(*args, **kw)
endTime = int... | 16 | 2013-08-30T08:12:23Z | [
"python",
"testing",
"time",
"profiling"
] |
Accurate timing of functions in python | 889,900 | <p>I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.</p>
<pre><code>def time_it(f, *args):
start = time.clock()
f(*args)
return (t... | 46 | 2009-05-20T19:52:35Z | 21,860,100 | <p>This is neater</p>
<pre><code>from contextlib import contextmanager
import time
@contextmanager
def timeblock(label):
start = time.clock()
try:
yield
finally:
end = time.clock()
print ('{} : {}'.format(label, end - start))
with timeblock("just a test"):
print "yip... | 4 | 2014-02-18T16:45:21Z | [
"python",
"testing",
"time",
"profiling"
] |
Is it possible to format a date with sqlite3? | 889,974 | <p>At start you have a string 'DDMMYYYY HHMMSS' and I want at the end to insert the string in a date field in sqlite3 database. The program is made in python. How can I do that ?</p>
| 0 | 2009-05-20T20:08:58Z | 890,025 | <p>Even though the ".schema" indicates that the field is a date or timestamp field... the field is actually a string. You can format the string anyway you want. If memory serves... their is no validation at all.</p>
| 1 | 2009-05-20T20:20:00Z | [
"python",
"sqlite",
"date"
] |
Is it possible to format a date with sqlite3? | 889,974 | <p>At start you have a string 'DDMMYYYY HHMMSS' and I want at the end to insert the string in a date field in sqlite3 database. The program is made in python. How can I do that ?</p>
| 0 | 2009-05-20T20:08:58Z | 890,032 | <p>I believe sqlite3 doesn't have a DATE type, therefore you have to do it manually in your python code. Either you store the date in exactly this form or you convert it into a timestamp or some other form.</p>
<p>Have a look at the <a href="http://docs.python.org/library/datetime.html" rel="nofollow">datetime module<... | 1 | 2009-05-20T20:21:04Z | [
"python",
"sqlite",
"date"
] |
Is it possible to format a date with sqlite3? | 889,974 | <p>At start you have a string 'DDMMYYYY HHMMSS' and I want at the end to insert the string in a date field in sqlite3 database. The program is made in python. How can I do that ?</p>
| 0 | 2009-05-20T20:08:58Z | 4,821,602 | <p>As indicated by the other answers, it is stored as a string. However, it <strong>will</strong> be recognized as a date if you insert it in one of the following formats</p>
<p>Time Strings</p>
<p>A time string can be in any of the following formats:</p>
<pre><code> 1. YYYY-MM-DD
2. YYYY-MM-DD HH:MM
3. YYYY-MM-D... | 1 | 2011-01-27T20:40:13Z | [
"python",
"sqlite",
"date"
] |
How do I generate circular thumbnails with PIL? | 890,051 | <p>How do I generate circular image thumbnails using PIL?
The space outside the circle should be transparent. </p>
<p>Snippets would be highly appreciated, thank you in advance.</p>
| 23 | 2009-05-20T20:26:27Z | 890,114 | <p>The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And put that shape as an alpha layer </p>
<pre><code>from PIL import Image, ImageOps
mask = Image.open('mask.png').convert('L')
im = Image.open('image.png')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
... | 52 | 2009-05-20T20:37:16Z | [
"python",
"thumbnails",
"python-imaging-library",
"circle"
] |
How do I generate circular thumbnails with PIL? | 890,051 | <p>How do I generate circular image thumbnails using PIL?
The space outside the circle should be transparent. </p>
<p>Snippets would be highly appreciated, thank you in advance.</p>
| 23 | 2009-05-20T20:26:27Z | 22,336,005 | <p>I would like to add to the already accepted answer a solution to antialias the resulting circle, the trick is to produce a bigger mask and then scale it down using an ANTIALIAS filter:
here is the code</p>
<pre><code>from PIL import Image, ImageOps, ImageDraw
im = Image.open('image.jpg')
bigsize = (im.size[0] * 3,... | 11 | 2014-03-11T20:31:44Z | [
"python",
"thumbnails",
"python-imaging-library",
"circle"
] |
How do I detect when my window is minimized with wxPython? | 890,170 | <p>I am writing a small wxPython utility.</p>
<p>I would like to use some event to detect when a user minimizes the application/window.</p>
<p>I have looked around but did not find an event like wx.EVT_MINIMIZE that I could bind to.</p>
<p>Anyone know of a way that can be used to detect this?</p>
| 5 | 2009-05-20T20:49:43Z | 890,223 | <p>Add a handler for the <a href="http://www.wxpython.org/docs/api/wx.IconizeEvent-class.html" rel="nofollow">wx.EVT_ICONIZE</a> event.</p>
| 2 | 2009-05-20T20:58:11Z | [
"python",
"wxpython",
"minimize"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,237 | <p>Well, you can find a solution to a percentage precision in polynomial time, but to actually find the optimal (absolute minimal difference) solution, the problem is NP-complete. This means that there is no polynomial time solution to the problem. As a result, even with a relatively small list of numbers, it is too co... | 2 | 2009-05-20T21:02:32Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,242 | <pre><code>class Team(object):
def __init__(self):
self.members = []
self.total = 0
def add(self, m):
self.members.append(m)
self.total += m
def __cmp__(self, other):
return cmp(self.total, other.total)
def make_teams(ns):
ns.sort(reverse = True)
t1, t2 = Team(), Team()
... | 0 | 2009-05-20T21:03:19Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,243 | <p><a href="http://en.wikipedia.org/wiki/Dynamic%5Fprogramming">Dynamic programming</a> is the solution you're looking for.</p>
<p>Example with {3,4,10,3,2,5}</p>
<pre>
X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up)
Y-Axis: Count elements in group. max = count numbers / 2 ... | 29 | 2009-05-20T21:03:29Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,260 | <p>For performance you save computations by replacing append() and sum() with running totals.</p>
| 0 | 2009-05-20T21:07:49Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,307 | <p>You could tighten your loop up a little by using the following:</p>
<pre><code>def make_teams(que):
que.sort()
t1, t2 = []
while que:
t1.append(que.pop())
if sum(t1) > sum(t2):
t2, t1 = t1, t2
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2))
</code></pre>
| 0 | 2009-05-20T21:18:31Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,338 | <p>Note that it is also an heuristic and I moved the sort out of the function.</p>
<pre><code> def g(data):
sums = [0, 0]
for pair in zip(data[::2], data[1::2]):
item1, item2 = sorted(pair)
sums = sorted([sums[0] + item2, sums[1] + item1])
print sums
data = sorted([2,3,10,5,8,9,7,3,5,2])
g(data)
</... | 1 | 2009-05-20T21:24:42Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,362 | <p>A test case where your method doesn't work is </p>
<pre><code>que = [1, 1, 50, 50, 50, 1000]
</code></pre>
<p>The problem is that you're analyzing things in pairs, and in this example, you want all the 50's to be in the same group. This should be solved though if you remove the pair analysis aspect and just do on... | 1 | 2009-05-20T21:30:07Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,372 | <p>Since the lists must me equal the problem isn't NP at all.</p>
<p>I split the sorted list with the pattern t1<-que(1st, last), t2<-que(2nd, last-1) ...</p>
<pre><code>def make_teams2(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1 = []
t2 = []
while que:
if len(que) > 2:
... | 0 | 2009-05-20T21:33:06Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,472 | <p>It's actually PARTITION, a special case of KNAPSACK. </p>
<p>It is NP Complete, with pseudo-polynomial dp algorithms. The pseudo in pseudo-polynomial refers to the fact that the run time depends on the range of the weights.</p>
<p>In general you will have to first decide if there is an exact solution before you c... | 1 | 2009-05-20T21:58:40Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,481 | <p>After some thinking, for not too big problem, I think that the best kind of heuristics will be something like:</p>
<pre><code>import random
def f(data, nb_iter=20):
diff = None
sums = (None, None)
for _ in xrange(nb_iter):
random.shuffle(data)
mid = len(data)/2
sum1 = sum(data[:mid])
sum2 = su... | 0 | 2009-05-20T22:01:34Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 890,500 | <p><strong>New Solution</strong></p>
<p>This is a breadth-first search with heuristics culling. The tree is limited to a depth of players/2. The player sum limit is totalscores/2. With a player pool of 100, it took approximately 10 seconds to solve.</p>
<pre><code>def team(t):
iterations = range(2, len(t)/2+1)
... | 5 | 2009-05-20T22:07:21Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 902,814 | <p>Q. Given a <strong>multiset S of integers</strong>, is there a way to partition S into <strong>two subsets</strong> S1 and S2 such that <strong>the sum</strong> of the numbers in S1 equals the sum of the numbers in S2? </p>
<p>A.<a href="http://en.wikipedia.org/wiki/Partition%5Fproblem" rel="nofollow">Set Partition... | 2 | 2009-05-24T00:59:36Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 1,732,720 | <p>In an earlier comment I hypothesized that the problem as set was tractable because they had carefully chosen the test data to be compatible with various algorithms within the time alloted. This turned out not to be the case - instead it is the problem constraints - numbers no higher than 450 and a final set no larg... | 0 | 2009-11-14T00:17:37Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Algorithm to Divide a list of numbers into 2 equal sum lists | 890,171 | <p>There is a list of numbers.</p>
<p>The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.</p>
<pre><code>#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
</code></pre>
<p>Is there an error in the following code algorit... | 23 | 2009-05-20T20:49:50Z | 1,738,637 | <p>They are obviously looking for a dynamic programming knapsack solution. So after my first effort (a pretty good original heuristic I thought), and my second effort (a really sneaky exact combinatorial solution that worked for shortish data sets, and even for sets up to 100 elements as long as the number of <em>uniq... | 1 | 2009-11-15T20:03:26Z | [
"python",
"algorithm",
"dynamic-programming",
"np-complete",
"knapsack-problem"
] |
Explain to me what the big deal with tail call optimization is and why Python needs it | 890,461 | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as Guido. I understa... | 20 | 2009-05-20T21:55:07Z | 890,488 | <p><a href="http://en.wikipedia.org/wiki/Tail%5Fcall%5Foptimization" rel="nofollow">Tail call optimization</a> makes it easier to write recursive functions without worrying about a stack overflow:</p>
<pre><code>def fac(n, result=1):
if n > 1:
return fac(n - 1, n * result)
return res... | 4 | 2009-05-20T22:02:50Z | [
"python",
"tail-recursion",
"tail-call-optimization"
] |
Explain to me what the big deal with tail call optimization is and why Python needs it | 890,461 | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as Guido. I understa... | 20 | 2009-05-20T21:55:07Z | 890,548 | <p>Personally, i put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). On minimalistic languages you get huge expressive power without sacrificing performance.</p>
<p>On a 'practical' language (like Python), OTOH, you usu... | 13 | 2009-05-20T22:19:21Z | [
"python",
"tail-recursion",
"tail-call-optimization"
] |
Explain to me what the big deal with tail call optimization is and why Python needs it | 890,461 | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as Guido. I understa... | 20 | 2009-05-20T21:55:07Z | 891,414 | <p>If you intensely want to use recursion for things that might alternatively be expressed as loops, then "tail call optimization" is really a must. However, Guido, Python's Benevolent Dictator For Life (BDFL), strongly believes in loops being expressed as loops -- so he's not going to special-case tail calls (sacrific... | 5 | 2009-05-21T04:46:01Z | [
"python",
"tail-recursion",
"tail-call-optimization"
] |
Explain to me what the big deal with tail call optimization is and why Python needs it | 890,461 | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as Guido. I understa... | 20 | 2009-05-20T21:55:07Z | 13,468,740 | <p>Guido recognized in a follow up <a href="http://neopythonic.blogspot.com.es/2009/04/final-words-on-tail-calls.html" rel="nofollow">post</a> that TCO allowed a cleaner the implementation of state machine as a collection of functions recursively calling each other. However in the same post he proposes an alternative e... | 0 | 2012-11-20T07:52:20Z | [
"python",
"tail-recursion",
"tail-call-optimization"
] |
Explain to me what the big deal with tail call optimization is and why Python needs it | 890,461 | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as Guido. I understa... | 20 | 2009-05-20T21:55:07Z | 33,579,945 | <p>I have been thinking to your question for years (believe it or not...). I was so deeply invested in this question that I finally wrote a whole article (which is also a presentation of one of my modules I wrote some months ago without taking the time to write a precise explanation of how to do it). If you are still i... | 1 | 2015-11-07T06:39:25Z | [
"python",
"tail-recursion",
"tail-call-optimization"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 890,502 | <p>Why not use <a href="http://docs.python.org/library/pickle.html">python pickle</a>?
Python has a great serializing module called pickle it is very easy to use.</p>
<pre><code>import cPickle
cPickle.dump(obj, open('save.p', 'wb'))
obj = cPickle.load(open('save.p', 'rb'))
</code></pre>
<p>There are two disadvantage... | 51 | 2009-05-20T22:07:34Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 890,551 | <p>I would use <a href="http://en.wikipedia.org/wiki/Zope%5FObject%5FDatabase" rel="nofollow">ZODB</a> if you need a dict too large to fit into memory to be persistent. </p>
| 0 | 2009-05-20T22:20:07Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 890,568 | <p>Write it out in a serialized format, such as pickle (a python standard library module for serialization) or perhaps by using JSON (which is a representation that can be evaled to produce the memory representation again).</p>
| 0 | 2009-05-20T22:27:09Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 890,654 | <p>I would suggest that you use <a href="http://www.yaml.org/" rel="nofollow">YAML</a> for your file format so you can tinker with it on the disc</p>
<pre><code>How does it look:
- It is indent based
- It can represent dictionaries and lists
- It is easy for humans to understand
An example: This block of code is... | 3 | 2009-05-20T22:57:08Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 890,694 | <p>I'd use <a href="http://docs.python.org/library/shelve.html"><code>shelve</code></a>, <code>json</code>, <code>yaml</code>, or whatever, as suggested by other answers. </p>
<p><code>shelve</code> is specially cool because you can have the <code>dict</code> on disk and still use it. Values will be loaded on-demand.<... | 11 | 2009-05-20T23:12:21Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 1,512,265 | <p>This solution at SourceForge uses only standard Python modules:</p>
<p>y_serial.py module :: warehouse Python objects with SQLite</p>
<p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Mo... | 0 | 2009-10-02T23:20:55Z | [
"python",
"pickle"
] |
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later? | 890,485 | <p>More specific dupe of <a href="http://stackoverflow.com/questions/875228/simple-data-storing-in-python">875228âSimple data storing in Python</a>.</p>
<p>I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing ... | 24 | 2009-05-20T22:02:21Z | 13,234,949 | <p>Here are a few alternatives depending on your requirements:</p>
<ul>
<li><p><code>numpy</code> stores your plain data in a compact form and performs group/mass operations well</p></li>
<li><p><code>shelve</code> is like a large dict backed up by a file</p></li>
<li><p>some 3rd party storage module, e.g. <code>stash... | 0 | 2012-11-05T15:15:06Z | [
"python",
"pickle"
] |
Looking for the "Hello World" of ctypes unicode processing (including both Python and C code) | 890,793 | <p>Can someone show me a really simple Python ctypes example involving Unicode strings <strong>including the C code?</strong></p>
<p>Say, a way to take a Python Unicode string and pass it to a C function which catenates it with itself and returns that to Python, which prints it.</p>
| 2 | 2009-05-20T23:50:24Z | 890,863 | <p>Untested, but I think this should work.</p>
<pre><code>s = "inputstring"
mydll.my_c_fcn.restype = c_char_p
result = mydll.my_c_fcn(s)
print result
</code></pre>
<p>As for memory management, my understanding is that your c code needs to manage the memory it creates. That is, it should not free the input string, bu... | 0 | 2009-05-21T00:13:26Z | [
"python",
"c",
"ctypes"
] |
Looking for the "Hello World" of ctypes unicode processing (including both Python and C code) | 890,793 | <p>Can someone show me a really simple Python ctypes example involving Unicode strings <strong>including the C code?</strong></p>
<p>Say, a way to take a Python Unicode string and pass it to a C function which catenates it with itself and returns that to Python, which prints it.</p>
| 2 | 2009-05-20T23:50:24Z | 891,056 | <pre><code>from ctypes import *
buffer = create_string_buffer(128)
cdll.msvcrt.strcat(buffer, "blah")
print buffer.value
</code></pre>
<blockquote>
<p>Note: I understand that the Python code is easy, but what I'm struggling with is the C code. Does it need to free its input string? Will its output string get freed ... | 0 | 2009-05-21T01:43:45Z | [
"python",
"c",
"ctypes"
] |
Looking for the "Hello World" of ctypes unicode processing (including both Python and C code) | 890,793 | <p>Can someone show me a really simple Python ctypes example involving Unicode strings <strong>including the C code?</strong></p>
<p>Say, a way to take a Python Unicode string and pass it to a C function which catenates it with itself and returns that to Python, which prints it.</p>
| 2 | 2009-05-20T23:50:24Z | 1,375,059 | <p>This program uses <code>ctypes</code> to call <a href="http://www.gnu.org/s/libc/manual/html%5Fnode/Copying-and-Concatenation.html#index-wcsncat-511"><code>wcsncat</code></a> from Python. It concatenates <code>a</code> and <code>b</code> into a buffer that is not quite long enough for <code>a + b + (null terminator)... | 6 | 2009-09-03T18:17:44Z | [
"python",
"c",
"ctypes"
] |
Install older versions of Python for testing on Mac OS X | 890,827 | <p>I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?</p>
| 2 | 2009-05-21T00:00:20Z | 890,955 | <p>You have two main options, install the python 2.3 from <a href="http://www.macports.org/" rel="nofollow">macports</a> (easy) or install from source.</p>
<p>For macports, run <code>port install python23</code></p>
<p>For the 2nd, you'll have to go to <a href="http://www.python.org/download/releases/2.3.7/" rel="nof... | 6 | 2009-05-21T00:51:55Z | [
"python",
"version",
"install"
] |
Install older versions of Python for testing on Mac OS X | 890,827 | <p>I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?</p>
| 2 | 2009-05-21T00:00:20Z | 891,486 | <p><a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">This page</a> has useful information on building python from source. It's talking about 3.0, but the advice will <em>probably</em> apply to 2.3 as well.</p>
| 0 | 2009-05-21T05:21:05Z | [
"python",
"version",
"install"
] |
Install older versions of Python for testing on Mac OS X | 890,827 | <p>I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?</p>
| 2 | 2009-05-21T00:00:20Z | 891,966 | <p>You can also use the Fink package manager and simply to "fink install python2.3".</p>
<p>If you need Python 2.3 to be your default, you can simply change /sw/bin/python and /sw/bin/pydoc to point to the version you want (they sit in /sw/bin/).</p>
| 0 | 2009-05-21T08:55:29Z | [
"python",
"version",
"install"
] |
Install older versions of Python for testing on Mac OS X | 890,827 | <p>I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?</p>
| 2 | 2009-05-21T00:00:20Z | 892,087 | <p>One alternative is to use a virtual machine. </p>
<p>With something like VMWare Fusion or Virtualbox you could install a complete Linux system with Python2.3, and do your testing there. The advantage is that it would be completely sand-boxed, so wouldn't affect your main system at all.</p>
| 0 | 2009-05-21T09:30:18Z | [
"python",
"version",
"install"
] |
Google App Engine Python Code: User Service | 890,857 | <p>What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)?</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
... | 2 | 2009-05-21T00:12:12Z | 890,879 | <p><code>self</code> refers to the <code>webapp.RequestHandler</code> class. Here is its documentation: <a href="http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html" rel="nofollow">http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html</a>, which tells you what... | 5 | 2009-05-21T00:21:51Z | [
"python",
"google-app-engine"
] |
Google App Engine Python Code: User Service | 890,857 | <p>What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)?</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
... | 2 | 2009-05-21T00:12:12Z | 890,941 | <p>self is a python convention which means 'this' in other languages like Java, C#, C++, etc...I've found it bizarre that you need to explicitly reference yourself when talking about objects (I have a Java background), but you sort of get used to it.</p>
<p>If you're going to use python, I suggest you get an editor th... | 3 | 2009-05-21T00:44:05Z | [
"python",
"google-app-engine"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 891,807 | <p><a href="http://ipython.scipy.org/" rel="nofollow">ipython console</a> does a <a href="http://ipython.scipy.org/doc/manual/html/api/generated/IPython.deep%5Freload.html" rel="nofollow">deep reload</a> with each <code>reload()</code> expression; and of course adds a lot of other useful stuff.</p>
| 3 | 2009-05-21T07:48:41Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 903,943 | <p>Well, I think I have to answer to this. The problem is that Django caches its models in a singleton (singleton like structure) called AppCache. Basically, to reload Django models you need to first reload and re-import all the model modules stored in the AppCache. Then you need to wipe out the AppCache. Here's the co... | 38 | 2009-05-24T14:59:27Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 1,579,190 | <p>Assuming your project is set up this way </p>
<ul>
<li>project name : bookstore</li>
<li>app name : shelf</li>
<li>model name : Books</li>
</ul>
<p>first load</p>
<pre><code>from bookstore.shelf.models import Books
</code></pre>
<p>subsequent reloads</p>
<pre><code>import bookstore;reload(bookstore.shelf.models... | 5 | 2009-10-16T16:57:11Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 3,466,579 | <p>As far as I'm concerned, none of the above solutions worked on their own, also <a href="http://stackoverflow.com/questions/2677649/how-to-reload-django-models-without-losing-my-locals-in-an-interactive-session">this</a> thread didn't help much on its own, but after combining the approaches I managed to reload my mod... | 5 | 2010-08-12T10:07:35Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 11,488,441 | <p>I wasn't able to get any of the above solutions to work, but I did come up with a workaround for reloading any other non-models module in my django project (e.g. a <code>functions.py</code> or <code>views.py</code> module).</p>
<ol>
<li><p>Create a file called <code>reimport_module.py</code>. I stored it in the <co... | 0 | 2012-07-15T00:24:45Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 20,513,568 | <p>You can also use django-extensions project with the following command:</p>
<pre><code>manage.py shell_plus --notebook
</code></pre>
<p>This will open a IPython notebook on your web browser instead of the IPython shell interpreter. Write your code there, and run it.</p>
<p>When you change your modules, just click ... | 4 | 2013-12-11T07:58:12Z | [
"python",
"django"
] |
How do you reload a Django model module using the interactive interpreter via "manage.py shell"? | 890,924 | <p>I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:</p>
<p><a href="http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module">How do I unload (reload) a Python module?</a></p>
<p>For some reason, I am ... | 49 | 2009-05-21T00:38:16Z | 39,919,311 | <p>Enable IPython autoreload extension before importing any code:</p>
<pre><code>%load_ext autoreload
%autoreload 2
</code></pre>
<p>I use it with the regular django shell and it works perfectly, although it does have some limitations:</p>
<p><strong>*Caveats:</strong></p>
<p>Reloading Python modules in a reliable ... | 0 | 2016-10-07T14:10:07Z | [
"python",
"django"
] |
Dynamic generation of .doc files | 891,315 | <p>How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file containing the user input for the webpage... | 1 | 2009-05-21T03:42:51Z | 891,356 | <p>It don't have to do much with ajax(in th sense that ajax is generally used for dynamic client side interactions)</p>
<p>You need a server side script which takes the input and converts it to doc.</p>
<p>You may use something like openoffice and python if it has some interface
see <a href="http://wiki.services.open... | 0 | 2009-05-21T04:00:26Z | [
"python",
"ajax",
"air",
"dynamic-data"
] |
Dynamic generation of .doc files | 891,315 | <p>How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file containing the user input for the webpage... | 1 | 2009-05-21T03:42:51Z | 891,372 | <p>The problem with the <code>*.doc</code> MS word format is, that it isn't documented enough, therefor it can't have a very good support like, for example, <code>PDF</code>, which is a standard.</p>
<p>Except of the problems with generating the <code>doc</code>, you're users might have problems reading the <code>doc<... | 2 | 2009-05-21T04:12:13Z | [
"python",
"ajax",
"air",
"dynamic-data"
] |
Dynamically specifying tags while using replaceWith in Beautiful Soup | 891,434 | <p>Previously I asked <a href="http://stackoverflow.com/questions/886111/can-i-use-re-sub-or-regexobject-sub-to-replace-text-in-a-subgroup">this</a> question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with.</p>
<pre><code>>>> from BeautifulSoup import ... | 0 | 2009-05-21T04:55:46Z | 891,462 | <p>Try <code>getattr(soup.find('link', id=1), sometag)</code> where you now have a hardcoded tag in <code>soup.find('link', id=1).mode</code> -- <code>getattr</code> is the Python way to get an attribute whose name is held as a string variable, after all!</p>
| 2 | 2009-05-21T05:09:18Z | [
"python",
"xml",
"beautifulsoup"
] |
Dynamically specifying tags while using replaceWith in Beautiful Soup | 891,434 | <p>Previously I asked <a href="http://stackoverflow.com/questions/886111/can-i-use-re-sub-or-regexobject-sub-to-replace-text-in-a-subgroup">this</a> question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with.</p>
<pre><code>>>> from BeautifulSoup import ... | 0 | 2009-05-21T04:55:46Z | 893,548 | <p>No need to use <code>getattr</code>:</p>
<pre><code>sometag = 'mode'
result = soup.find('link', id=1).find(sometag)
print result
</code></pre>
| 0 | 2009-05-21T15:28:31Z | [
"python",
"xml",
"beautifulsoup"
] |
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase? | 891,690 | <p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p>
<p>I'm not the first to ask a question on this subject [see <a href="htt... | 6 | 2009-05-21T07:03:24Z | 895,719 | <p>just use a propper xml parser instead of a lib thats made to deal with broken files</p>
<p>i sugest to just take a look at xml.etree or lxml</p>
| 0 | 2009-05-21T23:08:10Z | [
"python",
"xml",
"beautifulsoup"
] |
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase? | 891,690 | <p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p>
<p>I'm not the first to ask a question on this subject [see <a href="htt... | 6 | 2009-05-21T07:03:24Z | 896,444 | <pre><code>import html5lib
from html5lib import treebuilders
f = open("mydocument.html")
parser = html5lib.XMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup"))
document = parser.parse(f)
</code></pre>
<p>'document' is now a BeautifulSoup-like tree, but retains the cases of tags. See <a href="http://code.googl... | 6 | 2009-05-22T05:09:46Z | [
"python",
"xml",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.