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 |
|---|---|---|---|---|---|---|---|---|---|
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()
# This is what I want to do -> users = models.ManyToOneField(User)
</code></pre>
<p>Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField.</p>
| 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(models.Model):
name = models.CharField(max_length=64)
class User(models.Model):
name = models.CharField(max_length=64)
group = models.ForeignKey(Group)
g = Group.objects.get(id=1)
print g.user_set.all() # prints list of all users in the group
</code></pre>
<p>Remember that Django's models sit on top of a relational database... there's no way to define a single FK field in a table that points to more than one foreign key (without a M2M, that is), so putting the ManyToOne relationship on the Groups object doesn't map to the underlying data store. If you were writing raw SQL, you'd model this relationship with a foreign key from the user table to the group table in any event, if it helps to think of it that way. The syntax and logic of using a <code>ManyToOne</code> property that is defined on a Group instance, if such a concept existed, would be much less straightforward than the ForeignKey defined on User.</p>
| 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()
# This is what I want to do -> users = models.ManyToOneField(User)
</code></pre>
<p>Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField.</p>
| 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 the Profile model to the user model</a>.</p>
| 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()
# This is what I want to do -> users = models.ManyToOneField(User)
</code></pre>
<p>Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField.</p>
| 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 want to refer to this with a friendlier name, or provide additional filtering before returning, you can always wrap the call in a method:</p>
<pre><code>class Group(models.Model):
name = models.CharField(max_length=64)
def users(self):
return self.user_set.all()
</code></pre>
<p>Either can be called from the templates:</p>
<pre><code>{{ group.user_set.all }}
{{ group.users }}
</code></pre>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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 for python, i.e. <a href="http://cherrypy.org" rel="nofollow">cherrypy</a> or <a href="http://pythonpaste.org/" rel="nofollow">paste</a>. Both includes ready-to-use daemonizing scripts.</p>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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 ThreadingMixIn
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
server = ThreadedHTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']), HTTPHandler)
server.serve_forever()
</code></pre>
<p>Which for the most part comes after I fork and ended up resolving my problem.</p>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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 = HTTPServer(
(config['HTTPServer']['listen'], config['HTTPServer']['port']),
BaseHTTPRequestHandler)
# Make the context manager for becoming a daemon process.
daemon_context = daemon.DaemonContext()
daemon_context.files_preserve = [server.fileno()]
# Become a daemon process.
with daemon_context:
server.serve_forever()
</code></pre>
<p>As usual for a daemon, you need to decide how you will interact with the program after it becomes a daemon. For example, you might register a systemd service, or write a PID file, etc. That's all outside the scope of the question though.</p>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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 want to use the default logging module, you can do something like this:</p>
<pre><code># Get the default logger
default_logger = logging.getLogger('')
# Add the handler
default_logger.addHandler(myotherhandler)
# Remove the default stream handler
for handler in default_logger.handlers:
if isinstance(handler, logging.StreamHandler):
default_logger.removeHandler(handler)
</code></pre>
<p>Also at this point I have moved to using the very nice <a href="http://tornadoweb.org" rel="nofollow" title="Tornado">Tornado</a> project for my embedded http servers.</p>
| 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 believe this has something to do with the fact that BaseHTTPServer sends log data to STDOUT and STDERR. I am redirecting those to files. Here is the code snippet:</p>
<pre><code># Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
</code></pre>
<p>Am I doing something wrong here or is BaseHTTPServer somehow prevented from becoming daemonized? </p>
<p>Edit: Updated code to demonstrate the additional, previously missing code flow and that log.debug shows in my forked, background daemon I am hitting code after fork.</p>
| 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, format, *args):
pass
...
rest of custom class code
...
</code></pre>
| 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 a rational number (ex: 1.25).</p>
<p>Example code:</p>
<pre><code>if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
</code></pre>
| 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 a rational number (ex: 1.25).</p>
<p>Example code:</p>
<pre><code>if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
</code></pre>
| 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 a rational number (ex: 1.25).</p>
<p>Example code:</p>
<pre><code>if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
</code></pre>
| 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/library/exceptions.html#exceptions.ValueError">ValueError</a> when conversion fails. Thus:</p>
<pre><code>def isReal(txt):
try:
float(txt)
return True
except ValueError:
return False
</code></pre>
| 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 a rational number (ex: 1.25).</p>
<p>Example code:</p>
<pre><code>if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
</code></pre>
| 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 <module>
ValueError: invalid literal for float(): foo
</code></pre>
<p>You can just do something like:</p>
<pre><code>try:
# validate it's a float
value = float(self.components.txtZoomPos.text)
except ValueError, ve:
pass # your error handling goes here
</code></pre>
| 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 a rational number (ex: 1.25).</p>
<p>Example code:</p>
<pre><code>if self.components.txtZoomPos.text.isdigit():
step = int(self.components.txtZoomPos.text)
</code></pre>
| 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()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False
</code></pre>
<p>Notice that this does not treat floats any different from ints however. You could add that check if you really need it though.</p>
| 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, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"?</p>
<p>In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.</p>
| 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, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"?</p>
<p>In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.</p>
| 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):
match = match.group(0)
if regex2.match(match):
return match
return 'replacement'
regex1.sub(replace, data)
</code></pre>
| 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, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"?</p>
<p>In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.</p>
| 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></pre>
<p>So it's really your regex which could be a bit more precise.</p>
| 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, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"?</p>
<p>In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.</p>
| 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 string for the match. There is also a normal look ahead/behind assertion which will cause the string to match only if the string IS followed/preceded by the given pattern.</p>
<p>That's a bit confusing looking, here it is in pieces:</p>
<pre><code>"(?<!\{)" #Not preceded by a {
"\{" #A {
"(?!\{)" #Not followed by a {
".*?" #Any character(s) (non-greedy)
"(?<!\})" #Not preceded by a } (in reference to the next character)
"\}" #A }
"(?!\})" #Not followed by a }
</code></pre>
<p>So, we're looking for a { without any other {'s around it, followed by some characters, followed by a } without any other }'s around it.</p>
<p>By using negative look-ahead/behind assertion, we condense it down to a single regular expression which will successfully match only single {}'s anywhere in the string.</p>
<p>Also, note that * is a greedy operator. It will match as much as it possibly can. If you use <code>"\{.*\}"</code> and there is more than one {} block in the text, everything between will be taken with it.</p>
<blockquote>
<p>"This is some example text {block1} more text, watch me disappear {block2} even more text"</p>
</blockquote>
<p>becomes</p>
<blockquote>
<p>"This is some example text hello even more text"</p>
</blockquote>
<p>instead of</p>
<blockquote>
<p>"This is some example text hello more text, watch me disappear hello even more text"</p>
</blockquote>
<p>To get the proper output we need to make it non-greedy by appending a ?.</p>
<p>The python docs do a good job of presenting the re library, but the only way to really learn is to experiment.</p>
| 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
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
</code></pre>
<p>Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly.</p>
<p>That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
</code></pre>
<p>I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
</code></pre>
<p>I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same?</p>
| 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> allow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cases where the function really handles as many as there are thrown at it!</p>
<p><hr /></p>
<p><strong>Edit:</strong> if you're willing to put up with <code>verbose</code> as a special keyword argument, you can do this:</p>
<pre><code>import time
def timed(f):
def dec(*args, **kwargs):
verbose = kwargs.pop('verbose', False)
t = time.clock()
ret = f(*args, **kwargs)
if verbose:
print("%s executed in %ds" % (f.__name__, time.clock() - t))
return ret
return dec
@timed
def add(a, b):
return a + b
print(add(2, 2, verbose=True))
</code></pre>
<p>(Thanks <a href="http://stackoverflow.com/questions/889088/function-decorators/889235#889235">Alex Martelli</a> for the <code>kwargs.pop</code> tip!)</p>
| 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
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
</code></pre>
<p>Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly.</p>
<p>That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
</code></pre>
<p>I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
</code></pre>
<p>I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same?</p>
| 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 concisely as:</p>
<pre><code>verbose = kwargs.pop('verbose', False)
</code></pre>
| 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
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
</code></pre>
<p>Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly.</p>
<p>That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
</code></pre>
<p>I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like:</p>
<pre><code>some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
</code></pre>
<p>I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same?</p>
| 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_code.co_argcount) first take it out from kwargs
based on func.func_code.co_varnames, else last one from args
"""
extraArgs = []
newKwargs = {}
for name, value in kwargs.iteritems():
if name in func.func_code.co_varnames:
newKwargs[name] = value
else:
extraArgs.append(kwargs[name])
diff = len(args) + len(newKwargs) - func.func_code.co_argcount
if diff:
extraArgs.extend(args[-diff:])
args = args[:-diff]
func(*args, **newKwargs)
print "%s has extra args=%s"%(func.func_name, extraArgs)
return wrap
@mydeco
def func1(a, b, c=3):
pass
func1(1,b=2,c=3, d="x")
func1(1,2,3,"y")
</code></pre>
<p>output is</p>
<pre><code>func1 has extra args=['x']
func1 has extra args=['y']
</code></pre>
| 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 like</p>
<pre><code>###7######
########1###
</code></pre>
<p>which may or may not matter.</p>
<p>My regex above matches a string starting with #[0-7]## and ignores the end of the string. You could tack a <strong>$</strong> onto the end if you wanted it to match only if that's the entire line.</p>
<p>The first backreference gives you the entire #<number>## string and the second backreference gives you the number inside the #.</p>
| 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 example, and finally the [0-7] will only match a single character between 0 and 7.</p>
| 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 match object contains the digit given.</p>
<p>EDIT: The whole matched string is always available as <code>match.group(0)</code>. If all you need is the complete string, drop any parentheses in the regular expression:</p>
<pre><code>rex= re.compile(r'^\*#\*[0-7]##$')
</code></pre>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 dimensions, format version etc.. So you might see this as a superficial test for "validity".</p>
<p>For other definitions of "valid" you might have to write your own tests.</p>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 data. If this method finds any
problems, it raises suitable
exceptions. This method only works on
a newly opened image; if the image has
already been loaded, the result is
undefined. Also, if you need to load
the image after using this method, you
must reopen the image file. Attributes</p>
</blockquote>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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 OverflowError exception.</p>
<p>Is there someway I could include them as well?</p>
| 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>>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'
</code></pre>
<p>Using a module is much better than reimplementing similar functionality</p>
| 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</code>.</p>
| 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>If you want to divide everything in a list by 3, you want map(lambda x: x / 3, range(20)). if you want decimal answers, map(lambda x : x / 3.0, range(20)). These will return a new list where each element is a the number in the original list divided by three.</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 personal preference.</p>
| 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 code will actually print 3 4 5.</p>
<p>I think what you wanted to do is to check if i is a multiple of 3. Like this:</p>
<pre><code>if i % 3 == 0
</code></pre>
<p>You can of course use an if statement to do it. Or you can use <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> with if</p>
<pre><code>[x for x in range(20) if x % 3 == 0]
</code></pre>
<p><hr /></p>
<p>To those how are down voting this, from <a href="http://www.python.org/doc/2.5.2/lib/node34.html" rel="nofollow">python documentation</a>:</p>
<p>Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). <strong>In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.</strong></p>
| 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 want to do this, but in an HTTP fashion rather than spawning an ssh.</p>
<p>I've done python http before with:</p>
<pre><code>conn=httplib.HTTPConnection('localhost',8000)
conn.connect()
conn.request('POST','/someurl/')
response=conn.getresponse()
</code></pre>
<p>How do I get the inputstream/outputstream from the HTTPConnection so that my lib code can read from/write to just like the ssh example above?</p>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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 time.
t = Timer("""x.index(123)""", setup="""x = range(1000)""")
print t.timeit() # prints float, for example 5.8254
# ..or..
print t.timeit(1000) # repeat 1000 times instead of the default 1million
</code></pre>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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()
time= (end-start)/1000
</code></pre>
<p>The very inaccurate suffers from measurement bias if the run-time of the function is close to the accuracy of the clock. Most of the measured times are merely random numbers between 0 and a few ticks of the clock. </p>
<p>Depending on your system workload, the "time" you observe from a single function may be entirely an artifact of OS scheduling and other uncontrollable overheads.</p>
<p>The second version (less inaccurate) has less measurement bias. If your function is really fast, you may need to run it 10,000 times to damp out OS scheduling and other overheads.</p>
<p>Both are, of course, terribly misleading. The run time for your program -- as a whole -- is not the sum of the function run-times. You can only use the numbers for relative comparisons. They are not absolute measurements that convey much meaning.</p>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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, *args):
self.end = time.clock()
self.interval = self.end - self.start
</code></pre>
<p>Then you may want to time a connection method that may throw. Use</p>
<pre><code>import httplib
with Timer() as t:
conn = httplib.HTTPConnection('google.com')
conn.request('GET', '/')
print('Request took %.03f sec.' % t.interval)
</code></pre>
<p><code>__exit()__</code> method will be called even if the connection request thows. More precisely, you'd have you use <code>try</code> <code>finally</code> to see the result in case it throws, as with</p>
<pre><code>try:
with Timer() as t:
conn = httplib.HTTPConnection('google.com')
conn.request('GET', '/')
finally:
print('Request took %.03f sec.' % t.interval)
</code></pre>
<p><a href="http://preshing.com/20110924/timing-your-code-using-pythons-with-statement">More details here.</a></p>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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(round(time.time() * 1000))
print(endTime - startTime,'ms')
return result
return wrapper
@timeme
def func1(a,b,c = 'c',sleep = 1):
time.sleep(sleep)
print(a,b,c)
func1('a','b','c',0)
func1('a','b','c',0.5)
func1('a','b','c',0.6)
func1('a','b','c',1)
</code></pre>
| 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 (time.clock() - start)*1000
</code></pre>
<p>i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)</p>
<p>This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.</p>
<p>Is there a more standard or accepted way to do this?</p>
<p>When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?</p>
<p>One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.</p>
| 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 "yippee"
</code></pre>
| 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</a> and especially at the <code>strptime</code> function.</p>
| 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-DD HH:MM:SS
4. YYYY-MM-DD HH:MM:SS.SSS
5. YYYY-MM-DDTHH:MM
6. YYYY-MM-DDTHH:MM:SS
7. YYYY-MM-DDTHH:MM:SS.SSS
8. HH:MM
9. HH:MM:SS
10. HH:MM:SS.SSS
11. now
12. DDDDDDDDDD
</code></pre>
<p><strong>REFERENCE:</strong>
<hr>
<a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow">Date And Time Functions</a></p>
| 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))
output.putalpha(mask)
output.save('output.png')
</code></pre>
<p>Here is the mask I used</p>
<p><img src="http://imgur.com/d57og.png" alt="alt text" /></p>
<p><hr /></p>
<p>If you want the thumbnail size to be variable you can use the ImageDraw and draw the mask.</p>
<pre><code>from PIL import Image, ImageOps, ImageDraw
size = (128, 128)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=255)
im = Image.open('image.jpg')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
output.save('output.png')
</code></pre>
<p><hr /></p>
<p>If you want the output in GIF then you need to use the paste function instead of putalpha:</p>
<pre><code>from PIL import Image, ImageOps, ImageDraw
size = (128, 128)
mask = Image.new('L', size, 255)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=0)
im = Image.open('image.jpg')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.paste(0, mask=mask)
output.convert('P', palette=Image.ADAPTIVE)
output.save('output.gif', transparency=0)
</code></pre>
<p>Note that I did the following changes:</p>
<ul>
<li>The mask is now inverted. The white
was replace with black and vis-versa.</li>
<li>I'm converting into 'P' with an 'adaptive' palette. Otherwise PIL will only use web-safe colors and the result will look bad.</li>
<li>I'm adding transparency info with to the image</li>
</ul>
<p><strong>Please note</strong>: There is a big issue with this approach. If the gif image contained black parts, all of them will become transparent as well. You can work around this by choosing another color for the transparency.
I would strongly advice you to use PNG format for this. But if you can't then that is the best you could do. </p>
| 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, im.size[1] * 3)
mask = Image.new('L', bigsize, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + bigsize, fill=255)
mask = mask.resize(im.size, Image.ANTIALIAS)
im.putalpha(mask)
</code></pre>
<p>this produces a far better result in my opinion.</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 compute intensive to solve. If you really need a solution, take a look at some of the approximation algorithms for this. </p>
<p><a href="http://en.wikipedia.org/wiki/Subset_sum_problem" rel="nofollow">http://en.wikipedia.org/wiki/Subset_sum_problem</a> </p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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()
for n in ns:
t = t1 if t1 < t2 else t2
t.add(n)
return t1, t2
if __name__ == "__main__":
import sys
t1, t2 = make_teams([int(s) for s in sys.argv[1:]])
print t1.members, sum(t1.members)
print t2.members, sum(t2.members)
>python two_piles.py 1 50 50 100
[50, 50] 100
[100, 1] 101
</code></pre>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 (rounded up)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | | 4| | | | | | | | | | | // 4
2 | | | | | | | | | | | | | | |
3 | | | | | | | | | | | | | | |
</pre>
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | | | | | | | // 3
2 | | | | | | | 3| | | | | | | |
3 | | | | | | | | | | | | | | |
</pre>
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | |10| | | | | // 10
2 | | | | | | | 3| | | | | |10|10|
3 | | | | | | | | | | | | | | |
</pre>
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | | 3| 4| | | | | |10| | | | | // 3
2 | | | | | | 3| 3| | | | | |10|10|
3 | | | | | | | | | | 3| | | | |
</pre>
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | 2| 3| 4| | | | | |10| | | | | // 2
2 | | | | | 2| 3| 3| | | | | 2|10|10|
3 | | | | | | | | 2| 2| 3| | | | |
</pre>
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 | | 2| 3| 4| 5| | | | |10| | | | | // 5
2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10|
3 | | | | | | | | 2| 2| 3| 5| 5| | |
^
</pre>
<p>12 is our lucky number! Backtracing to get the group:</p>
<pre>
12 - 5 = 7 {5}
7 - 3 = 4 {5, 3}
4 - 4 = 0 {5, 3, 4}
</pre>
<p>The other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2}</p>
<p>All fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner.</p>
<p>BTW: It's called the <a href="http://en.wikipedia.org/wiki/Knapsack%5Fproblem">knapsack-problem</a>.</p>
<blockquote>
<p>If all weights (w1, ..., wn and W) are
nonnegative integers, the knapsack
problem can be solved in
pseudo-polynomial time using dynamic
programming.</p>
</blockquote>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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)
</code></pre>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 one entry at a time.</p>
<p>Here's the code that does this</p>
<pre><code>def make_teams(que):
que.sort()
que.reverse()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
if abs(len(t1)-len(t2))>=len(que):
[t1, t2][len(t1)>len(t2)].append(que.pop(0))
else:
[t1, t2][sum(t1)>sum(t2)].append(que.pop(0))
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
if __name__=="__main__":
que = [2,3,10,5,8,9,7,3,5,2]
make_teams(que)
que = [1, 1, 50, 50, 50, 1000]
make_teams(que)
</code></pre>
<p>This give 27, 27 and 150, 1002 which are the answers that make sense to me.</p>
<p><strong>Edit:</strong> In review, I find this to not actually work, though in the end, I'm not quite sure why. I'll post my test code here though, as it might be useful. The test just generates random sequence that have equal sums, puts these together and compares (with sad results).</p>
<p><strong>Edit #2:</strong> Based in the example pointed out by Unknown, <code>[87,100,28,67,68,41,67,1]</code>, it's clear why my method doesn't work. Specifically, to solve this example, the two largest numbers need to both be added to the same sequence to get a valid solution.</p>
<pre><code>def make_sequence():
"""return the sums and the sequence that's devided to make this sum"""
while 1:
seq_len = randint(5, 200)
seq_max = [5, 10, 100, 1000, 1000000][randint(0,4)]
seqs = [[], []]
for i in range(seq_len):
for j in (0, 1):
seqs[j].append(randint(1, seq_max))
diff = sum(seqs[0])-sum(seqs[1])
if abs(diff)>=seq_max:
continue
if diff<0:
seqs[0][-1] += -diff
else:
seqs[1][-1] += diff
return sum(seqs[0]), sum(seqs[1]), seqs[0], seqs[1]
if __name__=="__main__":
for i in range(10):
s0, s1, seq0, seq1 = make_sequence()
t0, t1 = make_teams(seq0+seq1)
print s0, s1, t0, t1
if s0 != t0 or s1 != t1:
print "FAILURE", s0, s1, t0, t1
</code></pre>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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:
t1.append(que.pop(0))
t1.append(que.pop())
t2.append(que.pop(0))
t2.append(que.pop())
else:
t1.append(que.pop(0))
t2.append(que.pop())
print sum(t1), sum(t2), "\n"
</code></pre>
<p><em>Edit</em>: I suppose that this is also a wrong method. Wrong results!</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 can admit a heuristic solution.</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 = sum(data[mid:])
if diff is None or abs(sum1 - sum2) < diff:
sums = (sum1, sum2)
print sums
</code></pre>
<p>You can adjust nb_iter if the problem is bigger.</p>
<p>It solves all the problem mentioned above mostly all the times.</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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)
totalscore = sum(t)
halftotalscore = totalscore/2.0
oldmoves = {}
for p in t:
people_left = t[:]
people_left.remove(p)
oldmoves[p] = people_left
if iterations == []:
solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])
for n in iterations:
newmoves = {}
for total, roster in oldmoves.iteritems():
for p in roster:
people_left = roster[:]
people_left.remove(p)
newtotal = total+p
if newtotal > halftotalscore: continue
newmoves[newtotal] = people_left
oldmoves = newmoves
solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])
print team([90,200,100])
print team([2,3,10,5,8,9,7,3,5,2])
print team([1,1,1,1,1,1,1,1,1,9])
print team([87,100,28,67,68,41,67,1])
print team([1, 1, 50, 50, 50, 1000])
#output
#(200, 190, [90, 100])
#(27, 27, [3, 9, 7, 3, 5])
#(5, 13, [1, 1, 1, 1, 9])
#(229, 230, [28, 67, 68, 67])
#(150, 1002, [1, 1, 1000])
</code></pre>
<p>Also note that I attempted to solve this using GS's description, but it is impossible to get enough information simply by storing the running totals. And if you stored <strong>both</strong> the number of items and totals, then it would be the same as this solution except you kept needless data. Because you only need to keep the n-1 and n iterations up to numplayers/2.</p>
<p>I had an old exhaustive one based on binomial coefficients (look in history). It solved the example problems of length 10 just fine, but then I saw that the competition had people of up to length 100.</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 Problem</a>.</p>
<p>Best of luck approximating. : )</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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 larger than 50 numbers is the key. These are compatible with solving the problem using the dynamic programming solution I put up in a later post. None of the other algorithms (heuristics, or exhaustive enumeration by a combinatorial pattern generator) can possibly work because there will be test cases large enough or hard enough to break those algorithms. It's rather annoying to be honest because those other solutions are more challenging and certainly more fun. Note that without a lot of extra work, the dynamic programming solution just says whether a solution is possible with N/2 for any given sum, but it doesn't tell you the contents of either partition.</p>
| 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 algorithm for some case? </p>
<p>How do I optimize and/or pythonize this?</p>
<pre><code>def make_teams(que):
que.sort()
if len(que)%2: que.insert(0,0)
t1,t2 = [],[]
while que:
val = (que.pop(), que.pop())
if sum(t1)>sum(t2):
t2.append(val[0])
t1.append(val[1])
else:
t1.append(val[0])
t2.append(val[1])
print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n"
</code></pre>
<p>Question is from <a href="http://www.codechef.com/problems/TEAMSEL/">http://www.codechef.com/problems/TEAMSEL/</a></p>
| 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>unique</em> values was low), I finally succumbed to peer pressure and wrote the one they wanted (not too hard - handling duplicated entries was the trickiest part - the underlying algorithm I based it on only works if all the inputs are unique - I'm sure glad that <em>long long</em> is big enough to hold 50 bits!).</p>
<p>So for all the test data and awkward edge cases I put together while testing my first two efforts, it gives the same answer. At least for the ones I checked with the combinatorial solver, I <em>know</em> they're correct. But I'm still failing the submission with some wrong answer!</p>
<p>I'm not asking for anyone to fix my code here, but I would be very greatful if anyone can find a case for which the code below generates the wrong answer.</p>
<p>Thanks,</p>
<p>Graham</p>
<p>PS This code does always execute within the time limit but it is <em>far</em> from optimised. i'm keeping it simple until it passes the test, then I have some ideas to speed it up, maybe by a factor of 10 or more.</p>
<pre>
#include <stdio.h>
#define TRUE (0==0)
#define FALSE (0!=0)
static int debug = TRUE;
//int simple(const void *a, const void *b) {
// return *(int *)a - *(int *)b;
//}
int main(int argc, char **argv) {
int p[101];
char *s, line[128];
long long mask, c0[45001], c1[45001];
int skill, players, target, i, j, tests, total = 0;
debug = (argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' && argv[1][2] == '\0');
s = fgets(line, 127, stdin);
tests = atoi(s);
while (tests --> 0) {
for (i = 0; i < 45001; i++) {c0[i] = 0LL;}
s = fgets(line, 127, stdin); /* blank line */
s = fgets(line, 127, stdin); /* no of players */
players = atoi(s);
for (i = 0; i < players; i++) {s = fgets(line, 127, stdin); p[i] = atoi(s);}
if (players == 1) {
printf("0 %d\n", p[0]);
} else {
if (players&1) p[players++] = 0; // odd player fixed by adding a single player of 0 strength
//qsort(p, players, sizeof(int), simple);
total = 0; for ( i = 0; i < players; i++) total += p[i];
target = total/2; // ok if total was odd and result rounded down - teams of n, n+1
mask = 1LL << (((long long)players/2LL)-1LL);
for (i = 0; i < players; i++) {
for (j = 0; j <= target; j++) {c1[j] = 0LL;} // memset would be faster
skill = p[i];
//add this player to every other player and every partial subset
for (j = 0; j <= target-skill; j++) {
if (c0[j]) c1[j+skill] = c0[j]<<1; // highest = highest j+skill for later optimising
}
c0[skill] |= 1; // so we don't add a skill number to itself unless it occurs more than once
for (j = 0; j <= target; j++) {c0[j] |= c1[j];}
if (c0[target]&mask) break; // early return for perfect fit!
}
for (i = target; i > 0; i--) {
if (debug || (c0[i] & mask)) {
fprintf(stdout, "%d %d\n", i, total-i);
if (debug) {
if (c0[i] & mask) printf("******** ["); else
printf(" [");
for (j = 0; j <= players; j++) if (c0[i] & (1LL<<(long long)j)) printf(" %d", j+1);
printf(" ]\n");
} else break;
}
}
}
if (tests) printf("\n");
}
return 0;
}
</pre>
| 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 understand the concept of tail call optimization. I just can't think of any reason why Python really <em>needs</em> it.</p>
<p>To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?</p>
| 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 result
</code></pre>
<p>Without tail call optimization, calling this with a big number could overflow the stack.</p>
| 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 understand the concept of tail call optimization. I just can't think of any reason why Python really <em>needs</em> it.</p>
<p>To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?</p>
| 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 usually have a lot of other constructions for almost every situation imaginable, so it's less critical. Always a good thing to have, to allow for unforeseen situations, of course</p>
| 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 understand the concept of tail call optimization. I just can't think of any reason why Python really <em>needs</em> it.</p>
<p>To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?</p>
| 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 (sacrificing stack-trace dumps and debugging regularity).</p>
| 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 understand the concept of tail call optimization. I just can't think of any reason why Python really <em>needs</em> it.</p>
<p>To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?</p>
| 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 equally cleaner solution without TCO.</p>
| 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 understand the concept of tail call optimization. I just can't think of any reason why Python really <em>needs</em> it.</p>
<p>To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?</p>
| 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 interested in that question, please read my answer on my <a href="http://baruchel.github.io/python/2015/11/07/explaining-functional-aspects-in-python/" rel="nofollow">blog</a>. In two words, I give a presentation of the <a href="https://github.com/baruchel/tco" rel="nofollow">tco</a> module; you will not find anything that you can't already do without tail-recursion elimination, but you may be interested by my thoughts about it.</p>
<p>I know that mere links are not the preferred usage on Stackoverflow; please consider however that I wrote a whole article for answering to this post (which I refer to in the body of my article) including also some pictures for illustrating it. For this reason, I post here this unusual answer.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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 disadvantages with pickle:</p>
<ul>
<li>It's not secure against erroneous or
maliciously constructed data. Never
unpickle data received from an
untrusted or unauthenticated source.</li>
<li>The format is not human readable.</li>
</ul>
<p>If you are using python 2.6 there is a builtin module called <a href="http://docs.python.org/library/json.html">json</a>. It is as easy as pickle to use:</p>
<pre><code>import json
encoded = json.dumps(obj)
obj = json.loads(encoded)
</code></pre>
<p>Json format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle. But might be slower than cPickle.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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 an example of YAML (a dict holding a list and a string)
Full syntax: http://www.yaml.org/refcard.html
</code></pre>
<p>To get it in python, just easy_install pyyaml. See <a href="http://pyyaml.org/" rel="nofollow">http://pyyaml.org/</a></p>
<p>It comes with easy file save / load functions, that I can't remember right this minute.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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.</p>
<p>But if you really want to parse the text of the <code>dict</code>, and it contains only <code>str</code>ings, <code>int</code>s and <code>tuple</code>s like you've shown, you can use <a href="http://docs.python.org/library/ast.html#ast.literal%5Feval"><code>ast.literal_eval</code></a> to parse it. It is a lot safer, since you can't eval full expressions with it - It only works with <code>str</code>ings, numbers, <code>tuple</code>s, <code>list</code>s, <code>dict</code>s, <code>bool</code>eans, and <code>None</code>:</p>
<pre><code>>>> import ast
>>> print ast.literal_eval("{12: 'mydict', 14: (1, 2, 3)}")
{12: 'mydict', 14: (1, 2, 3)}
</code></pre>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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. Most useful "standard" module for a database to store schema-less data."</p>
<p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p>
<p>The compression bonus will probably reduce your 6GB dictionary to 1GB. If you do not want a store a series of dictionaries, the module also contains a file.gz solution which might be more suitable given your dictionary size.</p>
| 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 in memory at once. I have other functions to run on this data, but the contents will not change.</p>
<p>Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values.</p>
<p>to oversimplify things it looks something like:
{((('word','list'),(1,2),(1,3)),(...)):0.0, ....}</p>
<p>I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.</p>
| 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</code>, stores arbitrary plain data</p></li>
<li><p>proper database, e.g. mongodb for hairy data or mysql or sqlite plain data and faster retrieval</p></li>
</ul>
| 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, but eventually needs to free the return string.</p>
| 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 by Python on its behalf?</p>
</blockquote>
<p>No, you need to manually free the buffer yourself. What people normally do is copy the python string immediately from buffer.value, and then free the buffer.</p>
<blockquote>
<p>Can you post the C code? â mike 2 hours ago</p>
</blockquote>
<pre><code>#include <string.h>
char* mystrcat(char* buffer) {
strcat(buffer, "blah");
return buffer;
}
</code></pre>
| 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)</code> to demonstrate the safer <code>n</code> version of concatenation.</p>
<p>You must pass <code>create_unicode_buffer()</code> instead of passing a regular immutable <code>u"unicode string"</code> for non-const <code>wchar_t*</code> parameters, otherwise you will probably get a segmentation fault.</p>
<p>If the function you need to talk to returns UCS-2 and <code>sizeof(wchar_t) == 4</code> then you will not be able to use <code>unicode_buffer()</code> because it converts between <code>wchar_t</code> to Python's internal Unicode representation. In that case you might be able to use some combination of <code>result.create_string_buffer()</code> and <code>result.decode('UCS2')</code> or just create an array of <code>c_short</code> and <code>u''.join(unichr(c) for c in buffer)</code>. I had to do that to debug an ODBC driver.</p>
<p>example.py:</p>
<pre><code>#!/usr/bin/env python
#-*- encoding: utf-8 -*-
import sys
from ctypes import *
example = cdll.LoadLibrary(".libs/libexample.so")
example.its_an_example.restype = c_wchar_p
example.its_an_example.argtypes = (c_wchar_p, c_wchar_p, c_uint)
buf = create_unicode_buffer(19) # writable, unlike u"example".
buf[0] = u"\u0000"
a = u"ããããã
â "
b = u"å人 ç¸å½ç ç¶²ä¸è¯ç"
print example.its_an_example(buf, a, len(buf) - len(buf.value) - 1)
print example.its_an_example(buf, b, len(buf) - len(buf.value) - 1)
print buf.value # you may have to .encode("utf-8") before printing
sys.stdout.write(buf.value.encode("utf-8") + "\n")
</code></pre>
<p>example.c:</p>
<pre><code>#include <stdlib.h>
#include <wchar.h>
wchar_t *its_an_example(wchar_t *dest, const wchar_t *src, size_t n) {
return wcsncat(dest, src, n);
}
</code></pre>
<p>Makefile: (ensure the indentation is one tab character, not spaces):</p>
<pre><code>all:
libtool --mode=compile gcc -g -O -c example.c
libtool --mode=link gcc -g -O -o libexample.la example.lo \
-rpath /usr/local/lib
</code></pre>
| 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="nofollow">http://www.python.org/download/releases/2.3.7/</a> to download the source tarball. Once you have that open a terminal and run <code>./configure --prefix /home/(your homedir)/software MACOSX_DEPLOYMENT_TARGET=10.5</code> then <code>make</code> and <code>make install</code>. This should place a separate install in the software directory that you can access directly.</p>
| 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
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</code></pre>
| 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 <code>response</code> means.</p>
| 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
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</code></pre>
| 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 that does code completion and understands python syntax, it'll make your life easier when trying to determine what functions are available for a given class or module</p>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 code for it:</p>
<pre><code>import os
from django.db.models.loading import AppCache
cache = AppCache()
curdir = os.getcwd()
for app in cache.get_apps():
f = app.__file__
if f.startswith(curdir) and f.endswith('.pyc'):
os.remove(f)
__import__(app.__name__)
reload(app)
from django.utils.datastructures import SortedDict
cache.app_store = SortedDict()
cache.app_models = SortedDict()
cache.app_errors = {}
cache.handled = {}
cache.loaded = False
</code></pre>
<p>I've put all of this in a separate file called reloadmodels.py in the root directory of my Django site. Using IPython I can reload everything by running:</p>
<pre><code>%run ~/mysite/reloadmodels.py
</code></pre>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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);from bookstore.shelf.models import Books
</code></pre>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 models in <a href="http://code.google.com/p/django-command-extensions/wiki/CommandExtensions" rel="nofollow">shell_plus</a>:</p>
<ol>
<li>Make changes to the model (MyModel)</li>
<li>remove <code>models.pyc</code></li>
<li><p>Clean Django model cache (like <a href="http://stackoverflow.com/questions/890924/how-do-you-reload-a-django-model-module-using-the-interactive-interpreter-via-ma/903943#903943">here</a>):</p>
<pre><code> from django.db.models.loading import AppCache
cache = AppCache()
from django.utils.datastructures import SortedDict
cache.app_store = SortedDict()
cache.app_models = SortedDict()
cache.app_errors = {}
cache.handled = {}
cache.loaded = False
</code></pre></li>
<li><p>Reload model like <a href="http://stackoverflow.com/questions/890924/how-do-you-reload-a-django-model-module-using-the-interactive-interpreter-via-ma/1579190#1579190">here</a></p>
<pre><code>reload(project.app.models)
from project.app.models import MyModel
</code></pre></li>
</ol>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 <code>local/</code> folder of my django project on my dev machine.</p>
<pre><code># Desc: Imports the module with the name passed in, or imports it for first
# time if it hasn't already been imported.
#
# Purpose of this script is to speed up development of functions that
# are written in an external editor then tested in IPython.
#
# Without this script you have to exit & reenter IPython then redo
# import statements, definitions of local variables, etc.
#
# Note: doesn't work for Django models files, because Django caches
# them in a structure called AppCache.
#
# Args: module to reload (string)
import sys
module_to_reload = sys.argv[1]
# Attempt to pop module
try:
sys.modules.pop(module_to_reload)
print 'reimporting...'
except KeyError:
print 'importing for first time...'
# (re)import module
import_str = 'from {0} import *'.format(module_to_reload)
exec(import_str)
</code></pre></li>
<li><p>Launch shell plus (which uses an embedded IPython shell):</p>
<p><code>python manage.py shell_plus</code></p></li>
<li><p>Use the following to import the module you are developing:</p>
<p><code>%run local/reimport_module.py 'your.module'</code></p></li>
<li><p>Use IPython to test functions in your module.</p></li>
<li>Make changes to the module in an external editor.</li>
<li><p>Use the following to reimport the module without having to exit & reenter IPython:</p>
<p><code>%run local/reimport_module.py 'your.module'</code></p>
<p>Note: this command was already used in step 3, so you can type <code>%run</code> then the up arrow to autocomplete it.</p></li>
</ol>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 on the web page menu item 'Kernel->Restart'</p>
<p>Re-running the code now uses your modified modules.</p>
| 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 having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Writing your first Django app, part 1</a></p>
<p>After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it.</p>
<pre><code>import polls.models as pm
</code></pre>
<p>Create a new "Poll" object:</p>
<pre><code>p = pm.Poll()
</code></pre>
<p>All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added:</p>
<pre><code>def x(self):
return 2+2
</code></pre>
<p>Now go back to the interpreter and "reload" the module:</p>
<pre><code>reload(pm)
</code></pre>
<p>Now try to use your new method or attribute:</p>
<pre><code>p1 = pm.Poll()
p1.x()
</code></pre>
<p>You'll get this message:</p>
<pre><code>'Poll' object has no attribute 'x'
</code></pre>
<p>What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work.</p>
<p>Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session.</p>
<p>By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.</p>
| 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 way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work:</p>
<ul>
<li>Functions and classes imported via âfrom xxx import fooâ are upgraded to new versions when âxxxâ is reloaded.</li>
<li>Methods and properties of classes are upgraded on reload, so that calling âc.foo()â on an object âcâ created before the reload causes the new code for âfooâ to be executed.</li>
</ul>
<p>Some of the known remaining caveats are:</p>
<ul>
<li>Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only).</li>
<li>Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded.</li>
<li>C extension modules cannot be reloaded, and so cannot be autoreloaded.*</li>
</ul>
<p>source: <a href="https://ipython.org/ipython-doc/3/config/extensions/autoreload.html#caveats" rel="nofollow">https://ipython.org/ipython-doc/3/config/extensions/autoreload.html#caveats</a></p>
<p>Another great option is to write your code in a separate script and send it to django shell, like this:</p>
<pre><code>manage.py shell < my_script.py
</code></pre>
| 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. Any solutions/suggestions would be much appreciated.</p>
<p>PS- I don't want to go the C#/Java way with this.</p>
| 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.openoffice.org/wiki/Python" rel="nofollow">http://wiki.services.openoffice.org/wiki/Python</a></p>
<p>or on windows you can directly use Word COM objects to create doc using win32apis
but it is less probable, that a windows server serving python :)</p>
<p>I think better alternative is to generate PDF which would be nicer and easier.
<a href="http://www.reportlab.org/downloads.html#reportlab" rel="nofollow">Reportlab</a> has a wonderful pdf generation library and it works like charm from python.
Once you have pdf you may use some pdf to doc converter, but I think PDF would be good enough.</p>
<p><strong>Edit: Doc generation</strong>
On second thought if you are insisting on DOC you may have windows server in that case
you can use COM objets to generate DOC, xls or whatever see
<a href="http://win32com.goermezer.de/content/view/173/284/" rel="nofollow">http://win32com.goermezer.de/content/view/173/284/</a></p>
| 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. Any solutions/suggestions would be much appreciated.</p>
<p>PS- I don't want to go the C#/Java way with this.</p>
| 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</code> files. For example users on linux machines.</p>
<p>You should consider producing RTF on the server. It is more standard, and thus more supported both for document generation, and for reading the document afterwards. Unless you need very specific features, it should suffice for most of documents types, and MS word opens it by default, just like it opens its own native format.</p>
<p><a href="http://pyrtf.sourceforge.net/" rel="nofollow">PyRTF</a> is an project you can use for RTF generation with python.</p>
| 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 BeautifulStoneSoup
>>> html = """
... <config>
... <links>
... <link name="Link1" id="1">
... <encapsulation>
... <mode>ipsec</mode>
... </encapsulation>
... </link>
... <link name="Link2" id="2">
... <encapsulation>
... <mode>udp</mode>
... </encapsulation>
... </link>
... </links>
... </config>
... """
>>> soup = BeautifulStoneSoup(html)
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>ipsec</mode>
</encapsulation>
</link>
>>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever')
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>whatever</mode>
</encapsulation>
</link>
</code></pre>
<p>The only problem with this is that the example has a hardcoded tag value (in this case "mode"), and I need to be able to specify any tag within the specified "link" tag. Simple variable substitution doesn't seem to work.</p>
| 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 BeautifulStoneSoup
>>> html = """
... <config>
... <links>
... <link name="Link1" id="1">
... <encapsulation>
... <mode>ipsec</mode>
... </encapsulation>
... </link>
... <link name="Link2" id="2">
... <encapsulation>
... <mode>udp</mode>
... </encapsulation>
... </link>
... </links>
... </config>
... """
>>> soup = BeautifulStoneSoup(html)
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>ipsec</mode>
</encapsulation>
</link>
>>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever')
>>> soup.find('link', id=1)
<link name="Link1" id="1">
<encapsulation>
<mode>whatever</mode>
</encapsulation>
</link>
</code></pre>
<p>The only problem with this is that the example has a hardcoded tag value (in this case "mode"), and I need to be able to specify any tag within the specified "link" tag. Simple variable substitution doesn't seem to work.</p>
| 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="http://stackoverflow.com/questions/567999/preventing-beautifulsoup-from-converting-my-xml-tags-to-lowercase">here</a>]. However, I did not understand the answer given to that question and in BeautifulSoup-3.1.0.1 BeautifulSoup.py does not appear to contain any instances of "<code>encodedName</code>" or "<code>Tag.__str__</code>"</p>
| 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="http://stackoverflow.com/questions/567999/preventing-beautifulsoup-from-converting-my-xml-tags-to-lowercase">here</a>]. However, I did not understand the answer given to that question and in BeautifulSoup-3.1.0.1 BeautifulSoup.py does not appear to contain any instances of "<code>encodedName</code>" or "<code>Tag.__str__</code>"</p>
| 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.google.com/p/html5lib/">html5lib</a> for documentation and installation.</p>
| 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.