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
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
575,937
<p>Use <code>from __future__ import division</code> to get the behavior you want. Then, in a pinch, you can do something like </p> <pre><code>from __future__ import division strings = ["0.1234", "1/2", "2/3"] numbers = map(eval, strings) </code></pre> <p>to get a list of floats out of your strings. If you want to do this the "right" way, don't use <code>eval()</code>, but instead write a function that accepts a string and calls <code>float()</code> on it if it contains no slash, or parses the string and divides the numerator and denominator if there's a slash in it.</p> <p>One way to do it:</p> <pre><code>def parse_float_string(x) parts = x.split('/', 1) if len(parts) == 1: return float(x) elif len(parts) == 2: return float(parts[0])/float(parts[1]) else: raise ValueError </code></pre> <p>Then just <code>map(parse_float_string, strings)</code> will get you your list.</p>
4
2009-02-22T22:16:05Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
575,939
<p>The problem with eval is that, as in python, the quotient of integers is an integer. So, you have several choices.</p> <p>The first is simply to make integer division return floats:</p> <pre><code>from __future__ import division </code></pre> <p>The other is to split the rational number:</p> <pre><code>reduce(lambda x, y: x*y, map(int, rat_str.split("/")), 1) </code></pre> <p>Where rat_str is the string with a rational number.</p>
2
2009-02-22T22:17:37Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
575,944
<p>I'd parse the string if conversion fails:</p> <pre><code>&gt;&gt;&gt; def convert(s): try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom) ... &gt;&gt;&gt; convert("0.1234") 0.1234 &gt;&gt;&gt; convert("1/2") 0.5 </code></pre> <p>Generally using eval is a bad idea, since it's a security risk. <em>Especially</em> if the string being evaluated came from outside the system.</p>
16
2009-02-22T22:18:47Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
575,967
<p>The suggestions with <code>from __future__ import division</code> combined with <code>eval</code> will certainly work.</p> <p>It's probably worth pointing out that the suggestions that don't use <code>eval</code> but rather parse the string do so because <code>eval</code> is dangerous: if there is some way for an arbitrary string to get sent to <code>eval</code>, then your system is vulnerable. So it's a bad habit. (But if this is just quick and dirty code, it's probably not <em>that</em> big a deal!)</p>
0
2009-02-22T22:29:11Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
575,976
<p>As others have pointed out, using <code>eval</code> is potentially a security risk, and certainly a bad habit to get into. (if you don't think it's as risky as <code>exec</code>, imagine <code>eval</code>ing something like: <code>__import__('os').system('rm -rf /')</code>)</p> <p>However, if you have python 2.6 or up, you can use <a href="http://docs.python.org/library/ast.html#ast.literal_eval"><code>ast.literal_eval</code></a>, for which the string provided:</p> <blockquote> <p>may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.</p> </blockquote> <p>Thus it should be quite safe :-)</p>
7
2009-02-22T22:34:55Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
576,025
<p>Another option (also only for 2.6 and up) is the <code>fractions</code> module.</p> <pre><code>&gt;&gt;&gt; from fractions import Fraction &gt;&gt;&gt; Fraction("0.1234") Fraction(617, 5000) &gt;&gt;&gt; Fraction("1/2") Fraction(1, 2) &gt;&gt;&gt; float(Fraction("0.1234")) 0.1234 &gt;&gt;&gt; float(Fraction("1/2")) 0.5 </code></pre>
6
2009-02-22T23:04:44Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
576,156
<p>In Python 3, this should work.</p> <pre><code>&gt;&gt;&gt; x = ["0.1234", "1/2"] &gt;&gt;&gt; [eval(i) for i in x] [0.1234, 0.5] </code></pre>
1
2009-02-23T00:18:53Z
[ "python", "rational-numbers" ]
How to convert rational and decimal number strings to floats in python?
575,925
<p>How can I convert strings which can denote decimal or rational numbers to floats</p> <pre><code>&gt;&gt;&gt; ["0.1234", "1/2"] ['0.1234', '1/2'] </code></pre> <p>I'd want [0.1234, 0.5].</p> <p>eval is what I was thinking but no luck:</p> <pre><code>&gt;&gt;&gt; eval("1/2") 0 </code></pre>
9
2009-02-22T22:08:47Z
576,395
<p><a href="http://code.google.com/p/sympy/" rel="nofollow">sympy</a> can help you out here:</p> <pre><code>import sympy half = sympy.Rational('1/2') p1234 = sympy.Rational('0.1234') print '%f, %f" % (half, p1234) </code></pre>
1
2009-02-23T02:54:20Z
[ "python", "rational-numbers" ]
Is there a special trick to downloading a zip file and writing it to disk with Python?
576,238
<p>I am FTPing a zip file from a remote FTP site using Python's ftplib. I then attempt to write it to disk. The file write works, however most attempts to open the zip using WinZip or WinRar fail; both apps claim the file is corrupted. Oddly however, when right clicking and attempting to extract the file using WinRar, the file <em>will</em> extract.</p> <p>So to be clear, the file write will work, but will not <em>open</em> inside the popular zip apps, but <em>will</em> decompress using those same apps. Note that the Python zipfile module <em>never</em> fails to extract the zips.</p> <p>Here is the code that I'm using to get the zip file from the FTP site (please ignore the bad tabbing, that's not the issue). </p> <pre><code>filedata = None def appender(chunk): global filedata filedata += chunk def getfile(filename): try: ftp = None try: ftp = FTP(address) ftp.login('user', 'password') except Exception, e: print e command = 'RETR ' + filename idx = filename.rfind('/') path = filename[0:idx] ftp.cwd(path) fileonly = filename[idx+1:len(filename)] ftp.retrbinary('RETR ' + filename, appender) global filedata data = filedata ftp.close() filedata = '' return data except Exception, e: print e data = getfile('/archives/myfile.zip') file = open(pathtoNTFileShare, 'wb') file.write(data) file.close() </code></pre>
1
2009-02-23T01:00:37Z
576,254
<p>I've never used that library, but urllib2 works fine, and is more straightforward. Curl is even better.</p> <p>Looking at your code, I can see a couple of things wrong. Your exception catching only prints the exception, then continues. For fatal errors like not getting an FTP connection, they need to print the message and then exit. Also, your filedata starts off as None, then your appender uses += to add to that, so you're trying to append a string + None, which gives a TypeError when I try it here. I'm surprised it's working at all; I would have guessed that the appender would throw an exception, and so the FTP copy would abort.</p> <p>While re-reading, I just noticed another answer about use of += on binary data. That could well be it; python tries to be smart sometimes, and could be "helping" when you join strings with whitespace or NULs in them, or something like that. Your best bet there is to have the file open (let's call it outfile), and use your appender to just outfile.write(chunk).</p>
1
2009-02-23T01:12:00Z
[ "python", "ftp", "ftplib" ]
Is there a special trick to downloading a zip file and writing it to disk with Python?
576,238
<p>I am FTPing a zip file from a remote FTP site using Python's ftplib. I then attempt to write it to disk. The file write works, however most attempts to open the zip using WinZip or WinRar fail; both apps claim the file is corrupted. Oddly however, when right clicking and attempting to extract the file using WinRar, the file <em>will</em> extract.</p> <p>So to be clear, the file write will work, but will not <em>open</em> inside the popular zip apps, but <em>will</em> decompress using those same apps. Note that the Python zipfile module <em>never</em> fails to extract the zips.</p> <p>Here is the code that I'm using to get the zip file from the FTP site (please ignore the bad tabbing, that's not the issue). </p> <pre><code>filedata = None def appender(chunk): global filedata filedata += chunk def getfile(filename): try: ftp = None try: ftp = FTP(address) ftp.login('user', 'password') except Exception, e: print e command = 'RETR ' + filename idx = filename.rfind('/') path = filename[0:idx] ftp.cwd(path) fileonly = filename[idx+1:len(filename)] ftp.retrbinary('RETR ' + filename, appender) global filedata data = filedata ftp.close() filedata = '' return data except Exception, e: print e data = getfile('/archives/myfile.zip') file = open(pathtoNTFileShare, 'wb') file.write(data) file.close() </code></pre>
1
2009-02-23T01:00:37Z
576,258
<p>Pass file.write directly inside the retrbinary function instead of passing appender. This will work and it will also not use that much RAM when you are downloading a big file. </p> <p>If you'd like the data stored inside a variable though, you can also have a variable named: </p> <pre><code>blocks = [] </code></pre> <p>Then pass to retrbinary instead of appender: </p> <pre><code>blocks.append </code></pre> <p>Your current appender function is wrong. += will not work correctly when there is binary data because it will try to do a string append and stop at the first NULL it sees. </p> <p>As mentioned by @Lee B you can also use urllib2 or Curl. But your current code is almost correct if you make the small modifications I mentioned above. </p>
2
2009-02-23T01:13:59Z
[ "python", "ftp", "ftplib" ]
Django Project structure, recommended structure to share an extended auth "User" model across apps?
576,345
<p>I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps. </p> <p>I'd like to reference the same user model in multiple apps. I haven't built the login interface yet, so I'm not sure how it should fit together.</p> <p>The following comes to mind:</p> <pre><code>project.loginapp.app1 project.loginapp.app2 </code></pre> <p>Is there a common pattern for this situation? Would login best be handled by a 'login app'?</p> <p>Similar to this question but more specific. <a href="http://stackoverflow.com/questions/464010/django-application-configuration">http://stackoverflow.com/questions/464010/django-application-configuration</a></p> <p><strong>UPDATE</strong></p> <p>Clarified my use-case above. I'd like to add fields (extend or subclass?) to the existing auth user model. And then reference that model in multiple apps.</p>
1
2009-02-23T02:17:32Z
576,353
<p>You should check first if the contrib.auth module satisfies your needs, so you don't have to reinvent the wheel:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth</a></p> <p>edit:</p> <p>Check this snippet that creates a UserProfile after the creation of a new User.</p> <pre><code>def create_user_profile_handler(sender, instance, created, **kwargs): if not created: return user_profile = UserProfile.objects.create(user=instance) user_profile.save() post_save.connect(create_user_profile_handler, sender=User) </code></pre>
3
2009-02-23T02:22:59Z
[ "python", "django", "django-models", "django-project-architect" ]
Django Project structure, recommended structure to share an extended auth "User" model across apps?
576,345
<p>I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps. </p> <p>I'd like to reference the same user model in multiple apps. I haven't built the login interface yet, so I'm not sure how it should fit together.</p> <p>The following comes to mind:</p> <pre><code>project.loginapp.app1 project.loginapp.app2 </code></pre> <p>Is there a common pattern for this situation? Would login best be handled by a 'login app'?</p> <p>Similar to this question but more specific. <a href="http://stackoverflow.com/questions/464010/django-application-configuration">http://stackoverflow.com/questions/464010/django-application-configuration</a></p> <p><strong>UPDATE</strong></p> <p>Clarified my use-case above. I'd like to add fields (extend or subclass?) to the existing auth user model. And then reference that model in multiple apps.</p>
1
2009-02-23T02:17:32Z
576,359
<p>i think the 'project/app' names are badly chosen. it's more like 'site/module'. an app can be very useful without having views, for example.</p> <p>check the <a href="http://www.youtube.com/view_play_list?p=D415FAF806EC47A1" rel="nofollow">2008 DjangoCon talks</a> on YouTube, especially the one about <a href="http://www.youtube.com/watch?v=A-S0tqpPga4&amp;feature=PlayList&amp;p=D415FAF806EC47A1&amp;index=14" rel="nofollow">reusable apps</a>, it will make you think totally different about how to structure your project.</p>
2
2009-02-23T02:25:52Z
[ "python", "django", "django-models", "django-project-architect" ]
Django Project structure, recommended structure to share an extended auth "User" model across apps?
576,345
<p>I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps. </p> <p>I'd like to reference the same user model in multiple apps. I haven't built the login interface yet, so I'm not sure how it should fit together.</p> <p>The following comes to mind:</p> <pre><code>project.loginapp.app1 project.loginapp.app2 </code></pre> <p>Is there a common pattern for this situation? Would login best be handled by a 'login app'?</p> <p>Similar to this question but more specific. <a href="http://stackoverflow.com/questions/464010/django-application-configuration">http://stackoverflow.com/questions/464010/django-application-configuration</a></p> <p><strong>UPDATE</strong></p> <p>Clarified my use-case above. I'd like to add fields (extend or subclass?) to the existing auth user model. And then reference that model in multiple apps.</p>
1
2009-02-23T02:17:32Z
576,362
<p>Why are you extending User? Please clarify.</p> <p>If you're adding more information about the users, you don't need to roll your own user and auth system. Django's version of that is quite solid. The user management is located in django.contrib.auth.</p> <p>If you need to customize the information stored with users, first define a model such as </p> <pre><code>class Profile(models.Model): ... user = models.ForeignKey("django.contrib.auth.models.User", unique=True) </code></pre> <p>and then set </p> <pre><code>AUTH_PROFILE_MODULE = "appname.profile" </code></pre> <p>in your settings.py</p> <p>The advantage of setting this allows you to use code like this in your views:</p> <pre><code>def my_view(request): profile = request.user.get_profile() etc... </code></pre> <p>If you're trying to provide more ways for users to authenticate, you can add an auth backend. Extend or re-implement django.contrib.auth.backends.ModelBackend and set it as your AUTHENTICATION_BACKENDS in settings.py. </p> <p>If you want to make use of a different permissions or groups concept than is provided by django, there's nothing that will stop you. Django makes use of those two concepts only in django.contrib.admin (That I know of), and you are free to use some other concept for those topics as you see fit.</p>
6
2009-02-23T02:27:09Z
[ "python", "django", "django-models", "django-project-architect" ]
Is it required to learn Python 2.6 along with Python 3.0?
576,557
<p>If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?</p> <p><hr></p> <p>Remarkably similar to:</p> <p><a href="http://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626">If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?</a></p>
0
2009-02-23T04:43:32Z
576,565
<p>No, 3.x is largely incompatible with 2.x (that was actually a major motivation for doing it). In fact, you probably shouldn't be using 3.0 at all-- it's rather unusable at the moment, and is still mostly intended for library developers to port to it so that it can be usable.</p>
5
2009-02-23T04:46:55Z
[ "python" ]
Is it required to learn Python 2.6 along with Python 3.0?
576,557
<p>If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?</p> <p><hr></p> <p>Remarkably similar to:</p> <p><a href="http://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626">If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?</a></p>
0
2009-02-23T04:43:32Z
576,567
<p>NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more <strong>useful</strong>.</p>
1
2009-02-23T04:47:38Z
[ "python" ]
Is it required to learn Python 2.6 along with Python 3.0?
576,557
<p>If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?</p> <p><hr></p> <p>Remarkably similar to:</p> <p><a href="http://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626">If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?</a></p>
0
2009-02-23T04:43:32Z
576,583
<p>Python 2.6 and Python 3.0 are <em>very</em> compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, but 2.6 to 3.0 for C-level stuff is a real pain).</p> <p>Just start learning 2.6. The infrastructure is there now, and there's plenty of help for when you finally want to move to 3.x. 2.x is not going away: there will be a 2.7 release at some point, so you're not going to be out of luck if you learn 2.6 now.</p>
4
2009-02-23T05:01:46Z
[ "python" ]
Is it required to learn Python 2.6 along with Python 3.0?
576,557
<p>If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?</p> <p><hr></p> <p>Remarkably similar to:</p> <p><a href="http://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626">If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?</a></p>
0
2009-02-23T04:43:32Z
576,666
<p>It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet. </p>
2
2009-02-23T06:14:30Z
[ "python" ]
PyGame not receiving events when 3+ keys are pressed at the same time
576,634
<p><em>I am developing a simple game in <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>... A rocket ship flying around and shooting stuff.</em> </p> <hr> <p><strong>Question:</strong> Why does pygame stop emitting keyboard events when too may keys are pressed at once?</p> <p><strong>About the Key Handling:</strong> The program has a number of variables like <code>KEYSTATE_FIRE, KEYSTATE_TURNLEFT</code>, etc...</p> <ol> <li>When a <code>KEYDOWN</code> event is handled, it sets the corresponding <code>KEYSTATE_*</code> variable to True.</li> <li>When a <code>KEYUP</code> event is handled, it sets the same variable to False.</li> </ol> <p><strong>The problem:</strong> If <code>UP-ARROW</code> and <code>LEFT-ARROW</code> are being pressed at the same time, pygame DOES NOT emit a <code>KEYDOWN</code> event when <code>SPACE</code> is pressed. This behavior varies depending on the keys. When pressing letters, it seems that I can hold about 5 of them before pygame stops emitting <code>KEYDOWN</code> events for additional keys.</p> <p><strong>Verification:</strong> In my main loop, I simply printed each event received to verify the above behavior.</p> <p><strong>The code:</strong> For reference, here is the (crude) way of handling key events at this point:</p> <pre><code>while GAME_RUNNING: FRAME_NUMBER += 1 CLOCK.tick(FRAME_PER_SECOND) #---------------------------------------------------------------------- # Check for events for event in pygame.event.get(): print event if event.type == pygame.QUIT: raise SystemExit() elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = False # remainder of game loop here... </code></pre> <p><strong>For pressing this sequence:</strong></p> <ul> <li><code>a (down)</code></li> <li><code>s (down)</code></li> <li><code>d (down)</code> </li> <li><code>f (down)</code> </li> <li><code>g (down)</code></li> <li><code>h (down)</code></li> <li><code>j (down)</code></li> <li><code>k (down)</code></li> <li><code>a (up)</code></li> <li><code>s (up)</code></li> <li><code>d (up)</code></li> <li><code>f (up)</code></li> <li><code>g (up)</code></li> <li><code>h (up)</code></li> <li><code>j (up)</code></li> <li><code>k (up)</code></li> </ul> <p><strong>Here is the output:</strong></p> <ul> <li><code>&lt;Event(2-KeyDown {'scancode': 30, 'key': 97, 'unicode': u'a', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 31, 'key': 115, 'unicode': u's', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 32, 'key': 100, 'unicode': u'd', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 33, 'key': 102, 'unicode': u'f', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 30, 'key': 97, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 31, 'key': 115, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 32, 'key': 100, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 33, 'key': 102, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 36, 'key': 106, 'unicode': u'j', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 37, 'key': 107, 'unicode': u'k', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 36, 'key': 106, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 37, 'key': 107, 'mod': 0})&gt;</code></li> </ul> <hr> <p>Is this a common issue? Is there a workaround? If not, what is the best way to handle multiple-key control issues when using pygame?</p>
3
2009-02-23T05:55:34Z
576,643
<p>This sounds like a input problem, not a code problem - are you sure the problem isn't the keyboard itself? Most keyboards have limitations on the number of keys that can be pressed at the same time. Often times you can't press more than a few keys that are close together at a time.</p> <p>To test it out, just start pressing and holding letters on the keyboard and see when new letters stop appearing.</p> <p>My suggestion is to try mapping SPACE to a different key somewhere else and see what happens.</p>
10
2009-02-23T06:02:08Z
[ "python", "pygame", "keyboard-events" ]
PyGame not receiving events when 3+ keys are pressed at the same time
576,634
<p><em>I am developing a simple game in <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>... A rocket ship flying around and shooting stuff.</em> </p> <hr> <p><strong>Question:</strong> Why does pygame stop emitting keyboard events when too may keys are pressed at once?</p> <p><strong>About the Key Handling:</strong> The program has a number of variables like <code>KEYSTATE_FIRE, KEYSTATE_TURNLEFT</code>, etc...</p> <ol> <li>When a <code>KEYDOWN</code> event is handled, it sets the corresponding <code>KEYSTATE_*</code> variable to True.</li> <li>When a <code>KEYUP</code> event is handled, it sets the same variable to False.</li> </ol> <p><strong>The problem:</strong> If <code>UP-ARROW</code> and <code>LEFT-ARROW</code> are being pressed at the same time, pygame DOES NOT emit a <code>KEYDOWN</code> event when <code>SPACE</code> is pressed. This behavior varies depending on the keys. When pressing letters, it seems that I can hold about 5 of them before pygame stops emitting <code>KEYDOWN</code> events for additional keys.</p> <p><strong>Verification:</strong> In my main loop, I simply printed each event received to verify the above behavior.</p> <p><strong>The code:</strong> For reference, here is the (crude) way of handling key events at this point:</p> <pre><code>while GAME_RUNNING: FRAME_NUMBER += 1 CLOCK.tick(FRAME_PER_SECOND) #---------------------------------------------------------------------- # Check for events for event in pygame.event.get(): print event if event.type == pygame.QUIT: raise SystemExit() elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = False # remainder of game loop here... </code></pre> <p><strong>For pressing this sequence:</strong></p> <ul> <li><code>a (down)</code></li> <li><code>s (down)</code></li> <li><code>d (down)</code> </li> <li><code>f (down)</code> </li> <li><code>g (down)</code></li> <li><code>h (down)</code></li> <li><code>j (down)</code></li> <li><code>k (down)</code></li> <li><code>a (up)</code></li> <li><code>s (up)</code></li> <li><code>d (up)</code></li> <li><code>f (up)</code></li> <li><code>g (up)</code></li> <li><code>h (up)</code></li> <li><code>j (up)</code></li> <li><code>k (up)</code></li> </ul> <p><strong>Here is the output:</strong></p> <ul> <li><code>&lt;Event(2-KeyDown {'scancode': 30, 'key': 97, 'unicode': u'a', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 31, 'key': 115, 'unicode': u's', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 32, 'key': 100, 'unicode': u'd', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 33, 'key': 102, 'unicode': u'f', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 30, 'key': 97, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 31, 'key': 115, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 32, 'key': 100, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 33, 'key': 102, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 36, 'key': 106, 'unicode': u'j', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 37, 'key': 107, 'unicode': u'k', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 36, 'key': 106, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 37, 'key': 107, 'mod': 0})&gt;</code></li> </ul> <hr> <p>Is this a common issue? Is there a workaround? If not, what is the best way to handle multiple-key control issues when using pygame?</p>
3
2009-02-23T05:55:34Z
576,646
<p>It may very well depend on the keyboard. My current no-name keyboard only supports two keys pressed at the same time, often a pain in games.</p>
1
2009-02-23T06:02:59Z
[ "python", "pygame", "keyboard-events" ]
PyGame not receiving events when 3+ keys are pressed at the same time
576,634
<p><em>I am developing a simple game in <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>... A rocket ship flying around and shooting stuff.</em> </p> <hr> <p><strong>Question:</strong> Why does pygame stop emitting keyboard events when too may keys are pressed at once?</p> <p><strong>About the Key Handling:</strong> The program has a number of variables like <code>KEYSTATE_FIRE, KEYSTATE_TURNLEFT</code>, etc...</p> <ol> <li>When a <code>KEYDOWN</code> event is handled, it sets the corresponding <code>KEYSTATE_*</code> variable to True.</li> <li>When a <code>KEYUP</code> event is handled, it sets the same variable to False.</li> </ol> <p><strong>The problem:</strong> If <code>UP-ARROW</code> and <code>LEFT-ARROW</code> are being pressed at the same time, pygame DOES NOT emit a <code>KEYDOWN</code> event when <code>SPACE</code> is pressed. This behavior varies depending on the keys. When pressing letters, it seems that I can hold about 5 of them before pygame stops emitting <code>KEYDOWN</code> events for additional keys.</p> <p><strong>Verification:</strong> In my main loop, I simply printed each event received to verify the above behavior.</p> <p><strong>The code:</strong> For reference, here is the (crude) way of handling key events at this point:</p> <pre><code>while GAME_RUNNING: FRAME_NUMBER += 1 CLOCK.tick(FRAME_PER_SECOND) #---------------------------------------------------------------------- # Check for events for event in pygame.event.get(): print event if event.type == pygame.QUIT: raise SystemExit() elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = False # remainder of game loop here... </code></pre> <p><strong>For pressing this sequence:</strong></p> <ul> <li><code>a (down)</code></li> <li><code>s (down)</code></li> <li><code>d (down)</code> </li> <li><code>f (down)</code> </li> <li><code>g (down)</code></li> <li><code>h (down)</code></li> <li><code>j (down)</code></li> <li><code>k (down)</code></li> <li><code>a (up)</code></li> <li><code>s (up)</code></li> <li><code>d (up)</code></li> <li><code>f (up)</code></li> <li><code>g (up)</code></li> <li><code>h (up)</code></li> <li><code>j (up)</code></li> <li><code>k (up)</code></li> </ul> <p><strong>Here is the output:</strong></p> <ul> <li><code>&lt;Event(2-KeyDown {'scancode': 30, 'key': 97, 'unicode': u'a', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 31, 'key': 115, 'unicode': u's', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 32, 'key': 100, 'unicode': u'd', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 33, 'key': 102, 'unicode': u'f', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 30, 'key': 97, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 31, 'key': 115, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 32, 'key': 100, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 33, 'key': 102, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 36, 'key': 106, 'unicode': u'j', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 37, 'key': 107, 'unicode': u'k', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 36, 'key': 106, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 37, 'key': 107, 'mod': 0})&gt;</code></li> </ul> <hr> <p>Is this a common issue? Is there a workaround? If not, what is the best way to handle multiple-key control issues when using pygame?</p>
3
2009-02-23T05:55:34Z
576,647
<p>Some keyboards cannot send certain keys together. Often this limit is reached with 3 keys.</p>
2
2009-02-23T06:03:05Z
[ "python", "pygame", "keyboard-events" ]
PyGame not receiving events when 3+ keys are pressed at the same time
576,634
<p><em>I am developing a simple game in <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>... A rocket ship flying around and shooting stuff.</em> </p> <hr> <p><strong>Question:</strong> Why does pygame stop emitting keyboard events when too may keys are pressed at once?</p> <p><strong>About the Key Handling:</strong> The program has a number of variables like <code>KEYSTATE_FIRE, KEYSTATE_TURNLEFT</code>, etc...</p> <ol> <li>When a <code>KEYDOWN</code> event is handled, it sets the corresponding <code>KEYSTATE_*</code> variable to True.</li> <li>When a <code>KEYUP</code> event is handled, it sets the same variable to False.</li> </ol> <p><strong>The problem:</strong> If <code>UP-ARROW</code> and <code>LEFT-ARROW</code> are being pressed at the same time, pygame DOES NOT emit a <code>KEYDOWN</code> event when <code>SPACE</code> is pressed. This behavior varies depending on the keys. When pressing letters, it seems that I can hold about 5 of them before pygame stops emitting <code>KEYDOWN</code> events for additional keys.</p> <p><strong>Verification:</strong> In my main loop, I simply printed each event received to verify the above behavior.</p> <p><strong>The code:</strong> For reference, here is the (crude) way of handling key events at this point:</p> <pre><code>while GAME_RUNNING: FRAME_NUMBER += 1 CLOCK.tick(FRAME_PER_SECOND) #---------------------------------------------------------------------- # Check for events for event in pygame.event.get(): print event if event.type == pygame.QUIT: raise SystemExit() elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = False # remainder of game loop here... </code></pre> <p><strong>For pressing this sequence:</strong></p> <ul> <li><code>a (down)</code></li> <li><code>s (down)</code></li> <li><code>d (down)</code> </li> <li><code>f (down)</code> </li> <li><code>g (down)</code></li> <li><code>h (down)</code></li> <li><code>j (down)</code></li> <li><code>k (down)</code></li> <li><code>a (up)</code></li> <li><code>s (up)</code></li> <li><code>d (up)</code></li> <li><code>f (up)</code></li> <li><code>g (up)</code></li> <li><code>h (up)</code></li> <li><code>j (up)</code></li> <li><code>k (up)</code></li> </ul> <p><strong>Here is the output:</strong></p> <ul> <li><code>&lt;Event(2-KeyDown {'scancode': 30, 'key': 97, 'unicode': u'a', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 31, 'key': 115, 'unicode': u's', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 32, 'key': 100, 'unicode': u'd', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 33, 'key': 102, 'unicode': u'f', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 30, 'key': 97, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 31, 'key': 115, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 32, 'key': 100, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 33, 'key': 102, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 36, 'key': 106, 'unicode': u'j', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(2-KeyDown {'scancode': 37, 'key': 107, 'unicode': u'k', 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 36, 'key': 106, 'mod': 0})&gt;</code></li> <li><code>&lt;Event(3-KeyUp {'scancode': 37, 'key': 107, 'mod': 0})&gt;</code></li> </ul> <hr> <p>Is this a common issue? Is there a workaround? If not, what is the best way to handle multiple-key control issues when using pygame?</p>
3
2009-02-23T05:55:34Z
579,243
<p>As others have eluded to already, certain (especially cheaper, lower-end) keyboards have a low quality <a href="http://en.wikipedia.org/wiki/Keyboard_technology#Keyboard_switch_matrix" rel="nofollow">keyboard matrix</a>. With these keyboards, certain key combinations will lead to the behavior you're experiencing. Another common side effect can be "ghost keys," where the an extra key press will appear in the input stream that was not actually pressed.</p> <p>The only solution (if the problem is related to the keyboard matrix) is to change your key mapping to use keys on different rows/columns of the matrix, or buy a keyboard with a better matrix.</p>
5
2009-02-23T20:42:15Z
[ "python", "pygame", "keyboard-events" ]
Writing a TTL decorator in Python
576,776
<p>I'm trying to write a TTL decorator in python. Basically I give it raise an exception if the function doesn't answer in the selected time.</p> <p>You can find the thead2 snippets on <a href="http://sebulba.wikispaces.com/recipe+thread2" rel="nofollow">http://sebulba.wikispaces.com/recipe+thread2</a></p> <pre><code>from thread2 import Thread """ A TTL decorator. """ class Worker(Thread): def __init__(self, q, f, args, kvargs): Thread.__init__(self) self.q = q self.f = f self.args = args self.kvargs = kvargs def run(self,): try: res = (True, self.f(*self.args, **self.kvargs)) self.q.put(res) except Exception, e: self.q.put((False, e)) class Referee(Thread): def __init__(self,q, ttl,exception_factory): Thread.__init__(self) self.exception_factory=exception_factory self.q=q self.ttl=ttl def run(self): time.sleep(self.ttl) res = (False, self.exception_factory()) self.q.put(res) def raise_if_too_long(ttl, exception_factory=lambda :RuntimeError("Timeout")): def raise_if_too_long_aux(f): def ritl(*args,**kvargs): q = Queue.Queue(2) referee = Referee(q, ttl, exception_factory) worker = Worker(q,f,args,kvargs) worker.start() referee.start() (valid, res)= q.get(1) q.task_done() referee.terminate() worker.terminate() if valid: return res else: raise res return ritl return raise_if_too_long_aux </code></pre> <p>However, I get some pretty bad result. It seems like sometimes the function is returning alright yet the decorator doesn't return until the TTL is reached and the error raises.</p> <p>Do you see something wrong in this code? Is there a common way/library to write function with a TTL in python?</p>
3
2009-02-23T07:16:49Z
576,801
<p>The code provided is a bit tough to follow -- how is it going to raise an exception in the right place at the right time in the right thread?</p> <p><strong>Consider this rough flow:</strong></p> <p>Decorator function called with target function. Return a function which:</p> <ol> <li>Starts thread, calling target function</li> <li>Joins to thread using thread.join([timeout])</li> <li>If you get a timeout, raise an exception, and ignore the result of the thread.</li> <li>If you don't get a timeout, capture the result of the thread and return it.</li> </ol> <p>(You would need to devise a way to capture the output of the thread...)</p> <p>See <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a> for info on the threading timeout... </p> <p><em>(Or just start using <a href="http://www.erlang.org" rel="nofollow">erlang</a> <strong><code>:)</code></em></strong></p>
5
2009-02-23T07:33:17Z
[ "python", "decorator", "ttl" ]
Writing a TTL decorator in Python
576,776
<p>I'm trying to write a TTL decorator in python. Basically I give it raise an exception if the function doesn't answer in the selected time.</p> <p>You can find the thead2 snippets on <a href="http://sebulba.wikispaces.com/recipe+thread2" rel="nofollow">http://sebulba.wikispaces.com/recipe+thread2</a></p> <pre><code>from thread2 import Thread """ A TTL decorator. """ class Worker(Thread): def __init__(self, q, f, args, kvargs): Thread.__init__(self) self.q = q self.f = f self.args = args self.kvargs = kvargs def run(self,): try: res = (True, self.f(*self.args, **self.kvargs)) self.q.put(res) except Exception, e: self.q.put((False, e)) class Referee(Thread): def __init__(self,q, ttl,exception_factory): Thread.__init__(self) self.exception_factory=exception_factory self.q=q self.ttl=ttl def run(self): time.sleep(self.ttl) res = (False, self.exception_factory()) self.q.put(res) def raise_if_too_long(ttl, exception_factory=lambda :RuntimeError("Timeout")): def raise_if_too_long_aux(f): def ritl(*args,**kvargs): q = Queue.Queue(2) referee = Referee(q, ttl, exception_factory) worker = Worker(q,f,args,kvargs) worker.start() referee.start() (valid, res)= q.get(1) q.task_done() referee.terminate() worker.terminate() if valid: return res else: raise res return ritl return raise_if_too_long_aux </code></pre> <p>However, I get some pretty bad result. It seems like sometimes the function is returning alright yet the decorator doesn't return until the TTL is reached and the error raises.</p> <p>Do you see something wrong in this code? Is there a common way/library to write function with a TTL in python?</p>
3
2009-02-23T07:16:49Z
5,914,987
<p>If you want the function's execution to be terminated after the timeout has been exceeded, you might want to try code that has that capability. To use the module, all that needs to be done is for your function to be called as an argument to <code>add_timeout</code>, and the returned value can run. Once called, the object's <code>ready</code> property can be polled, and anything returned can be accessed via the <code>value</code> property. The code's documentation should provide an explanation for the rest of the available API.</p> <pre><code>## {{{ http://code.activestate.com/recipes/577045/ (r2) #! /usr/bin/env python """Provide way to add timeout specifications to arbitrary functions. There are many ways to add a timeout to a function, but no solution is both cross-platform and capable of terminating the procedure. This module use the multiprocessing module to solve both of those problems.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell &lt;Noctis.Skytower@gmail.com&gt;' __date__ = '11 February 2010' __version__ = '$Revision: 3 $' ################################################################################ import inspect import sys import time import multiprocessing ################################################################################ def add_timeout(function, limit=60): """Add a timeout parameter to a function and return it. It is illegal to pass anything other than a function as the first parameter. If the limit is not given, it gets a default value equal to one minute. The function is wrapped and returned to the caller.""" assert inspect.isfunction(function) if limit &lt;= 0: raise ValueError() return _Timeout(function, limit) class NotReadyError(Exception): pass ################################################################################ def _target(queue, function, *args, **kwargs): """Run a function with arguments and return output via a queue. This is a helper function for the Process created in _Timeout. It runs the function with positional arguments and keyword arguments and then returns the function's output by way of a queue. If an exception gets raised, it is returned to _Timeout to be raised by the value property.""" try: queue.put((True, function(*args, **kwargs))) except: queue.put((False, sys.exc_info()[1])) class _Timeout: """Wrap a function and add a timeout (limit) attribute to it. Instances of this class are automatically generated by the add_timeout function defined above. Wrapping a function allows asynchronous calls to be made and termination of execution after a timeout has passed.""" def __init__(self, function, limit): """Initialize instance in preparation for being called.""" self.__limit = limit self.__function = function self.__timeout = time.clock() self.__process = multiprocessing.Process() self.__queue = multiprocessing.Queue() def __call__(self, *args, **kwargs): """Execute the embedded function object asynchronously. The function given to the constructor is transparently called and requires that "ready" be intermittently polled. If and when it is True, the "value" property may then be checked for returned data.""" self.cancel() self.__queue = multiprocessing.Queue(1) args = (self.__queue, self.__function) + args self.__process = multiprocessing.Process(target=_target, args=args, kwargs=kwargs) self.__process.daemon = True self.__process.start() self.__timeout = self.__limit + time.clock() def cancel(self): """Terminate any possible execution of the embedded function.""" if self.__process.is_alive(): self.__process.terminate() @property def ready(self): """Read-only property indicating status of "value" property.""" if self.__queue.full(): return True elif not self.__queue.empty(): return True elif self.__timeout &lt; time.clock(): self.cancel() else: return False @property def value(self): """Read-only property containing data returned from function.""" if self.ready is True: flag, load = self.__queue.get() if flag: return load raise load raise NotReadyError() def __get_limit(self): return self.__limit def __set_limit(self, value): if value &lt;= 0: raise ValueError() self.__limit = value limit = property(__get_limit, __set_limit, doc="Property for controlling the value of the timeout.") ## end of http://code.activestate.com/recipes/577045/ }}} </code></pre>
0
2011-05-06T17:37:34Z
[ "python", "decorator", "ttl" ]
Is there a known Win32 Tkinter bug with respect to displaying photos on a canvas?
576,843
<p>I'm noticing a pretty strange bug with tkinter, and I am wondering if it's because there's something in how the python interacts with the tcl, at least in Win32.</p> <p>Here I have a super simple program that displays a gif image. It works perfectly.</p> <pre><code>from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') canvas.pack() photo=PhotoImage(file=sys.argv[1]) canvas.create_image(0, 0, image=photo, anchor=NW) # embed a photo print canvas print photo mainloop( ) </code></pre> <p>Now, I change the program slightly to edit the canvas object from within a function. This time, I just get a blank canvas.</p> <pre><code># demo all basic canvas interfaces from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') canvas.pack() def set_canvas(cv): photo=PhotoImage(file=sys.argv[1]) cv.create_image(0, 0, image=photo, anchor=NW) # embed a photo print cv print photo set_canvas(canvas) mainloop( ) </code></pre> <p>The only difference between the two is that in one the canvas object is passed to a function instead of being used directly. Both print statements return identical results. I am wondering if there is perhaps some breakdown in the object model at the tcl/python layer.</p> <p>Any thoughts, folks?</p> <p>Thanks, /YGA</p>
3
2009-02-23T07:55:51Z
579,364
<p>Do that as a quick solution, and I'll try to explain:</p> <pre><code>def set_canvas(cv): global photo # here! photo=PhotoImage(file=sys.argv[1]) cv.create_image(0, 0, image=photo, anchor=NW) # embed a photo print cv print photo </code></pre> <p>A PhotoImage needs to have at least one reference from any Python object, otherwise it's garbage collected. In my solution, I suggest to make <code>photo</code> be a module-level name, so when the function ends, there will still be a reference to the PhotoImage object. You might prefer to create a class and make <code>set_canvas</code> into a method, and store the PhotoImage object as an instance variable.</p>
6
2009-02-23T21:08:36Z
[ "python", "user-interface", "winapi", "tkinter" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
576,954
<p>I'm not sure if this is the best approach, but here's what I typically do to retrieve a record set using a DB-API 2 compliant module:</p> <pre><code>cursor.execute("""SELECT foo, bar, baz, quux FROM table WHERE id = %s;""", (interesting_record_id,)) for foo, bar, baz, quux in cursor.fetchall(): frobnicate(foo + bar, baz * quux) </code></pre> <p>The query formatting method is one of the DB-API standards, but happens to be the preferred method for Psycopg2; other DB-API adapters might suggest a different convention which will be fine.</p> <p>Writing queries like this, where implicit tuple unpacking is used to work with the result set, has typically been more effective for me than trying to worry about matching Python variable names to SQL column names (which I usually only use to drop prefixes, and then only if I'm working with a subset of the column names such that the prefixes don't help to clarify things anymore), and is <em>much</em> better than remembering numerical column IDs.</p> <p>This style also helps you avoid <code>SELECT * FROM table...</code>, which is just a maintenance disaster for anything but the simplest tables and queries.</p> <p>So, not exactly the answer you were asking for, but possibly enlightening nonetheless.</p>
9
2009-02-23T09:01:05Z
[ "python", "sqlite" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
577,004
<p>To access columns by name, use the <a href="http://oss.itsystementwicklung.de/download/pysqlite/doc/sqlite3.html#sqlite3.Connection.row_factory"><code>row_factory</code></a> attribute of the Connection instance. It lets you set a function that takes the arguments <code>cursor</code> and <code>row</code>, and return whatever you'd like. There's a few builtin to pysqlite, namely <code>sqlite3.Row</code>, which does what you've asked.</p>
13
2009-02-23T09:25:44Z
[ "python", "sqlite" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
577,916
<p>The SQLite API supports cursor.description so you can easily do it like this</p> <pre><code>headers = {} for record in cursor.fetchall(): if not headers: headers = dict((desc[0], idx) for idx,desc in cursor.description)) data.append(record[headers['column_name']]) </code></pre> <p>A little long winded but gets the job done. I noticed they even have it in the factory.py file under dict_factory.</p>
1
2009-02-23T15:06:27Z
[ "python", "sqlite" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
7,099,412
<p>This can be done by adding a single line after the "connect" statment:</p> <pre><code>conn.row_factory = sqlite3.Row </code></pre> <p>Check the documentation here: <a href="http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index">http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index</a></p>
8
2011-08-17T21:00:19Z
[ "python", "sqlite" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
11,664,048
<p>kushal's answer to <a href="http://www.gossamer-threads.com/lists/python/python/755969" rel="nofollow">this forum</a> works fine:</p> <blockquote> <p>Use a DictCursor:</p> </blockquote> <pre><code>import MySQLdb.cursors . . . cursor = db.cursor (MySQLdb.cursors.DictCursor) cursor.execute (query) rows = cursor.fetchall () for row in rows: print row['employee_id'] </code></pre> <p>Please take note that the column name is case sensitive. </p>
1
2012-07-26T06:59:46Z
[ "python", "sqlite" ]
How can I reference columns by their names in python calling SQLite?
576,933
<p>I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite:</p> <pre><code>cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) </code></pre> <p>This gives the following error:</p> <pre><code> TypeError: tuple indices must be integers </code></pre> <p>Whereas if I change the reference to use a column number, it works fine:</p> <pre><code> data.append(row[1]) </code></pre> <p>Can I execute the query in such a way that I can reference columns by their names?</p>
10
2009-02-23T08:50:12Z
20,042,292
<p>In the five years since the question was asked and then answered, a very simple solution has arisen. Any new code can simply wrap the connection object with a row factory. Code example:</p> <pre><code>import sqlite3 conn = sqlite3.connect('./someFile') conn.row_factory = sqlite3.Row // Here's the magic! cursor = conn.execute("SELECT name, age FROM someTable") for row in cursor: print(row['name']) </code></pre> <p>Here are some <a href="http://docs.python.org/2/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index">fine docs</a>. Enjoy!</p>
8
2013-11-18T07:27:11Z
[ "python", "sqlite" ]
How do I design sms service?
576,940
<p>I want to design a website that can send and receive sms.</p> <ol> <li>How should I approach the problem ?</li> <li>What are the resources available ?</li> <li>I know php,python what else do I need or are the better options available?</li> <li>How can experiment using my pc only?[somthing like localhost]</li> <li>What are some good hosting services for this? [edit this]</li> <li>[Add more questions you can think of?]</li> </ol>
1
2009-02-23T08:53:45Z
576,947
<p>You need a SMS server. <a href="http://www.ozeki.hu/" rel="nofollow">This</a> should get you started.</p>
0
2009-02-23T08:55:54Z
[ "php", "python", "sms", "mobile-phones", "bulksms" ]
How do I design sms service?
576,940
<p>I want to design a website that can send and receive sms.</p> <ol> <li>How should I approach the problem ?</li> <li>What are the resources available ?</li> <li>I know php,python what else do I need or are the better options available?</li> <li>How can experiment using my pc only?[somthing like localhost]</li> <li>What are some good hosting services for this? [edit this]</li> <li>[Add more questions you can think of?]</li> </ol>
1
2009-02-23T08:53:45Z
576,959
<p>You can take a look at <a href="http://www.kannel.org" rel="nofollow">Kannel</a>. It's so simple to create SMS services using it. Just define a keyword, then put in the URL to which the incoming SMS request will be routed (you'll get the info such as mobile number and SMS text in query string parameters), then whatever output your web script generates (you can use any web scripting/language/platform) will be sent back to the sender.</p> <p>It's simple to test. You can use your own PC and just use the fakesmsc "SMS center" and just send it HTTP requests. If you have a GSM modem you can use that too, utilising the modem's AT command set.</p>
3
2009-02-23T09:04:35Z
[ "php", "python", "sms", "mobile-phones", "bulksms" ]
How do I design sms service?
576,940
<p>I want to design a website that can send and receive sms.</p> <ol> <li>How should I approach the problem ?</li> <li>What are the resources available ?</li> <li>I know php,python what else do I need or are the better options available?</li> <li>How can experiment using my pc only?[somthing like localhost]</li> <li>What are some good hosting services for this? [edit this]</li> <li>[Add more questions you can think of?]</li> </ol>
1
2009-02-23T08:53:45Z
577,001
<p>First thing, You need to sign up for an account (SMS gateway), most of them also give you example code how to send and receive sms using their API. Then you will wrap the the sms functionality around your sites logic. </p> <p>e.g <a href="http://www.clickatell.com/developers/php.php" rel="nofollow">http://www.clickatell.com/developers/php.php</a></p>
2
2009-02-23T09:25:06Z
[ "php", "python", "sms", "mobile-phones", "bulksms" ]
How do I design sms service?
576,940
<p>I want to design a website that can send and receive sms.</p> <ol> <li>How should I approach the problem ?</li> <li>What are the resources available ?</li> <li>I know php,python what else do I need or are the better options available?</li> <li>How can experiment using my pc only?[somthing like localhost]</li> <li>What are some good hosting services for this? [edit this]</li> <li>[Add more questions you can think of?]</li> </ol>
1
2009-02-23T08:53:45Z
577,345
<p>Since my company does this sometimes (text promotions etc, though our main focus is much much lower level stuff), I figured I should pitch in.</p> <p>By far the simplest way is to use a service such as <a href="http://www.clickatell.com" rel="nofollow">Clickatell</a>, which provides a HTTP API, as well as FTP and <a href="http://en.wikipedia.org/wiki/SMPP" rel="nofollow">SMPP</a> amongst others. I don't know how Clickatell deals with receiving messages, however, as we use direct SMPP binds to our local mobile operators for this.</p> <p>If you are willing to pay for it, you should be able to get an SMPP bind to your local mobile operator, but its often expensive. This would also allow you to purchase your own <a href="http://en.wikipedia.org/wiki/Short_code" rel="nofollow">shortcode</a>.</p> <p>You may also want to give <a href="http://www.mblox.com/" rel="nofollow">mBlox</a> or <a href="http://netxcell.com/bulk_sms_gateway.html" rel="nofollow">Nextcell</a> a look. A quick <a href="http://www.google.com/?q=sms+gateway+provider" rel="nofollow">Google search</a> will turn up more.</p> <p>you could also buy a GSM modem, which would allow you to send and receive messages as you normally would with a phone, except through a PC. This usually means you will pay whatever you would with a phone. (In Ireland anyway)</p>
0
2009-02-23T11:32:17Z
[ "php", "python", "sms", "mobile-phones", "bulksms" ]
How do I design sms service?
576,940
<p>I want to design a website that can send and receive sms.</p> <ol> <li>How should I approach the problem ?</li> <li>What are the resources available ?</li> <li>I know php,python what else do I need or are the better options available?</li> <li>How can experiment using my pc only?[somthing like localhost]</li> <li>What are some good hosting services for this? [edit this]</li> <li>[Add more questions you can think of?]</li> </ol>
1
2009-02-23T08:53:45Z
577,357
<p>I've copied this from an <a href="http://stackoverflow.com/questions/432944/sms-from-web-application/433020#433020">answer I gave</a> in relation to <a href="http://stackoverflow.com/questions/432944/sms-from-web-application/">this question</a>. However, in addition to the text below, take a look at <a href="http://sms.wadja.com/" rel="nofollow">Wadja's SMS Gateway</a> deals (<a href="http://wadja.com/api" rel="nofollow">API link</a>)... they appear to be a really good option at the moment, though I've not used them, personally.</p> <blockquote> <p>Your main option for sending SMS messages is using an existing SMS provider. In my experience (which is extensive with SMS messaging web applications), you will often find that negotiating with different providers is the best way to get the best deal for your application.</p> <p>Different providers often offer different services, and different features. My favourite provider, and indeed, the one that has happily negotiated with me for lower rates in the past, is TM4B (<a href="http://www.tm4b.com" rel="nofollow">http://www.tm4b.com</a>). These guys have excellent rates, cover a huge proportion of the globe, and have excellent customer service.</p> <p>Below is some code extracted (and some parts obfuscated) from one of my live web applications, for sending a simple message via their API:</p> </blockquote> <pre><code>require_once("tm4b.lib.php"); $smsEngine = new tm4b(); // Prepare the array for sending $smsRequest["username"] = "YOURUNAME"; $smsRequest["password"] = "YOURPWORD"; $smsRequest["to"] = "+441234554443"; $smsRequest["from"] = "ME!"; $smsRequest["msg"] = "Hello, test message!"; // Do the actual sending $smsResult = $smsEngine-&gt;ClientAPI($smsRequest); // Check the result if( $smsResult['status'] == "ok" ) { print "Message sent!"; } else { print "Message not sent."; } </code></pre> <blockquote> <p>Many other providers that I've used in the past, have very similar interfaces, and all are really competitive when it comes to pricing. You simply have to look around for a provider that suits your needs.</p> <p>In regard to cost, you're looking at prices ranging from a few pence/cents for most Western countries (prices are a little bit higher for most third-world countries, though, so beware). Most providers you will have to pay in bulk, if you want decent rates from them, but they'll often negotiate with you for 'smaller-than-usual' batches. Most providers do offer a post-pay option, but only when you've successfully completed a few transactions with them... others offer it from the start, but the prices are extortionate.</p> </blockquote> <p>Hope it helps!</p>
2
2009-02-23T11:38:17Z
[ "php", "python", "sms", "mobile-phones", "bulksms" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
576,976
<p>It's only wasteful if you don't have disk to spare. That is, fix it when it's a problem. Your solution looks ok as a first attempt.</p> <p>It's not wasteful of memory because a file handler is a stream.</p>
1
2009-02-23T09:15:35Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
576,984
<p>Yes, open() treats the file as a stream, as does readline(). It'll only read the next line. If you call read(), however, it'll read everything into memory.</p> <p>Your example code looks ok at first glance. Almost every solution will require you to copy the file elsewhere. Its not exactly easy to modify the contents of a file inplace without a 1:1 replacement.</p> <p>It <em>may</em> be faster to use some standard unix utilities (awk and sed most likely), but I lack the unix and bash-fu necessary to provide a full solution.</p>
4
2009-02-23T09:18:55Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
576,995
<p>Reading lines is simply done using a <a href="http://docs.python.org/library/stdtypes.html#file.next" rel="nofollow">file iterator</a>:</p> <pre><code>for line in fin: if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") </code></pre> <p>Also consider the <a href="http://docs.python.org/library/csv.html#writer-objects" rel="nofollow">CSV writer object</a> to write CSV files, e.g:</p> <pre><code>import csv writer = csv.writer(open("some.csv", "wb")) writer.writerows(someiterable) </code></pre>
1
2009-02-23T09:23:05Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
577,047
<p>[For the problem exactly as stated] There's no way that this can be done without copying the data, in python or any other language. If your processing always replaced substrings with new substrings of <em>equal length</em>, maybe you could do it in-place. But whenever you replace <code>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;></code> with <code>"</code> you are changing the position of all subsequent characters in the file. Copying from one place to another is the only way to handle this. </p> <p>EDIT:</p> <p>Note that the use of <code>sed</code> won't actually save any copying...sed doesn't really edit in-place either. From the <a href="http://www.gnu.org/software/sed/manual/html_node/Invoking-sed.html#fn-1" rel="nofollow">GNU sed manual</a>: </p> <blockquote> -i[SUFFIX]<br/> --in-place[=SUFFIX]<br/> This option specifies that files are to be edited in-place. GNU sed does this by <em>creating a temporary file</em> and sending output to this file rather than to the standard output. </blockquote> <p>(emphasis mine.)</p>
0
2009-02-23T09:44:55Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
577,068
<p>If you're delimiting fields with double quotes, it looks like you need to escape the double quotes you have occurring in your elements (for example <code>1231214 ""</code> will need to be <code>\n1231214 \"\"</code>).</p> <p>Something like</p> <pre><code>fin = open("input", "r") fout = open("output", "w") for line in fin: if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line.replace('"',r'\"') fin.close() fout.close() </code></pre>
0
2009-02-23T09:55:01Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
577,158
<p>@richard-levasseur</p> <p>I agree, <code>sed</code> seems like the right way to go. Here's a rough cut at what the OP describes:</p> <pre><code> sed -i -e's/&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;/"/g' foo.txt </code></pre> <p>This will do the replacement in-place in the existing <code>foo.txt</code>. For that reason, I recommend having the original file under some sort of version control; any of the DVCS should fit the bill.</p>
5
2009-02-23T10:27:42Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
577,867
<p>With python you will have to create a new file for safety sake, it will cause alot less headaches than trying to write in place.</p> <p>The below listed reads your input 1 line at a time and buffers the columns (from what I understood of your test input file was 1 row) and then once the end of row delimiter is hit it will write that buffer to disk, flushing manually every 1000 lines of the original file. This will save some IO as well instead of writing every segment, 1000 writes of 32 bytes each will be faster than 4000 writes of 8 bytes.</p> <pre><code>fin = open(input_fn, "rb") fout = open(output_fn, "wb") row_delim = "&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;" write_buffer = [] for i, line in enumerate(fin): if not i % 1000: fout.flush() if row_delim in line and i: fout.write('"%s"\r\n'%'","'.join(write_buffer)) write_buffer = [] else: write_buffer.append(line.strip()) </code></pre> <p>Hope that helps.</p> <p>EDIT: Forgot to mention, while using .readline() is not a bad thing don't use .readlines() which will go and read the entire content of the file into a list containing each line which is incredibly inefficient. Using the built in iterator that comes with a file object is the best memory usage and speed.</p>
1
2009-02-23T14:53:51Z
[ "python", "file", "csv" ]
How can I change a huge file into csv in python
576,967
<p>I'm a beginner in python. I have a huge text file (hundreds of GB) and I want to convert the file into csv file. In my text file, I know the row delimiter is a string "&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>". If a line contains that string, I want to replace it with ". Is there a way to do it without having to read the old file and rewriting a new file.</p> <p>Normally I thought I need to do something like this:</p> <pre><code>fin = open("input", "r") fout = open("outpout", "w") line = f.readline while line != "": if line.contains("&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;"): fout.writeline("\"") else: fout.writeline(line) line = f.readline </code></pre> <p>but copying hundreds of GB is wasteful. Also I don't know if open will eat lots of memory (does it treat file handler as a stream?)</p> <p>Any help is greatly appreciated.</p> <p>Note: an example of the file would be</p> <pre><code>file.txt &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; abcdefeghsduai asdjliwa 1231214 "" &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; </code></pre> <p>would be one row and one column in csv.</p>
2
2009-02-23T09:10:01Z
580,169
<p>@Constatin suggests that if you would be satisfied with replacing <pre><code>'&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>&lt;>\n'</code></pre> by <pre><code>'" \n'</code></pre> then the replacement string is the same length, and in that case you can craft a solution to in-place editing with <code>mmap</code>. You will need python 2.6. It's vital that the file is opened in the right mode!</p> <pre><code> import mmap, os CHUNK = 2**20 oldStr = '' newStr = '" ' strLen = len(oldStr) assert strLen==len(newStr) f = open("myfilename", "r+") size = os.fstat(f.fileno()).st_size for offset in range(0,size,CHUNK): map = mmap.mmap(f.fileno(), length=min(CHUNK+strLen,size-offset), # not beyond EOF offset=offset) index = 0 # start at beginning while 1: index = map.find(oldStr,index) # find next match if index == -1: # no more matches in this map break map[index:index+strLen] = newStr f.close() </code></pre> <p>This code is not debugged! It works for me on a 3 MB test case, but it <em>may not</em> work on a large ( > 2GB) file - the <code>mmap</code> module still seems a bit immature, so I wouldn't rely on it too much.</p> <p>Looking at the bigger picture, from what you've posted it isn't clear that your file will end up as valid CSV. Also be aware that the tool you're planning to use to actually process the CSV may be flexible enough to deal with the file as it stands.</p>
1
2009-02-24T01:59:12Z
[ "python", "file", "csv" ]
How to exit a module before it has finished parsing?
577,119
<p>I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the <code>ImportError</code> exception in the case the module doesn't exist, how can I stop Python from parsing the rest of the module? I'm open to other solutions if that's not possible.</p> <p>Here is a basic example (selfaware.py):</p> <pre><code>try: from skynet import SkyNet except ImportError: class SelfAwareSkyNet(): pass exit_module_parsing_here() class SelfAwareSkyNet(SkyNet): pass </code></pre> <p>The only ways I can think to do this is:</p> <ul> <li>Before importing the <code>selfaware.py</code> module, check if the <code>skynet</code> module is available, and simply pass or create a stub class. This will cause DRY if <code>selfaware.py</code> is imported multiple times.</li> <li><p>Within <code>selfaware.py</code> have the class defined withing the <code>try</code> block. e.g.:</p> <pre><code>try: from skynet import SkyNet class SelfAwareSkyNet(SkyNet): pass except ImportError: class SelfAwareSkyNet(): pass </code></pre></li> </ul>
4
2009-02-23T10:15:09Z
577,172
<p>You could use:</p> <pre><code>try: from skynet import SkyNet inherit_from = SkyNet except ImportError: inherit_from = object class SelfAwareSkyeNet(inherit_from): pass </code></pre> <p>This works only if the implementation do not differ.</p> <p><strong>Edit:</strong> New solution after comment.</p>
2
2009-02-23T10:34:43Z
[ "python", "import", "module" ]
How to exit a module before it has finished parsing?
577,119
<p>I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the <code>ImportError</code> exception in the case the module doesn't exist, how can I stop Python from parsing the rest of the module? I'm open to other solutions if that's not possible.</p> <p>Here is a basic example (selfaware.py):</p> <pre><code>try: from skynet import SkyNet except ImportError: class SelfAwareSkyNet(): pass exit_module_parsing_here() class SelfAwareSkyNet(SkyNet): pass </code></pre> <p>The only ways I can think to do this is:</p> <ul> <li>Before importing the <code>selfaware.py</code> module, check if the <code>skynet</code> module is available, and simply pass or create a stub class. This will cause DRY if <code>selfaware.py</code> is imported multiple times.</li> <li><p>Within <code>selfaware.py</code> have the class defined withing the <code>try</code> block. e.g.:</p> <pre><code>try: from skynet import SkyNet class SelfAwareSkyNet(SkyNet): pass except ImportError: class SelfAwareSkyNet(): pass </code></pre></li> </ul>
4
2009-02-23T10:15:09Z
577,211
<p>try: supports an else: clause</p> <pre><code>try: from skynet import SkyNet except ImportError: class SelfAwareSkyNet(): pass else: class SelfAwareSkyNet(SkyNet): pass </code></pre>
8
2009-02-23T10:51:16Z
[ "python", "import", "module" ]
Python "extend" for a dictionary
577,234
<p>Which is the best way to extend a dictionary with another one? For instance:</p> <pre><code>&gt;&gt;&gt; a = { "a" : 1, "b" : 2 } &gt;&gt;&gt; b = { "c" : 3, "d" : 4 } &gt;&gt;&gt; a {'a': 1, 'b': 2} &gt;&gt;&gt; b {'c': 3, 'd': 4} </code></pre> <p>I'm looking for any operation to obtain this avoiding <code>for</code> loop:</p> <pre><code>{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } </code></pre> <p>I wish to do something like:</p> <pre><code>a.extend(b) # This does not work </code></pre>
211
2009-02-23T10:59:32Z
577,241
<pre><code>a.update(b) </code></pre> <p><a href="http://docs.python.org/2/library/stdtypes.html#dict.update">Python Standard Library Documentation</a></p>
352
2009-02-23T11:01:49Z
[ "python", "dictionary" ]
Python "extend" for a dictionary
577,234
<p>Which is the best way to extend a dictionary with another one? For instance:</p> <pre><code>&gt;&gt;&gt; a = { "a" : 1, "b" : 2 } &gt;&gt;&gt; b = { "c" : 3, "d" : 4 } &gt;&gt;&gt; a {'a': 1, 'b': 2} &gt;&gt;&gt; b {'c': 3, 'd': 4} </code></pre> <p>I'm looking for any operation to obtain this avoiding <code>for</code> loop:</p> <pre><code>{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } </code></pre> <p>I wish to do something like:</p> <pre><code>a.extend(b) # This does not work </code></pre>
211
2009-02-23T10:59:32Z
577,245
<pre><code>a.update(b) </code></pre> <p>Will add keys and values from <em>b</em> to <em>a</em>, overwriting if there's already a value for a key.</p>
18
2009-02-23T11:04:22Z
[ "python", "dictionary" ]
Python "extend" for a dictionary
577,234
<p>Which is the best way to extend a dictionary with another one? For instance:</p> <pre><code>&gt;&gt;&gt; a = { "a" : 1, "b" : 2 } &gt;&gt;&gt; b = { "c" : 3, "d" : 4 } &gt;&gt;&gt; a {'a': 1, 'b': 2} &gt;&gt;&gt; b {'c': 3, 'd': 4} </code></pre> <p>I'm looking for any operation to obtain this avoiding <code>for</code> loop:</p> <pre><code>{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } </code></pre> <p>I wish to do something like:</p> <pre><code>a.extend(b) # This does not work </code></pre>
211
2009-02-23T10:59:32Z
1,552,420
<p>A beautiful gem in <a href="http://stackoverflow.com/questions/1551666/how-can-2-python-dictionaries-become-1/1551878#1551878">this closed question</a>:</p> <p>The "oneliner way", altering neither of the input dicts, is</p> <pre><code>basket = dict(basket_one, **basket_two) </code></pre> <p>Learn what <a href="http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/"><code>**basket_two</code> (the <code>**</code>) means here</a>.</p> <p>In case of conflict, the items from <code>basket_two</code> will override the ones from <code>basket_one</code>. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or her towards learning about <code>dict</code> and the <code>**</code> form;-). So, for example, uses like:</p> <pre><code>x = mungesomedict(dict(adict, **anotherdict)) </code></pre> <p>are reasonably frequent occurrences in my code.</p> <p>Originally submitted by <a href="http://stackoverflow.com/users/95810/alex-martelli">Alex Martelli</a></p> <p><strong><em>Note:</em> In Python 3, this will only work if every key in basket_two is a <code>string</code>.</strong></p>
109
2009-10-12T02:27:52Z
[ "python", "dictionary" ]
Python "extend" for a dictionary
577,234
<p>Which is the best way to extend a dictionary with another one? For instance:</p> <pre><code>&gt;&gt;&gt; a = { "a" : 1, "b" : 2 } &gt;&gt;&gt; b = { "c" : 3, "d" : 4 } &gt;&gt;&gt; a {'a': 1, 'b': 2} &gt;&gt;&gt; b {'c': 3, 'd': 4} </code></pre> <p>I'm looking for any operation to obtain this avoiding <code>for</code> loop:</p> <pre><code>{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } </code></pre> <p>I wish to do something like:</p> <pre><code>a.extend(b) # This does not work </code></pre>
211
2009-02-23T10:59:32Z
12,697,215
<p>As others have mentioned, <code>a.update(b)</code> for some dicts <code>a</code> and <code>b</code> will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the <code>extend</code> method of mapping/set objects desire that in the syntax <code>a.extend(b)</code>, <code>a</code>'s values should NOT be overwritten by <code>b</code>'s values. <code>a.update(b)</code> overwrites <code>a</code>'s values, and so isn't a good choice for <code>extend</code>.</p> <p>Note that some languages call this method <code>defaults</code> or <code>inject</code>, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.</p> <p>Of course, you could simple note that <code>a.extend(b)</code> is nearly the same as <code>b.update(a); a=b</code>. To remove the assignment, you could do it thus:</p> <pre><code>def extend(a,b): """Create a new dictionary with a's properties extended by b, without overwriting. &gt;&gt;&gt; extend({'a':1,'b':2},{'b':3,'c':4}) {'a': 1, 'c': 4, 'b': 2} """ return dict(b,**a) </code></pre> <p>Thanks to Tom Leys for that smart idea using a side-effect-less <code>dict</code> constructor for <code>extend</code>.</p>
12
2012-10-02T19:48:15Z
[ "python", "dictionary" ]
gtk TextView widget doesn't update during function
577,302
<p>I'm new to GUI programming with python and gtk, so this is a bit of a beginners question. I have a function that is called when a button is pressed which does various tasks, and a TextView widget which I write to after each task is completed. The problem is that the TextView widget doesn't update until the entire function has finished. I need it to update after each task.</p>
0
2009-02-23T11:18:37Z
577,461
<p>After each update to the TextView call</p> <pre><code>while gtk.events_pending(): gtk.main_iteration() </code></pre> <p>You can do your update through a custom function:</p> <pre><code>def my_insert(self, widget, report, text): report.insert_at_cursor(text) while gtk.events_pending(): gtk.main_iteration() </code></pre> <p>From the PyGTK FAQ: <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq03.007.htp" rel="nofollow">How can I force updates to the application windows during a long callback or other internal operation?</a></p>
4
2009-02-23T12:17:22Z
[ "python", "gtk", "pygtk" ]
Django - how do I _not_ dispatch a signal?
577,376
<p>I wrote some smart generic counters and managers for my models (to avoid <code>select count</code> queries etc.). Therefore I got some heavy logic going on for post_save. </p> <p>I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be:</p> <pre><code>instance.save(dispatch_signal=False) </code></pre> <p>How can I accomplish this?</p> <p><hr /></p> <p><strong>Update</strong></p> <p>More information about what I'm doing, if anyone's interested:</p> <ol> <li>Generic counters are stored in a separate table</li> <li>Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.</li> <li>Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.</li> <li>I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.</li> <li>For testing purposes I run my little command-extension -- <a href="http://code.google.com/p/dilla" rel="nofollow">Dilla</a>, to populate random data around.</li> <li>I've noticed unwanted signals triggering, therefore I'd like them to run conditionally. </li> </ol> <p>Hope it's clear enough. Excuse my language mistakes.</p>
4
2009-02-23T11:45:25Z
577,432
<p>A quick and dirty solution would be:</p> <pre><code>from django.db.models.signals import post_save from somewhere_in_my_app import my_post_save_handler post_save.disconnect(my_post_save_handler) instance.save() post_save.connect(my_post_save_handler) </code></pre> <p>But otherwise i strongly recommend moving your logic into the <code>save()</code> method of your model.</p>
11
2009-02-23T12:05:29Z
[ "python", "django", "django-signals" ]
Django - how do I _not_ dispatch a signal?
577,376
<p>I wrote some smart generic counters and managers for my models (to avoid <code>select count</code> queries etc.). Therefore I got some heavy logic going on for post_save. </p> <p>I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be:</p> <pre><code>instance.save(dispatch_signal=False) </code></pre> <p>How can I accomplish this?</p> <p><hr /></p> <p><strong>Update</strong></p> <p>More information about what I'm doing, if anyone's interested:</p> <ol> <li>Generic counters are stored in a separate table</li> <li>Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.</li> <li>Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.</li> <li>I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.</li> <li>For testing purposes I run my little command-extension -- <a href="http://code.google.com/p/dilla" rel="nofollow">Dilla</a>, to populate random data around.</li> <li>I've noticed unwanted signals triggering, therefore I'd like them to run conditionally. </li> </ol> <p>Hope it's clear enough. Excuse my language mistakes.</p>
4
2009-02-23T11:45:25Z
1,420,789
<p>You can also call <code>instance.save_base(raw=True)</code> and check for the <code>raw</code> argument in your <code>pre_save</code> or <code>post_save</code> signal handler:</p> <pre><code>def my_post_save_handler(instance, raw, **kwargs): if not raw: heavy_logic() </code></pre> <p>You can add some sugar and get your perfect interface:</p> <pre><code>class MyModel: def save(self, dispatch_signal=True, **kwargs): self.save_base(raw=not dispatch_signal, **kwargs) </code></pre> <p>Note that <code>save_base()</code> is not part of the public API of Django, so it might change in a future version.</p>
2
2009-09-14T10:39:02Z
[ "python", "django", "django-signals" ]
Django - how do I _not_ dispatch a signal?
577,376
<p>I wrote some smart generic counters and managers for my models (to avoid <code>select count</code> queries etc.). Therefore I got some heavy logic going on for post_save. </p> <p>I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be:</p> <pre><code>instance.save(dispatch_signal=False) </code></pre> <p>How can I accomplish this?</p> <p><hr /></p> <p><strong>Update</strong></p> <p>More information about what I'm doing, if anyone's interested:</p> <ol> <li>Generic counters are stored in a separate table</li> <li>Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.</li> <li>Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.</li> <li>I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.</li> <li>For testing purposes I run my little command-extension -- <a href="http://code.google.com/p/dilla" rel="nofollow">Dilla</a>, to populate random data around.</li> <li>I've noticed unwanted signals triggering, therefore I'd like them to run conditionally. </li> </ol> <p>Hope it's clear enough. Excuse my language mistakes.</p>
4
2009-02-23T11:45:25Z
10,881,618
<p>You can disconnect and reconnect the signal. Try using a <code>with:</code> statement with this utility class:</p> <pre><code>class SignalBlocker(object): def __init__(self, signal, receiver, **kwargs): self.signal = signal self.receiver = receiver self.kwargs = kwargs def __enter__(self, *args, **kwargs): self.signal.disconnect(self.receiver) def __exit__(self, *args, **kwargs): self.signal.connect(self.receiver, **self.kwargs) </code></pre> <p>You can now use:</p> <pre><code>with SignalBlocker(post_save, my_post_save_handler): instance.save() </code></pre>
11
2012-06-04T12:49:48Z
[ "python", "django", "django-signals" ]
Django - how do I _not_ dispatch a signal?
577,376
<p>I wrote some smart generic counters and managers for my models (to avoid <code>select count</code> queries etc.). Therefore I got some heavy logic going on for post_save. </p> <p>I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be:</p> <pre><code>instance.save(dispatch_signal=False) </code></pre> <p>How can I accomplish this?</p> <p><hr /></p> <p><strong>Update</strong></p> <p>More information about what I'm doing, if anyone's interested:</p> <ol> <li>Generic counters are stored in a separate table</li> <li>Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.</li> <li>Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.</li> <li>I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.</li> <li>For testing purposes I run my little command-extension -- <a href="http://code.google.com/p/dilla" rel="nofollow">Dilla</a>, to populate random data around.</li> <li>I've noticed unwanted signals triggering, therefore I'd like them to run conditionally. </li> </ol> <p>Hope it's clear enough. Excuse my language mistakes.</p>
4
2009-02-23T11:45:25Z
16,556,300
<p>I found simple and easy solution:</p> <pre><code>MyModel.objects.filter(pk=instance.id).update(**data) </code></pre> <p>It is due to (<a href="https://docs.djangoproject.com/en/1.5/ref/models/querysets/#update">https://docs.djangoproject.com/en/1.5/ref/models/querysets/#update</a>):</p> <blockquote> <p>Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()).</p> </blockquote>
11
2013-05-15T03:25:55Z
[ "python", "django", "django-signals" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
577,486
<p>In Windows, you can use the <a href="http://docs.python.org/library/msvcrt.html#msvcrt-console" rel="nofollow"><code>msvcrt</code></a> module. </p> <blockquote> <p><strong>msvcrt.kbhit()</strong> Return true if a keypress is waiting to be read.</p> <p><strong>msvcrt.getch()</strong> Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.</p> </blockquote> <p>If you want it to also work on Unix-like systems you can try <a href="http://pyfaq.infogami.com/how-do-i-get-a-single-keypress-at-a-time" rel="nofollow">this solution</a> using the <a href="http://docs.python.org/library/termios.html" rel="nofollow">termios</a> and <a href="http://docs.python.org/library/fcntl.html" rel="nofollow">fcntl</a> modules.</p>
3
2009-02-23T12:28:33Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
577,487
<p>There's no need to wait for input before closing, just change your command like so:</p> <pre><code>cmd /K python &lt;script&gt; </code></pre> <p>The <code>/K</code> switch will execute the command that follows, but leave the command interpreter window open, in contrast to <code>/C</code>, which executes and then closes.</p>
12
2009-02-23T12:29:39Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
577,488
<p>One way is to leave a <code>raw_input()</code> at the end so the script waits for you to press Enter before it terminates.</p>
43
2009-02-23T12:30:06Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
577,499
<p>An external WConio module can help here: <a href="http://newcenturycomputers.net/projects/wconio.html" rel="nofollow">http://newcenturycomputers.net/projects/wconio.html</a></p> <pre><code>import WConio WConio.getch() </code></pre>
0
2009-02-23T12:35:08Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
577,529
<blockquote> <p>One way is to leave a raw_input() at the end so the script waits for you to press enter before it terminates.</p> </blockquote> <p>The advantage of using raw_input() instead of msvcrt.* stuff is that the former is a part of standard Python (i.e. absolutely cross-platform). This also means that the script window will be alive after double-clicking on the script file icon, without the need to do </p> <pre><code>cmd /K python &lt;script&gt; </code></pre>
7
2009-02-23T12:51:41Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
578,751
<pre><code>import pdb pdb.debug() </code></pre> <p>This is used to debug the script. Should be useful to break also.</p>
0
2009-02-23T18:35:12Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
4,130,571
<p>Try <code>os.system("pause")</code>I used it and it worked for me :)</p>
26
2010-11-09T04:41:40Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
4,130,603
<p>Getting python to read a single character from the terminal in an unbuffered manner is a little bit tricky, but here's a recipe that'll do it: </p> <p><a href="http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/" rel="nofollow">Recipe 134892: getch()-like unbuffered character reading from stdin on both Windows and Unix (Python)</a></p>
0
2010-11-09T04:49:09Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
15,254,312
<p>The best option: <code>os.system('pause')</code> &lt;-- this will actually display a message saying 'press any key to continue' whereas adding just <code>raw_input('')</code> will print no message, just the cursor will be available. </p> <p>not related to answer:</p> <p><code>os.system("some cmd command")</code> is a really great command as the command can execute any batch file/cmd commands.</p>
6
2013-03-06T17:44:46Z
[ "python", "command-line" ]
Pause in Python
577,467
<p>I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.</p> <p>After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.</p> <p>What is the most straightforward way to keep the interpreter window open until any key is pressed?</p> <p>In batch files, one can end the script with pause. The closest thing to this I found in python is <code>raw_input()</code> which is sub-optimal because it requires pressing the return key (instead of any key).</p> <p>Any ideas?</p>
38
2009-02-23T12:20:26Z
22,947,778
<p>If you type </p> <pre><code>input("") </code></pre> <p>It will wait for them to press any button then it will continue. Also you can put text between the quotes.</p>
-1
2014-04-08T20:44:16Z
[ "python", "command-line" ]
Rotating a glViewport?
577,639
<p>In a "multitouch" environement, any application showed on a surface can be rotated/scaled to the direction of an user. Actual solution is to drawing the application on a FBO, and draw a rotated/scaled rectangle with the texture on it. I don't think it's good for performance, and all graphics cards don't provide FBO.</p> <p>The idea is to clip the rendering viewport in the direction of user. Since glViewport cannot be used for that, is another way exist to achieve that ?</p> <p>(glViewport use (x, y, width, height), and i would like (x, y, width, height, rotation from center?))</p> <p>PS: rotating the modelview or projection matrix will not help, i would like to "rotate the clipping plan" generated by glViewport. (only part of the all scene).</p>
2
2009-02-23T13:33:48Z
577,672
<p>If you already have the code set up to render your scene, try adding a <code>glRotate()</code> call to the viewmodel matrix setup, to "rotate the camera" before rendering the scene.</p>
2
2009-02-23T13:42:21Z
[ "python", "math", "opengl" ]
Rotating a glViewport?
577,639
<p>In a "multitouch" environement, any application showed on a surface can be rotated/scaled to the direction of an user. Actual solution is to drawing the application on a FBO, and draw a rotated/scaled rectangle with the texture on it. I don't think it's good for performance, and all graphics cards don't provide FBO.</p> <p>The idea is to clip the rendering viewport in the direction of user. Since glViewport cannot be used for that, is another way exist to achieve that ?</p> <p>(glViewport use (x, y, width, height), and i would like (x, y, width, height, rotation from center?))</p> <p>PS: rotating the modelview or projection matrix will not help, i would like to "rotate the clipping plan" generated by glViewport. (only part of the all scene).</p>
2
2009-02-23T13:33:48Z
593,825
<p>There's no way to have a rotated viewport in OpenGL, you have to handle it manually. I see the following possible solutions :</p> <ul> <li><p>Keep on using textures, perhaps using glCopyTexSubImage instead of FBOs, as this is basic OpenGL feature. If your target platforms are hardware accelerated, performance should be ok, depending on the number of viewports you need on your desk, as this is a very common use case nowadays.</p></li> <li><p>Without textures, you could setup your glViewport to the screen-aligned bounding rectangle (rA) of your rotated viewport (rB) (setting also proper scissor testing area). Then draw a masking area, possibly only in depth or stencil buffer, filling the (rA - rB) area, that will prevent further drawing on those pixels. Then draw normally your application, using a glRotate to adjust you projection matrix, so that the rendering is properly oriented according to rB.</p></li> </ul>
2
2009-02-27T07:20:43Z
[ "python", "math", "opengl" ]
How do I prevent Python's os.walk from walking across mount points?
577,761
<p>In Unix all disks are exposed as paths in the main filesystem, so <code>os.walk('/')</code> would traverse, for example, <code>/media/cdrom</code> as well as the primary hard disk, and that is undesirable for some applications.</p> <p>How do I get an <code>os.walk</code> that stays on a single device?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/530645/is-there-a-way-to-determine-if-a-subdirectory-is-in-the-same-filesystem-from-pyth/">Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?</a></li> </ul>
7
2009-02-23T14:16:59Z
577,807
<p><code>os.walk()</code> can't tell (as far as I know) that it is browsing a different drive. You will need to check that yourself.</p> <p>Try using <code>os.stat()</code>, or checking that the root variable from <code>os.walk()</code> is not <code>/media</code></p>
1
2009-02-23T14:31:05Z
[ "python", "linux", "unix" ]
How do I prevent Python's os.walk from walking across mount points?
577,761
<p>In Unix all disks are exposed as paths in the main filesystem, so <code>os.walk('/')</code> would traverse, for example, <code>/media/cdrom</code> as well as the primary hard disk, and that is undesirable for some applications.</p> <p>How do I get an <code>os.walk</code> that stays on a single device?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/530645/is-there-a-way-to-determine-if-a-subdirectory-is-in-the-same-filesystem-from-pyth/">Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?</a></li> </ul>
7
2009-02-23T14:16:59Z
577,830
<p>From <code>os.walk</code> docs:</p> <blockquote> <p>When topdown is true, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search</p> </blockquote> <p>So something like this should work:</p> <pre><code>for root, dirnames, filenames in os.walk(...): dirnames[:] = [ dir for dir in dirnames if not os.path.ismount(os.path.join(root, dir))] ... </code></pre>
15
2009-02-23T14:39:56Z
[ "python", "linux", "unix" ]
How do I prevent Python's os.walk from walking across mount points?
577,761
<p>In Unix all disks are exposed as paths in the main filesystem, so <code>os.walk('/')</code> would traverse, for example, <code>/media/cdrom</code> as well as the primary hard disk, and that is undesirable for some applications.</p> <p>How do I get an <code>os.walk</code> that stays on a single device?</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/530645/is-there-a-way-to-determine-if-a-subdirectory-is-in-the-same-filesystem-from-pyth/">Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?</a></li> </ul>
7
2009-02-23T14:16:59Z
577,835
<p>I think <a href="http://docs.python.org/library/os.path.html#os.path.ismount" rel="nofollow">os.path.ismount</a> might work for you. You code might look something like this:</p> <pre><code>import os import os.path for root, dirs, files in os.walk('/'): # Handle files. dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs) </code></pre> <p>You may also find <a href="http://stackoverflow.com/questions/571850/adding-elements-to-python-generators">this answer</a> helpful in building your solution.</p> <p>*Thanks for the comments on filtering <code>dirs</code> correctly.</p>
3
2009-02-23T14:40:49Z
[ "python", "linux", "unix" ]
Python Socket help (Syntax error)
577,779
<pre><code>import socket HOST = "swemach.se" PORT = 21 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT) data = s.recv(1024) s.close() print "%s" % data </code></pre> <p>Gives me error</p> <pre><code>File "main.txt", line 7 data = s.recv(1024) ^ SyntaxError: invaild syntax </code></pre> <p>What im going wrong? any tip/solution?</p>
0
2009-02-23T14:22:21Z
577,784
<p>You've forgot parenthesis.</p> <pre><code>s.connect((HOST, PORT)) </code></pre>
4
2009-02-23T14:24:33Z
[ "python" ]
Python Socket help (Syntax error)
577,779
<pre><code>import socket HOST = "swemach.se" PORT = 21 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT) data = s.recv(1024) s.close() print "%s" % data </code></pre> <p>Gives me error</p> <pre><code>File "main.txt", line 7 data = s.recv(1024) ^ SyntaxError: invaild syntax </code></pre> <p>What im going wrong? any tip/solution?</p>
0
2009-02-23T14:22:21Z
577,789
<pre><code>(( HOST, PORT) </code></pre> <p>^ there you go</p>
4
2009-02-23T14:24:58Z
[ "python" ]
PyQt: No such slot
577,824
<p>I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:</p> <p>lcdrange.py:</p> <pre><code>from PyQt4 import QtGui, QtCore class LCDRange(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) lcd = QtGui.QLCDNumber(2) self.slider = QtGui.QSlider() self.slider.setRange(0,99) self.slider.setValue(0) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), lcd, QtCore.SLOT('display(int)')) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), self, QtCore.SIGNAL('valueChanged(int)')) layout = QtGui.QVBoxLayout() layout.addWidget(lcd) layout.addWidget(self.slider) self.setLayout(layout) def value(self): self.slider.value() def setValue(self,value): self.slider.setValue(value) </code></pre> <p>main.py:</p> <pre><code>import sys from PyQt4 import QtGui, QtCore from lcdrange import LCDRange class MyWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) quit = QtGui.QPushButton('Quit') quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold)) self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) grid = QtGui.QGridLayout() previousRange = None for row in range(0,3): for column in range(0,3): lcdRange = LCDRange() grid.addWidget(lcdRange, row, column) if not previousRange == None: self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'), previousRange, QtCore.SLOT('setValue(int)')) previousRange = lcdRange layout = QtGui.QVBoxLayout() layout.addWidget(quit) layout.addLayout(grid) self.setLayout(layout) app = QtGui.QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec_()) </code></pre> <p>When i run this i get the following errors:</p> <pre><code>Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) </code></pre> <p>I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?</p> <p>I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:</p> <pre><code>class LCDRange &lt; Qt::Widget signals 'valueChanged(int)' slots 'setValue(int)' def initialize(parent = nil) ... </code></pre> <p>So my guess was that i have to somehow declare the existence of the custom slot?</p>
1
2009-02-23T14:37:06Z
577,882
<p>Try this:</p> <pre><code>self.connect(lcdRange, QtCore.SIGNAL('valueChanged'), previousRange.setValue) </code></pre> <h1>What's the difference?</h1> <p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#signal-and-slot-support" rel="nofollow">The PyQt documentation</a> has a section about SIGNALS/SLOTS in PyQt, they work a little differently.</p> <h2>SIGNAL</h2> <p><code>SIGNAL('valueChanged')</code> is something called a <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#short-circuit-signals" rel="nofollow">short-circuit signal</a>. They work only for Python-to-Python methods, but they are faster and easier to implement.</p> <h2>SLOT</h2> <p>If you have a python slot, you can specify it just by tipping the method: <code>previousRange.setValue</code>. This works for all methods accessible by Python.</p> <p>If your slots should be accessible like C++ Qt slots, as you tried in your code, you have to use a special syntax. You can find information about <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html#the-pyqtslot-decorator" rel="nofollow">pyqtSignature decorator</a> on the PyQt website.</p>
7
2009-02-23T14:57:53Z
[ "python", "ruby", "qt4", "pyqt" ]
PyQt: No such slot
577,824
<p>I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:</p> <p>lcdrange.py:</p> <pre><code>from PyQt4 import QtGui, QtCore class LCDRange(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) lcd = QtGui.QLCDNumber(2) self.slider = QtGui.QSlider() self.slider.setRange(0,99) self.slider.setValue(0) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), lcd, QtCore.SLOT('display(int)')) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), self, QtCore.SIGNAL('valueChanged(int)')) layout = QtGui.QVBoxLayout() layout.addWidget(lcd) layout.addWidget(self.slider) self.setLayout(layout) def value(self): self.slider.value() def setValue(self,value): self.slider.setValue(value) </code></pre> <p>main.py:</p> <pre><code>import sys from PyQt4 import QtGui, QtCore from lcdrange import LCDRange class MyWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) quit = QtGui.QPushButton('Quit') quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold)) self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) grid = QtGui.QGridLayout() previousRange = None for row in range(0,3): for column in range(0,3): lcdRange = LCDRange() grid.addWidget(lcdRange, row, column) if not previousRange == None: self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'), previousRange, QtCore.SLOT('setValue(int)')) previousRange = lcdRange layout = QtGui.QVBoxLayout() layout.addWidget(quit) layout.addLayout(grid) self.setLayout(layout) app = QtGui.QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec_()) </code></pre> <p>When i run this i get the following errors:</p> <pre><code>Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) </code></pre> <p>I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?</p> <p>I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:</p> <pre><code>class LCDRange &lt; Qt::Widget signals 'valueChanged(int)' slots 'setValue(int)' def initialize(parent = nil) ... </code></pre> <p>So my guess was that i have to somehow declare the existence of the custom slot?</p>
1
2009-02-23T14:37:06Z
958,995
<p>NOTE</p> <p>The "text" within the SIGNAL must match the c++ API documentation. </p> <pre><code># This will work - its IDENTICAL to the documentation QtCore.SIGNAL('customContextMenuRequested(const QPoint&amp;)') # this wont QtCore.SIGNAL('customContextMenuRequested(QPoint&amp;)') # and this wont QtCore.SIGNAL('customContextMenuRequested(const QPoint)') # Spot the bug QtCore.SIGNAL('selectionChanged(const QItemSelection,const QItemSelection&amp;)') ^ &lt; missing &amp; </code></pre>
0
2009-06-06T04:29:47Z
[ "python", "ruby", "qt4", "pyqt" ]
PyQt: No such slot
577,824
<p>I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:</p> <p>lcdrange.py:</p> <pre><code>from PyQt4 import QtGui, QtCore class LCDRange(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) lcd = QtGui.QLCDNumber(2) self.slider = QtGui.QSlider() self.slider.setRange(0,99) self.slider.setValue(0) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), lcd, QtCore.SLOT('display(int)')) self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'), self, QtCore.SIGNAL('valueChanged(int)')) layout = QtGui.QVBoxLayout() layout.addWidget(lcd) layout.addWidget(self.slider) self.setLayout(layout) def value(self): self.slider.value() def setValue(self,value): self.slider.setValue(value) </code></pre> <p>main.py:</p> <pre><code>import sys from PyQt4 import QtGui, QtCore from lcdrange import LCDRange class MyWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) quit = QtGui.QPushButton('Quit') quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold)) self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) grid = QtGui.QGridLayout() previousRange = None for row in range(0,3): for column in range(0,3): lcdRange = LCDRange() grid.addWidget(lcdRange, row, column) if not previousRange == None: self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'), previousRange, QtCore.SLOT('setValue(int)')) previousRange = lcdRange layout = QtGui.QVBoxLayout() layout.addWidget(quit) layout.addLayout(grid) self.setLayout(layout) app = QtGui.QApplication(sys.argv) widget = MyWidget() widget.show() sys.exit(app.exec_()) </code></pre> <p>When i run this i get the following errors:</p> <pre><code>Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) Object::connect: No such slot LCDRange::setValue(int) </code></pre> <p>I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?</p> <p>I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:</p> <pre><code>class LCDRange &lt; Qt::Widget signals 'valueChanged(int)' slots 'setValue(int)' def initialize(parent = nil) ... </code></pre> <p>So my guess was that i have to somehow declare the existence of the custom slot?</p>
1
2009-02-23T14:37:06Z
1,750,986
<p><br /> you forgot to put </p> <pre><code> @Qt.pyqtSlot() </code></pre> <p>above method you are using as slot. <br /></p> <p>For example your code should look like this</p> <pre><code> @Qt.pyqtSlot('const QPoint&') def setValue(self,value): self.slider.setValue(value) </code></pre> <p>Here is one good page about pyqt slot decorator:</p> <p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#the-qtcore-pyqtslot-decorator" rel="nofollow">click :-)</a></p> <p>Bye</p>
1
2009-11-17T18:55:25Z
[ "python", "ruby", "qt4", "pyqt" ]
How can I make this Python recursive function return a flat list?
577,940
<p>Look at this simple function</p> <pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n </code></pre> <p>Here's the result of <code>prime_factors(120)</code></p> <pre><code>(2, (2, (2, (3, 5)))) </code></pre> <p>Instead of nested tuples, I want it to return one flat tuple or list.</p> <pre><code>(2, 2, 2, 3, 5) </code></pre> <p>Is there a simple way to do that?</p>
9
2009-02-23T15:12:37Z
577,955
<pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: yield i for p in prime_factors(n / i): yield p return yield n </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; tuple(prime_factors(100)) (2, 2, 5, 5) </code></pre>
10
2009-02-23T15:16:14Z
[ "python", "recursion" ]
How can I make this Python recursive function return a flat list?
577,940
<p>Look at this simple function</p> <pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n </code></pre> <p>Here's the result of <code>prime_factors(120)</code></p> <pre><code>(2, (2, (2, (3, 5)))) </code></pre> <p>Instead of nested tuples, I want it to return one flat tuple or list.</p> <pre><code>(2, 2, 2, 3, 5) </code></pre> <p>Is there a simple way to do that?</p>
9
2009-02-23T15:12:37Z
577,961
<pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: return [i] + prime_factors(n / i) return [n] </code></pre>
18
2009-02-23T15:17:03Z
[ "python", "recursion" ]
How can I make this Python recursive function return a flat list?
577,940
<p>Look at this simple function</p> <pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n </code></pre> <p>Here's the result of <code>prime_factors(120)</code></p> <pre><code>(2, (2, (2, (3, 5)))) </code></pre> <p>Instead of nested tuples, I want it to return one flat tuple or list.</p> <pre><code>(2, 2, 2, 3, 5) </code></pre> <p>Is there a simple way to do that?</p>
9
2009-02-23T15:12:37Z
577,971
<p>Without changing the original function, from <a href="http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks" rel="nofollow">Python Tricks</a>:</p> <pre><code>def flatten(x): """flatten(sequence) -&gt; list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: &gt;&gt;&gt; [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] &gt;&gt;&gt; flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]""" result = [] for el in x: #if isinstance(el, (list, tuple)): if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result </code></pre>
7
2009-02-23T15:19:23Z
[ "python", "recursion" ]
How can I make this Python recursive function return a flat list?
577,940
<p>Look at this simple function</p> <pre><code>def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n </code></pre> <p>Here's the result of <code>prime_factors(120)</code></p> <pre><code>(2, (2, (2, (3, 5)))) </code></pre> <p>Instead of nested tuples, I want it to return one flat tuple or list.</p> <pre><code>(2, 2, 2, 3, 5) </code></pre> <p>Is there a simple way to do that?</p>
9
2009-02-23T15:12:37Z
578,236
<p>liw.fi suggested in a <a href="http://stackoverflow.com/questions/577940/how-can-i-make-this-python-recursive-function-return-a-flat-list/577961#577961">comment</a>:</p> <blockquote> <p>Instead of creating a new list for each return value, you could pass the list as an argument and append to it. If the list gets large, this may save some space and time.</p> </blockquote> <p>Here's an implementation of liw.fi's suggestion. </p> <pre><code>def prime_factors(n, factors=None): if factors is None: factors = [] for i in range(2,n): if n % i == 0: factors.append(i) return prime_factors(n / i, factors) factors.append(n) return factors </code></pre>
2
2009-02-23T16:18:41Z
[ "python", "recursion" ]
Easiest way to create a scrollable area using wxPython?
578,200
<p>Okay, so I want to display a series of windows within windows and have the whole lot scrollable. I've been hunting through <a href="http://docs.wxwidgets.org/stable/wx_wxscrolledwindow.html#wxscrolledwindow" rel="nofollow">the wxWidgets documentation</a> and a load of examples from various sources on t'internet. Most of those seem to imply that a wx.ScrolledWindow should work if I just pass it a nested group of sizers(?):</p> <blockquote> <p>The most automatic and newest way is to simply let sizers determine the scrolling area.This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate.</p> </blockquote> <p>...but all the example's I've seen seem to use the older methods listed as ways to achieve scrolling. I've got something basic working, but as soon as you start scrolling you lose the child windows:</p> <pre><code>import wx class MyCustomWindow(wx.Window): def __init__(self, parent): wx.Window.__init__(self, parent) self.Bind(wx.EVT_PAINT, self.OnPaint) self.SetSize((50,50)) def OnPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetPen(wx.Pen('blue', 2)) dc.SetBrush(wx.Brush('blue')) (width, height)=self.GetSizeTuple() dc.DrawRoundedRectangle(0, 0,width, height, 8) class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1) self.Bind(wx.EVT_SIZE, self.OnSize) self.scrolling_window = wx.ScrolledWindow( self ) self.scrolling_window.SetScrollRate(1,1) self.scrolling_window.EnableScrolling(True,True) self.sizer_container = wx.BoxSizer( wx.VERTICAL ) self.sizer = wx.BoxSizer( wx.HORIZONTAL ) self.sizer_container.Add(self.sizer,1,wx.CENTER,wx.EXPAND) self.child_windows = [] for i in range(0,50): wind = MyCustomWindow(self.scrolling_window) self.sizer.Add(wind, 0, wx.CENTER|wx.ALL, 5) self.child_windows.append(wind) self.scrolling_window.SetSizer(self.sizer_container) def OnSize(self, event): self.scrolling_window.SetSize(self.GetClientSize()) if __name__=='__main__': app = wx.PySimpleApp() f = TestFrame() f.Show() app.MainLoop() </code></pre>
0
2009-02-23T16:12:36Z
580,006
<p>Oops.. turns out I was creating my child windows badly:</p> <pre><code>wind = MyCustomWindow(self) </code></pre> <p>should be:</p> <pre><code>wind = MyCustomWindow(self.scrolling_window) </code></pre> <p>..which meant the child windows were waiting for the top-level window (the frame) to be re-drawn instead of listening to the scroll window. Changing that makes it all work wonderfully :)</p>
1
2009-02-24T00:32:25Z
[ "python", "scroll", "wxwidgets", "scrolledwindow" ]
Python 2.5 to Python 2.2 converter
578,262
<p>I am working on a PyS60 application for S60 2nd Edition devices. I have coded my application logic in Python 2.5.</p> <p>Is there any tool that automates th conversion from Python 2.5 to Python 2.2 or do I need to do in manually?</p>
1
2009-02-23T16:24:09Z
578,337
<p>I don't know of any tool that would go from 2.5 to 2.2 automatically; but there was one a while ago that did 2.3 to 2.2 by <a href="http://www.radlogic.com.au/downloads.htm" rel="nofollow">RADLogic</a>.</p> <p>Depending on how many recent features your code uses, it may be trivial to convert it manually. </p> <p>I had to backport some code a while back and all it actually took was to define True and False if they weren't already defined, write up some simple replacements for <code>sum()</code>, <code>enumerate()</code>, etc, and grab old versions of modules like <code>datetime</code> and <code>logging</code> that weren't yet in the 2.2 standard library.</p>
1
2009-02-23T16:42:25Z
[ "python", "pys60" ]
Python 2.5 to Python 2.2 converter
578,262
<p>I am working on a PyS60 application for S60 2nd Edition devices. I have coded my application logic in Python 2.5.</p> <p>Is there any tool that automates th conversion from Python 2.5 to Python 2.2 or do I need to do in manually?</p>
1
2009-02-23T16:24:09Z
578,966
<p>The latest Python for S60, <a href="http://discussion.forum.nokia.com/forum/showthread.php?t=154215" rel="nofollow">1.9.0</a>, actually includes Python 2.5.1. So maybe you don't need to convert.</p>
3
2009-02-23T19:23:54Z
[ "python", "pys60" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
578,393
<p>For one thing, I would suggest summing up the terms as you calculate them rather than storing them in an array and summing the array afterwards, since you don't need to do anything with the individual terms other than adding them up. (That's just good computational sense in any language)</p>
4
2009-02-23T16:56:56Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
578,417
<p>I would make the following changes:</p> <ul> <li>Use iteration instead of recursion</li> <li>Just keep a running total instead of keeping a list of all Fibonacci numbers and then finding the sum of the even ones a posterior</li> </ul> <p>Other than that, it's <em>reasonably</em> Pythonic.</p> <pre><code>def even_fib_sum(limit): a,b,sum = 0,1,0 while a &lt;= limit: if a%2 == 0: sum += a a,b = b,a+b return sum print(even_fib_sum(4000000)) </code></pre>
2
2009-02-23T17:00:56Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
578,424
<p>Using generators is a Pythonic way to generate long sequences while preserving memory:</p> <pre><code>def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b import itertools upto_4000000 = itertools.takewhile(lambda x: x &lt;= 4000000, fibonacci()) print(sum(x for x in upto_4000000 if x % 2 == 0)) </code></pre>
16
2009-02-23T17:02:01Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
578,426
<p>First I'd do fibo() as a generator:</p> <pre><code>def fibo(a=-1,b=1,upto=4000000): while a+b&lt;upto: a,b = b,a+b yield b </code></pre> <p>Then I'd also select for evenness as a generator rather than a list comprehension.</p> <pre><code>print sum(i for i in fibo() if not i%2) </code></pre>
12
2009-02-23T17:02:33Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
578,491
<p>I'd use the fibonacci generator as in <a href="http://stackoverflow.com/questions/578379/python-program-to-find-fibonacci-series-more-pythonic-way/578424#578424">@constantin' answer</a> but generator expressions could be replaced by a plain <code>for</code> loop:</p> <pre><code>def fibonacci(a=0, b=1): while True: yield a a, b = b, a + b sum_ = 0 for f in fibonacci(): if f &gt; 4000000: break if f % 2 == 0: sum_ += f print sum_ </code></pre>
2
2009-02-23T17:19:28Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
3,277,816
<p>Here's an alternate direct method It relies on a few properties:</p> <ol> <li>Each Fibonacci number can be calculated directly as floor( pow( phi, n ) + 0.5 ) (See Computation by Rounding in <a href="http://en.wikipedia.org/wiki/Fibonacci_number" rel="nofollow">http://en.wikipedia.org/wiki/Fibonacci_number</a> ). Conversely the index of the biggest Fibonacci number less than i is given by floor( log(i*sqrt(5)) / log(phi) )</li> <li>The sum of the first N Fibonacci numbers is the N+2th fibonacci number minus 1 (See Second Identity on the same wikipedia page) </li> <li>The even Fibonacci numbers are are every third number. ( Look at the sequence mod 2 and the result is trivial )</li> <li>The sum of the even Fibonacci numbers is half the sum of the odd Fibonacci numbers upto the same point in the sequence. </li> </ol> <p>Point 4 can be seen from this:</p> <pre><code>Sum of first 3N fibonacci numbers =(F(1) + F(2))+ F(3) +(F(4) + F(5))+ F(6) + ... +(F(3N-2) + F(3N-1))+ F(3N) = F(3) + F(3) + F(6) + F(6) + ... + F(3N) + F(3N) = 2( F(3) + F(6) + ... + F(3N) ) = 2 ( Sum of odd fibonacci numbers up to F(3N) ) </code></pre> <p>So convert our maximum value of 4000000 calculate the index of the highest Fibonacci number less than it. </p> <pre><code>int n = floor(log(4000000*sqrt(5))/log(phi)); // ( = 33) </code></pre> <p>33 is divisible by 3 so it is an even Fibonacci number, if it wasn't we'd need to adjust n like this.</p> <pre><code>n = (n/3)*3; </code></pre> <p>The sum of all Fibonacci numbers up to this point if given by</p> <pre><code>sum = floor( pow( phi, n+2 ) + 0.5 ) - 1; // ( = 9227464 ) </code></pre> <p>The sum of all even numbers is half of this:</p> <pre><code>sum_even = sum/2; // ( = 4613732 ) </code></pre> <p>Nice thing about this is that its an O(1) (or O(log(N)) if you include the cost of pow/log) algorithm, and works on doubles.. so we can calculate the sum for very large values.</p> <p>NOTE: I edited and moved this answer from a closed duplicate of this question. <a href="http://stackoverflow.com/questions/3270863">http://stackoverflow.com/questions/3270863</a></p>
1
2010-07-19T00:37:09Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
7,895,823
<p>In Python 3 at least if you give a generator to the <code>sum</code> function it will lazily evaluate it so there is no need to reinvent the wheel.</p> <p>This is what @Constantin did and is correct.</p> <p>Tested by comparing the memory usage of using generators:</p> <p><code>sum(range(9999999))</code></p> <p>compared with not doing so:</p> <p><code>sum(list(range(9999999)))</code></p> <p>The one with the generator does not cause memory exceptions with higher numbers either.</p>
0
2011-10-25T21:00:26Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
17,396,950
<pre><code>print ("Fibonacci Series\n") a = input ("Enter a nth Term: ") b = 0 x = 0 y = 1 print x,("\n"), y while b &lt;=a-2: b = b+1 z = x + y print z x = y y = z </code></pre>
0
2013-07-01T03:10:48Z
[ "python" ]
Python program to find fibonacci series. More Pythonic way
578,379
<p>There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. <a href="http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python">How to write the Fibonacci Sequence in Python</a></p> <p>I am in love with this program I wrote to solve Project Euler Q2. I am newly coding in Python and rejoice each time I do it The Pythonic way! Can you suggest a better Pythonic way to do this?</p> <p><a href="http://projecteuler.net/index.php?section=problems&amp;id=2">Project Euler Q2</a>. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.</p> <pre><code>fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b&gt;=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) </code></pre>
6
2009-02-23T16:53:23Z
24,467,465
<pre><code>def main(): a = 1 b = 2 num = 2 while b &lt; 4000000: a, b = b, a+b num += b if b % 2 == 0 else 0 print num if __name__ == '__main__': main() </code></pre>
0
2014-06-28T13:49:48Z
[ "python" ]
How to pass values by ref in Python?
578,635
<p>Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:</p> <pre><code>GetPoint ( Point &amp;p, Object obj ) </code></pre> <p>so how can I translate to Python? Is there a pass by ref symbol?</p>
3
2009-02-23T17:58:20Z
578,645
<p>There is no pass by reference symbol in Python.</p> <p>Just modify the passed in point, your modifications will be visible from the calling function.</p> <pre><code>&gt;&gt;&gt; def change(obj): ... obj.x = 10 ... &gt;&gt;&gt; class Point(object): x,y = 0,0 ... &gt;&gt;&gt; p = Point() &gt;&gt;&gt; p.x 0 &gt;&gt;&gt; change(p) &gt;&gt;&gt; p.x 10 </code></pre> <p>...</p> <blockquote> <p>So I should pass it like: GetPoint (p, obj)?</p> </blockquote> <p>Yes, though <a href="http://stackoverflow.com/questions/578635/how-to-pass-values-by-ref-in-python/578651#578651">Iraimbilanja</a> has a good point. The bindings may have changed the call to return the point rather than use an out parameter.</p>
4
2009-02-23T18:00:41Z
[ "python", "variables", "pass-by-reference" ]
How to pass values by ref in Python?
578,635
<p>Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:</p> <pre><code>GetPoint ( Point &amp;p, Object obj ) </code></pre> <p>so how can I translate to Python? Is there a pass by ref symbol?</p>
3
2009-02-23T17:58:20Z
578,647
<p>I'm pretty sure Python passes the value of the reference to a variable. <a href="http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/" rel="nofollow">This article</a> can probably explain it better than I.</p>
2
2009-02-23T18:01:43Z
[ "python", "variables", "pass-by-reference" ]
How to pass values by ref in Python?
578,635
<p>Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:</p> <pre><code>GetPoint ( Point &amp;p, Object obj ) </code></pre> <p>so how can I translate to Python? Is there a pass by ref symbol?</p>
3
2009-02-23T17:58:20Z
578,649
<p>Objects are always passed as reference in Python. So wrapping up in object produces similar effect.</p>
1
2009-02-23T18:02:10Z
[ "python", "variables", "pass-by-reference" ]
How to pass values by ref in Python?
578,635
<p>Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:</p> <pre><code>GetPoint ( Point &amp;p, Object obj ) </code></pre> <p>so how can I translate to Python? Is there a pass by ref symbol?</p>
3
2009-02-23T17:58:20Z
578,651
<p>It's likely that your Python bindings have turned that signature into:</p> <pre><code>Point GetPoint(Object obj) </code></pre> <p>or even:</p> <pre><code>Point Object::GetPoint() </code></pre> <p>So look into the bindings' documentation or sources.</p>
3
2009-02-23T18:02:48Z
[ "python", "variables", "pass-by-reference" ]
How to pass values by ref in Python?
578,635
<p>Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:</p> <pre><code>GetPoint ( Point &amp;p, Object obj ) </code></pre> <p>so how can I translate to Python? Is there a pass by ref symbol?</p>
3
2009-02-23T17:58:20Z
578,655
<p>There is not ref by symbol in python - the right thing to do depends on your API. The question to ask yourself is who owns the object passed from C++ to python. Sometimes, the easiest ting it just to copy the object into a python object, but that may not always be the best thing to do.</p> <p>You may be interested in boost.python <a href="http://www.boost.org/doc/libs/1_38_0/libs/python/doc/index.html" rel="nofollow">http://www.boost.org/doc/libs/1_38_0/libs/python/doc/index.html</a></p>
1
2009-02-23T18:04:21Z
[ "python", "variables", "pass-by-reference" ]
Alternative to 'for i in xrange(len(x))'
578,677
<p>So I see in <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns">another post</a> the following "bad" snippet, but the only alternatives I have seen involve patching Python.</p> <pre><code>for i in xrange(len(something)): workwith = something[i] # do things with workwith... </code></pre> <p>What do I do to avoid this "antipattern"?</p>
9
2009-02-23T18:10:52Z
578,685
<p>See <a href="http://docs.python.org/glossary.html#term-pythonic">Pythonic</a></p> <pre><code>for workwith in something: # do things with workwith </code></pre>
22
2009-02-23T18:12:36Z
[ "python", "for-loop", "anti-patterns" ]
Alternative to 'for i in xrange(len(x))'
578,677
<p>So I see in <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns">another post</a> the following "bad" snippet, but the only alternatives I have seen involve patching Python.</p> <pre><code>for i in xrange(len(something)): workwith = something[i] # do things with workwith... </code></pre> <p>What do I do to avoid this "antipattern"?</p>
9
2009-02-23T18:10:52Z
578,689
<p>for example:</p> <pre><code>[workwith(i) for i in something] </code></pre>
0
2009-02-23T18:13:05Z
[ "python", "for-loop", "anti-patterns" ]
Alternative to 'for i in xrange(len(x))'
578,677
<p>So I see in <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns">another post</a> the following "bad" snippet, but the only alternatives I have seen involve patching Python.</p> <pre><code>for i in xrange(len(something)): workwith = something[i] # do things with workwith... </code></pre> <p>What do I do to avoid this "antipattern"?</p>
9
2009-02-23T18:10:52Z
578,692
<p>What is <code>x</code>? If its a sequence or iterator or string then </p> <pre><code>for i in x: workwith = i </code></pre> <p>will work fine.</p>
-3
2009-02-23T18:14:03Z
[ "python", "for-loop", "anti-patterns" ]
Alternative to 'for i in xrange(len(x))'
578,677
<p>So I see in <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns">another post</a> the following "bad" snippet, but the only alternatives I have seen involve patching Python.</p> <pre><code>for i in xrange(len(something)): workwith = something[i] # do things with workwith... </code></pre> <p>What do I do to avoid this "antipattern"?</p>
9
2009-02-23T18:10:52Z
578,694
<p>If you need to know the index in the loop body:</p> <pre><code>for index, workwith in enumerate(something): print "element", index, "is", workwith </code></pre>
23
2009-02-23T18:14:59Z
[ "python", "for-loop", "anti-patterns" ]
Alternative to 'for i in xrange(len(x))'
578,677
<p>So I see in <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns">another post</a> the following "bad" snippet, but the only alternatives I have seen involve patching Python.</p> <pre><code>for i in xrange(len(something)): workwith = something[i] # do things with workwith... </code></pre> <p>What do I do to avoid this "antipattern"?</p>
9
2009-02-23T18:10:52Z
582,541
<p>As there are <a href="http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578694#578694">two</a> <a href="http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578685#578685">answers</a> to question that are perfectly valid (with an assumption each) and author of the question didn't inform us about the destiny of index, the valid answer should read:</p> <blockquote> <p>If you <a href="http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578685#578685">do not need index</a> at all:</p> <pre><code>for workwith in something: print "element", workwith </code></pre> <p>If you <a href="http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578694#578694">need index</a>:</p> <pre><code>for index, workwith in enumerate(something): print "element", index, "is", workwith </code></pre> </blockquote> <p>If my answer is not appropriate, comment please, and I'll delete it :)</p>
11
2009-02-24T16:54:18Z
[ "python", "for-loop", "anti-patterns" ]