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
Dynamic Table Creation and ORM mapping in SqlAlchemy
973,481
<p>I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.</p> <p>I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.</p> <p>Can someone give me some tips to help me get past my brain freeze? Is this even possible? </p> <p>Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)</p>
7
2009-06-10T02:51:11Z
1,615,689
<p>I faced the same problem when I was trying to automate simple CRUD tasks using SQLAlchemy. Here is simple explanation and some code: <a href="http://www.devx.com/dbzone/Article/42015" rel="nofollow">http://www.devx.com/dbzone/Article/42015</a></p>
1
2009-10-23T20:21:20Z
[ "python", "database", "sqlalchemy" ]
Dynamic Table Creation and ORM mapping in SqlAlchemy
973,481
<p>I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.</p> <p>I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.</p> <p>Can someone give me some tips to help me get past my brain freeze? Is this even possible? </p> <p>Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)</p>
7
2009-06-10T02:51:11Z
16,454,798
<p>maybe i didn't quite understand what you want, but this recipe create identical column in different __tablename__</p> <pre><code>class TBase(object): """Base class is a 'mixin'. Guidelines for declarative mixins is at: http://www.sqlalchemy.org/docs/orm/extensions/declarative.html#mixin-classes """ id = Column(Integer, primary_key=True) data = Column(String(50)) def __repr__(self): return "%s(data=%r)" % ( self.__class__.__name__, self.data ) class T1Foo(TBase, Base): __tablename__ = 't1' class T2Foo(TBase, Base): __tablename__ = 't2' engine = create_engine('sqlite:///foo.db', echo=True) Base.metadata.create_all(engine) sess = sessionmaker(engine)() sess.add_all([T1Foo(data='t1'), T1Foo(data='t2'), T2Foo(data='t3'), T1Foo(data='t4')]) print sess.query(T1Foo).all() print sess.query(T2Foo).all() sess.commit() </code></pre> <p><a href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/EntityName" rel="nofollow">info in example sqlalchemy </a></p>
0
2013-05-09T05:10:16Z
[ "python", "database", "sqlalchemy" ]
how to integrate ZSH and (i)python?
973,520
<p>I have been in love with <code>zsh</code> for a long time, and more recently I have been discovering the advantages of the <code>ipython</code> interactive interpreter over <code>python</code> itself. Being able to <i>cd</i>, to <i>ls</i>, to <i>run</i> or to <i>!</i> is indeed very handy. But now it feels weird to have such a clumsy shell when in ipython, and I wonder how I could integrate my zsh and my ipython better.</p> <p>Of course, I could rewrite my .zshrc and all my scripts in python, and emulate most of my shell world from ipython, but it doesn't feel right. And I am obviously not ready to use ipython as a main shell anyway.</p> <p>So, here comes my question: how do you work efficiently between your shell and your python command-loop ? Am I missing some obvious integration strategy ? Should I do all that in emacs ? </p>
9
2009-06-10T03:11:55Z
974,030
<p>You can run shell commands by starting them with an exclamation mark and capture the output in a python variable. Example: listing directories in your <code>/tmp</code> directory:</p> <pre><code>ipy&gt; import os ipy&gt; tmplist = !find /tmp ipy&gt; [dir for dir in tmplist if os.path.isdir(dir)] </code></pre> <p>The list object is a special ipython object with several useful methods. Example: listing files ending with <em>.pdf</em></p> <pre><code>ipy&gt; tmplist.grep(lambda a: a.endswith('.pdf')) # using a lambda ipy&gt; tmplist.grep('\.pdf$') # using a regexp </code></pre> <p>There is a lot of things you can do by reading the list of magic commands:</p> <pre><code>ipy&gt; %magic </code></pre> <p>See the <a href="https://ipython.readthedocs.io/en/stable/overview.html#enhanced-interactive-python-shell" rel="nofollow">shell section</a> of the Ipython documentation.</p>
6
2009-06-10T06:44:42Z
[ "python", "shell", "zsh", "ipython" ]
how to integrate ZSH and (i)python?
973,520
<p>I have been in love with <code>zsh</code> for a long time, and more recently I have been discovering the advantages of the <code>ipython</code> interactive interpreter over <code>python</code> itself. Being able to <i>cd</i>, to <i>ls</i>, to <i>run</i> or to <i>!</i> is indeed very handy. But now it feels weird to have such a clumsy shell when in ipython, and I wonder how I could integrate my zsh and my ipython better.</p> <p>Of course, I could rewrite my .zshrc and all my scripts in python, and emulate most of my shell world from ipython, but it doesn't feel right. And I am obviously not ready to use ipython as a main shell anyway.</p> <p>So, here comes my question: how do you work efficiently between your shell and your python command-loop ? Am I missing some obvious integration strategy ? Should I do all that in emacs ? </p>
9
2009-06-10T03:11:55Z
1,070,597
<p>I asked this question on the zsh list and this answer worked for me. YMMV.</p> <p>In genutils.py after the line </p> <blockquote> <p>if not debug:</p> </blockquote> <p>Remove the line:</p> <blockquote> <p>stat = os.system(cmd)</p> </blockquote> <p>Replace it with:</p> <blockquote> <p>stat = subprocess.call(cmd,shell=True,executable='/bin/zsh')</p> </blockquote> <p>you see, the problem is that that "!" call uses os.system to run it, which defaults to manky old /bin/sh .</p> <p>Like I said, it worked for me, although I'm not sure what got borked behind the scenes.</p>
9
2009-07-01T18:19:24Z
[ "python", "shell", "zsh", "ipython" ]
writing to a file via FTP in python
973,551
<p>So i've followed the docs on this page: <a href="http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary" rel="nofollow">http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary</a></p> <p>And maybe i'm confused just as to what 'retrbinary' does...i'm thinking it retrives a binary file and from there i can open it and write out to that file.</p> <p>here's the line that is giving me problems...</p> <pre><code>ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write) </code></pre> <p>what i don't understand is i'd like to write out to temp.txt, so i was trying</p> <pre><code>ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write('some new txt')) </code></pre> <p>but i was getting errors, i'm able to make a FTP connection, do pwd(), cwd(), rename(), etc.</p> <p>p.s. i'm trying to google this as much as possible, thanks!</p>
1
2009-06-10T03:24:13Z
973,576
<p>It looks like the original code should have worked, <em>if you were trying to download a file from the server</em>. The <code>retrbinary</code> command accepts a function object you specify (that is, the name of the function with no <code>()</code> after it); it is called whenever a piece of data (a binary file) arrives. In this case, it will call the <code>write</code> method of the file you <code>open</code>ed. This is slightly different than <code>retrlines</code>, because <code>retrlines</code> will assume the data is a text file, and will convert newline characters appropriately (but corrupt, say, images).</p> <p>With further reading it looks like you're trying to write to a file on the server. In that case, you'll need to pass a file object (or some other object with a <code>read</code> method that behaves like a file) to be called by the store function:</p> <pre><code>ftp.storbinary("STOR test.txt", open("file_on_my_computer.txt", "rb")) </code></pre>
2
2009-06-10T03:34:54Z
[ "python", "ftp", "ftplib" ]
writing to a file via FTP in python
973,551
<p>So i've followed the docs on this page: <a href="http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary" rel="nofollow">http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary</a></p> <p>And maybe i'm confused just as to what 'retrbinary' does...i'm thinking it retrives a binary file and from there i can open it and write out to that file.</p> <p>here's the line that is giving me problems...</p> <pre><code>ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write) </code></pre> <p>what i don't understand is i'd like to write out to temp.txt, so i was trying</p> <pre><code>ftp.retrbinary('RETR temp.txt',open('temp.txt','wb').write('some new txt')) </code></pre> <p>but i was getting errors, i'm able to make a FTP connection, do pwd(), cwd(), rename(), etc.</p> <p>p.s. i'm trying to google this as much as possible, thanks!</p>
1
2009-06-10T03:24:13Z
973,584
<p>ftp.retrbinary takes second argument as callback function it can be directly write method of file object i.e.open('temp.txt','wb').write but instead you are calling write directly</p> <p>you may supply your own callback and do whatever you want to do with data</p> <pre><code>def mywriter(data): print data ftp.retrbinary('RETR temp.txt', mywriter) </code></pre>
0
2009-06-10T03:37:56Z
[ "python", "ftp", "ftplib" ]
Python library for playing fixed-frequency sound
974,071
<p>I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.</p> <p>One method would be creating an MP3 with a a single, fixed-frequency tone (<a href="http://www.google.co.il/search?q=audacity%2Bgenerate%2Btone&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">This can easily done by audacity</a>), <a href="http://stackoverflow.com/questions/307305/play-a-sound-with-python">opening it with a python library</a> and playing it repeatedly.</p> <p>The second would be playing a sound using the computer built-in speaker. I'm looking for something similar to QBasic <em>Sound</em>:</p> <pre><code>SOUND 17000, 100 </code></pre> <p>Is there a python library for that?</p>
22
2009-06-10T07:05:02Z
974,291
<p><a href="http://pypi.python.org/pypi/pyaudiere/" rel="nofollow">PyAudiere</a> is a simple cross-platform solution for the problem:</p> <pre><code>&gt;&gt;&gt; import audiere &gt;&gt;&gt; d = audiere.open_device() &gt;&gt;&gt; t = d.create_tone(17000) # 17 KHz &gt;&gt;&gt; t.play() # non-blocking call &gt;&gt;&gt; import time &gt;&gt;&gt; time.sleep(5) &gt;&gt;&gt; t.stop() </code></pre> <p>pyaudiere.org is gone. <a href="https://web.archive.org/web/20120221041148/http://pyaudiere.org/" rel="nofollow">The site</a> and binary installers for Python 2 (debian, windows) are available via the wayback machine e.g., <a href="https://web.archive.org/web/20120221041148/http://pyaudiere.org/download.php?get=pyaudiere-0.2.tar.gz" rel="nofollow">here's source code <code>pyaudiere-0.2.tar.gz</code></a>.</p> <p>To support both Python 2 and 3 on Linux, Windows, OSX, <a href="https://pypi.python.org/pypi/PyAudio" rel="nofollow"><code>pyaudio</code> module</a> could be used instead:</p> <pre><code>#!/usr/bin/env python """Play a fixed frequency sound.""" from __future__ import division import math from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio try: from itertools import izip except ImportError: # Python 3 izip = zip xrange = range def sine_tone(frequency, duration, volume=1, sample_rate=22050): n_samples = int(sample_rate * duration) restframes = n_samples % sample_rate p = PyAudio() stream = p.open(format=p.get_format_from_width(1), # 8bit channels=1, # mono rate=sample_rate, output=True) s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate) samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples)) for buf in izip(*[samples]*sample_rate): # write several samples at a time stream.write(bytes(bytearray(buf))) # fill remainder of frameset with silence stream.write(b'\x80' * restframes) stream.stop_stream() stream.close() p.terminate() </code></pre> <p>Example:</p> <pre><code>sine_tone( # see http://www.phy.mtu.edu/~suits/notefreqs.html frequency=440.00, # Hz, waves per second A4 duration=3.21, # seconds to play sound volume=.01, # 0..1 how loud it is # see http://en.wikipedia.org/wiki/Bit_rate#Audio sample_rate=22050 # number of samples per second ) </code></pre> <p>It is a modified (to support Python 3) version of <a href="http://askubuntu.com/a/455825/3712">this AskUbuntu answer</a>.</p>
11
2009-06-10T08:20:33Z
[ "python", "audio", "mp3", "frequency" ]
Python library for playing fixed-frequency sound
974,071
<p>I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.</p> <p>One method would be creating an MP3 with a a single, fixed-frequency tone (<a href="http://www.google.co.il/search?q=audacity%2Bgenerate%2Btone&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">This can easily done by audacity</a>), <a href="http://stackoverflow.com/questions/307305/play-a-sound-with-python">opening it with a python library</a> and playing it repeatedly.</p> <p>The second would be playing a sound using the computer built-in speaker. I'm looking for something similar to QBasic <em>Sound</em>:</p> <pre><code>SOUND 17000, 100 </code></pre> <p>Is there a python library for that?</p>
22
2009-06-10T07:05:02Z
974,381
<p>You can use the <a href="http://pygame.seul.org/news.html" rel="nofollow">Python binding</a> of the SDL (<a href="http://www.libsdl.org/" rel="nofollow">Simple Direct Media Library</a>). </p>
0
2009-06-10T08:45:34Z
[ "python", "audio", "mp3", "frequency" ]
Python library for playing fixed-frequency sound
974,071
<p>I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.</p> <p>One method would be creating an MP3 with a a single, fixed-frequency tone (<a href="http://www.google.co.il/search?q=audacity%2Bgenerate%2Btone&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">This can easily done by audacity</a>), <a href="http://stackoverflow.com/questions/307305/play-a-sound-with-python">opening it with a python library</a> and playing it repeatedly.</p> <p>The second would be playing a sound using the computer built-in speaker. I'm looking for something similar to QBasic <em>Sound</em>:</p> <pre><code>SOUND 17000, 100 </code></pre> <p>Is there a python library for that?</p>
22
2009-06-10T07:05:02Z
976,848
<p>The module <a href="http://docs.python.org/library/winsound.html" rel="nofollow">winsound</a> is included with Python, so there are no external libraries to install, and it should do what you want (and not much else).</p> <pre><code> import winsound winsound.Beep(17000, 100) </code></pre> <p>It's very simple and easy, though is only available for Windows.</p> <p>But:<br> A complete answer to this question should note that although this method will produce a sound, <strong>it will not deter mosquitoes</strong>. It's already been tested: see <a href="http://biology.stackexchange.com/questions/2056/are-mosquitoes-repelled-by-high-frequency-sound">here</a> and <a href="http://www.cbc.ca/news/high-frequency-mosquito-repellents-don-t-work-study-finds-1.658894" rel="nofollow">here</a></p>
9
2009-06-10T16:50:20Z
[ "python", "audio", "mp3", "frequency" ]
How to send a SIGINT to Python from a bash script?
974,189
<p>I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.</p> <p>loop.py:</p> <pre><code>#! /usr/bin/env python if __name__ == "__main__": try: print 'starting loop' while True: pass except KeyboardInterrupt: print 'quitting loop' </code></pre> <p>From the shell I can interrupt it:</p> <pre><code>$ python loop.py &amp; [1] 15420 starting loop $ kill -SIGINT 15420 quitting loop [1]+ Done python loop.py </code></pre> <p>kill.sh:</p> <pre><code>#! /bin/bash python loop.py &amp; PID=$! echo "sending SIGINT to process $PID" kill -SIGINT $PID </code></pre> <p>But from a script I can't:</p> <pre><code>$ ./kill.sh starting loop sending SIGINT to process 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:08 python loop.py </code></pre> <p>And, if it's been launched from a script I can no longer kill it from the shell:</p> <pre><code>$ kill -SIGINT 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:34 python loop.py </code></pre> <p>I'm assuming I'm missing some fine point of bash job control.</p>
5
2009-06-10T07:46:27Z
974,229
<p>You're not registering a signal handler. Try the below. It seems to work fairly reliably. I think the rare exception is when it catches the signal before Python registers the script's handler. Note that KeyboardInterrupt is only supposed to be raised, "when the user hits the interrupt key". I think the fact that it works for a explicit (e.g. via kill) SIGINT at all is an accident of implementation.</p> <pre><code>import signal def quit_gracefully(*args): print 'quitting loop' exit(0); if __name__ == "__main__": signal.signal(signal.SIGINT, quit_gracefully) try: print 'starting loop' while True: pass except KeyboardInterrupt: quit_gracefully() </code></pre>
10
2009-06-10T08:00:35Z
[ "python", "bash" ]
How to send a SIGINT to Python from a bash script?
974,189
<p>I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.</p> <p>loop.py:</p> <pre><code>#! /usr/bin/env python if __name__ == "__main__": try: print 'starting loop' while True: pass except KeyboardInterrupt: print 'quitting loop' </code></pre> <p>From the shell I can interrupt it:</p> <pre><code>$ python loop.py &amp; [1] 15420 starting loop $ kill -SIGINT 15420 quitting loop [1]+ Done python loop.py </code></pre> <p>kill.sh:</p> <pre><code>#! /bin/bash python loop.py &amp; PID=$! echo "sending SIGINT to process $PID" kill -SIGINT $PID </code></pre> <p>But from a script I can't:</p> <pre><code>$ ./kill.sh starting loop sending SIGINT to process 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:08 python loop.py </code></pre> <p>And, if it's been launched from a script I can no longer kill it from the shell:</p> <pre><code>$ kill -SIGINT 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:34 python loop.py </code></pre> <p>I'm assuming I'm missing some fine point of bash job control.</p>
5
2009-06-10T07:46:27Z
974,257
<p>I agree with Matthew Flaschen; the problem is with python, which apparently doesn't register the KeyboardInterrupt exception with SIGINT when it's not called from an interactive shell.</p> <p>Of course, nothing prevents you from registering your signal handler like this:</p> <pre><code>def signal_handler(signum, frame): raise KeyboardInterrupt, "Signal handler" </code></pre>
3
2009-06-10T08:12:13Z
[ "python", "bash" ]
How to send a SIGINT to Python from a bash script?
974,189
<p>I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.</p> <p>loop.py:</p> <pre><code>#! /usr/bin/env python if __name__ == "__main__": try: print 'starting loop' while True: pass except KeyboardInterrupt: print 'quitting loop' </code></pre> <p>From the shell I can interrupt it:</p> <pre><code>$ python loop.py &amp; [1] 15420 starting loop $ kill -SIGINT 15420 quitting loop [1]+ Done python loop.py </code></pre> <p>kill.sh:</p> <pre><code>#! /bin/bash python loop.py &amp; PID=$! echo "sending SIGINT to process $PID" kill -SIGINT $PID </code></pre> <p>But from a script I can't:</p> <pre><code>$ ./kill.sh starting loop sending SIGINT to process 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:08 python loop.py </code></pre> <p>And, if it's been launched from a script I can no longer kill it from the shell:</p> <pre><code>$ kill -SIGINT 15452 $ ps ax | grep loop.py | grep -v grep 15452 pts/3 R 0:34 python loop.py </code></pre> <p>I'm assuming I'm missing some fine point of bash job control.</p>
5
2009-06-10T07:46:27Z
975,778
<p>When you run command in background with &amp;, SIGINT will be ignored. Here's the relevant section of man bash:</p> <blockquote> <p>Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a result of command substitution ignore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP.</p> </blockquote> <p>I think you need to set signal handler explicitly as Matthew commented.</p> <p>The script kill.sh also have a problem. Since loop.py is sent to background, there's no guarantee that kill runs after python loop.py. </p> <pre><code>#! /bin/bash python loop.py &amp; PID=$! # # NEED TO WAIT ON EXISTENCE OF python loop.py PROCESS HERE. # echo "sending SIGINT to process $PID" kill -SIGINT $PID </code></pre>
0
2009-06-10T13:58:15Z
[ "python", "bash" ]
concurrently iterating through even and odd items of list
974,219
<p>I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run. My code looks like this:</p> <pre><code>for top, bottom in izip(table[::2], table[1::2]): #do something with top #do something else with bottom </code></pre> <p>How to make this code less ugly? Or maybe is it good way to do this?</p> <p>EDIT: </p> <pre><code>table[1::2], table[::2] =&gt; table[::2], table[1::2] </code></pre>
3
2009-06-10T07:56:19Z
974,238
<p>Looks good. My only suggestion would be to wrap this in a function or method. That way, you can give it a name (<code>evenOddIter()</code>) which makes it much more readable.</p>
0
2009-06-10T08:04:39Z
[ "python", "for-loop", "itertools" ]
concurrently iterating through even and odd items of list
974,219
<p>I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run. My code looks like this:</p> <pre><code>for top, bottom in izip(table[::2], table[1::2]): #do something with top #do something else with bottom </code></pre> <p>How to make this code less ugly? Or maybe is it good way to do this?</p> <p>EDIT: </p> <pre><code>table[1::2], table[::2] =&gt; table[::2], table[1::2] </code></pre>
3
2009-06-10T07:56:19Z
974,239
<p><code>izip</code> is a pretty good option, but here's a few alternatives since you're unhappy with it:</p> <pre><code>&gt;&gt;&gt; def chunker(seq, size): ... return (tuple(seq[pos:pos+size]) for pos in xrange(0, len(seq), size)) ... &gt;&gt;&gt; x = range(11) &gt;&gt;&gt; x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; chunker(x, 2) &lt;generator object &lt;genexpr&gt; at 0x00B44328&gt; &gt;&gt;&gt; list(chunker(x, 2)) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10,)] &gt;&gt;&gt; list(izip(x[1::2], x[::2])) [(1, 0), (3, 2), (5, 4), (7, 6), (9, 8)] </code></pre> <p>As you can see, this has the advantage of properly handling an uneven amount of elements, which may or not be important to you. There's also this recipe from the <a href="http://docs.python.org/library/itertools.html#recipes" rel="nofollow">itertools documentation itself</a>:</p> <pre><code>&gt;&gt;&gt; def grouper(n, iterable, fillvalue=None): ... "grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx" ... args = [iter(iterable)] * n ... return izip_longest(fillvalue=fillvalue, *args) ... &gt;&gt;&gt; &gt;&gt;&gt; from itertools import izip_longest &gt;&gt;&gt; list(grouper(2, x)) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)] </code></pre>
5
2009-06-10T08:04:56Z
[ "python", "for-loop", "itertools" ]
concurrently iterating through even and odd items of list
974,219
<p>I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run. My code looks like this:</p> <pre><code>for top, bottom in izip(table[::2], table[1::2]): #do something with top #do something else with bottom </code></pre> <p>How to make this code less ugly? Or maybe is it good way to do this?</p> <p>EDIT: </p> <pre><code>table[1::2], table[::2] =&gt; table[::2], table[1::2] </code></pre>
3
2009-06-10T07:56:19Z
974,577
<p>Try:</p> <pre><code>def alternate(i): i = iter(i) while True: yield(i.next(), i.next()) &gt;&gt;&gt; list(alternate(range(10))) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] </code></pre> <p>This solution works on any sequence, not just lists, and doesn't copy the sequence (it will be far more efficient if you only want the first few elements of a long sequence).</p>
4
2009-06-10T09:33:42Z
[ "python", "for-loop", "itertools" ]
How to create single Python dict from a list of dicts by summing values with common keys?
974,678
<p>I have a list of dictionaries, e.g:</p> <pre><code>dictList = [ {'a':3, 'b':9, 'c':4}, {'a':9, 'b':24, 'c':99}, {'a':10, 'b':23, 'c':88} ] </code></pre> <p>All the dictionaries have the same keys e.g. <em>a</em>, <em>b</em>, <em>c</em>. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same keys from all the dictionaries in the original list.</p> <p>So for the above example, the output should be:</p> <pre><code>{'a':22, 'b':56, 'c':191} </code></pre> <p>What would be the most efficient way of doing this? I currently have:</p> <pre><code>result = {} for myDict in dictList: for k in myDict: result[k] = result.setdefault(k, 0) + myDict[k] </code></pre>
7
2009-06-10T10:01:46Z
974,692
<p>If all dicts have all keys, you could do this as:</p> <pre><code>&gt;&gt;&gt; dict((key, sum(d[key] for d in dictList)) for key in dictList[0]) {'a': 22, 'b': 56, 'c': 191} </code></pre> <p><strong>[Edit]</strong> If speed is a big priority, you can also shave off ~20% (though at the cost of some readability) with the following instead:</p> <pre><code>import operator, itertools dict((key, sum(itertools.imap(operator.itemgetter(key), dictList))) for key in dictList[0]) </code></pre> <p>The speed depends on the size of the dict. I get the following timings for the original 3 item list, and for various different sizes (created by mutliplying the original list by 10, 100 or 1000 etc):</p> <pre><code>List Size Original dict+generator imap+itemgetter 3 0.054 0.090 0.097 30 0.473 0.255 0.236 300 4.668 1.884 1.529 3000 46.668 17.975 14.499 </code></pre> <p>(All times for 10,000 runs)</p> <p>So it's slightly slower for just 3, but two to three times as fast for larger lists.</p>
18
2009-06-10T10:06:16Z
[ "python" ]
How to create single Python dict from a list of dicts by summing values with common keys?
974,678
<p>I have a list of dictionaries, e.g:</p> <pre><code>dictList = [ {'a':3, 'b':9, 'c':4}, {'a':9, 'b':24, 'c':99}, {'a':10, 'b':23, 'c':88} ] </code></pre> <p>All the dictionaries have the same keys e.g. <em>a</em>, <em>b</em>, <em>c</em>. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same keys from all the dictionaries in the original list.</p> <p>So for the above example, the output should be:</p> <pre><code>{'a':22, 'b':56, 'c':191} </code></pre> <p>What would be the most efficient way of doing this? I currently have:</p> <pre><code>result = {} for myDict in dictList: for k in myDict: result[k] = result.setdefault(k, 0) + myDict[k] </code></pre>
7
2009-06-10T10:01:46Z
974,868
<p>Try this.</p> <pre><code>from collections import defaultdict result = defaultdict(int) for myDict in dictList: for k in myDict: result[k] += myDict[k] </code></pre>
7
2009-06-10T10:52:58Z
[ "python" ]
How to create single Python dict from a list of dicts by summing values with common keys?
974,678
<p>I have a list of dictionaries, e.g:</p> <pre><code>dictList = [ {'a':3, 'b':9, 'c':4}, {'a':9, 'b':24, 'c':99}, {'a':10, 'b':23, 'c':88} ] </code></pre> <p>All the dictionaries have the same keys e.g. <em>a</em>, <em>b</em>, <em>c</em>. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same keys from all the dictionaries in the original list.</p> <p>So for the above example, the output should be:</p> <pre><code>{'a':22, 'b':56, 'c':191} </code></pre> <p>What would be the most efficient way of doing this? I currently have:</p> <pre><code>result = {} for myDict in dictList: for k in myDict: result[k] = result.setdefault(k, 0) + myDict[k] </code></pre>
7
2009-06-10T10:01:46Z
12,960,608
<p>I'm not sure how it relates to the other answers speed wise, but there is always</p> <pre><code>from collections import Counter result = sum(map(Counter,dictList),Counter()) </code></pre> <p><code>Counter</code> is a subclass of <code>dict</code> and it can be used in place of <code>dict</code> in most places. If necessary, you could just convert it back into a <code>dict</code></p> <pre><code>result = dict(result) </code></pre>
0
2012-10-18T17:46:56Z
[ "python" ]
Python + MySQLdb executemany
974,702
<p>I'm using Python and its MySQLdb module to import some measurement data into a Mysql database. The amount of data that we have is quite high (currently about ~250 MB of csv files and plenty of more to come).</p> <p>Currently I use cursor.execute(...) to import some metadata. This isn't problematic as there are only a few entries for these.</p> <p>The problem is that when I try to use cursor.executemany() to import larger quantities of the actual measurement data, MySQLdb raises a</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>My current code is</p> <pre><code>def __insert_values(self, values): cursor = self.connection.cursor() cursor.executemany(""" insert into values (ensg, value, sampleid) values (%s, %s, %s)""", values) cursor.close() </code></pre> <p>where <code>values</code> is a list of tuples containing three strings each. Any ideas what could be wrong with this?</p> <p><strong>Edit:</strong></p> <p>The values are generated by</p> <pre><code>yield (prefix + row['id'], row['value'], sample_id) </code></pre> <p>and then read into a list one thousand at a time where row is and iterator coming from <code>csv.DictReader</code>.</p>
4
2009-06-10T10:09:58Z
974,917
<p>The message you get indicates that inside the <code>executemany()</code> method, one of the conversions failed. Check your <code>values</code> list for a tuple longer than 3.</p> <p>For a quick verification:</p> <pre><code>max(map(len, values)) </code></pre> <p>If the result is higher than 3, locate your bad tuple with a filter:</p> <pre><code>[t for t in values if len(t) != 3] </code></pre> <p>or, if you need the index:</p> <pre><code>[(i,t) for i,t in enumerate(values) if len(t) != 3] </code></pre>
3
2009-06-10T11:02:20Z
[ "python", "mysql", "executemany" ]
Python + MySQLdb executemany
974,702
<p>I'm using Python and its MySQLdb module to import some measurement data into a Mysql database. The amount of data that we have is quite high (currently about ~250 MB of csv files and plenty of more to come).</p> <p>Currently I use cursor.execute(...) to import some metadata. This isn't problematic as there are only a few entries for these.</p> <p>The problem is that when I try to use cursor.executemany() to import larger quantities of the actual measurement data, MySQLdb raises a</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>My current code is</p> <pre><code>def __insert_values(self, values): cursor = self.connection.cursor() cursor.executemany(""" insert into values (ensg, value, sampleid) values (%s, %s, %s)""", values) cursor.close() </code></pre> <p>where <code>values</code> is a list of tuples containing three strings each. Any ideas what could be wrong with this?</p> <p><strong>Edit:</strong></p> <p>The values are generated by</p> <pre><code>yield (prefix + row['id'], row['value'], sample_id) </code></pre> <p>and then read into a list one thousand at a time where row is and iterator coming from <code>csv.DictReader</code>.</p>
4
2009-06-10T10:09:58Z
1,002,018
<p>In retrospective this was a really stupid but hard to spot mistake. Values is a keyword in sql so the table name values needs quotes around it.</p> <pre><code>def __insert_values(self, values): cursor = self.connection.cursor() cursor.executemany(""" insert into `values` (ensg, value, sampleid) values (%s, %s, %s)""", values) cursor.close() </code></pre>
5
2009-06-16T14:54:47Z
[ "python", "mysql", "executemany" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
974,809
<p>Maybe you can wget and then inspect the data in Python?</p>
1
2009-06-10T10:38:52Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
975,759
<p>There shouldn't be a difference really. All urlretrieve does is make a simple HTTP GET request. Have you taken out your data processing code and done a straight throughput comparison of wget vs. pure python?</p>
0
2009-06-10T13:55:34Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
976,135
<p>Please show us some code. I'm pretty sure that it has to be with the code and not on urlretrieve. </p> <p>I've worked with it in the past and never had any speed related issues.</p>
0
2009-06-10T14:59:41Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
977,289
<pre><code>import subprocess myurl = 'http://some_server/data/' subprocess.call(["wget", "-r", "-np", "-A", "files", myurl]) </code></pre>
1
2009-06-10T18:10:46Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
977,311
<p>Probably a unit math error on your part. </p> <p>Just noticing that <a href="http://www.google.com/search?hl=en&amp;rlz=1C1GGLS%5FenUS291US304&amp;q=500%20KB%20in%20Mb&amp;aq=f&amp;oq=&amp;aqi=g1">500KB/s (kilobytes) is equal to 4Mb/s (megabits)</a>.</p>
37
2009-06-10T18:14:50Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
977,466
<p>As for the html parsing, the fastest/easiest you will probably get is using <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> As for the http requests themselves: <a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a> is very easy to use, and could possibly speed up downloads because it supports http 1.1 keep-alive connections and gzip compression. There is also <a href="http://pycurl.sourceforge.net/" rel="nofollow">pycURL</a> which claims to be very fast (but more difficult to use), and is build on curllib, but I've never used that.</p> <p>You could also try to download different files concurrently, but also keep in mind that trying to optimize your download times too far may be not very polite towards the website in question.</p> <p>Sorry for the lack of hyperlinks, but SO tells me "sorry, new users can only post a maximum of one hyperlink"</p>
3
2009-06-10T18:46:07Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
981,185
<p>Transfer speeds can be easily misleading.. Could you try with the following script, which simply downloads the same URL with both <code>wget</code> and <code>urllib.urlretrieve</code> - run it a few times incase you're behind a proxy which caches the URL on the second attempt.</p> <p>For small files, wget will take slightly longer due to the external process' startup time, but for larger files that should be come irrelevant.</p> <pre><code>from time import time import urllib import subprocess target = "http://example.com" # change this to a more useful URL wget_start = time() proc = subprocess.Popen(["wget", target]) proc.communicate() wget_end = time() url_start = time() urllib.urlretrieve(target) url_end = time() print "wget -&gt; %s" % (wget_end - wget_start) print "urllib.urlretrieve -&gt; %s" % (url_end - url_start) </code></pre>
3
2009-06-11T13:47:59Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
2,003,565
<p>urllib works for me as fast as wget. try this code. it shows the progress in percentage just as wget.</p> <pre><code>import sys, urllib def reporthook(a,b,c): # ',' at the end of the line is important! print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c), #you can also use sys.stdout.write #sys.stdout.write("\r% 3.1f%% of %d bytes" # % (min(100, float(a * b) / c * 100), c) sys.stdout.flush() for url in sys.argv[1:]: i = url.rfind('/') file = url[i+1:] print url, "-&gt;", file urllib.urlretrieve(url, file, reporthook) </code></pre>
6
2010-01-05T01:27:12Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
2,350,655
<p>You can use <code>wget -k</code> to engage relative links in all urls.</p>
0
2010-02-28T09:35:55Z
[ "python", "urllib2", "wget" ]
wget Vs urlretrieve of python
974,741
<p>I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.</p> <p>The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.</p> <p>But, just to play around I was also using python to build my urlparser.</p> <p>Downloading via Python's urlretrieve is damm slow, possible 4 times as slow as wget. The download rate is 500kb/sec. I use HTMLParser for parsing the href tags.</p> <p>I am not sure why is this happening. Are there any settings for this.</p> <p>Thanks</p>
8
2009-06-10T10:18:59Z
7,782,898
<p>Since python suggests using <code>urllib2</code> instead of <code>urllib</code>, I take a test between <code>urllib2.urlopen</code> and <code>wget</code>.</p> <p>The result is, it takes nearly the same time for both of them to download the same file.Sometimes, <code>urllib2</code> performs even better. </p> <p>The advantage of <code>wget</code> lies in a dynamic progress bar to show the percent finished and the current download speed when transferring.</p> <p>The file size in my test is <code>5MB</code>.I haven't used any cache module in python and I am not aware of how <code>wget</code> works when downloading big size file. </p>
1
2011-10-16T07:13:37Z
[ "python", "urllib2", "wget" ]
Cleaning up an internal pysqlite connection on object destruction
974,813
<p>I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit <code>close</code> method, but this is somewhat cumbersome, especially when exceptions can happen in the calling code.</p> <p>I'm considering using the <code>__del__</code> method for closing, but after some reading online I have concerns. Is this a valid usage pattern? Can I be sure that the internal resources will be freed in <code>__del__</code> correctly?</p> <p><a href="http://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object">This discussion</a> raised a similar question but found no satisfactory answer. I don't want to have an explicit <code>close</code> method, and using <code>with</code> isn't an option, because my object isn't used as simply as open-play-close, but is kept as a member of another, larger object, that uses it while running in a GUI.</p> <p>C++ has perfectly working destructors where one can free resources safely, so I would imagine Python has something agreed-upon too. For some reason it seems not to be the case, and many in the community vow against <code>__del__</code>. What's the alternative, then?</p>
5
2009-06-10T10:39:34Z
974,859
<p>Read up on the <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement">with</a> statement. You're describing its use case.</p> <p>You'll need to wrap your connection in a "Context Manager" class that handles the <code>__enter__</code> and <code>__exit__</code> methods used by the <code>with</code> statement.</p> <p>See <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a> for more information.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"my object isn't used as simply as open-play-close, but is kept as a member of another, larger object"</p> <pre><code>class AnObjectWhichMustBeClosed( object ): def __enter__( self ): # acquire def __exit__( self, type, value, traceback ): # release def open( self, dbConnectionInfo ): # open the connection, updating the state for __exit__ to handle. class ALargerObject( object ): def __init__( self ): pass def injectTheObjectThatMustBeClosed( self, anObject ): self.useThis = anObject class MyGuiApp( self ): def run( self ): # build GUI objects large = ALargeObject() with AnObjectWhichMustBeClosed() as x: large.injectTheObjectThatMustBeClosed( x ) mainLoop() </code></pre> <p>Some folks call this "Dependency Injection" and "Inversion of Control". Other folks call this the <strong>Strategy</strong> pattern. The "ObjectThatMustBeClosed" is a strategy, plugged into some larger object. The assembly is created at a top-level of the GUI app, since that's usually where resources like databases are acquired.</p>
7
2009-06-10T10:51:46Z
[ "python", "destructor", "pysqlite" ]
Cleaning up an internal pysqlite connection on object destruction
974,813
<p>I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit <code>close</code> method, but this is somewhat cumbersome, especially when exceptions can happen in the calling code.</p> <p>I'm considering using the <code>__del__</code> method for closing, but after some reading online I have concerns. Is this a valid usage pattern? Can I be sure that the internal resources will be freed in <code>__del__</code> correctly?</p> <p><a href="http://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object">This discussion</a> raised a similar question but found no satisfactory answer. I don't want to have an explicit <code>close</code> method, and using <code>with</code> isn't an option, because my object isn't used as simply as open-play-close, but is kept as a member of another, larger object, that uses it while running in a GUI.</p> <p>C++ has perfectly working destructors where one can free resources safely, so I would imagine Python has something agreed-upon too. For some reason it seems not to be the case, and many in the community vow against <code>__del__</code>. What's the alternative, then?</p>
5
2009-06-10T10:39:34Z
974,951
<p>You can make a connection module, since modules keep the same object in the whole application, and register a function to close it with the <a href="http://docs.python.org/library/atexit.html" rel="nofollow"><code>atexit</code></a> module</p> <pre><code># db.py: import sqlite3 import atexit con = None def get_connection(): global con if not con: con = sqlite3.connect('somedb.sqlite') atexit.register(close_connection, con) return con def close_connection(some_con): some_con.commit() some_con.close() # your_program.py import db con = db.get_connection() cur = con.cursor() cur.execute("SELECT ...") </code></pre> <p>This sugestion is based on the assumption that the connection in your application seems like a single instance (singleton) which a module global provides well.</p> <p>If that's not the case, then you can use a destructor.</p> <p>However destructors don't go well with garbage collectors and circular references (you must remove the circular reference yourself before the destructor is called) and if that's not the case (you need multiple connections) then you can go for a destructor. Just don't keep circular references around or you'll have to break them yourself.</p> <p>Also, what you said about C++ is wrong. If you use destructors in C++ they are called either when the block that defines the object finishes (like python's <code>with</code>) or when you use the <code>delete</code> keyword (that deallocates an object created with <code>new</code>). Outside that you must use an explicit <code>close()</code> that is not the destructor. So it is just like python - python is even "better" because it has a garbage collector.</p>
4
2009-06-10T11:09:59Z
[ "python", "destructor", "pysqlite" ]
python not starting properly
974,821
<p>I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?</p>
0
2009-06-10T10:42:38Z
974,834
<p>you can't run a command that isn't in your path. it should be set globally when you installed python.</p> <p>type 'set' at a dos prompt and look at the PATH variable. c:\python25 (or whever you installed python) has to be in that variable ie PATH=c:\windows;c:\python25;... etc </p> <p>if it isn't in PATH then you or the installer missed the part where you needed to set it. It can be done from the 'Environment Variables' button in the 'System' control panel.</p>
1
2009-06-10T10:45:35Z
[ "python", "windows", "django-admin" ]
python not starting properly
974,821
<p>I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?</p>
0
2009-06-10T10:42:38Z
974,848
<p>Either use the system control panel to set the <code>PATH</code> environment variable that applies permanently or</p> <p>Reinstall Python as a system administrator so that the installer can set the registry and environment variables for you.</p> <p>If you install the "just for me" option, then you have to set the <code>PATH</code> variable in the control panel.</p>
0
2009-06-10T10:48:41Z
[ "python", "windows", "django-admin" ]
python not starting properly
974,821
<p>I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?</p>
0
2009-06-10T10:42:38Z
975,238
<p>You probably need to add Python to you dos path. Here's a video that may help you out:</p> <p><a href="http://showmedo.com/videotutorials/video?name=960000&amp;fromSeriesID=96" rel="nofollow">http://showmedo.com/videotutorials/video?name=960000&amp;fromSeriesID=96</a></p>
2
2009-06-10T12:19:19Z
[ "python", "windows", "django-admin" ]
python not starting properly
974,821
<p>I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run properly?</p>
0
2009-06-10T10:42:38Z
975,292
<p>In your path, I think you need to have both the location of the Python install and the Python\Scripts folder. For example, on XP, I have C:\Python25;C:\Python25\Scripts. Can you verify that you have both?</p>
0
2009-06-10T12:34:46Z
[ "python", "windows", "django-admin" ]
Multiply operator applied to list(data structure)
974,931
<p>I'm reading <a href="http://openbookproject.net/thinkCSpy/">How to think like a computer scientist</a> which is an introductory text for "Python Programming".</p> <p>I want to clarify the behaviour of multiply operator (<code>*</code>) when applied to lists.</p> <p>Consider the function <strong>make_matrix</strong></p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ return [[0] * columns] * rows </code></pre> <p>The actual output is </p> <pre><code>[[0, 7], [0, 7], [0, 7], [0, 7]] </code></pre> <p>The correct version of <strong>make_matrix</strong> is :</p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(3, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ matrix = [] for row in range(rows): matrix += [[0] * columns] return matrix </code></pre> <p>The reason why first version of <strong>make_matrix</strong> fails ( as explained in the book at 9.8 ) is that</p> <p><em>...each row is an alias of the other rows...</em></p> <p>I wonder why </p> <pre><code>[[0] * columns] * rows </code></pre> <p>causes <em>...each row is an alias of the other rows...</em></p> <p>but not </p> <pre><code>[[0] * columns] </code></pre> <p>i.e. why each <code>[0]</code> in a row is not an alias of other row element.</p>
11
2009-06-10T11:06:42Z
974,959
<p>lists are not primitives, they are passed by reference. A copy of a list is a pointer to a list (in C jargon). Anything you do to the list happens to all copies of the list and the copies of its contents unless you do a shallow copy.</p> <pre><code>[[0] * columns] * rows </code></pre> <p>Oops, we've just made a big list of pointers to [0]. Change one and you change them all.</p> <p>Integers are not passed by reference, they are really copied, therefore [0] * contents is really making lots of NEW 0's and appending them to the list.</p>
-3
2009-06-10T11:11:43Z
[ "python", "python-datamodel" ]
Multiply operator applied to list(data structure)
974,931
<p>I'm reading <a href="http://openbookproject.net/thinkCSpy/">How to think like a computer scientist</a> which is an introductory text for "Python Programming".</p> <p>I want to clarify the behaviour of multiply operator (<code>*</code>) when applied to lists.</p> <p>Consider the function <strong>make_matrix</strong></p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ return [[0] * columns] * rows </code></pre> <p>The actual output is </p> <pre><code>[[0, 7], [0, 7], [0, 7], [0, 7]] </code></pre> <p>The correct version of <strong>make_matrix</strong> is :</p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(3, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ matrix = [] for row in range(rows): matrix += [[0] * columns] return matrix </code></pre> <p>The reason why first version of <strong>make_matrix</strong> fails ( as explained in the book at 9.8 ) is that</p> <p><em>...each row is an alias of the other rows...</em></p> <p>I wonder why </p> <pre><code>[[0] * columns] * rows </code></pre> <p>causes <em>...each row is an alias of the other rows...</em></p> <p>but not </p> <pre><code>[[0] * columns] </code></pre> <p>i.e. why each <code>[0]</code> in a row is not an alias of other row element.</p>
11
2009-06-10T11:06:42Z
975,024
<p>EVERYTHING in python are objects, and python never makes copies unless explicity asked to do so.</p> <p>When you do </p> <pre><code>innerList = [0] * 10 </code></pre> <p>you create a list with 10 elements, <strong>all of them refering to the same <code>int</code> object <em><code>0</code></em></strong>.</p> <p>Since integer objects are <strong>immutable</strong>, when you do</p> <pre><code>innerList[1] = 15 </code></pre> <p>You are changing the second element of the list so that it refers to another integer <em><code>15</code></em>. That always works because of <em><code>int</code></em> objects immutability.</p> <p>That's why</p> <pre><code>outerList = innerList * 5 </code></pre> <p>Will create a <code>list</code> object with 5 elements, each one is a reference to <strong>the same <code>innerList</code></strong> just as above. But since <code>list</code> objects are <strong>mutable</strong>:</p> <pre><code>outerList[2].append('something') </code></pre> <p>Is the same as:</p> <pre><code>innerList.append('something') </code></pre> <p>Because they are two references to the <strong>same <code>list</code> object</strong>. So the element ends up in that single <code>list</code>. It appears to be duplicated, but the fact is that there is only one <code>list</code> object, and many references to it.</p> <p>By contrast if you do</p> <pre><code>outerList[1] = outerList[1] + ['something'] </code></pre> <p>Here you are <strong>creating <em>another</em> <code>list</code> object</strong> (using <code>+</code> with lists is an explicit copy), and assigning a reference to it into the second position of <code>outerList</code>. If you "append" the element this way (not really appending, but creating another list), <code>innerList</code> will be unaffected.</p>
18
2009-06-10T11:27:19Z
[ "python", "python-datamodel" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
974,956
<p>Just create a string out of it.</p> <pre><code>myinteger = 212345 number_string = str(myinteger) </code></pre> <p>That's enough. Now you can iterate over it:</p> <pre><code>for ch in number_string: print ch # will print each digit in order </code></pre> <p>Or you can slice it:</p> <pre><code>print number_string[:2] # first two digits print number_string[-3:] # last three digits print number_string[3] # forth digit </code></pre> <p><hr /></p> <p>Or better, don't convert the user's input to an integer (the user types a string)</p> <pre><code>isbn = raw_input() for pos, ch in enumerate(reversed(isbn)): print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2) </code></pre> <p>For more information read a <a href="http://docs.python.org/tut">tutorial</a>.</p>
66
2009-06-10T11:11:07Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
974,967
<pre><code>list_of_ints = [int(i) for i in str(ISBN)] </code></pre> <p>Will give you a ordered list of ints. Of course, given duck typing, you might as well work with str(ISBN).</p> <p>Edit: As mentioned in the comments, this list isn't sorted in the sense of being ascending or descending, but it does have a defined order (sets, dictionaries, etc in python in theory don't, although in practice the order tends to be fairly reliable). If you want to sort it:</p> <p>list_of_ints.sort()</p> <p>is your friend. Note that sort() sorts in place (as in, actually changes the order of the existing list) and doesn't return a new list.</p>
15
2009-06-10T11:12:53Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
975,039
<pre><code>while number: digit = number % 10 # do whatever with digit # remove last digit from number (as integer) number //= 10 </code></pre> <p>On each iteration of the loop, it removes the last digit from number, assigning it to $digit. It's in reverse, starts from the last digit, finishes with the first</p>
48
2009-06-10T11:30:36Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
3,706,281
<p>How about a one-liner list of digits...</p> <pre><code>ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l) </code></pre>
0
2010-09-14T05:20:40Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
3,706,468
<p>On Older versions of Python...</p> <pre><code>map(int,str(123)) </code></pre> <p>On New Version 3k</p> <pre><code>list(map(int,str(123))) </code></pre>
10
2010-09-14T06:07:16Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
7,787,740
<p>Convert it to string and map over it with the int() function.</p> <pre><code>map(int, str(1231231231)) </code></pre>
2
2011-10-16T22:19:24Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
12,435,874
<p>Recursion version:</p> <pre><code>def int_digits(n): return [n] if n&lt;10 else int_digits(n/10)+[n%10] </code></pre>
0
2012-09-15T08:38:56Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
17,458,472
<p>Converting to <code>str</code> is definitely slower then dividing by 10.</p> <p><code>map</code> is sligthly slower than list comprehension:</p> <pre><code>convert to string with map 2.13599181175 convert to string with list comprehension 1.92812991142 modulo, division, recursive 0.948769807816 modulo, division 0.699964046478 </code></pre> <p>These times were returned by the following code on my laptop:</p> <pre><code>foo = """\ def foo(limit): return sorted(set(map(sum, map(lambda x: map(int, list(str(x))), map(lambda x: x * 9, range(limit)))))) foo(%i) """ bar = """\ def bar(limit): return sorted(set([sum([int(i) for i in str(n)]) for n in [k *9 for k in range(limit)]])) bar(%i) """ rac = """\ def digits(n): return [n] if n&lt;10 else digits(n / 10)+[n %% 10] def rabbit(limit): return sorted(set([sum(digits(n)) for n in [k *9 for k in range(limit)]])) rabbit(%i) """ rab = """\ def sum_digits(number): result = 0 while number: digit = number %% 10 result += digit number /= 10 return result def rabbit(limit): return sorted(set([sum_digits(n) for n in [k *9 for k in range(limit)]])) rabbit(%i) """ import timeit print "convert to string with map", timeit.timeit(foo % 100, number=10000) print "convert to string with list comprehension", timeit.timeit(bar % 100, number=10000) print "modulo, division, recursive", timeit.timeit(rac % 100, number=10000) print "modulo, division", timeit.timeit(rab % 100, number=10000) </code></pre>
1
2013-07-03T21:33:35Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
21,102,087
<p>Use the body of this loop to do whatever you want to with the digits</p> <pre><code>for digit in map(int, str(my_number)): </code></pre>
1
2014-01-13T21:51:31Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
21,158,316
<p>I have made this program and here is the bit of code that actually calculates the check digit in my program</p> <pre><code> #Get the 10 digit number number=input("Please enter ISBN number: ") #Explained below no11 = (((int(number[0])*11) + (int(number[1])*10) + (int(number[2])*9) + (int(number[3])*8) + (int(number[4])*7) + (int(number[5])*6) + (int(number[6])*5) + (int(number[7])*4) + (int(number[8])*3) + (int(number[9])*2))/11) #Round to 1 dp no11 = round(no11, 1) #explained below no11 = str(no11).split(".") #get the remainder and check digit remainder = no11[1] no11 = (11 - int(remainder)) #Calculate 11 digit ISBN print("Correct ISBN number is " + number + str(no11)) </code></pre> <p>Its a long line of code, but it splits the number up, multiplies the digits by the appropriate amount, adds them together and divides them by 11, in one line of code. The .split() function just creates a list (being split at the decimal) so you can take the 2nd item in the list and take that from 11 to find the check digit. This could also be made even more efficient by changing these two lines:</p> <pre><code> remainder = no11[1] no11 = (11 - int(remainder)) </code></pre> <p>To this:</p> <pre><code> no11 = (11 - int(no11[1])) </code></pre> <p>Hope this helps :)</p>
1
2014-01-16T09:48:27Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
22,963,974
<pre><code>(number/10**x)%10 </code></pre> <p>You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.</p>
3
2014-04-09T13:24:56Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
30,133,786
<p>Similar to <a href="http://stackoverflow.com/a/975039/18866">this</a> answer but more a more "pythonic" way to iterate over the digis would be:</p> <pre><code>while number: # "pop" the rightmost digit number, digit = divmod(number, 10) </code></pre>
0
2015-05-08T22:31:46Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
32,567,460
<p><strong>Answer:</strong> 165</p> <p><strong>Method:</strong> brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.</p> <pre><code>from math import sqrt, floor is_ps = lambda x: floor(sqrt(x)) ** 2 == x count = 0 for n in range(1002, 10000, 3): if n % 11 and is_ps(sum(map(int, str(n)))): count += 1 print "#%i: %s" % (count, n) </code></pre>
0
2015-09-14T14:32:51Z
[ "python", "integer", "decimal" ]
Split an integer into digits to compute an ISBN checksum
974,952
<p>I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.</p>
38
2009-06-10T11:10:07Z
32,616,787
<p>Just assuming you want to get the <em>i</em>-th least significant digit from an integer number <em>x</em>, you can try:</p> <pre><code>(abs(x)%(10**i))/(10**(i-1)) </code></pre> <p>I hope it helps.</p>
0
2015-09-16T19:09:35Z
[ "python", "integer", "decimal" ]
access is denied in GAE in eclipse
975,016
<p>When I am trying to to do Model.put() in eclipse for a google python app after changing the parameter of --datastore_path="F:/tmp/myapp_datastore" in arguments of debug configurations.I dont know if its related to above change or is there any other magic behind the scene. Any help.</p> <pre><code>exception value:[Error 5] Access is denied </code></pre> <p><strong>UPDATE</strong>, Added codes for OP,</p> <p>Everything is working fine for another application from command prompt but when i use the same from eclipse i get following dump </p> <p>The below comes in console window of eclipse </p> <pre><code>ERROR 2009-06-11 10:19:41,312 dev_appserver.py:2906] Exception encountered handling request Traceback (most recent call last): File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2876, in _HandleRequest base_env_dict=env_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2163, in Dispatch self._module_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2081, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 1979, in ExecuteOrImportScript script_module.main() File "F:\eclipse\workspace\checkthis\src\carpoolkaro.py", line 749, in main run_wsgi_app(application) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\util.py", line 76, in run_wsgi_app result = application(env, _start_response) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\__init__.py", line 517, in __call__ handler.handle_exception(e, self.__debug) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\__init__.py", line 384, in handle_exception self.error(500) TypeError: 'str' object is not callable INFO 2009-06-11 10:19:41,312 dev_appserver.py:2935] "POST /suggest HTTP/1.1" 500 - </code></pre> <p>This is screen dump of application in browser window </p> <pre><code> F:\Program Files\Google\google_appengine\google\appengine\ext\webapp \__init__.py in handle_exception(self=&lt;__main__.SuggestHandler object at 0x019C0510&gt;, exception=WindowsError(5, 'Access is denied'), debug_mode=True) </code></pre>
0
2009-06-10T11:24:18Z
2,046,254
<p>According to this error,</p> <pre><code>TypeError: 'str' object is not callable </code></pre> <p>I guess, you have shadowed built-in object <code>str</code> to something else.</p> <p>For example, you used <code>str="dummy"</code> in your code and <code>str</code> became uncallable object.</p>
1
2010-01-12T02:14:26Z
[ "python", "eclipse", "google-app-engine" ]
access is denied in GAE in eclipse
975,016
<p>When I am trying to to do Model.put() in eclipse for a google python app after changing the parameter of --datastore_path="F:/tmp/myapp_datastore" in arguments of debug configurations.I dont know if its related to above change or is there any other magic behind the scene. Any help.</p> <pre><code>exception value:[Error 5] Access is denied </code></pre> <p><strong>UPDATE</strong>, Added codes for OP,</p> <p>Everything is working fine for another application from command prompt but when i use the same from eclipse i get following dump </p> <p>The below comes in console window of eclipse </p> <pre><code>ERROR 2009-06-11 10:19:41,312 dev_appserver.py:2906] Exception encountered handling request Traceback (most recent call last): File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2876, in _HandleRequest base_env_dict=env_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2163, in Dispatch self._module_dict) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 2081, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "F:\Program Files\Google\google_appengine\google\appengine\tools \dev_appserver.py", line 1979, in ExecuteOrImportScript script_module.main() File "F:\eclipse\workspace\checkthis\src\carpoolkaro.py", line 749, in main run_wsgi_app(application) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\util.py", line 76, in run_wsgi_app result = application(env, _start_response) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\__init__.py", line 517, in __call__ handler.handle_exception(e, self.__debug) File "F:\Program Files\Google\google_appengine\google\appengine\ext \webapp\__init__.py", line 384, in handle_exception self.error(500) TypeError: 'str' object is not callable INFO 2009-06-11 10:19:41,312 dev_appserver.py:2935] "POST /suggest HTTP/1.1" 500 - </code></pre> <p>This is screen dump of application in browser window </p> <pre><code> F:\Program Files\Google\google_appengine\google\appengine\ext\webapp \__init__.py in handle_exception(self=&lt;__main__.SuggestHandler object at 0x019C0510&gt;, exception=WindowsError(5, 'Access is denied'), debug_mode=True) </code></pre>
0
2009-06-10T11:24:18Z
17,333,455
<p>Error 5 generally means the path you specified is wrong. I recommend you to remove the double quotation marks in your command:</p> <p>Try:</p> <pre><code>--datastore_path=F:/tmp/myapp_datastore </code></pre> <p>and let us know if that helped you</p>
0
2013-06-27T02:11:26Z
[ "python", "eclipse", "google-app-engine" ]
Sending email using google apps SMTP server in Python 2.4
975,065
<p>I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.</p> <pre><code>print "connecting" server = smtplib.SMTP("smtp.gmail.com", 465) print "ehlo" server.ehlo() print "start tls" server.starttls() print "ehlo" server.ehlo() print "log in" if self.smtpuser: server.login(smtpuser, smtppassword) </code></pre> <p>Does anybody have any advice for getting the above code to work with python 2.4?</p>
2
2009-06-10T11:36:35Z
975,081
<p>When I tried setting something similar up for Django apps, I could never get it to work on port 465. Using port 587, which is the other port listed in the <a href="http://mail.google.com/support/bin/answer.py?hl=en&amp;answer=13287" rel="nofollow">GMail docs</a> seemed to work.</p>
3
2009-06-10T11:40:19Z
[ "python", "python-2.4" ]
Sending email using google apps SMTP server in Python 2.4
975,065
<p>I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.</p> <pre><code>print "connecting" server = smtplib.SMTP("smtp.gmail.com", 465) print "ehlo" server.ehlo() print "start tls" server.starttls() print "ehlo" server.ehlo() print "log in" if self.smtpuser: server.login(smtpuser, smtppassword) </code></pre> <p>Does anybody have any advice for getting the above code to work with python 2.4?</p>
2
2009-06-10T11:36:35Z
975,102
<p>Yes I used 587 as the port for my vb.net app too. 465 did not work for me too.</p>
1
2009-06-10T11:43:51Z
[ "python", "python-2.4" ]
Sending email using google apps SMTP server in Python 2.4
975,065
<p>I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.</p> <pre><code>print "connecting" server = smtplib.SMTP("smtp.gmail.com", 465) print "ehlo" server.ehlo() print "start tls" server.starttls() print "ehlo" server.ehlo() print "log in" if self.smtpuser: server.login(smtpuser, smtppassword) </code></pre> <p>Does anybody have any advice for getting the above code to work with python 2.4?</p>
2
2009-06-10T11:36:35Z
980,900
<p>try</p> <p>server.ehlo('user.name@gmail.com')</p> <p>in both places above</p> <p>also look at setting </p> <p>server.set_debuglevel(1) value as required for more info</p>
1
2009-06-11T12:53:39Z
[ "python", "python-2.4" ]
redirecting sys.stdout to python logging
975,248
<p>So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout/sys.stderr goes into the python logging module.</p> <p>Now the main thing is, we want the following printed out: </p> <pre><code>[&lt;ERROR LEVEL&gt;] | &lt;TIME&gt; | &lt;WHERE&gt; | &lt;MSG&gt; </code></pre> <p>Now all sys.stdout / sys.stderr msgs pretty much in all of the python error messages are in the format of [LEVEL] - MSG, which are all written using sys.stdout/sys.stderr. I can parse the fine, in my sys.stdout wrapper and in the sys.stderr wrapper. Then call the corresponding logging level, depending on the parsed input.</p> <p>So basically we have a package called foo, and a subpackage called log. In <code>__init__.py</code> we define the following:</p> <pre><code>def initLogging(default_level = logging.INFO, stdout_wrapper = None, \ stderr_wrapper = None): """ Initialize the default logging sub system """ root_logger = logging.getLogger('') strm_out = logging.StreamHandler(sys.__stdout__) strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_TIME_FORMAT, \ DEFAULT_LOG_TIME_FORMAT)) root_logger.setLevel(default_level) root_logger.addHandler(strm_out) console_logger = logging.getLogger(LOGGER_CONSOLE) strm_out = logging.StreamHandler(sys.__stdout__) #strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_MSG_FORMAT, \ # DEFAULT_LOG_TIME_FORMAT)) console_logger.setLevel(logging.INFO) console_logger.addHandler(strm_out) if stdout_wrapper: sys.stdout = stdout_wrapper if stderr_wrapper: sys.stderr = stderr_wrapper def cleanMsg(msg, is_stderr = False): logy = logging.getLogger('MSG') msg = msg.rstrip('\n').lstrip('\n') p_level = r'^(\s+)?\[(?P&lt;LEVEL&gt;\w+)\](\s+)?(?P&lt;MSG&gt;.*)$' m = re.match(p_level, msg) if m: msg = m.group('MSG') if m.group('LEVEL') in ('WARNING'): logy.warning(msg) return elif m.group('LEVEL') in ('ERROR'): logy.error(msg) return if is_stderr: logy.error(msg) else: logy.info(msg) class StdOutWrapper: """ Call wrapper for stdout """ def write(self, s): cleanMsg(s, False) class StdErrWrapper: """ Call wrapper for stderr """ def write(self, s): cleanMsg(s, True) </code></pre> <p>Now we would call this in one of our scripts for example:</p> <pre><code>import foo.log foo.log.initLogging(20, foo.log.StdOutWrapper(), foo.log.StdErrWrapper()) sys.stdout.write('[ERROR] Foobar blew') </code></pre> <p>Which would be converted into an error log message. Like:</p> <pre><code>[ERROR] | 20090610 083215 | __init__.py | Foobar Blew </code></pre> <p>Now the problem is when we do that, The module where the error message was logged is now the <code>__init__</code> (corresponding to <code>foo.log.__init__.py</code> file) which defeats the whole purpose.</p> <p>I tried doing a deepCopy/shallowCopy of the stderr/stdout objects, but that does nothing, it still says the module the message occured in <code>__init__.py</code>. How can i make it so this doesn't happen?</p>
11
2009-06-10T12:22:23Z
975,504
<p>I think the problem is that your actual log messages are now being created by the <code>logy.error</code> and <code>logy.info</code> calls in <code>cleanMsg</code>, hence that method is the source of the log messages and you are seeing this as <code>__init__.py</code></p> <p>If you look in the source of Python's <code>lib/logging/__init__.py</code> you will see a method defined called <code>findCaller</code> which is what the logging module uses to derive the caller of a logging request.<br> Perhaps you can override this on your logging object to customise the behaviour? </p>
2
2009-06-10T13:15:11Z
[ "python", "logging" ]
redirecting sys.stdout to python logging
975,248
<p>So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout/sys.stderr goes into the python logging module.</p> <p>Now the main thing is, we want the following printed out: </p> <pre><code>[&lt;ERROR LEVEL&gt;] | &lt;TIME&gt; | &lt;WHERE&gt; | &lt;MSG&gt; </code></pre> <p>Now all sys.stdout / sys.stderr msgs pretty much in all of the python error messages are in the format of [LEVEL] - MSG, which are all written using sys.stdout/sys.stderr. I can parse the fine, in my sys.stdout wrapper and in the sys.stderr wrapper. Then call the corresponding logging level, depending on the parsed input.</p> <p>So basically we have a package called foo, and a subpackage called log. In <code>__init__.py</code> we define the following:</p> <pre><code>def initLogging(default_level = logging.INFO, stdout_wrapper = None, \ stderr_wrapper = None): """ Initialize the default logging sub system """ root_logger = logging.getLogger('') strm_out = logging.StreamHandler(sys.__stdout__) strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_TIME_FORMAT, \ DEFAULT_LOG_TIME_FORMAT)) root_logger.setLevel(default_level) root_logger.addHandler(strm_out) console_logger = logging.getLogger(LOGGER_CONSOLE) strm_out = logging.StreamHandler(sys.__stdout__) #strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_MSG_FORMAT, \ # DEFAULT_LOG_TIME_FORMAT)) console_logger.setLevel(logging.INFO) console_logger.addHandler(strm_out) if stdout_wrapper: sys.stdout = stdout_wrapper if stderr_wrapper: sys.stderr = stderr_wrapper def cleanMsg(msg, is_stderr = False): logy = logging.getLogger('MSG') msg = msg.rstrip('\n').lstrip('\n') p_level = r'^(\s+)?\[(?P&lt;LEVEL&gt;\w+)\](\s+)?(?P&lt;MSG&gt;.*)$' m = re.match(p_level, msg) if m: msg = m.group('MSG') if m.group('LEVEL') in ('WARNING'): logy.warning(msg) return elif m.group('LEVEL') in ('ERROR'): logy.error(msg) return if is_stderr: logy.error(msg) else: logy.info(msg) class StdOutWrapper: """ Call wrapper for stdout """ def write(self, s): cleanMsg(s, False) class StdErrWrapper: """ Call wrapper for stderr """ def write(self, s): cleanMsg(s, True) </code></pre> <p>Now we would call this in one of our scripts for example:</p> <pre><code>import foo.log foo.log.initLogging(20, foo.log.StdOutWrapper(), foo.log.StdErrWrapper()) sys.stdout.write('[ERROR] Foobar blew') </code></pre> <p>Which would be converted into an error log message. Like:</p> <pre><code>[ERROR] | 20090610 083215 | __init__.py | Foobar Blew </code></pre> <p>Now the problem is when we do that, The module where the error message was logged is now the <code>__init__</code> (corresponding to <code>foo.log.__init__.py</code> file) which defeats the whole purpose.</p> <p>I tried doing a deepCopy/shallowCopy of the stderr/stdout objects, but that does nothing, it still says the module the message occured in <code>__init__.py</code>. How can i make it so this doesn't happen?</p>
11
2009-06-10T12:22:23Z
976,281
<p>The problem is that the logging module is looking a single layer up the call stack to find who called it, but now your function is an intermediate layer at that point (Though I'd have expected it to report <code>cleanMsg</code>, not <code>__init__</code>, as that's where you're calling into log()). Instead, you need it to go up two levels, or else pass who your caller is into the logged message. You can do this by inspecting up the stack frame yourself and grabbing the calling function, inserting it into the message.</p> <p>To find your calling frame, you can use the inspect module:</p> <pre><code>import inspect f = inspect.currentframe(N) </code></pre> <p>will look up N frames, and return you the frame pointer. ie your immediate caller is currentframe(1), but you may have to go another frame up if this is the stdout.write method. Once you have the calling frame, you can get the executing code object, and look at the file and function name associated with it. eg:</p> <pre><code>code = f.f_code caller = '%s:%s' % (code.co_filename, code.co_name) </code></pre> <p>You may also need to put some code to handle non-python code calling into you (ie. C functions or builtins), as these may lack f_code objects.</p> <p>Alternatively, following up <a href="http://stackoverflow.com/questions/975248/redirecting-sys-stdout-to-python-logging/975504#975504">mikej's answer</a>, you could use the same approach in a custom Logger class inheriting from logging.Logger that overrides findCaller to navigate several frames up, rather than one.</p>
6
2009-06-10T15:18:15Z
[ "python", "logging" ]
Why is Logging going in an infinite Loop?
975,456
<p>I have the following code:</p> <pre><code>#!/usr/bin/env python import logging import sys import copy class Wrapper: def write(self, s): #sys.__stdout__.write(s) loggy = logging.getLogger('foobar') loggy.info(s) def blah(): logger = logging.getLogger('foobar') logger.setLevel(logging.DEBUG) streamhandle = logging.StreamHandler(sys.stdout) streamhandle.setFormatter(logging.Formatter('[%(message)s]')) logger.addHandler(streamhandle) sys.stdout = Wrapper() sys.stderr = Wrapper() if __name__ == '__main__': blah() logger = logging.getLogger('') #print logger.handlers #for handler in logger.handlers: # print handler fooy = logging.getLogger('foobar') #print fooy.handlers sys.stdout.write('i love you') logging.log(logging.DEBUG, 'i love you') </code></pre> <p>This code causes python to go in an infinite recursive loop, and the output is actually incredibly cool:</p> <pre><code>[Error in sys.exitfunc: ] [INFO:foobar:Error in sys.exitfunc: ] [INFO:foobar:INFO:foobar:Error in sys.exitfunc: ] [INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc: ] [INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc: ] [INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc: </code></pre> <p>This keeps growing exponentially :) Its pretty but why is this happening?</p>
0
2009-06-10T13:09:10Z
975,519
<p>The infinite loop is happening because your logger's <code>StreamHandler</code> is set to write its log messages to <code>sys.stdout</code>, but <code>sys.stdout</code> is in turn wrapped and writes back to the very logger that just sent it a write message.</p> <p>Depending on your goals, you're probably better having the <code>Wrapper</code> actually perform output, rather than use logging internally. Something like:</p> <pre><code>class Wrapper(object): def write(self, s): sys.__stdout__.write(s) # sys.__stdout__ points to the original stdout, rather # than the redirected sys.stdout </code></pre>
5
2009-06-10T13:18:05Z
[ "python", "logging" ]
connection reset for concurrent usage by two users GAE
975,651
<p>I am trying to access same python web app in GAE from firefox and IE with different user login and when I start the IE session I get the following error with IE going standstill. why?</p> <pre><code>error: (10054, 'Connection reset by peer') </code></pre>
1
2009-06-10T13:35:40Z
975,692
<p>Do you get a similar outcome when you start the IE session first, then the Firefox session? what about trying two IE sessions, two Firefox sessions, that why you can rule in/out browser differences.</p>
0
2009-06-10T13:42:25Z
[ "python", "google-app-engine", "connection", "reset" ]
connection reset for concurrent usage by two users GAE
975,651
<p>I am trying to access same python web app in GAE from firefox and IE with different user login and when I start the IE session I get the following error with IE going standstill. why?</p> <pre><code>error: (10054, 'Connection reset by peer') </code></pre>
1
2009-06-10T13:35:40Z
979,869
<p>I presume this is on the dev_appserver? Bear in mind that the dev_appserver is single-threaded, so it will not handle multiple concurrent users well.</p> <p>Can you give more detail about exactly what sequence of operations causes this? Are there any stack traces on the dev_appserver console when it happens?</p>
1
2009-06-11T07:54:13Z
[ "python", "google-app-engine", "connection", "reset" ]
connection reset for concurrent usage by two users GAE
975,651
<p>I am trying to access same python web app in GAE from firefox and IE with different user login and when I start the IE session I get the following error with IE going standstill. why?</p> <pre><code>error: (10054, 'Connection reset by peer') </code></pre>
1
2009-06-10T13:35:40Z
993,456
<p>Eclipse creates multiple instances on range of ports and few of them conflicts with pythons working. I could not locate the exact port or did not know how to stop eclipse from doing so. I did simple netstat and observed this behavior of port capturing and causing reset</p>
0
2009-06-14T18:40:55Z
[ "python", "google-app-engine", "connection", "reset" ]
Perl and CopSSH
975,785
<p>I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH?</p>
0
2009-06-10T13:59:25Z
975,857
<p>I suspect CopSSH is giving you different environment vars to a normal GUI login. I'd suggest you type 'set' and see if perl is in the path with any other environment vars it might need. </p> <p>Here is some explanation of <a href="http://apps.sourceforge.net/mediawiki/controltier/index.php?title=OpenSSH%5Fon%5FWindows" rel="nofollow">setting up the CopSSH user environment</a>. It may be of use.</p>
4
2009-06-10T14:13:29Z
[ "python", "perl", "ssh", "openssh" ]
Perl and CopSSH
975,785
<p>I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH?</p>
0
2009-06-10T13:59:25Z
975,889
<p>Are you using <a href="http://www.activestate.com/activeperl/" rel="nofollow">ActiveState</a> or <a href="http://strawberryperl.com/" rel="nofollow">Strawberry</a> Perl? What error messages are you getting? You may find the answers to <a href="http://stackoverflow.com/questions/667471/how-do-i-run-programs-with-strawberry-perl">How do I run programs with Strawberry Perl</a> helpful.</p>
2
2009-06-10T14:18:51Z
[ "python", "perl", "ssh", "openssh" ]
Perl and CopSSH
975,785
<p>I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH?</p>
0
2009-06-10T13:59:25Z
976,287
<p>I just realized CopSSH is based on Cygwin which I think means paths would have to be specified differently. Try using, for example, </p> <p><code>/cygdrive/c/Program\ Files/My\ Program/myprog.exe</code> </p> <p>instead of </p> <p><code>"C:\Program Files\My Program\myprog.exe"</code>.</p> <p>BTW, the following CopSSH FAQ might be applicable as well: <a href="http://www.itefix.no/i2/node/31" rel="nofollow">http://www.itefix.no/i2/node/31</a>.</p>
2
2009-06-10T15:19:08Z
[ "python", "perl", "ssh", "openssh" ]
Can Python adodbapi be used to connect to a paradox db?
976,324
<p>Can Python adodbapi be used to connect to a paradox db? If yes what would the connection string look like?</p>
0
2009-06-10T15:24:32Z
977,156
<p>Yes, that depends on the Paradox ADODB driver you have installed in your windows.</p> <p>Examples:</p> <p>For Paradox 5.x, using Microsoft Jet OLEDB 4.0 driver:</p> <pre><code>r"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\myDb; Extended Properties=Paradox 5.x;" </code></pre> <p>For Paradox 5.x, using Microsoft's Paradox ODBC Driver:</p> <pre><code>r"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X; DefaultDir=c:\pathToDb\;Dbq=c:\pathToDb\;CollatingSequence=ASCII;" </code></pre> <p>For Paradox 7.x, using Microsoft's Paradox ODBC Driver:</p> <pre><code>r"Provider=MSDASQL;Persist Security Info=False;Mode=Read; Extended Properties='DSN=Paradox;DBQ=C:\myDb;DefaultDir=C:\myDb;DriverId=538; FIL=Paradox 7.X;MaxBufferSize=2048;PageTimeout=600;';Initial Catalog=C:\myDb;" </code></pre> <p>Since you're probably going to use the ODBC driver anyway I strongly suggest you use <a href="http://code.google.com/p/pyodbc" rel="nofollow">pyodbc</a> instead. It seems better supported than adodbapi and is also cross-platform.</p> <p>Remember that you must point to the folder containing the .db files, not to the .db itself.</p>
0
2009-06-10T17:47:59Z
[ "python", "paradox" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
976,436
<p>Keep a <code>dict</code> with keys that are the <code>.Id</code> of the buttons and values that are the button names or whatever, so instead of a long <code>if/elif</code> chain you do a single <code>dict</code> lookup in <code>buttonClick</code>.</p> <p>Code snippets: in <code>__init__</code>, add creation and update of the <code>dict</code>:</p> <pre><code>self.panel1 = wx.Panel(self, -1) self.thebuttons = dict() self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.thebuttons[self.button1.Id] = 'Button 1' self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) </code></pre> <p>and so on for 50 buttons (or whatever) [they might be better created in a loop, btw;-)]. So <code>buttonClick</code> becomes:</p> <pre><code> def buttonClick(self,event): button_name = self.thebuttons.get(event.Id, '?No button?') self.setTitle(button_name + ' clicked') </code></pre>
3
2009-06-10T15:41:22Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
976,443
<p>You could create a dictionary of buttons, and do the look based on the <code>id</code> ... something like this:</p> <pre><code>class MyFrame(wx.Frame): def _add_button (self, *args): btn = wx.Button (*args) btn.Bind (wx.EVT_BUTTON, self.buttonClick) self.buttons[btn.id] = btn def __init__ (self): self.button = dict () self._add_button (self.panel1, id=-1, pos=(10, 20), size = (20,20)) self._add_button = (self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.Show (True) def buttonClick(self,event): self.SetTitle (self.buttons[event.Id].label) </code></pre>
1
2009-06-10T15:43:12Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
976,452
<p>I ran into a similar problem: I was generating buttons based on user-supplied data, and I needed the buttons to affect another class, so I needed to pass along information about the buttonclick. What I did was explicitly assign button IDs to each button I generated, then stored information about them in a dictionary to lookup later.</p> <p>I would have thought there would be a prettier way to do this, constructing a custom event passing along more information, but all I've seen is the dictionary-lookup method. Also, I keep around a list of the buttons so I can erase all of them when needed.</p> <p>Here's a slightly scrubbed code sample of something similar:</p> <pre><code>self.buttonDefs = {} self.buttons = [] id_increment = 800 if (row, col) in self.items: for ev in self.items[(row, col)]: id_increment += 1 #### Populate a dict with the event information self.buttonDefs[id_increment ] = (row, col, ev['user']) #### tempBtn = wx.Button(self.sidebar, id_increment , "Choose", (0,50+len(self.buttons)*40), (50,20) ) self.sidebar.Bind(wx.EVT_BUTTON, self.OnShiftClick, tempBtn) self.buttons.append(tempBtn) def OnShiftClick(self, evt): ### Lookup the information from the dict row, col, user = self.buttonDefs[evt.GetId()] self.WriteToCell(row, col, user) self.DrawShiftPicker(row, col) </code></pre>
0
2009-06-10T15:45:16Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
976,691
<p>You could give the button a name, and then look at the name in the event handler.</p> <p>When you make the button</p> <pre><code>b = wx.Button(self, 10, "Default Button", (20, 20)) b.myname = "default button" self.Bind(wx.EVT_BUTTON, self.OnClick, b) </code></pre> <p>When the button is clicked:</p> <pre><code>def OnClick(self, event): name = event.GetEventObject().myname </code></pre>
8
2009-06-10T16:21:51Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
977,110
<p>I recommend that you use different event handlers to handle events from each button. If there is a lot of commonality, you can combine that into a function which <em>returns</em> a function with the specific behavior you want, for instance:</p> <pre><code>def goingTo(self, where): def goingToHandler(event): self.SetTitle("I'm going to " + where) return goingToHandler def __init__(self): buttonA.Bind(wx.EVT_BUTTON, self.goingTo("work")) # clicking will say "I'm going to work" buttonB.Bind(wx.EVT_BUTTON, self.goingTo("home")) # clicking will say "I'm going to home" </code></pre>
5
2009-06-10T17:38:56Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
982,887
<p>Take advantage of what you can do in a language like Python. You can pass extra arguments to your event callback function, like so.</p> <pre><code>import functools def __init__(self): # ... for i in range(10): name = 'Button %d' % i button = wx.Button(parent, -1, name) func = functools.partial(self.on_button, name=name) button.Bind(wx.EVT_BUTTON, func) # ... def on_button(self, event, name): print '%s clicked' % name </code></pre> <p>Of course, the arguments can be anything you want.</p>
7
2009-06-11T18:41:41Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Best way to get the name of a button that called an event?
976,395
<p>In the following code (inspired by <a href="http://www.daniweb.com/code/snippet508.html" rel="nofollow">this</a> snippet), I use a single event handler <code>buttonClick</code> to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() </code></pre>
4
2009-06-10T15:34:43Z
1,040,158
<p>I needed to do the same thing to keep track of button-presses . I used a lambda function to bind to the event . That way I could pass in the entire button object to the event handler function to manipulate accordingly.</p> <pre><code> class PlatGridderTop(wx.Frame): numbuttons = 0 buttonlist = [] def create_another_button(self, event): # wxGlade: PlateGridderTop.&lt;event_handler&gt; buttoncreator_id = wx.ID_ANY butonname = "button" + str(buttoncreator_id) PlateGridderTop.numbuttons = PlateGridderTop.numbuttons + 1 thisbutton_number = PlateGridderTop.numbuttons self.buttonname = wx.Button(self,buttoncreator_id ,"ChildButton %s" % thisbutton_number ) self.Bind(wx.EVT_BUTTON,lambda event, buttonpressed=self.buttonname: self.print_button_press(event,buttonpressed),self.buttonname) self.buttonlist.append(self.buttonname) self.__do_layout() print "Clicked plate button %s" % butonname event.Skip() def print_button_press(self,event,clickerbutton): """Just a dummy method that responds to a button press""" print "Clicked a created button named %s with wxpython ID %s" % (clickerbutton.GetLabel(),event.GetId()) </code></pre> <p>Disclaimer : This is my first post to stackoverflow </p>
0
2009-06-24T18:41:08Z
[ "python", "user-interface", "events", "event-handling", "wxpython" ]
Problem with Python interpreter in Eclipse
976,506
<p>When trying to set the interpreter for python in Eclipse by choosing the executable, clicking OK displays "An error has occured." Does the interpreter name matter?</p>
1
2009-06-10T15:54:47Z
983,463
<p>Testing/running your apps on the command line is the safest bet, especially when writing threaded applications (you can kill your threadlocked program without killing eclipse)</p>
0
2009-06-11T20:29:05Z
[ "python", "eclipse", "ubuntu", "interpreter" ]
Problem with Python interpreter in Eclipse
976,506
<p>When trying to set the interpreter for python in Eclipse by choosing the executable, clicking OK displays "An error has occured." Does the interpreter name matter?</p>
1
2009-06-10T15:54:47Z
1,393,294
<p>I had a similar problems with this on Mac OS X. My problem was that I had a space in Eclipse's application path, e.g. "/Applications/eclipse 3.3/Eclipse".</p> <p>I changed the folder name to "/Applications/eclipse3.3" and it fixed it.</p>
1
2009-09-08T10:50:50Z
[ "python", "eclipse", "ubuntu", "interpreter" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
976,607
<p>A md5-hash is just a 128-bit value, so if you want a random one:</p> <pre><code>import random hash = random.getrandbits(128) print "hash value: %032x" % hash </code></pre> <p>I don't really see the point, though. Maybe you should elaborate why you need this...</p>
72
2009-06-10T16:09:12Z
[ "python", "hash", "md5" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
984,184
<p>Another approach to this specific question:</p> <pre><code>import random, string def random_md5like_hash(): available_chars= string.hexdigits[:16] return ''.join( random.choice(available_chars) for dummy in xrange(32)) </code></pre> <p>I'm not saying it's faster or preferable to any other answer; just that it's <em>another</em> approach :)</p>
5
2009-06-11T22:52:23Z
[ "python", "hash", "md5" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
9,011,133
<p>Yet another approach. You won't have to format an int to get it.</p> <pre><code>import random import string def random_string(length): pool = string.letters + string.digits return ''.join(random.choice(pool) for i in xrange(length)) </code></pre> <p>Gives you flexibility on the length of the string.</p> <pre><code>&gt;&gt;&gt; random_string(64) 'XTgDkdxHK7seEbNDDUim9gUBFiheRLRgg7HyP18j6BZU5Sa7AXiCHP1NEIxuL2s0' </code></pre>
7
2012-01-25T22:10:22Z
[ "python", "hash", "md5" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
9,816,388
<p>This works for both python 2.x and 3.x</p> <pre><code>import os import binascii print(binascii.hexlify(os.urandom(16))) '4a4d443679ed46f7514ad6dbe3733c3d' </code></pre>
33
2012-03-22T04:19:41Z
[ "python", "hash", "md5" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
17,888,044
<pre><code>import uuid from md5 import md5 print md5(str(uuid.uuid4())).hexdigest() </code></pre>
2
2013-07-26T18:03:28Z
[ "python", "hash", "md5" ]
Random hash in Python
976,577
<p>What is the <strong>easiest</strong> way to generate a random hash (MD5) in Python?</p>
40
2009-06-10T16:05:02Z
20,060,712
<p>I think what you are looking for is a universal unique identifier.Then the module UUID in python is what you are looking for.</p> <pre><code>import uuid uuid.uuid4().hex </code></pre> <p>UUID4 gives you a random unique identifier that has the same length as a md5 sum. Hex will represent is as an hex string instead of returning a uuid object. </p> <p><a href="http://docs.python.org/2/library/uuid.html">http://docs.python.org/2/library/uuid.html</a></p>
28
2013-11-19T00:18:52Z
[ "python", "hash", "md5" ]
python-scapy: how to translate port numbers to service names?
976,599
<p>A TCP layer in Scapy contains source port:</p> <pre><code>&gt;&gt;&gt; a[TCP].sport 80 </code></pre> <p>Is there a simple way to convert port number to service name? I've seen Scapy has <code>TCP_SERVICES</code> and <code>UDP_SERVICES</code> to translate port number, but </p> <pre><code>print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 </code></pre> <p>Someone know how can I map ports to services? </p> <p>Thank you in advance</p>
0
2009-06-10T16:08:05Z
978,667
<p>Python's <a href="http://docs.python.org/library/socket.html">socket</a> module will do that:</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; socket.getservbyport(80) 'http' &gt;&gt;&gt; socket.getservbyport(21) 'ftp' &gt;&gt;&gt; socket.getservbyport(53, 'udp') 'domain' </code></pre>
10
2009-06-10T23:46:23Z
[ "python", "tcp", "scapy" ]
python-scapy: how to translate port numbers to service names?
976,599
<p>A TCP layer in Scapy contains source port:</p> <pre><code>&gt;&gt;&gt; a[TCP].sport 80 </code></pre> <p>Is there a simple way to convert port number to service name? I've seen Scapy has <code>TCP_SERVICES</code> and <code>UDP_SERVICES</code> to translate port number, but </p> <pre><code>print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 </code></pre> <p>Someone know how can I map ports to services? </p> <p>Thank you in advance</p>
0
2009-06-10T16:08:05Z
978,677
<p>This may work for you (filtering the dictionary based on the value):</p> <pre><code>&gt;&gt;&gt; [k for k, v in TCP_SERVICES.iteritems() if v == 80][0] 'www' </code></pre>
1
2009-06-10T23:50:58Z
[ "python", "tcp", "scapy" ]
python-scapy: how to translate port numbers to service names?
976,599
<p>A TCP layer in Scapy contains source port:</p> <pre><code>&gt;&gt;&gt; a[TCP].sport 80 </code></pre> <p>Is there a simple way to convert port number to service name? I've seen Scapy has <code>TCP_SERVICES</code> and <code>UDP_SERVICES</code> to translate port number, but </p> <pre><code>print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 </code></pre> <p>Someone know how can I map ports to services? </p> <p>Thank you in advance</p>
0
2009-06-10T16:08:05Z
978,695
<p>If this is something you need to do frequently, you can create a reverse mapping of <code>TCP_SERVICES</code>:</p> <pre><code>&gt;&gt;&gt; TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys()) &gt;&gt;&gt; TCP_REVERSE[80] 'www' </code></pre>
3
2009-06-10T23:57:50Z
[ "python", "tcp", "scapy" ]
python-scapy: how to translate port numbers to service names?
976,599
<p>A TCP layer in Scapy contains source port:</p> <pre><code>&gt;&gt;&gt; a[TCP].sport 80 </code></pre> <p>Is there a simple way to convert port number to service name? I've seen Scapy has <code>TCP_SERVICES</code> and <code>UDP_SERVICES</code> to translate port number, but </p> <pre><code>print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 </code></pre> <p>Someone know how can I map ports to services? </p> <p>Thank you in advance</p>
0
2009-06-10T16:08:05Z
984,262
<p>If you are using unix or linux there is a file /etc/services which contains this mapping.</p>
0
2009-06-11T23:12:29Z
[ "python", "tcp", "scapy" ]
python-scapy: how to translate port numbers to service names?
976,599
<p>A TCP layer in Scapy contains source port:</p> <pre><code>&gt;&gt;&gt; a[TCP].sport 80 </code></pre> <p>Is there a simple way to convert port number to service name? I've seen Scapy has <code>TCP_SERVICES</code> and <code>UDP_SERVICES</code> to translate port number, but </p> <pre><code>print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print TCP_SERVICES['www'] # works, but it's not what i need 80 </code></pre> <p>Someone know how can I map ports to services? </p> <p>Thank you in advance</p>
0
2009-06-10T16:08:05Z
1,053,486
<p>I've found a good solution filling another dict self.MYTCP_SERVICES</p> <pre><code>for p in scapy.data.TCP_SERVICES.keys(): self.MYTCP_SERVICES[scapy.data.TCP_SERVICES[p]] = p </code></pre>
0
2009-06-27T19:46:15Z
[ "python", "tcp", "scapy" ]
Thinking in AppEngine
976,639
<p>I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques. </p> <p>I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.</p> <p>Please respond if:</p> <ol> <li>You have ported a non-trivial application over to AppEngine</li> <li>You've created a common type of application from scratch in AppEngine</li> <li>You've done neither 1 or 2, but are considering it and want to share your own findings so far.</li> </ol>
6
2009-06-10T16:13:56Z
977,509
<p>I played around with Google App Engine for Java and found that it had many shortcomings:</p> <p>This is not general purpose Java application hosting. In particular, you do not have access to a full JRE (e.g. cannot create threads, etc.) Given this fact, you pretty much have to build your application from the ground up with the Google App Engine JRE in mind. Porting any non-trival application would be impossible.</p> <p>More pertinent to your datastore questions...</p> <p>The datastore performance is abysmal. I was trying to write 5000 weather observations per hour -- nothing too massive -- but I could not do it because I kept on running into time out exception both with the datastore and the HTTP request. Using the "low-level" datastore API helped somewhat, but not enough.</p> <p>I wanted to delete those weather observation after 24 hours to not fill up my quota. Again, could not do it because the delete operation took too long. This problem in turn led to my datastore quota filling up. Insanely, you cannot easily delete large swaths of data in the GAE datastore.</p> <p>There are some features that I did like. Eclipse integration is snazzy. The appspot application server UI is a million times better than working with Tomcat (e.g. nice views of logs). But the minuses far outweighed those benefits for me.</p> <p>In sum, I constantly found myself having to <a href="http://sethgodin.typepad.com/seths%5Fblog/2005/03/dont%5Fshave%5Fthat.html" rel="nofollow">shave the yak</a>, in order to do something that would have been pretty trivial in any normal Java / application hosting environment.</p>
1
2009-06-10T18:54:28Z
[ "java", "python", "google-app-engine", "data-modeling" ]
Thinking in AppEngine
976,639
<p>I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques. </p> <p>I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.</p> <p>Please respond if:</p> <ol> <li>You have ported a non-trivial application over to AppEngine</li> <li>You've created a common type of application from scratch in AppEngine</li> <li>You've done neither 1 or 2, but are considering it and want to share your own findings so far.</li> </ol>
6
2009-06-10T16:13:56Z
978,757
<p>The timeouts are tight and performance was ok but not great, so I found myself using extra space to save time; for example I had a many-to-many relationship between trading cards and players, so I duplicated the information of who owns what: Card objects have a list of Players and Player objects have a list of Cards.</p> <p>Normally storing all your information twice would have been silly (and prone to get out of sync) but it worked really well.</p> <p>In Python they recently released a remote API so you can get an interactive shell to the datastore so you can play with your datastore without any timeouts or limits (for example, you can delete large swaths of data, or refactor your models); this is fantastically useful since otherwise as Julien mentioned it was very difficult to do any bulk operations. </p>
1
2009-06-11T00:21:54Z
[ "java", "python", "google-app-engine", "data-modeling" ]
Thinking in AppEngine
976,639
<p>I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques. </p> <p>I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.</p> <p>Please respond if:</p> <ol> <li>You have ported a non-trivial application over to AppEngine</li> <li>You've created a common type of application from scratch in AppEngine</li> <li>You've done neither 1 or 2, but are considering it and want to share your own findings so far.</li> </ol>
6
2009-06-10T16:13:56Z
979,391
<p>The non relational database design essentially involves denormalization wherever possible.</p> <p>Example: Since the BigTable doesnt provide enough aggregation features, the sum(cash) option that would be in the RDBMS world is not available. Instead it would have to be stored on the model and the model save method must be overridden to compute the denormalized field sum.</p> <p>Essential basic design that comes to mind is that each template has its own model where all the required fields to be populated are present denormalized in the corresponding model; and you have an entire signals-update-bots complexity going on in the models.</p>
1
2009-06-11T05:00:52Z
[ "java", "python", "google-app-engine", "data-modeling" ]
Thinking in AppEngine
976,639
<p>I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques. </p> <p>I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.</p> <p>Please respond if:</p> <ol> <li>You have ported a non-trivial application over to AppEngine</li> <li>You've created a common type of application from scratch in AppEngine</li> <li>You've done neither 1 or 2, but are considering it and want to share your own findings so far.</li> </ol>
6
2009-06-10T16:13:56Z
979,412
<blockquote> <p>I'm wondering if there's a place we could pool knowledge from experience</p> </blockquote> <p>Various Google Groups are good for that, though I don't know if any are directly applicable to Java-GAE yet -- my GAE experience so far is all-Python (I'm kind of proud to say that Guido van Rossum, inventor of Python and now working at Google on App Engine, told me I had taught him a few things about how his brainchild worked -- his recommendation mentioning that is now the one I'm proudest, on amongst all those on my linkedin profile;-). [I work at Google but my impact on App Engine was very peripheral -- I worked on "building the cloud", cluster and network management SW, and App Engine is about making that infrastructure useful for third party developers].</p> <p>There are indeed many essays &amp; presentations on how best to denormalize and shard your data for optimal GAE scaling and performance -- they're of varying quality, though. The books that are out so far are so-so; many more are coming in the next few months, hopefully better ones (I had a project to write one of those, with two very skilled friends, but we're all so busy that we ended up dropping it). In general, I'd recommend the Google I/O videos and the essays that Google blessed in its app engine site and blogs, PLUS every bit of content from <a href="http://blog.appenginefan.com/">appenginefan's blog</a> -- what Guido commended me for teaching him about GAE, I in turn mostly learned from appenginefan (partly through the wonderful <a href="http://www.meetup.com/appengine/calendar/9332524/?eventId=9332524&amp;action=detail">app engine meetup</a> in Palo Alto, but his blog is great too;-).</p>
6
2009-06-11T05:09:17Z
[ "java", "python", "google-app-engine", "data-modeling" ]
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
976,796
<p>I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use Ctrl-z and then enter. Is there any way to use Ctrl-d?</p>
5
2009-06-10T16:40:43Z
977,031
<p>You can change the key set that Idle should be using. </p> <ol> <li><p>Under Options->"Configure IDLE..." go to the "Keys" tab. </p></li> <li><p>On the right you can select the "IDLE Classic Unix" key set.</p></li> </ol>
0
2009-06-10T17:28:08Z
[ "python", "windows", "python-2.5" ]
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
976,796
<p>I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use Ctrl-z and then enter. Is there any way to use Ctrl-d?</p>
5
2009-06-10T16:40:43Z
977,063
<p>You can't use <strong><kbd>CTRL</kbd>+<kbd>D</kbd></strong> on windows. </p> <p><strong><kbd>CTRL</kbd>+<kbd>Z</kbd></strong> is a <a href="http://en.wikipedia.org/wiki/End_of_file" rel="nofollow">windows-specific control char that prints EOF</a>. On *nix, it is typically <strong><kbd>CTRL</kbd>+<kbd>D</kbd></strong>. That's the reason for the difference.</p> <p>You <em>can</em>, however, train yourself to use <code>exit()</code>, which is cross-platform.</p>
6
2009-06-10T17:33:23Z
[ "python", "windows", "python-2.5" ]
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
976,796
<p>I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use Ctrl-z and then enter. Is there any way to use Ctrl-d?</p>
5
2009-06-10T16:40:43Z
977,170
<p>Ctrl-d works to exit from <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> <br /> (installed by <a href="http://www.pythonxy.com/foreword.php" rel="nofollow">python(x,y)</a> package).<br /></p> <ul> <li>OS: WinXP</li> <li>Python version: 2.5.4</li> </ul> <p><hr /></p> <p><strong>Edit: I've been informed in the comments by the OP, Jason Baker, that Ctrl-d functionality on Windows OSes is made possible by the <a href="http://pypi.python.org/pypi/pyreadline/1.3.svn" rel="nofollow">PyReadline</a> package</strong>: "The pyreadline package is a python implementation of GNU readline functionality it is based on the ctypes based UNC readline package by Gary Bishop. It is not complete. It has been tested for use with windows 2000 and windows xp." <hr /></p> <p>Since you're accustomed to *nix you may like that IPython also offers *nix-like shell functionality without using something like Cygwin...</p> <ul> <li>Proper bash-like tab completion.</li> <li>Use of / instead of \, everywhere</li> <li>Persistent %bookmark's</li> <li>%macro</li> <li>%store. Especially when used with macros and aliases.</li> <li>cd -. (easily jump around directory history). Directory history persists across sessions.</li> <li>%env (see cookbook)</li> <li>Shadow history - %hist and %rep (see cookbook)</li> <li>%mglob</li> <li>Expansion of $python_variables in system commands</li> <li>var = !ls -la (capture command output to handy string lists)</li> </ul>
4
2009-06-10T17:51:26Z
[ "python", "windows", "python-2.5" ]
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
976,796
<p>I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use Ctrl-z and then enter. Is there any way to use Ctrl-d?</p>
5
2009-06-10T16:40:43Z
978,669
<p>Run Cygwin Python if windowisms are bothering you... Unless what you are doing depends on pywin32 that is.</p>
0
2009-06-10T23:47:15Z
[ "python", "windows", "python-2.5" ]
Shuffling a list of objects in python
976,882
<p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p> <pre><code>import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) </code></pre> <p>This will fail.</p>
290
2009-06-10T16:56:59Z
976,918
<p><a href="https://docs.python.org/library/random.html#random.shuffle"><code>random.shuffle</code></a> should work. Here's an example, where the objects are lists:</p> <pre><code>from random import shuffle x = [[i] for i in range(10)] shuffle(x) # print x gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] # of course your results will vary </code></pre> <p>Note that shuffle works <strong>in place</strong>, and returns None.</p>
485
2009-06-10T17:03:37Z
[ "python", "list", "random", "shuffle" ]
Shuffling a list of objects in python
976,882
<p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p> <pre><code>import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) </code></pre> <p>This will fail.</p>
290
2009-06-10T16:56:59Z
976,921
<pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; a = ['hi','world','cat','dog'] &gt;&gt;&gt; random.shuffle(a,random.random) &gt;&gt;&gt; a ['hi', 'cat', 'dog', 'world'] </code></pre> <p>It works fine for me. Make sure to set the random method.</p>
8
2009-06-10T17:04:16Z
[ "python", "list", "random", "shuffle" ]
Shuffling a list of objects in python
976,882
<p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p> <pre><code>import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) </code></pre> <p>This will fail.</p>
290
2009-06-10T16:56:59Z
4,353,542
<pre><code>#!/usr/bin/python3 import random s=list(range(5)) random.shuffle(s) # &lt;&lt; shuffle before print or assignment print(s) # print: [2, 4, 1, 3, 0] </code></pre>
19
2010-12-04T12:46:10Z
[ "python", "list", "random", "shuffle" ]
Shuffling a list of objects in python
976,882
<p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p> <pre><code>import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) </code></pre> <p>This will fail.</p>
290
2009-06-10T16:56:59Z
12,978,830
<p>As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using <code>sample(a, len(a))</code> is the solution.</p> <p>Here's a simple version using <code>random.sample()</code> that returns the shuffled result as a new list.</p> <pre><code>import random a = range(5) b = random.sample(a, len(a)) print a, b, "two list same:", a == b # print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False # The function sample allows no duplicates. # Result can be smaller but not larger than the input. a = range(555) b = random.sample(a, len(a)) print "no duplicates:", a == list(set(b)) try: random.sample(a, len(a) + 1) except ValueError as e: print "Nope!", e # print: no duplicates: True # print: Nope! sample larger than population </code></pre>
49
2012-10-19T16:50:08Z
[ "python", "list", "random", "shuffle" ]
Shuffling a list of objects in python
976,882
<p>I have a list of objects in Python and I want to shuffle them. I thought I could use the <code>random.shuffle</code> method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?</p> <pre><code>import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) </code></pre> <p>This will fail.</p>
290
2009-06-10T16:56:59Z
16,737,991
<p>'print func(foo)' will print the return value of 'func' when called with 'foo'. 'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing. Workaround:</p> <pre><code># shuffle the list in place random.shuffle(b) # print it print(b) </code></pre> <p>If you're more into functional programming style you might want to make the following wrapper function:</p> <pre><code>def myshuffle(ls): random.shuffle(ls) return ls </code></pre>
2
2013-05-24T14:59:33Z
[ "python", "list", "random", "shuffle" ]