title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
wxPython gauge problem (skipping)
1,235,884
<p>Pastebin link: <a href="http://pastebin.com/f40ae1bcf" rel="nofollow">http://pastebin.com/f40ae1bcf</a></p> <p>The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that when the value is 50 it should be full.</p> <p>Why does it do this? I also tried with a wx.Timer instead of binding to wx.EVT_IDLE but I didn't have luck.</p>
1
2009-08-05T21:33:06Z
1,236,293
<p>Are you sure that the code you posted is the code that is giving you the problems? This code looks very similar to the demo code for wxPython, and works on my machine without problems.</p> <p>If you did actually set your gauge's value to 50, that could be your issue. You have to be sure not to exceed that range of a wx.Gauge. If the range is 50, the highest value you can set in it will be 49.</p>
0
2009-08-05T23:36:26Z
[ "python", "wxpython" ]
wxPython gauge problem (skipping)
1,235,884
<p>Pastebin link: <a href="http://pastebin.com/f40ae1bcf" rel="nofollow">http://pastebin.com/f40ae1bcf</a></p> <p>The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that when the value is 50 it should be full.</p> <p>Why does it do this? I also tried with a wx.Timer instead of binding to wx.EVT_IDLE but I didn't have luck.</p>
1
2009-08-05T21:33:06Z
1,236,327
<p>A few things.</p> <ul> <li>I can't reproduce this on my iMac, it goes all the way to full. Python 2.5.4, wxPython 2.8.9.2</li> <li>Idle events can come at strange times. Try adding <code>print event</code> to your idle handler to see exactly when those events are coming. A timer would be best. Is the gauge moving really fast or flickering?</li> <li>You can try calling gauge.Update() to force a complete redraw too.</li> <li>I always just use 100 as my gauge limit, maybe just try that.</li> </ul> <p>An easier way than a timer could be:</p> <pre><code>import wx class GaugeFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Gauge example", size=(350, 150)) panel = wx.Panel(self, -1) self.count = 0 self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25)) self.update_gauge() def update_gauge(self): self.count = self.count + 1 if self.count &gt;= 50: self.count = 0 self.gauge.SetValue(self.count) wx.CallLater(100, self.update_gauge) app = wx.PySimpleApp() GaugeFrame().Show() app.MainLoop() </code></pre>
1
2009-08-05T23:51:15Z
[ "python", "wxpython" ]
wxPython gauge problem (skipping)
1,235,884
<p>Pastebin link: <a href="http://pastebin.com/f40ae1bcf" rel="nofollow">http://pastebin.com/f40ae1bcf</a></p> <p>The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that when the value is 50 it should be full.</p> <p>Why does it do this? I also tried with a wx.Timer instead of binding to wx.EVT_IDLE but I didn't have luck.</p>
1
2009-08-05T21:33:06Z
1,237,498
<p>After more tests I discovered that I must override the range of 2 units to display the gauge when completely full. On windows vista it seems not to cause problems. Does it cause problems on linux or mac?</p>
0
2009-08-06T07:56:48Z
[ "python", "wxpython" ]
Compiling python modules whith DEBUG defined on MSVC
1,236,060
<p>Python rather stupidly has a pragma directive in its include files that forces a link against <code>python26_d.lib</code> when the <code>DEBUG</code> preprocessor variable is defined. This is a problem because the python installer doesn't come with <code>python26_d.lib</code>! So I can't build applications in msvc in debug mode. If i temporarily <code>#undef DEBUG</code> for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.</p> <p>I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python</p> <p>Can anyone give me any advice on how to get round this?</p> <p>Thanks</p>
17
2009-08-05T22:16:28Z
1,236,116
<p>From <a href="http://mail.python.org/pipermail/python-list/2009-March/1198717.html">python list</a></p> <blockquote> <p>As a workaround to the situation, try to copy the file python26.dll to python26_d.dll. (I'm not sure this will work; you say you are building a SWIG library in debug mode, and it's possible that SWIG will try to use features of the Python debugging version. If that's the case, you'll have no choice but to use the debugging version of Python.)</p> </blockquote> <p>Edit: From comments:</p> <blockquote> <p>You should also edit pyconfig.h and comment out the line "#define Py_DEBUG" (line 374)</p> </blockquote>
19
2009-08-05T22:33:08Z
[ "python", "debugging", "visual-c++" ]
Compiling python modules whith DEBUG defined on MSVC
1,236,060
<p>Python rather stupidly has a pragma directive in its include files that forces a link against <code>python26_d.lib</code> when the <code>DEBUG</code> preprocessor variable is defined. This is a problem because the python installer doesn't come with <code>python26_d.lib</code>! So I can't build applications in msvc in debug mode. If i temporarily <code>#undef DEBUG</code> for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.</p> <p>I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python</p> <p>Can anyone give me any advice on how to get round this?</p> <p>Thanks</p>
17
2009-08-05T22:16:28Z
2,190,931
<p>This works also when linking with static libraries. I made a copy of python26.lib, and renamed it python26_d.lib. I commented out the line #define PY_DEBUG in pyconfig.h. Also changed the pragma to "pragma comment(lib,"python26.lib")" on line 332. Voila! It worked.</p>
2
2010-02-03T09:33:35Z
[ "python", "debugging", "visual-c++" ]
Compiling python modules whith DEBUG defined on MSVC
1,236,060
<p>Python rather stupidly has a pragma directive in its include files that forces a link against <code>python26_d.lib</code> when the <code>DEBUG</code> preprocessor variable is defined. This is a problem because the python installer doesn't come with <code>python26_d.lib</code>! So I can't build applications in msvc in debug mode. If i temporarily <code>#undef DEBUG</code> for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.</p> <p>I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python</p> <p>Can anyone give me any advice on how to get round this?</p> <p>Thanks</p>
17
2009-08-05T22:16:28Z
2,454,541
<p>You can also go the other way: switch to «Release» and then debug it. you need to enable generation of debugging symbols info in project properties in compiler and linker prefs; MSDN <a href="http://msdn.microsoft.com/en-us/library/fsk896zz%28VS.71%29.aspx" rel="nofollow">here</a> will tell you exactly what options you need to set to debug a release build.</p>
4
2010-03-16T13:15:09Z
[ "python", "debugging", "visual-c++" ]
Compiling python modules whith DEBUG defined on MSVC
1,236,060
<p>Python rather stupidly has a pragma directive in its include files that forces a link against <code>python26_d.lib</code> when the <code>DEBUG</code> preprocessor variable is defined. This is a problem because the python installer doesn't come with <code>python26_d.lib</code>! So I can't build applications in msvc in debug mode. If i temporarily <code>#undef DEBUG</code> for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.</p> <p>I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python</p> <p>Can anyone give me any advice on how to get round this?</p> <p>Thanks</p>
17
2009-08-05T22:16:28Z
3,548,850
<p>After you comment out "#define Py_DEBUG" on line 332 and modify</p> <pre><code># ifdef _DEBUG # pragma comment(lib,"python26_d.lib") # else </code></pre> <p>to</p> <pre><code># ifdef _DEBUG # pragma comment(lib,"python26.lib") # else </code></pre> <p>you do not need to python26_d.lib anymore.</p>
7
2010-08-23T15:06:34Z
[ "python", "debugging", "visual-c++" ]
Compiling python modules whith DEBUG defined on MSVC
1,236,060
<p>Python rather stupidly has a pragma directive in its include files that forces a link against <code>python26_d.lib</code> when the <code>DEBUG</code> preprocessor variable is defined. This is a problem because the python installer doesn't come with <code>python26_d.lib</code>! So I can't build applications in msvc in debug mode. If i temporarily <code>#undef DEBUG</code> for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.</p> <p>I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python</p> <p>Can anyone give me any advice on how to get round this?</p> <p>Thanks</p>
17
2009-08-05T22:16:28Z
26,108,616
<p>Based on all answers I successfully disabled <code>_DEBUG</code> temporary:</p> <pre><code>#if _DEBUG #define _DEBUG_IS_ENABLED #undef _DEBUG #endif #include "pyconfig.h" #if defined(_DEBUG_IS_ENABLED) #define _DEBUG #endif </code></pre>
4
2014-09-29T20:48:31Z
[ "python", "debugging", "visual-c++" ]
py2app error: "can't copy '%s': doesn't exist or not a regular file"
1,236,104
<p>I'm trying to pack my Python app with py2app. I'm running the <code>setup.py</code> I created, and I get this error:</p> <pre><code> File "C:\Python26\lib\distutils\file_util.py", line 119, in copy_file "can't copy '%s': doesn't exist or not a regular file" % src DistutilsFileError: can't copy '--dist-dir': doesn't exist or not a regular file &gt; c:\python26\lib\distutils\file_util.py(119)copy_file() -&gt; "can't copy '%s': doesn't exist or not a regular file" % src </code></pre> <p>Does anyone have any clue what I'm supposed to do?</p>
0
2009-08-05T22:30:04Z
1,236,111
<p>It looks like, for some reason or other, it's trying to interpret the command-line switch <code>--dist-dir</code> as a filename. Perhaps the actual switch is named something else and you typo'd it? Or perhaps it needs to be specified in a different order?</p>
1
2009-08-05T22:31:49Z
[ "python", "osx", "py2app" ]
py2app error: "'module' object has no attribute 'symlink'"
1,236,172
<p>I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py ", line 548, in _run self.run_normal() File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py ", line 619, in run_normal self.create_binaries(py_files, pkgdirs, extensions, loader_files) File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py ", line 710, in create_binaries target, arcname, pkgexts, copyexts, target.script) File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py ", line 1067, in build_executable self.symlink('../../site.py', os.path.join(pydir, 'site.py')) File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py ", line 377, in symlink os.symlink(src, dst) AttributeError: 'module' object has no attribute 'symlink' &gt; c:\python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py(377)s ymlink() -&gt; os.symlink(src, dst) </code></pre> <p>Anyone has an idea?</p>
0
2009-08-05T22:49:20Z
1,236,175
<p><code>os.symlink</code> is only available on Unix and Unix-like operating systems (including the Mac), not Windows.</p> <p>py2app is for the Mac - are you deliberately running it on Windows? Did you mean to use <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>?</p>
1
2009-08-05T22:51:38Z
[ "python", "osx", "py2app" ]
How do I see stdout when running Django tests?
1,236,285
<p>When I run tests with <code>./manage.py test</code>, whatever I send to the standard output through <code>print</code> doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass).</p>
24
2009-08-05T23:34:08Z
1,236,326
<p>You probably have some intermediate test runner, such as Nose, intercepting and storing stdout. Try either running the Django tests directly, or write to stderr instead.</p>
4
2009-08-05T23:51:09Z
[ "python", "django", "debugging", "testing", "stdout" ]
How do I see stdout when running Django tests?
1,236,285
<p>When I run tests with <code>./manage.py test</code>, whatever I send to the standard output through <code>print</code> doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass).</p>
24
2009-08-05T23:34:08Z
1,239,545
<p>Checked <code>TEST_RUNNER</code> in <code>settings.py</code>, it's using a project-specific runner that calls out to Nose. <em>Nose has the <code>-s</code> option to stop it from capturing <code>stdout</code></em>, but if I run:</p> <p><code>./manage.py test -s</code></p> <p><code>manage.py</code> captures it first and throws a "no such option" error. The help for <code>manage.py</code> doesn't mention this, but I found that if I run:</p> <p><code>./manage.py test -- -s</code></p> <p>it ignores the <code>-s</code> and lets me capture it on the custom runner's side, passing it to Nose without a problem.</p>
28
2009-08-06T15:09:16Z
[ "python", "django", "debugging", "testing", "stdout" ]
How do I see stdout when running Django tests?
1,236,285
<p>When I run tests with <code>./manage.py test</code>, whatever I send to the standard output through <code>print</code> doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass).</p>
24
2009-08-05T23:34:08Z
22,777,773
<p>Yeah, this issue is cause by <code>NoseTestSuiteRunner</code>. Add <code>-- -s</code> is a tricky but not the best solutions. Try to add follow lines in the <code>settings.py</code>:</p> <pre><code>NOSE_ARGS = ['--nocapture', '--nologcapture',] </code></pre> <p>Which solved my problems.</p>
22
2014-04-01T05:48:07Z
[ "python", "django", "debugging", "testing", "stdout" ]
Creating multiple Python modules in different directories that share a portion of the package structure
1,236,443
<p>I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems.</p> <p>Here's my file structure (with __init__.py files where appropriate):</p> <pre><code>$HOME/django-sites/mydomain $HOME/django-apps/mydomain/cms </code></pre> <p>And my PYTHONPATH:</p> <pre><code>$HOME/django-sites:$HOME/django-apps </code></pre> <p>If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site.</p> <p>It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH.</p> <p>It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions __path__, but I have no idea how to use it:</p> <blockquote> <p>Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.</p> <p>While this feature is not often needed, it can be used to extend the set of modules found in a package.</p> </blockquote> <p>Has anyone else come across this? Is there something I can do with __path__ to make this function as expected?</p>
2
2009-08-06T00:41:28Z
1,236,518
<p>Your analysis seems about right. The python path is used to locate modules to import; python imports the first one it finds. I'm not sure what you could do to work around this other than name your modules different things or put them in the same location in the search path.</p>
1
2009-08-06T01:18:44Z
[ "python", "django" ]
Creating multiple Python modules in different directories that share a portion of the package structure
1,236,443
<p>I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems.</p> <p>Here's my file structure (with __init__.py files where appropriate):</p> <pre><code>$HOME/django-sites/mydomain $HOME/django-apps/mydomain/cms </code></pre> <p>And my PYTHONPATH:</p> <pre><code>$HOME/django-sites:$HOME/django-apps </code></pre> <p>If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site.</p> <p>It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH.</p> <p>It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions __path__, but I have no idea how to use it:</p> <blockquote> <p>Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.</p> <p>While this feature is not often needed, it can be used to extend the set of modules found in a package.</p> </blockquote> <p>Has anyone else come across this? Is there something I can do with __path__ to make this function as expected?</p>
2
2009-08-06T00:41:28Z
1,236,581
<p>You basically have two modules named the same thing (mydomain). Why not set up your PYTHONPATH like so?</p> <pre><code>$HOME/django-sites:$HOME/django-apps/mydomain </code></pre> <p>It would avoid your import problems.</p>
1
2009-08-06T01:45:47Z
[ "python", "django" ]
Creating multiple Python modules in different directories that share a portion of the package structure
1,236,443
<p>I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems.</p> <p>Here's my file structure (with __init__.py files where appropriate):</p> <pre><code>$HOME/django-sites/mydomain $HOME/django-apps/mydomain/cms </code></pre> <p>And my PYTHONPATH:</p> <pre><code>$HOME/django-sites:$HOME/django-apps </code></pre> <p>If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site.</p> <p>It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH.</p> <p>It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions __path__, but I have no idea how to use it:</p> <blockquote> <p>Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.</p> <p>While this feature is not often needed, it can be used to extend the set of modules found in a package.</p> </blockquote> <p>Has anyone else come across this? Is there something I can do with __path__ to make this function as expected?</p>
2
2009-08-06T00:41:28Z
1,236,696
<p>Here's how <code>__path__</code> in a package's <code>__init__.py</code> is intended to be used:</p> <pre><code>$ export PYTHONPATH=$HOME/django-sites $ ls -d $HOME/django* django-apps/ django-sites/ $ cat /tmp/django-sites/mydomain/__init__.py import os _components = __path__[0].split(os.path.sep) if _components[-2] == 'django-sites': _components[-2] = 'django-apps' __path__.append(os.path.sep.join(_components)) $ python -c'import mydomain; import mydomain.foo' foo here /tmp/django-apps/mydomain/foo.pyc $ </code></pre> <p>as you see, this makes the contents of <code>django-apps/mydomain</code> part of the <code>mydomain</code> package (whose <code>__init__.py</code> resides under <code>django-sites/mydomain</code>) -- you don't need <code>django-apps</code> on <code>sys.path</code> for this purpose, either, if you use this approach.</p> <p>Whether this is a better arrangement than the one @defrex's answer suggests may be moot, but since a package's enriching its <code>__path__</code> is a pretty important bit of a python programmer's bag of tools, I thought I had better illustrate it anyway;-).</p>
4
2009-08-06T02:31:53Z
[ "python", "django" ]
How do I use PIL with Tkinter?
1,236,540
<p>I'm missing something at a very basic level when it comes to loading an image using PIL and displaying it in a window created by Tkinter. The simplest form of what I'm trying to do is:</p> <pre><code>import Tkinter as TK from PIL import Image, ImageTk im = Image.open("C:\\tinycat.jpg") tkIm = ImageTk.PhotoImage(im) tkIm.pack() TK.mainloop() </code></pre> <p>When I try to run the code above, I get the following:</p> <pre><code>RuntimeError: Too early to create image Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__photo'" in &lt;bound method PhotoImage.__del__ of &lt;PIL.ImageTk.PhotoImage instance at 0x00C00030&gt;&gt; ignored </code></pre> <p>I've confirmed the file is present and can be opened in an image editor and also that it can be displayed using im.show(). What am I missing?</p>
3
2009-08-06T01:25:27Z
1,236,579
<p>Tkinter has to be instantiated before you call ImageTk.PhotoImage():</p> <pre><code>TK.Tk() </code></pre>
6
2009-08-06T01:44:20Z
[ "python", "python-imaging-library", "tkinter" ]
How do I use PIL with Tkinter?
1,236,540
<p>I'm missing something at a very basic level when it comes to loading an image using PIL and displaying it in a window created by Tkinter. The simplest form of what I'm trying to do is:</p> <pre><code>import Tkinter as TK from PIL import Image, ImageTk im = Image.open("C:\\tinycat.jpg") tkIm = ImageTk.PhotoImage(im) tkIm.pack() TK.mainloop() </code></pre> <p>When I try to run the code above, I get the following:</p> <pre><code>RuntimeError: Too early to create image Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__photo'" in &lt;bound method PhotoImage.__del__ of &lt;PIL.ImageTk.PhotoImage instance at 0x00C00030&gt;&gt; ignored </code></pre> <p>I've confirmed the file is present and can be opened in an image editor and also that it can be displayed using im.show(). What am I missing?</p>
3
2009-08-06T01:25:27Z
14,996,618
<p>It's very true what Meredith said you need to add that line for sure!</p> <p>I would like to show you my image formatting and then compare it to yours and see if there any different, my code for a image is</p> <pre><code>master.image = PhotoImage(file="Banditlogo.gif") w = Label(master, image=master.image) w.photo = master w.pack() </code></pre> <p>And your code is</p> <pre><code>im = Image.open("C:\\tinycat.jpg") tkIm = ImageTk.PhotoImage(im) tkIm.pack() </code></pre> <p>We are both using PIL with PhotoImage I can't help wondering are both ways correct? At this point in time I don't have enough knowledge to fully answer your PIL question but it is interesting to compare both codes as they are different. I can only suggest doing what I do when it comes to example codes people share with me, and that is "if mine don't work, try the example code and see if that fixes the code" when I find something that works I stick with it.</p> <p>Would someone with more understanding of Tkinter please explane the workings of, How do I use PIL with Tkinter?</p> <p>Knowledge is power so please share. </p>
-1
2013-02-21T07:19:07Z
[ "python", "python-imaging-library", "tkinter" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
1,236,619
<p>First choice: use the existing join template tag.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join</a></p> <p>Here's their example</p> <pre><code>{{ value|join:" // " }} </code></pre> <p>Second choice: do it in the view.</p> <pre><code>fruits_text = ", ".join( fruits ) </code></pre> <p>Provide <code>fruits_text</code> to the template for rendering.</p>
89
2009-08-06T02:02:37Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
1,236,716
<p>I would suggest a custom django templating <em>filter</em> rather than a custom <em>tag</em> -- filter is handier and simpler (where appropriate, like here). <code>{{ fruits | joinby:", " }}</code> looks like what I'd want to have for the purpose... with a custom <code>joinby</code> filter:</p> <pre><code>def joinby(value, arg): return arg.join(value) </code></pre> <p>which as you see is simplicity itself!</p>
26
2009-08-06T02:41:01Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
1,242,107
<p>Here's the filter I wrote to solve my problem:</p> <pre><code>def join_with_commas(obj_list): """Takes a list of objects and returns their unicode representations, seperated by commas and with 'and' between the penultimate and final items For example, for a list of fruit objects: [&lt;Fruit: apples&gt;,&lt;Fruit: oranges&gt;,&lt;Fruit: pears&gt;] -&gt; 'apples, oranges and pears' """ if not obj_list: return "" l=len(obj_list) if l==1: return u"%s" % obj_list[0] else: return ", ".join(unicode(obj) for obj in obj_list[:l-1]) \ + " and " + unicode(obj_list[l-1]) </code></pre> <p>To use it in the template: <code>{{ fruits | join_with_commas }}</code></p>
5
2009-08-06T23:37:27Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
3,649,002
<p>Here's a super simple solution. Put this code into comma.html:</p> <pre><code>{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %} </code></pre> <p>And now wherever you'd put the comma, include "comma.html" instead:</p> <pre><code>{% for cat in cats %} Kitty {{cat.name}}{% include "comma.html" %} {% endfor %} </code></pre>
47
2010-09-06T04:28:13Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
14,798,747
<p>If you want a '.' on the end of Michael Matthew Toomim's answer, then use:</p> <pre><code>{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %}{% if forloop.last %}.{% endif %} </code></pre>
4
2013-02-10T14:28:14Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
16,820,985
<p>Django doesn't have support for this out-of-the-box. You can define a custom filter for this:</p> <pre><code>from django import template register = template.Library() @register.filter def join_and(value): """Given a list of strings, format them with commas and spaces, but with 'and' at the end. &gt;&gt;&gt; join_and(['apples', 'oranges', 'pears']) "apples, oranges, and pears" """ # convert numbers to strings value = [str(item) for item in value] if len(value) == 1: return value[0] # join all but the last element all_but_last = ", ".join(value[:-1]) return "%s, and %s" % (all_but_last, value[-1]) </code></pre> <p>However, if you want to deal with something more complex than just lists of strings, you'll have to use an explicit <code>{% for x in y %}</code> loop in your template.</p>
1
2013-05-29T18:09:03Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
35,526,258
<p>If you like one-liners:</p> <pre><code>@register.filter def lineup(ls): return ', '.join(ls[:-1])+' and '+ls[-1] if len(ls)&gt;1 else ls[0] </code></pre> <p>and then in the template:</p> <pre><code>{{ fruits|lineup }} </code></pre>
0
2016-02-20T17:00:32Z
[ "python", "django", "list", "django-templates" ]
Comma separated lists in django templates
1,236,593
<p>If <code>fruits</code> is the list <code>['apples', 'oranges', 'pears']</code>,</p> <p>is there a quick way using django template tags to produce "apples, oranges, and pears"?</p> <p>I know it's not difficult to do this using a loop and <code>{% if counter.last %}</code> statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom <del>tags</del> filters, and I don't want to reinvent the wheel if it's already been done.</p> <p>As an extension, my attempts to drop the <a href="http://en.wikipedia.org/wiki/Serial%5Fcomma">Oxford Comma</a> (ie return "apples, oranges and pears") are even messier.</p>
41
2009-08-06T01:50:18Z
37,598,156
<p>On the Django template this all you need to do for establishing a comma after each fruit. The comma will stop once its reached the last fruit.</p> <pre><code>{% if not forloop.last %}, {% endif %} </code></pre>
3
2016-06-02T17:11:26Z
[ "python", "django", "list", "django-templates" ]
Is 'for x in array' always result in sorted x? [Python/NumPy]
1,236,695
<p>For arrays and lists in Python and Numpy are the following lines equivalent:</p> <pre><code>itemlist = [] for j in range(len(myarray)): item = myarray[j] itemlist.append(item) </code></pre> <p>and:</p> <pre><code>itemlist = [] for item in myarray: itemlist.append(item) </code></pre> <p>I'm interested in the <em>order</em> of itemlist. In a few examples that I have tried they are identical, but is it <em>guaranteed</em>? For example, I know that the <code>foreach</code> statement in C# doesn't guarantee order, and that I should be careful with it.</p>
4
2009-08-06T02:31:46Z
1,236,701
<p>Yes, it's entirely guaranteed. <code>for item in myarray</code> (where <code>myarray</code> is a <em>sequence</em>, which includes numpy's arrays, builtin lists, Python's array.arrays, etc etc), is in fact equivalent in Python to:</p> <pre><code>_aux = 0 while _aux &lt; len(myarray): item = myarray[_aux] ...etc... </code></pre> <p>for some phantom variable <code>_aux</code>;-). Btw, both of your constructs are also equivalent to</p> <pre><code>itemlist = list(myarray) </code></pre>
9
2009-08-06T02:34:00Z
[ "python", "arrays", "list", "numpy" ]
Is 'for x in array' always result in sorted x? [Python/NumPy]
1,236,695
<p>For arrays and lists in Python and Numpy are the following lines equivalent:</p> <pre><code>itemlist = [] for j in range(len(myarray)): item = myarray[j] itemlist.append(item) </code></pre> <p>and:</p> <pre><code>itemlist = [] for item in myarray: itemlist.append(item) </code></pre> <p>I'm interested in the <em>order</em> of itemlist. In a few examples that I have tried they are identical, but is it <em>guaranteed</em>? For example, I know that the <code>foreach</code> statement in C# doesn't guarantee order, and that I should be careful with it.</p>
4
2009-08-06T02:31:46Z
1,236,709
<p>Yes, the <a href="http://docs.python.org/reference/compound%5Fstmts.html#for" rel="nofollow">Python Language Reference</a> guarantees this (emphasis is mine):</p> <pre><code> for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] </code></pre> <blockquote> <p>"The suite is then executed once for each item provided by the iterator, <strong>in the order of ascending indices</strong>."</p> </blockquote>
6
2009-08-06T02:39:29Z
[ "python", "arrays", "list", "numpy" ]
Is 'for x in array' always result in sorted x? [Python/NumPy]
1,236,695
<p>For arrays and lists in Python and Numpy are the following lines equivalent:</p> <pre><code>itemlist = [] for j in range(len(myarray)): item = myarray[j] itemlist.append(item) </code></pre> <p>and:</p> <pre><code>itemlist = [] for item in myarray: itemlist.append(item) </code></pre> <p>I'm interested in the <em>order</em> of itemlist. In a few examples that I have tried they are identical, but is it <em>guaranteed</em>? For example, I know that the <code>foreach</code> statement in C# doesn't guarantee order, and that I should be careful with it.</p>
4
2009-08-06T02:31:46Z
1,236,808
<p>It is guaranteed for lists. I think the more relevant Python parallel to your C# example would be to iterate over the keys in a dictionary, which is NOT guaranteed to be in any order.</p> <pre><code># Always prints 0-9 in order a_list = [0,1,2,3,4,5,6,7,8,9] for x in a_list: print x # May or may not print 0-9 in order. Implementation dependent. a_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} for x in a_dict: print x </code></pre> <p>The <code>for &lt;element&gt; in &lt;iterable&gt;</code> structure only worries that the <code>iterable</code> supplies a <code>next()</code> function which returns something. There is no general guarantee that these elements get returned in any order over the domain of the <code>for..in</code> statement; lists are a special case.</p>
7
2009-08-06T03:17:50Z
[ "python", "arrays", "list", "numpy" ]
Help with MySQL LOAD DATA INFILE
1,236,971
<p>I want to load a CSV file that looks like this:</p> <pre><code>Acct. No.,1-15 Days,16-30 Days,31-60 Days,61-90 Days,91-120 Days,Beyond 120 Days 2314134101,898.89,8372.16,5584.23,7744.41,9846.54,2896.25 2414134128,5457.61,7488.26,9594.02,6234.78,273.7,2356.13 2513918869,2059.59,7578.59,9395.51,7159.15,5827.48,3041.62 1687950783,4846.85,8364.22,9892.55,7213.45,8815.33,7603.4 2764856043,5250.11,9946.49,8042.03,6058.64,9194.78,8296.2 2865446086,596.22,7670.04,8564.08,3263.85,9662.46,7027.22 ,4725.99,1336.24,9356.03,1572.81,4942.11,6088.94 ,8248.47,956.81,8713.06,2589.14,5316.68,1543.67 ,538.22,1473.91,3292.09,6843.89,2687.07,9808.05 ,9885.85,2730.72,6876,8024.47,1196.87,1655.29 </code></pre> <p>But if you notice, some of the fields are incomplete. I'm thinking MySQL will just skip the row where the first column is missing. When I run the command:</p> <pre><code>LOAD DATA LOCAL INFILE 'test-long.csv' REPLACE INTO TABLE accounts FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (cf_535, cf_580, cf_568, cf_569, cf_571, cf_572); </code></pre> <p>And the MySQL output is:</p> <pre><code>Query OK, 41898 rows affected, 20948 warnings (0.78 sec) Records: 20949 Deleted: 20949 Skipped: 0 Warnings: 20948 </code></pre> <p>The number of lines is only 20,949 but MySQL reports it as 41,898 rows affected. Why so? Also, nothing really changed in the table. I also couldn't see what the warnings generated is all about. I wanted to use the LOAD DATA INFILE because it takes python half a second to update each row which translates to 2.77 hours for a file with 20,000+ records.</p> <p><strong>UPDATE:</strong> Modified the code to set auto-commit to 'False' and added a db.commit() statement:</p> <pre><code># Tell MySQLdb to turn off auto-commit db.autocommit(False) # Set count to 1 count = 1 while count &lt; len(contents): if contents[count][0] != '': cursor.execute(""" UPDATE accounts SET cf_580 = %s, cf_568 = %s, cf_569 = %s, cf_571 = %s, cf_572 = %s WHERE cf_535 = %s""" % (contents[count][1], contents[count][2], contents[count][3], contents[count][4], contents[count][5], contents[count][0])) count += 1 try: db.commit() except: db.rollback() </code></pre>
3
2009-08-06T04:27:01Z
1,237,030
<p>You have basically 3 issues here. In reverse order</p> <ol> <li>Are you doing your Python inserts in individual statements? You probably want to surround them all with a begin transaction/commit. 20,000 commits could easily take hours. </li> <li>Your import statement defines 6 fields, but the CSV has 7 fields. That would explain the double row count: every line of input results in 2 rows in the database, the 2nd one with fields 2-6 null.</li> <li>Incomplete rows will be inserted with null or default values for the missing columns. This may not be what you want with those malformed rows.</li> </ol> <p>If your python program can't perform fast enough even with a single transaction, you should at least have the python program edit/clean the data file before importing. If Acct. No. is the primary key, as seems reasonable, inserting rows with blank will either cause the whole import to fail, or if auto number is on, cause bogus data to be imported.</p>
2
2009-08-06T04:50:37Z
[ "python", "mysql", "load", "load-data-infile" ]
Help with MySQL LOAD DATA INFILE
1,236,971
<p>I want to load a CSV file that looks like this:</p> <pre><code>Acct. No.,1-15 Days,16-30 Days,31-60 Days,61-90 Days,91-120 Days,Beyond 120 Days 2314134101,898.89,8372.16,5584.23,7744.41,9846.54,2896.25 2414134128,5457.61,7488.26,9594.02,6234.78,273.7,2356.13 2513918869,2059.59,7578.59,9395.51,7159.15,5827.48,3041.62 1687950783,4846.85,8364.22,9892.55,7213.45,8815.33,7603.4 2764856043,5250.11,9946.49,8042.03,6058.64,9194.78,8296.2 2865446086,596.22,7670.04,8564.08,3263.85,9662.46,7027.22 ,4725.99,1336.24,9356.03,1572.81,4942.11,6088.94 ,8248.47,956.81,8713.06,2589.14,5316.68,1543.67 ,538.22,1473.91,3292.09,6843.89,2687.07,9808.05 ,9885.85,2730.72,6876,8024.47,1196.87,1655.29 </code></pre> <p>But if you notice, some of the fields are incomplete. I'm thinking MySQL will just skip the row where the first column is missing. When I run the command:</p> <pre><code>LOAD DATA LOCAL INFILE 'test-long.csv' REPLACE INTO TABLE accounts FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (cf_535, cf_580, cf_568, cf_569, cf_571, cf_572); </code></pre> <p>And the MySQL output is:</p> <pre><code>Query OK, 41898 rows affected, 20948 warnings (0.78 sec) Records: 20949 Deleted: 20949 Skipped: 0 Warnings: 20948 </code></pre> <p>The number of lines is only 20,949 but MySQL reports it as 41,898 rows affected. Why so? Also, nothing really changed in the table. I also couldn't see what the warnings generated is all about. I wanted to use the LOAD DATA INFILE because it takes python half a second to update each row which translates to 2.77 hours for a file with 20,000+ records.</p> <p><strong>UPDATE:</strong> Modified the code to set auto-commit to 'False' and added a db.commit() statement:</p> <pre><code># Tell MySQLdb to turn off auto-commit db.autocommit(False) # Set count to 1 count = 1 while count &lt; len(contents): if contents[count][0] != '': cursor.execute(""" UPDATE accounts SET cf_580 = %s, cf_568 = %s, cf_569 = %s, cf_571 = %s, cf_572 = %s WHERE cf_535 = %s""" % (contents[count][1], contents[count][2], contents[count][3], contents[count][4], contents[count][5], contents[count][0])) count += 1 try: db.commit() except: db.rollback() </code></pre>
3
2009-08-06T04:27:01Z
1,326,393
<p>If you use REPLACE keyword in LOAD DATA, then number after "Deleted: " shows how many rows were actually replaced</p>
0
2009-08-25T06:33:03Z
[ "python", "mysql", "load", "load-data-infile" ]
math.sin incorrect result
1,237,085
<pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.sin(68) -0.897927680689 </code></pre> <p>But</p> <pre><code>sin(68) = 0.927 (3 decimal places) </code></pre> <p>Any ideas about why I am getting this result?<br> Thanks.</p>
4
2009-08-06T05:16:09Z
1,237,087
<pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; print math.sin.__doc__ sin(x) Return the sine of x (measured in radians). </code></pre> <p>math.sin expects its argument to be in radians, not degrees, so:</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; print math.sin(math.radians(68)) 0.927183854567 </code></pre>
22
2009-08-06T05:18:56Z
[ "python", "math", "trigonometry", "sin" ]
math.sin incorrect result
1,237,085
<pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.sin(68) -0.897927680689 </code></pre> <p>But</p> <pre><code>sin(68) = 0.927 (3 decimal places) </code></pre> <p>Any ideas about why I am getting this result?<br> Thanks.</p>
4
2009-08-06T05:16:09Z
33,218,237
<h3>Quote from <a href="http://stackoverflow.com/a/8691808/3787376" title="The answer to a Stack Overflow question">a Stack Overflow answer</a> for the question<br> <a href="http://stackoverflow.com/questions/8691800/unusual-math-with-incorrect-results" title="The Stack Overflow question">http://stackoverflow.com/questions/8691800/unusual-math-with-incorrect-results</a>:</h3> <blockquote> <p>This is being caused by the fact that you are using degrees and the trigonometric functions expect radians as input: sin(radians)</p> <p>The description for sin is:</p> <pre><code>sin(x) Return the sine of x (measured in radians). </code></pre> <p>In Python, you can convert degrees to radians with the math.radians function.</p> <p>So if you do this with your input:</p> <pre><code>&gt;&gt;&gt; math.sin(math.radians(35)) * 15 + 9 17.60364654526569 </code></pre> <p>it gives the same result as your calculator.</p> </blockquote> <p>So really, the truth is that "<strong>math.sin incorrect result</strong>" isn't true,<br> the <strong><code>math.sin</code> result is correct</strong>, but just uses in a different<br> format/style (radians) for input to the one you want to use (degrees). </p> <p>Therefore, you <strong>just need to convert the radians into degrees</strong> to<br> make the result how you want (perhaps like your calculator).</p>
1
2015-10-19T15:25:12Z
[ "python", "math", "trigonometry", "sin" ]
Cron job python Google App Engine
1,237,126
<p>I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?</p>
0
2009-08-06T05:32:45Z
1,237,224
<p>"fetch" your OWN url (on appspot.com probably, but, who cares -- use a relative url anywau1-), not <code>google.com</code>, the homepage of the search engine -- what's that got to do w/your app anyway?!-)...</p>
0
2009-08-06T06:16:38Z
[ "python", "google-app-engine", "cron", "scheduled-tasks" ]
How do I set sys.excepthook to invoke pdb globally in python?
1,237,379
<p>From Python docs:</p> <blockquote> <p><code>sys.excepthook(type, value, traceback)</code></p> <p>This function prints out a given traceback and exception to <code>sys.stderr</code>.</p> <p>When an exception is raised and uncaught, the interpreter calls <code>sys.excepthook</code> with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to <code>sys.excepthook</code>.</p> </blockquote> <p><a href="http://docs.python.org/library/sys.html" rel="nofollow">http://docs.python.org/library/sys.html</a></p> <p>How do I modify this globally so the default action is to always invoke <code>pdb</code>? Is there a configuration file I can change? I don't want to wrap my code to do this.</p>
6
2009-08-06T07:15:46Z
1,237,407
<p>Here's what you need</p> <p><a href="http://ynniv.com/blog/2007/11/debugging-python.html">http://ynniv.com/blog/2007/11/debugging-python.html</a></p> <p>Three ways, the first is simple but crude (<a href="http://mail.python.org/pipermail/python-list/2001-April/713230.html">Thomas Heller</a>) - add the following to site-packages/sitecustomize.py:</p> <pre><code>import pdb, sys, traceback def info(type, value, tb): traceback.print_exception(type, value, tb) pdb.pm() sys.excepthook = info </code></pre> <p>The second is more sophisticated, and checks for interactive mode (weirdly skipping the debugging in interactive mode), from the <a href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287">cookbook</a>:</p> <pre><code># code snippet, to be included in 'sitecustomize.py' import sys def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info </code></pre> <p>And the third (which always start the debugger unless stdin or stderr are redirected) by <a href="http://ynniv.com/blog/2007/11/debugging-python.html">ynniv</a></p> <pre><code># code snippet, to be included in 'sitecustomize.py' import sys def info(type, value, tb): if (#hasattr(sys, "ps1") or not sys.stderr.isatty() or not sys.stdin.isatty()): # stdin or stderr is redirected, just do the normal thing original_hook(type, value, tb) else: # a terminal is attached and stderr is not redirected, debug import traceback, pdb traceback.print_exception(type, value, tb) print pdb.pm() #traceback.print_stack() original_hook = sys.excepthook if sys.excepthook == sys.__excepthook__: # if someone already patched excepthook, let them win sys.excepthook = info </code></pre>
17
2009-08-06T07:27:07Z
[ "python", "debugging", "configuration", "pdb" ]
How do I set sys.excepthook to invoke pdb globally in python?
1,237,379
<p>From Python docs:</p> <blockquote> <p><code>sys.excepthook(type, value, traceback)</code></p> <p>This function prints out a given traceback and exception to <code>sys.stderr</code>.</p> <p>When an exception is raised and uncaught, the interpreter calls <code>sys.excepthook</code> with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to <code>sys.excepthook</code>.</p> </blockquote> <p><a href="http://docs.python.org/library/sys.html" rel="nofollow">http://docs.python.org/library/sys.html</a></p> <p>How do I modify this globally so the default action is to always invoke <code>pdb</code>? Is there a configuration file I can change? I don't want to wrap my code to do this.</p>
6
2009-08-06T07:15:46Z
1,237,422
<p>Try:</p> <pre><code>import pdb import sys def excepthook(type, value, traceback): pdb.post_mortem(traceback) excepthook.old = sys.excepthook sys.excepthook = excepthook def raise_exception(): raise_exception() raise_exception() </code></pre>
0
2009-08-06T07:31:43Z
[ "python", "debugging", "configuration", "pdb" ]
How do I set sys.excepthook to invoke pdb globally in python?
1,237,379
<p>From Python docs:</p> <blockquote> <p><code>sys.excepthook(type, value, traceback)</code></p> <p>This function prints out a given traceback and exception to <code>sys.stderr</code>.</p> <p>When an exception is raised and uncaught, the interpreter calls <code>sys.excepthook</code> with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to <code>sys.excepthook</code>.</p> </blockquote> <p><a href="http://docs.python.org/library/sys.html" rel="nofollow">http://docs.python.org/library/sys.html</a></p> <p>How do I modify this globally so the default action is to always invoke <code>pdb</code>? Is there a configuration file I can change? I don't want to wrap my code to do this.</p>
6
2009-08-06T07:15:46Z
1,336,425
<p>Another option is to use ipython, which I consider a must-have tool for any python developer anyway. Instead of running your script from the shell, run it from ipython with %run. When an exception occurs, you can type %debug to debug it. (There's also an option to automatically debug any exception that occurs, but I forget what it is.)</p>
1
2009-08-26T17:48:08Z
[ "python", "debugging", "configuration", "pdb" ]
Choose the filename of an uploaded file with Django
1,237,602
<p>I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.</p> <p>I want them to be formated like that:</p> <p><code>"%d-%d-%s.%s" % (width, height, md5hash, original_extension)</code></p> <p>I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField class or ... ? Everything is so linked I don't know where to start.</p>
6
2009-08-06T08:26:14Z
1,237,741
<p>You don't need to write your own FileStorage class or anything that complicated.</p> <p>The 'upload_to' parameter on File/ImageFields can take a function that returns the path/file to use.</p> <p>How to do this has already been answered <a href="http://stackoverflow.com/questions/1190697/django-filefield-with-uploadto-determined-at-runtime">here</a></p>
18
2009-08-06T08:59:38Z
[ "python", "django", "django-models" ]
Choose the filename of an uploaded file with Django
1,237,602
<p>I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.</p> <p>I want them to be formated like that:</p> <p><code>"%d-%d-%s.%s" % (width, height, md5hash, original_extension)</code></p> <p>I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField class or ... ? Everything is so linked I don't know where to start.</p>
6
2009-08-06T08:26:14Z
1,237,762
<p>My initial instinct when reading this was that you need to overload the save method on the model, and use the os.rename() method, but that causes a lot of overhead, and is just generally a hassle from start to finish. If you simply want to rename the file, but don't want to make any physical changes to it (resizing, duplicating, etc.), then I'd definitely recommend the approach arcanum suggests above.</p>
-1
2009-08-06T09:04:15Z
[ "python", "django", "django-models" ]
How to implement a state-space tree?
1,237,634
<p>I'm trying to solve a knapsack like problem from <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm" rel="nofollow">MIT OCW</a>. Its problem set 5.</p> <p>I need use branch and bound algorithm to find the optimal states. So I need implement a state-space tree. I understand the idea of this algorithm, but I find it's not so easy to implement.</p> <p>If I find a node where the budget is not enough, I should stop here. Should I add an attribute to every tree node?</p> <p>When I add a node, I should start from a node with the largest upper bound. How can I find such a node? Do I need to traverse all the nodes before I add each node? Or could I save some var to help with that?</p> <p>Do you have any idea? Could you implement it in python?</p>
2
2009-08-06T08:34:18Z
1,246,858
<p>I hope I understood correctly the problem, if not please direct me :)<br /> (sorry for the confusion arising from the two different meanings of "state")</p> <p>You can of course add the attribute in the node (it's part of the state!), since it's a very tiny amount of data. Mind that it is not mandatory to save it though, since it is implicitly present in the rest of the state (given the states that you have already chosen, you can compute it). Personally, I'd add the attribute, since there's no point in calculating it many times.</p> <p>On the second question: IIRC, when you add nodes, you don't have to traverse ALL the tree, but rather only the fringe (that is, the set of nodes which have no descendants - not to be confused by the deepest level of the tree). Since you're looking for an upper bound, (and since you're using only positive costs), there are three cases when you are looking for the node with the highest value:</p> <ul> <li>on the last step you appended to the node which had the highest value, so the node which you just added has now the highest value</li> <li>on the last step adding the you exceeded the budget, so you had to exclude the option. try to add another state</li> <li>there are no more states to try to add to build a new node. This branch can't go further. Look at the fringe for the highest value in the other nodes</li> </ul>
2
2009-08-07T20:29:54Z
[ "python", "algorithm" ]
Python: binary/hex string conversion?
1,238,002
<p>I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex.</p> <p>The string is as below:</p> <pre><code>&lt;81&gt;^Q&lt;81&gt;"^Q^@^[)^G ^Q^A^S^A^V^@&lt;83&gt;^Cd&lt;80&gt;&lt;99&gt;}^@N^@^@^A^@^@^@^@^@^@^@j </code></pre> <p>How do I go about converting this string in Python so that the output in hex format is similar to this below?</p> <pre><code>24208040901811001B12050809081223431235113245422F0A23000000000000000000001F </code></pre>
7
2009-08-06T10:03:27Z
1,238,129
<p>You can use ord and hex like this :</p> <pre><code>&gt;&gt;&gt; s = 'some string' &gt;&gt;&gt; hex_chars = map(hex,map(ord,s)) &gt;&gt;&gt; print hex_chars ['0x73', '0x6f', '0x6d', '0x65', '0x20', '0x73', '0x74', '0x72', '0x69', '0x6e', '0x67'] &gt;&gt;&gt; hex_string = "".join(c[2:4] for c in hex_chars) &gt;&gt;&gt; print hex_string 736f6d6520737472696e67 &gt;&gt;&gt; </code></pre> <p>Or use the builtin encoding :</p> <pre><code>&gt;&gt;&gt; s = 'some string' &gt;&gt;&gt; print s.encode('hex_codec') 736f6d6520737472696e67 &gt;&gt;&gt; </code></pre>
20
2009-08-06T10:36:46Z
[ "python", "binary", "hex" ]
Python: binary/hex string conversion?
1,238,002
<p>I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex.</p> <p>The string is as below:</p> <pre><code>&lt;81&gt;^Q&lt;81&gt;"^Q^@^[)^G ^Q^A^S^A^V^@&lt;83&gt;^Cd&lt;80&gt;&lt;99&gt;}^@N^@^@^A^@^@^@^@^@^@^@j </code></pre> <p>How do I go about converting this string in Python so that the output in hex format is similar to this below?</p> <pre><code>24208040901811001B12050809081223431235113245422F0A23000000000000000000001F </code></pre>
7
2009-08-06T10:03:27Z
7,565,322
<p>Faster solution see:</p> <pre><code>from timeit import Timer import os import binascii def testSpeed(statement, setup = 'pass'): print '%s' % statement print '%s' % Timer(statement, setup).timeit() setup = """ import os value = os.urandom(32) """ # winner statement = """ import binascii binascii.hexlify(value) """ testSpeed(statement, setup) # loser statement = """ import binascii value.encode('hex_codec') """ testSpeed(statement, setup) </code></pre> <p>Results:</p> <pre><code>import binascii binascii.hexlify(value) 2.18547999816 value.encode('hex_codec') 2.91231595077 </code></pre>
1
2011-09-27T07:00:29Z
[ "python", "binary", "hex" ]
Python: binary/hex string conversion?
1,238,002
<p>I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex.</p> <p>The string is as below:</p> <pre><code>&lt;81&gt;^Q&lt;81&gt;"^Q^@^[)^G ^Q^A^S^A^V^@&lt;83&gt;^Cd&lt;80&gt;&lt;99&gt;}^@N^@^@^A^@^@^@^@^@^@^@j </code></pre> <p>How do I go about converting this string in Python so that the output in hex format is similar to this below?</p> <pre><code>24208040901811001B12050809081223431235113245422F0A23000000000000000000001F </code></pre>
7
2009-08-06T10:03:27Z
7,813,649
<pre><code>&gt;&gt;&gt; import binascii &gt;&gt;&gt; s = '2F' &gt;&gt;&gt; hex_str = binascii.b2a_hex(s) &gt;&gt;&gt; hex_str &gt;&gt;&gt; '3246' </code></pre> <p>OR</p> <pre><code>&gt;&gt;&gt;import binascii &gt;&gt;&gt; hex_str = binascii.hexlify(s) &gt;&gt;&gt; hex_str &gt;&gt;&gt; '3246' &gt;&gt;&gt; </code></pre>
5
2011-10-18T20:58:57Z
[ "python", "binary", "hex" ]
What does % do to strings in Python?
1,238,306
<p>I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?</p>
11
2009-08-06T11:29:00Z
1,238,316
<p>It's the string formatting operator. Read up on <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations">string formatting in Python</a>.</p> <pre><code>format % values </code></pre> <p>Creates a string where <code>format</code> specifies a format and <code>values</code> are the values to be filled in.</p>
20
2009-08-06T11:30:46Z
[ "python", "string", "documentation", "operators" ]
What does % do to strings in Python?
1,238,306
<p>I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?</p>
11
2009-08-06T11:29:00Z
1,238,321
<p>The '%' operator is used for string interpolation. Since Python 2.6 the String method "format" is used insted. For details see <a href="http://www.python.org/dev/peps/pep-3101/" rel="nofollow">http://www.python.org/dev/peps/pep-3101/</a></p>
6
2009-08-06T11:31:57Z
[ "python", "string", "documentation", "operators" ]
What does % do to strings in Python?
1,238,306
<p>I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?</p>
11
2009-08-06T11:29:00Z
1,238,353
<p>It applies <a href="http://en.wikipedia.org/wiki/Printf">printf-like formatting</a> to a string, so that you can substitute certain parts of a string with values of variables. Example</p> <pre><code># assuming numFiles is an int variable print "Found %d files" % (numFiles, ) </code></pre> <p>See the link provided by Konrad</p>
6
2009-08-06T11:38:41Z
[ "python", "string", "documentation", "operators" ]
What does % do to strings in Python?
1,238,306
<p>I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?</p>
11
2009-08-06T11:29:00Z
1,238,611
<p>Note that starting from Python 2.6, it's recommended to use the new <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow"><code>str.format()</code></a> method:</p> <pre><code>&gt;&gt;&gt; "The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3' </code></pre> <p>If you are using 2.6, you may want to keep using <code>%</code> in order to remain compatible with older versions, but in Python 3 there's no reason not to use <code>str.format()</code>.</p>
2
2009-08-06T12:40:28Z
[ "python", "string", "documentation", "operators" ]
Python Multiprocessing exit error
1,238,349
<p>Hey everyone I am seeing this when I press Ctrl-C to exit my app</p> <pre><code>Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.6/multiprocessing/util.py", line 269, in _exit_function p.join() File "/usr/lib/python2.6/multiprocessing/process.py", line 119, in join res = self._popen.wait(timeout) File "/usr/lib/python2.6/multiprocessing/forking.py", line 117, in wait return self.poll(0) File "/usr/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 4] Interrupted system call Error in sys.exitfunc: Traceback (most recent call last): File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.6/multiprocessing/util.py", line 269, in _exit_function p.join() File "/usr/lib/python2.6/multiprocessing/process.py", line 119, in join res = self._popen.wait(timeout) File "/usr/lib/python2.6/multiprocessing/forking.py", line 117, in wait return self.poll(0) File "/usr/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 4] Interrupted system call </code></pre> <p>I am using twisted on top of my own stuff,</p> <p>I registered the signal Ctrl-C with the following code</p> <pre><code> def sigHandler(self, arg1, arg2): if not self.backuped: self.stopAll() else: out('central', 'backuped ALREADY, now FORCE exiting') exit() def stopAll(self): self.parserM.shutdown() for each in self.crawlM: each.shutdown() self.backup() reactor.stop() </code></pre> <p>and when they signal others to shutdown, it tries to tell them to shutdown nicely through </p> <pre><code>exit = multiprocessing.Event() def shutdown(self): self.exit.set() </code></pre> <p>where all my processes are in some form,</p> <pre><code>def run(self): while not self.exit.is_set(): do something out('crawler', 'crawler exited sucessfully') </code></pre> <p>Any idea what this error is? I only get it when I have more than one instance of a particular thread. </p>
6
2009-08-06T11:37:57Z
1,244,229
<p>This is related to interactions OS system calls, signals and how it's handled in the multiprocessing module. I'm not really sure if it's a bug or a feature, but it's in somewhat tricky territory as it's where python meets the os.</p> <p>The problem is that multiprocessing is blocking on waitpid until the child it's waiting for has terminated. However, since you've installed a signal-handler for SIGINT and your program gets this signal, it interrupts the system call to execute your signal handler, and waitpid exits indicating that it was interrupted by a signal. The way python handles this case is by exceptions.</p> <p>As a workaround, you can enclose the offending section(s) in a while-loop and try/catch blocks like this, either around where you wait for threads to finish, or subclass multiprocessing.Popen:</p> <pre><code>import errno from multiprocessing import Process p = Processing( target=func, args=stuff ) p.start() notintr = False while not notintr: try: p.join() # "Offending code" notintr = True except OSError, ose: if ose.errno != errno.EINTR: raise ose </code></pre> <p>For mucking about with multiprocessing.forking.Popen you'd have to do something like this:</p> <pre><code>import errno from multiprocessing import Process from multiprocessing.forking import Popen import os # see /path/to/python/libs/multiprocessing/forking.py class MyPopen(Popen): def poll(self, flag=os.WNOHANG): # from forking.py if self.returncode is None: # from forking.py notintr = False while not notintr: try: pid, sts = os.waitpid(self.pid, flag) # from forking.py notintr = True except OSError, ose: if ose.errno != errno.EINTR: raise ose # Rest of Popen.poll from forking.py goes here p = Process( target=func args=stuff ) p._Popen = p p.start() p.join() </code></pre>
5
2009-08-07T11:20:21Z
[ "python", "exception", "multiprocessing" ]
Python Multiprocessing exit error
1,238,349
<p>Hey everyone I am seeing this when I press Ctrl-C to exit my app</p> <pre><code>Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.6/multiprocessing/util.py", line 269, in _exit_function p.join() File "/usr/lib/python2.6/multiprocessing/process.py", line 119, in join res = self._popen.wait(timeout) File "/usr/lib/python2.6/multiprocessing/forking.py", line 117, in wait return self.poll(0) File "/usr/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 4] Interrupted system call Error in sys.exitfunc: Traceback (most recent call last): File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.6/multiprocessing/util.py", line 269, in _exit_function p.join() File "/usr/lib/python2.6/multiprocessing/process.py", line 119, in join res = self._popen.wait(timeout) File "/usr/lib/python2.6/multiprocessing/forking.py", line 117, in wait return self.poll(0) File "/usr/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 4] Interrupted system call </code></pre> <p>I am using twisted on top of my own stuff,</p> <p>I registered the signal Ctrl-C with the following code</p> <pre><code> def sigHandler(self, arg1, arg2): if not self.backuped: self.stopAll() else: out('central', 'backuped ALREADY, now FORCE exiting') exit() def stopAll(self): self.parserM.shutdown() for each in self.crawlM: each.shutdown() self.backup() reactor.stop() </code></pre> <p>and when they signal others to shutdown, it tries to tell them to shutdown nicely through </p> <pre><code>exit = multiprocessing.Event() def shutdown(self): self.exit.set() </code></pre> <p>where all my processes are in some form,</p> <pre><code>def run(self): while not self.exit.is_set(): do something out('crawler', 'crawler exited sucessfully') </code></pre> <p>Any idea what this error is? I only get it when I have more than one instance of a particular thread. </p>
6
2009-08-06T11:37:57Z
1,435,075
<p>I was seeing this, but it went away when I overrode signal handlers with my own. Use reactor.run(installSignalHandlers=False) and define your own functions for SIGINT, SIGTERM, etc.</p>
0
2009-09-16T19:46:34Z
[ "python", "exception", "multiprocessing" ]
Is it necessary or useful to inherit from python's object in Python 3.x?
1,238,606
<p>In older python version when you create a class in python, it can inherit from <em>object</em> which is as far I understand a special built-in python element that allow your object to be a new-style object.</p> <p>What about newer version (> 3.0 and 2.6)? I googled about the class object but I get so much result (for an obvious reasons). Any hint?</p> <p>Thank!</p>
32
2009-08-06T12:39:53Z
1,238,632
<p>You don't need to inherit from <code>object</code> to have new style in python 3. All classes are new-style.</p>
27
2009-08-06T12:43:53Z
[ "python", "python-3.x" ]
surprising time shift for python call
1,238,648
<p>I'm using the following code in Python 2.5.1 to generate a UTC timestamp from a string representation of a date:</p> <pre><code>time.mktime(time.strptime("2009-06-16", "%Y-%m-%d")) </code></pre> <p>The general result is: 1245103200 (16.6.2009 0:00 UTC or 15.6.09 22:00:00, if you're in my time zone). </p> <p>But now, I found that on some computers running Windows XP, this statement would generate a time shifted by 1 hour, 1 minute and 1 second: 1245099539 (15.6.2009 22:58:59 UTC or 15.6.09 20:58:59 in my time zone). </p> <p>DST and time zone do not seem to be the cause of the problem, because the time shift seems to appear additionally to DST and time zone calculation. </p> <p>Has anybody experienced the same behaviour or is able to describe what happens here?</p>
0
2009-08-06T12:45:36Z
1,238,813
<p>What version of Python are you running? There are two bug descriptions here which sound a lot like what you are experiencing:</p> <ul> <li><a href="http://bugs.python.org/issue5582" rel="nofollow">http://bugs.python.org/issue5582</a></li> <li><a href="http://mercurial.selenic.com/bts/issue1364" rel="nofollow">http://mercurial.selenic.com/bts/issue1364</a></li> </ul>
0
2009-08-06T13:16:32Z
[ "python", "windows-xp", "timestamp" ]
surprising time shift for python call
1,238,648
<p>I'm using the following code in Python 2.5.1 to generate a UTC timestamp from a string representation of a date:</p> <pre><code>time.mktime(time.strptime("2009-06-16", "%Y-%m-%d")) </code></pre> <p>The general result is: 1245103200 (16.6.2009 0:00 UTC or 15.6.09 22:00:00, if you're in my time zone). </p> <p>But now, I found that on some computers running Windows XP, this statement would generate a time shifted by 1 hour, 1 minute and 1 second: 1245099539 (15.6.2009 22:58:59 UTC or 15.6.09 20:58:59 in my time zone). </p> <p>DST and time zone do not seem to be the cause of the problem, because the time shift seems to appear additionally to DST and time zone calculation. </p> <p>Has anybody experienced the same behaviour or is able to describe what happens here?</p>
0
2009-08-06T12:45:36Z
1,259,669
<p>Found the answer myself:</p> <p>When executing the following on the python command line interface, I get the result:</p> <blockquote> <p>time.strptime("2009-06-16", "%Y-%m-%d")<br /> time.struct_time(tm_year=2009, tm_mon=6, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=167, tm_isdst=-1) </p> </blockquote> <p>If I run the same command in an executable built with py2exe, it results in the following time structure:</p> <blockquote> <p>time.struct_time(tm_year=2009, tm_mon=8, tm_mday=11, tm_hour=-1, tm_min=-1, tm_sec=-1, tm_wday=1, tm_yday=224, tm_isdst=-1)</p> </blockquote> <p>The internal time structure apparently initializes differently on command line and when using py2exe. Fixed the problem by adding a midnight time to the command.</p>
1
2009-08-11T11:00:44Z
[ "python", "windows-xp", "timestamp" ]
Does 'a+' mode allow random access to files, on all systems?
1,238,922
<p>According to the <a href="http://docs.python.org/library/functions.html?highlight=open#open" rel="nofollow">documentation</a> of open function 'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.</p> <p>Will 'a+' allow random writes to any position in the file on all systems?</p>
2
2009-08-06T13:33:33Z
1,238,996
<p>On my linux system with Python 2.5.2 writes to a file opened with 'a+' appear to always append to the end, regardless of the current seek position.</p> <p>Here is an example:</p> <pre><code>import os if __name__ == "__main__": f = open("test", "w") f.write("Hello") f.close() f = open("test", "a+") f.seek(0, os.SEEK_SET) f.write("Goodbye") f.close() </code></pre> <p>On my system (event though I seeked to the beginning of the file) this results in the file "test" containing:</p> <blockquote> <p>HelloGoodbye</p> </blockquote> <p>The python documentation says that the mode argument is the same as stdio's.</p> <p>The linux man page for <a href="http://linux.die.net/man/3/fopen" rel="nofollow">fopen()</a> does say that (emphasis added):</p> <blockquote> <p>Opening a file in append mode (a as the <strong>first character</strong> of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded by an</p> <pre><code>fseek(stream,0,SEEK_END); </code></pre> <p>call.</p> </blockquote> <p>My stdio reference says that appending a '+' to the mode (i.e. 'a+') means that the stream is opened for <em>input and output</em>. However before switching between input and output a call must be made to explicitly set the file position.</p> <p>So adding the '+' doesn't change the fact that on some systems writes for a file opened in 'a' or 'a+' mode will always append to the end of the file.</p>
2
2009-08-06T13:48:45Z
[ "python" ]
Can all language constructs be first-class in languages with offside-rules?
1,238,975
<p>In LISP-like languages all language constructs are first-class citizens.</p> <p>Consider the following example in Dylan:</p> <pre><code>let x = if (c) foo(); else bar(); end; </code></pre> <p>and in LISP:</p> <pre><code>(setf x (if c (foo) (bar))) </code></pre> <p>In Python you would have to write:</p> <pre><code>if c: x = foo(); else: x = bar(); </code></pre> <p>Because Python destinguishes statements and expressions.</p> <p>Can all language constructs in a language which adheres to the off-side rule (has an indention-based syntax) be expressions, so that you can assign them to variables or pass them as parameters?</p>
2
2009-08-06T13:44:22Z
1,239,015
<p>I don't see the relation with first-classness here - you're not passing the <code>if</code> <strong>statement</strong> to the function, but the object it returns, which is as fully first class in python as in lisp. However as far as having a statement/expression dichotomy, clearly it is possible: Haskell for instance has indentation-based syntax, yet as a purely functional language obviously has no statements.</p> <p>I think Python's separation here has more to do with forbidding dangerous constructs like "if x=4:" etc than any syntax limitation. (Though I think it loses more than it gains by this - sometimes having the flexibility sufficient to shoot off your foot is very valuable, even if you do risk losing a few toes now and again.)</p>
4
2009-08-06T13:52:42Z
[ "python", "lisp", "expression", "indentation", "if-statement" ]
Can all language constructs be first-class in languages with offside-rules?
1,238,975
<p>In LISP-like languages all language constructs are first-class citizens.</p> <p>Consider the following example in Dylan:</p> <pre><code>let x = if (c) foo(); else bar(); end; </code></pre> <p>and in LISP:</p> <pre><code>(setf x (if c (foo) (bar))) </code></pre> <p>In Python you would have to write:</p> <pre><code>if c: x = foo(); else: x = bar(); </code></pre> <p>Because Python destinguishes statements and expressions.</p> <p>Can all language constructs in a language which adheres to the off-side rule (has an indention-based syntax) be expressions, so that you can assign them to variables or pass them as parameters?</p>
2
2009-08-06T13:44:22Z
1,239,032
<p>Python has the following syntax that performs the same thing:</p> <pre><code>x = foo() if c else bar() </code></pre>
9
2009-08-06T13:54:55Z
[ "python", "lisp", "expression", "indentation", "if-statement" ]
Changing the default indentation of etree.tostring in lxml
1,238,988
<p>I have an XML document which I'm pretty-printing using <code>lxml.etree.tostring</code></p> <pre><code>print etree.tostring(doc, pretty_print=True) </code></pre> <p>The default level of indentation is 2 spaces, and I'd like to change this to 4 spaces. There isn't any argument for this in the <code>tostring</code> function; is there a way to do this easily with lxml?</p>
5
2009-08-06T13:47:37Z
1,239,193
<p>As said in <a href="http://codespeak.net/pipermail/lxml-dev/2009-February/004350.html" rel="nofollow">this thread</a>, there is no real way to change the indent of the <code>lxml.etree.tostring</code> pretty-print.</p> <p>But, you can:</p> <ul> <li>add a XSLT transform to change the indent</li> <li>add whitespace to the tree, with something like in the <a href="http://effbot.org/zone/element-lib.htm" rel="nofollow">cElementTree</a> library</li> </ul> <p>code:</p> <pre><code>def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i </code></pre>
3
2009-08-06T14:20:28Z
[ "python", "lxml", "pretty-print" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
1,239,059
<p>It's not in the language core, but a very mature library that does what you want is <a href="http://twistedmatrix.com/">Twisted</a>. It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually.</p>
25
2009-08-06T13:59:22Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
1,239,108
<p>What about something like</p> <pre><code>import threading thr = threading.Thread(target=foo, args=(), kwargs={}) thr.start() # will run "foo" .... thr.is_alive() # will return whether foo is running currently .... thr.join() # will wait till "foo" is done </code></pre> <p>See the docs at <a href="https://docs.python.org/2/library/threading.html#module-threading">https://docs.python.org/2/library/threading.html#module-threading</a> for more details; this code should work for python 3 as well.</p>
108
2009-08-06T14:05:52Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
1,239,139
<p>Is there any reason not to use threads? You can use the <code>threading</code> class. Instead of <code>finished()</code> function use the <code>isAlive()</code>. The <code>result()</code> function could <code>join()</code> the thread and retrieve the result. And, if you can, override the <code>run()</code> and <code>__init__</code> functions to call the function specified in the constructor and save the value somewhere to the instance of the class.</p>
2
2009-08-06T14:11:16Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
1,239,252
<p>You can use the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing">multiprocessing module</a> added in Python 2.6. You can use pools of processes and then get results asynchronously with: </p> <pre><code>apply_async(func[, args[, kwds[, callback]]]) </code></pre> <p>E.g.:</p> <pre><code>from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': pool = Pool(processes=1) # Start a worker processes. result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished. </code></pre> <p>This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.</p>
82
2009-08-06T14:28:14Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
5,239,576
<p>My solution is:</p> <pre><code>import threading class TimeoutError(RuntimeError): pass class AsyncCall(object): def __init__(self, fnc, callback = None): self.Callable = fnc self.Callback = callback def __call__(self, *args, **kwargs): self.Thread = threading.Thread(target = self.run, name = self.Callable.__name__, args = args, kwargs = kwargs) self.Thread.start() return self def wait(self, timeout = None): self.Thread.join(timeout) if self.Thread.isAlive(): raise TimeoutError() else: return self.Result def run(self, *args, **kwargs): self.Result = self.Callable(*args, **kwargs) if self.Callback: self.Callback(self.Result) class AsyncMethod(object): def __init__(self, fnc, callback=None): self.Callable = fnc self.Callback = callback def __call__(self, *args, **kwargs): return AsyncCall(self.Callable, self.Callback)(*args, **kwargs) def Async(fnc = None, callback = None): if fnc == None: def AddAsyncCallback(fnc): return AsyncMethod(fnc, callback) return AddAsyncCallback else: return AsyncMethod(fnc, callback) </code></pre> <p>And works exactly as requested:</p> <pre><code>@Async def fnc(): pass </code></pre>
5
2011-03-08T23:22:14Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
5,485,574
<p>You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The <code>multiprocessing</code> module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.</p> <pre><code>from inspect import getmodule from multiprocessing import Pool def async(decorated): r'''Wraps a top-level function around an asynchronous dispatcher. when the decorated function is called, a task is submitted to a process pool, and a future object is returned, providing access to an eventual return value. The future object has a blocking get() method to access the task result: it will return immediately if the job is already done, or block until it completes. This decorator won't work on methods, due to limitations in Python's pickling machinery (in principle methods could be made pickleable, but good luck on that). ''' # Keeps the original function visible from the module global namespace, # under a name consistent to its __name__ attribute. This is necessary for # the multiprocessing pickling machinery to work properly. module = getmodule(decorated) decorated.__name__ += '_original' setattr(module, decorated.__name__, decorated) def send(*args, **opts): return async.pool.apply_async(decorated, args, opts) return send </code></pre> <p>The code below illustrates usage of the decorator:</p> <pre><code>@async def printsum(uid, values): summed = 0 for value in values: summed += value print("Worker %i: sum value is %i" % (uid, summed)) return (uid, summed) if __name__ == '__main__': from random import sample # The process pool must be created inside __main__. async.pool = Pool(4) p = range(0, 1000) results = [] for i in range(4): result = printsum(i, sample(p, 100)) results.append(result) for result in results: print("Worker %i: sum value is %i" % result.get()) </code></pre> <p>In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.</p>
16
2011-03-30T11:16:36Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
12,780,318
<p>Just</p> <pre><code>import threading, time def f(): print "f started" time.sleep(3) print "f finished" threading.Thread(target=f).start() </code></pre>
7
2012-10-08T10:57:53Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
21,007,695
<p>You could use eventlet. It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.</p> <p>Here's an example of a super minimal crawler:</p> <pre><code>urls = ["http://www.google.com/intl/en_ALL/images/logo.gif", "https://wiki.secondlife.com/w/images/secondlife.jpg", "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"] import eventlet from eventlet.green import urllib2 def fetch(url): return urllib2.urlopen(url).read() pool = eventlet.GreenPool() for body in pool.imap(fetch, urls): print "got body", len(body) </code></pre>
6
2014-01-08T22:12:46Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
22,138,142
<p>Something like this works for me, you can then call the function, and it will dispatch itself onto a new thread.</p> <pre><code>from thread import start_new_thread def dowork(asynchronous=True): if asynchronous: args = (False) start_new_thread(dowork,args) #Call itself on a new thread. else: while True: #do something... time.sleep(60) #sleep for a minute return </code></pre>
2
2014-03-03T03:26:23Z
[ "python", "asynchronous" ]
Asynchronous method call in Python?
1,239,035
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29">Python</a>. It would be great if you could do something like</p> <pre><code>@async def longComputation(): &lt;code&gt; token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() </code></pre> <p>Or to call a non-async routine asynchronously</p> <pre><code>def longComputation() &lt;code&gt; token = asynccall(longComputation()) </code></pre> <p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p>
92
2009-08-06T13:55:35Z
36,272,211
<p>As of Python 3.5, you can use enhanced generators for async functions.</p> <pre><code>import asyncio import datetime </code></pre> <p><strong>Enhanced generator syntax:</strong></p> <pre><code>@asyncio.coroutine def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) &gt;= end_time: break yield from asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close() </code></pre> <p><strong>New <code>async/await</code> syntax:</strong></p> <pre><code>async def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) &gt;= end_time: break await asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close() </code></pre>
12
2016-03-28T22:21:40Z
[ "python", "asynchronous" ]
How to co host django app with php5 on apache2 with mod_python?
1,239,246
<p>I have django+python+apache2+mod_python installed hosted and working on ubuntu server/ linode VPS. php5 is installed and configured. We don't have a domain name as in example.com. Just IP address. So my apache .conf file looks like this</p> <p> ServerAdmin webmaster@localhost DocumentRoot /var/www</p> <pre><code> &lt;Location "/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonPath "['/var/www/djangoprojects',] + sys.path" PythonDebug On &lt;/Location&gt; </code></pre> <p></p> <p>I want to install vtiger so if I change my .conf file like say this </p> <pre><code>&lt;VirtualHost *:80&gt; DocumentRoot /var/www/vtigercrm/ ErrorLog /var/log/apache2/vtiger.error_log CustomLog /var/log/apache2/vtiger.access_log combined &lt;Directory /var/www/vtigercrm&gt; Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all &lt;/Directory&gt; </code></pre> <p></p> <p>This way vtiger the php based app works fine and ofcourse django app is not accessible. How do I make both co-exist in one file. i cannot use virtual host/subdomains. I can do with a diff port no thou.</p> <p>Any clue guys ?</p> <p>Regards Ankur Gupta </p>
0
2009-08-06T14:27:04Z
1,242,332
<p>I need to test it, but this should get your Django project running at /mysite/:</p> <pre><code>&lt;VirtualHost *:80&gt; DocumentRoot /var/www/vtigercrm/ ErrorLog /var/log/apache2/vtiger.error_log CustomLog /var/log/apache2/vtiger.access_log combined &lt;Directory /var/www/vtigercrm&gt; Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all &lt;/Directory&gt; &lt;Location "/mysite/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonPath "['/var/www/djangoprojects',] + sys.path" PythonDebug On &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre> <p>Also, the <a href="http://docs.djangoproject.com/en/dev/topics/install/#install-apache-and-mod-wsgi" rel="nofollow">preferred way to host Django apps is with mod_wsgi</a>.</p>
1
2009-08-07T00:51:06Z
[ "php", "python", "django", "apache", "mod-python" ]
Limit choices to
1,239,433
<p>I have a model named Project which has a m2m field users. I have a task model with a FK project. And it has a field assigned_to. How can i limit the choices of assigned_to to only the users of the current project?</p>
3
2009-08-06T14:53:42Z
1,239,568
<p>You need to create a <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">custom form for the admin</a>.</p> <p>Your form should contain a <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField" rel="nofollow">ModelChoiceField</a> in which you can specify a queryset parameter that defines what the available choices are. This form <em>can</em> be a ModelForm.</p> <p><em>(the following example assumes users have an FK to your Project model)</em></p> <p><strong>forms.py</strong></p> <pre><code>from django import forms class TaskForm(forms.ModelForm): assigned_to = forms.ModelChoiceField(queryset=Users.objects.filter(user__project=project)) class Meta: model = Task </code></pre> <p>Then assign the form to the ModelAdmin.</p> <p><strong>admin.py</strong></p> <pre><code>from django.contrib import admin from models import Task from forms import TaskForm class TaskAdmin(admin.ModelAdmin): form = TaskForm admin.site.register(Task, TaskAdmin) </code></pre>
0
2009-08-06T15:12:04Z
[ "python", "django-models" ]
Limit choices to
1,239,433
<p>I have a model named Project which has a m2m field users. I have a task model with a FK project. And it has a field assigned_to. How can i limit the choices of assigned_to to only the users of the current project?</p>
3
2009-08-06T14:53:42Z
1,371,169
<p>You could do this another way, using this nifty form factory trick.</p> <pre><code>def make_task_form(project): class _TaskForm(forms.Form): assigned_to = forms.ModelChoiceField( queryset=User.objects.filter(user__project=project)) class Meta: model = Task return _TaskForm </code></pre> <p>Then from your view code you can do something like this:</p> <pre><code>project = Project.objects.get(id=234) form_class = make_task_form(project) ... form = form_class(request.POST) </code></pre>
1
2009-09-03T02:37:19Z
[ "python", "django-models" ]
comparing and sorting array
1,239,509
<p>From two unequal arrays, i need to compare &amp; delete based on the last value of an array.</p> <p>Example:</p> <p><code>m[0]</code> and <code>n[0]</code> are read form a text file &amp; saved as a array, <code>[0]</code> - their column number in text file.</p> <pre><code>m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44] n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57] </code></pre> <p><code>n[0]</code> last value is <code>3.57</code>, it lies between <code>3.40</code> and <code>3.80 of m[0] so I need to print till 3.40 in </code>m[0]`</p> <p><strong>Required output:</strong></p> <pre><code>p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40] </code></pre>
1
2009-08-06T15:04:54Z
1,239,574
<p>I haven't been able to test this but here you go...</p> <pre><code>p = [] for item in m[0]: if (item &lt; n[0][-1]): p.append(item) else: break </code></pre>
0
2009-08-06T15:12:48Z
[ "python", "list" ]
comparing and sorting array
1,239,509
<p>From two unequal arrays, i need to compare &amp; delete based on the last value of an array.</p> <p>Example:</p> <p><code>m[0]</code> and <code>n[0]</code> are read form a text file &amp; saved as a array, <code>[0]</code> - their column number in text file.</p> <pre><code>m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44] n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57] </code></pre> <p><code>n[0]</code> last value is <code>3.57</code>, it lies between <code>3.40</code> and <code>3.80 of m[0] so I need to print till 3.40 in </code>m[0]`</p> <p><strong>Required output:</strong></p> <pre><code>p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40] </code></pre>
1
2009-08-06T15:04:54Z
1,239,590
<p>Some details are a little unclear, but this should do what you want:</p> <pre><code>p[0] = [x for x in m[0] if x &lt; n[0][-1]] </code></pre>
6
2009-08-06T15:14:10Z
[ "python", "list" ]
comparing and sorting array
1,239,509
<p>From two unequal arrays, i need to compare &amp; delete based on the last value of an array.</p> <p>Example:</p> <p><code>m[0]</code> and <code>n[0]</code> are read form a text file &amp; saved as a array, <code>[0]</code> - their column number in text file.</p> <pre><code>m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44] n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57] </code></pre> <p><code>n[0]</code> last value is <code>3.57</code>, it lies between <code>3.40</code> and <code>3.80 of m[0] so I need to print till 3.40 in </code>m[0]`</p> <p><strong>Required output:</strong></p> <pre><code>p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40] </code></pre>
1
2009-08-06T15:04:54Z
1,239,697
<p>if both lists are ordered, you can do:</p> <pre><code>import bisect m[0][:bisect.bisect(m[0],n[0][-1])] </code></pre>
1
2009-08-06T15:30:34Z
[ "python", "list" ]
Python SOAP document handling
1,239,538
<p>I've been trying to use <a href="https://fedorahosted.org/suds/wiki" rel="nofollow">suds</a> for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through <a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">the examples</a> and <a href="http://jortel.fedorapeople.org/suds/doc/" rel="nofollow">the documentation</a>, but I can't seem to find a way to return the XML document that the SOAP service gives me. </p> <p>Is there an easy way to do this I'm overlooking? Is there an easier way to do this in Python than suds? </p>
1
2009-08-06T15:08:22Z
1,239,558
<p>You could take a look at a library such as <a href="http://wiki.github.com/jkp/soaplib" rel="nofollow">soaplib</a>: its a really nice way to consume (and serve) SOAP webservices in Python. The latest version has some code to dynamically generate Python bindings either dynamically (at runtime) or statically (run a script against some WSDL). </p> <p>[disclaimer: I'm the maintainer of the project! - I didn't write the bulk of it though]</p>
0
2009-08-06T15:10:48Z
[ "python", "xml", "soap", "wsdl", "suds" ]
Python SOAP document handling
1,239,538
<p>I've been trying to use <a href="https://fedorahosted.org/suds/wiki" rel="nofollow">suds</a> for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through <a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">the examples</a> and <a href="http://jortel.fedorapeople.org/suds/doc/" rel="nofollow">the documentation</a>, but I can't seem to find a way to return the XML document that the SOAP service gives me. </p> <p>Is there an easy way to do this I'm overlooking? Is there an easier way to do this in Python than suds? </p>
1
2009-08-06T15:08:22Z
1,240,791
<p>At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.</p> <p>The examples on the site show us with something like this:</p> <pre><code>client = Client(url) result = client.service.Invoke(subm) </code></pre> <p>however, the result is a pre-parsed object that is great for access by Python, but not for XML document access. Fortunately the Client object still has the original SOAP message received stored.</p> <pre><code>result = client.last_received() print result </code></pre> <p>Will give you the actual SOAP message received back.</p>
3
2009-08-06T19:13:57Z
[ "python", "xml", "soap", "wsdl", "suds" ]
Qt HTTP authentication with QNetworkAccessManager
1,239,669
<p>I'm working with a webservice which requires a valid username/password. From PyQt, I'm accessing the webservice using QNetworkAccessManager which emits the </p> <pre><code>authenticationRequired (QNetworkReply*, QAuthenticator*) </code></pre> <p>signal when (obviously),authentication is required. When I fill in the user and psswd for QAuthenticator, everything works fine. However, I can't see how to break the look when the user is <em>not</em> valid.</p> <p>From the docs for authenticationRequired:</p> <p>"If it rejects the credentials, this signal will be emitted again."</p> <p>For invalid credentials this signal is emitted again, and again, and again....looking at the error code in the reply showed 0. How is this loop supposed to be broken or handled so that it terminates with an error?</p>
2
2009-08-06T15:26:22Z
1,239,722
<p>Yeh, it's odd. What I've done previously is check if I've already authenticated with those details and if I have then call <code>QNetworkReply.abort()</code></p>
2
2009-08-06T15:33:17Z
[ "python", "qt", "networking", "qt4", "pyqt" ]
Qt HTTP authentication with QNetworkAccessManager
1,239,669
<p>I'm working with a webservice which requires a valid username/password. From PyQt, I'm accessing the webservice using QNetworkAccessManager which emits the </p> <pre><code>authenticationRequired (QNetworkReply*, QAuthenticator*) </code></pre> <p>signal when (obviously),authentication is required. When I fill in the user and psswd for QAuthenticator, everything works fine. However, I can't see how to break the look when the user is <em>not</em> valid.</p> <p>From the docs for authenticationRequired:</p> <p>"If it rejects the credentials, this signal will be emitted again."</p> <p>For invalid credentials this signal is emitted again, and again, and again....looking at the error code in the reply showed 0. How is this loop supposed to be broken or handled so that it terminates with an error?</p>
2
2009-08-06T15:26:22Z
1,239,750
<p>What about trying:</p> <pre><code>QNetworkReply::abort() </code></pre> <p>or</p> <pre><code>QNetworkReply::close() </code></pre> <p>?</p>
1
2009-08-06T15:38:27Z
[ "python", "qt", "networking", "qt4", "pyqt" ]
Qt HTTP authentication with QNetworkAccessManager
1,239,669
<p>I'm working with a webservice which requires a valid username/password. From PyQt, I'm accessing the webservice using QNetworkAccessManager which emits the </p> <pre><code>authenticationRequired (QNetworkReply*, QAuthenticator*) </code></pre> <p>signal when (obviously),authentication is required. When I fill in the user and psswd for QAuthenticator, everything works fine. However, I can't see how to break the look when the user is <em>not</em> valid.</p> <p>From the docs for authenticationRequired:</p> <p>"If it rejects the credentials, this signal will be emitted again."</p> <p>For invalid credentials this signal is emitted again, and again, and again....looking at the error code in the reply showed 0. How is this loop supposed to be broken or handled so that it terminates with an error?</p>
2
2009-08-06T15:26:22Z
27,430,047
<p>Calling <code>QNetworkReply::abort()</code> will cause the request to fail with the error 'Operation Aborted' instead of the original 401 error. The correct thing to do now seems to be not to call <code>QAuthenticator::setUser()</code> or <code>QAuthenticator::setPassword()</code> inside your <code>authenticationRequired()</code> slot. This will leave the <code>QAuthenticatorPrivate::phase</code> as <code>Done</code> which will cause the request to terminate cleanly with the correct error code.</p> <p>The Qt documentation is rather unclear on this point.</p> <p>This did not seem to be the behaviour in Qt 4.7, and was introduced at some point in Qt 4.8.</p>
0
2014-12-11T18:37:01Z
[ "python", "qt", "networking", "qt4", "pyqt" ]
Qt HTTP authentication with QNetworkAccessManager
1,239,669
<p>I'm working with a webservice which requires a valid username/password. From PyQt, I'm accessing the webservice using QNetworkAccessManager which emits the </p> <pre><code>authenticationRequired (QNetworkReply*, QAuthenticator*) </code></pre> <p>signal when (obviously),authentication is required. When I fill in the user and psswd for QAuthenticator, everything works fine. However, I can't see how to break the look when the user is <em>not</em> valid.</p> <p>From the docs for authenticationRequired:</p> <p>"If it rejects the credentials, this signal will be emitted again."</p> <p>For invalid credentials this signal is emitted again, and again, and again....looking at the error code in the reply showed 0. How is this loop supposed to be broken or handled so that it terminates with an error?</p>
2
2009-08-06T15:26:22Z
32,416,102
<p>If you return from a slot connected to &amp;QNetworkAccessManager::proxyAuthenticationRequired without calling any QAuthenticator method, the request will be aborted with real HTTP code (e.g. 401 or 407).</p> <p>For instance you can call QAuthenticator::setUser and setPassword when the user clics OK and call nothing when he clics Cancel. That's all :-)</p> <p>This is also true for slots connected to &amp;QNetworkAccessManager::authenticationRequired (where you do not have to call QNetworkReply::abort(), you can simply call no QAuthenticator method at all, which preserve HTTP code too, whereas calling abort() alter it).</p>
0
2015-09-05T17:57:41Z
[ "python", "qt", "networking", "qt4", "pyqt" ]
Pythonic Comparison Functions
1,239,751
<p>For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.</p> <pre><code>class Person: def __init__(self, firstname, lastname, dob): self.firstname = firstname; self.lastname = lastname; self.dob = dob; </code></pre> <p>In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.</p> <p>The naive solution for creating the first comparison function would be something like this:</p> <pre><code>def comparepeople(person1, person2): if cmp(person1.lastname, person2.lastname) == 0: if cmp(person1.firstname, person2.firstname) == 0: return cmp(person1.dob, person2.dob); return cmp(person1.firstname, person2.firstname); return cmp(person1.lastname, person2.lastname); </code></pre> <p>It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.</p> <p>So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?</p>
1
2009-08-06T15:39:06Z
1,239,780
<p>Here's one way (maybe not the fastest):</p> <pre><code>def compare_people_flexibly(p1, p2, attrs): """Compare `p1` and `p2` based on the attributes in `attrs`.""" v1 = [getattr(p1, a) for a in attrs] v2 = [getattr(p2, a) for a in attrs] return cmp(v1, v2) def compare_people_firstname(p1, p2): return compare_people_flexibly(p1, p2, ['firstname', 'lastname', 'dob']) def compare_people_lastname(p1, p2): return compare_people_flexibly(p1, p2, ['lastname', 'firstname', 'dob']) </code></pre> <p>This works because getattr can be used to get attributes named by a string, and because Python compares lists as you'd expect, based on the comparison of the first non-equal items.</p> <p>Another way:</p> <pre><code>def compare_people_flexibly(p1, p2, attrs): """Compare `p1` and `p2` based on the attributes in `attrs`.""" for a in attrs: c = cmp(getattr(p1, a), getattr(p2, a)) if c: return c return 0 </code></pre> <p>This has the advantage that it doesn't build two complete lists of attributes, so may be faster if the attribute lists are long, or if many comparisons complete on the first attribute.</p> <p>Lastly, as Martin mentions, you may need a key function rather than a comparison function:</p> <pre><code>def flexible_person_key(attrs): def key(p): return [getattr(p, a) for a in attrs] return key l.sort(key=flexible_person_key('firstname', 'lastname', 'dob')) </code></pre>
4
2009-08-06T15:45:13Z
[ "comparison", "metaprogramming", "python" ]
Pythonic Comparison Functions
1,239,751
<p>For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.</p> <pre><code>class Person: def __init__(self, firstname, lastname, dob): self.firstname = firstname; self.lastname = lastname; self.dob = dob; </code></pre> <p>In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.</p> <p>The naive solution for creating the first comparison function would be something like this:</p> <pre><code>def comparepeople(person1, person2): if cmp(person1.lastname, person2.lastname) == 0: if cmp(person1.firstname, person2.firstname) == 0: return cmp(person1.dob, person2.dob); return cmp(person1.firstname, person2.firstname); return cmp(person1.lastname, person2.lastname); </code></pre> <p>It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.</p> <p>So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?</p>
1
2009-08-06T15:39:06Z
1,239,782
<p>If you really want a comparison function, you can use</p> <pre><code>def comparepeople(p1, p2): o1 = p1.lastname, p1.firstname, p1.dob o2 = p2.lastname, p2.firstname, p2.dob return cmp(o1,o2) </code></pre> <p>This relies on tuple comparison. If you want to sort a list, you shouldn't write a comparison function, though, but a key function:</p> <pre><code>l.sort(key=lambda p:(p.lastname, p.firstname, p.dob)) </code></pre> <p>This has the advantage that it is a) shorter and b) faster, because each key gets computed only once (rather than tons of tuples being created in the comparison function during sorting).</p>
10
2009-08-06T15:45:27Z
[ "comparison", "metaprogramming", "python" ]
Pythonic Comparison Functions
1,239,751
<p>For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.</p> <pre><code>class Person: def __init__(self, firstname, lastname, dob): self.firstname = firstname; self.lastname = lastname; self.dob = dob; </code></pre> <p>In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.</p> <p>The naive solution for creating the first comparison function would be something like this:</p> <pre><code>def comparepeople(person1, person2): if cmp(person1.lastname, person2.lastname) == 0: if cmp(person1.firstname, person2.firstname) == 0: return cmp(person1.dob, person2.dob); return cmp(person1.firstname, person2.firstname); return cmp(person1.lastname, person2.lastname); </code></pre> <p>It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.</p> <p>So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?</p>
1
2009-08-06T15:39:06Z
1,239,861
<p>Can you not use the comparison methods on the class, see <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">__cmp__</a> and the other rich comparison methods...</p>
0
2009-08-06T15:55:57Z
[ "comparison", "metaprogramming", "python" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,236
<p>No, unless you want to confuse every other programmer that looks at your code after you write it. <code>self</code> is not a keyword because it is an identifier. It <em>could</em> have been a keyword and the fact that it isn't one was a design decision.</p>
9
2009-08-06T17:12:11Z
[ "python", "naming-conventions" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,239
<p>I think that the main reason <code>self</code> is used by convention rather than being a Python keyword is because it's simpler to have all methods/functions take arguments the same way rather than having to put together different argument forms for functions, class methods, instance methods, etc.</p> <p>Note that if you have an <em>actual</em> class method (i.e. one defined using the <code>classmethod</code> decorator), the convention is to use "cls" instead of "self".</p>
1
2009-08-06T17:13:02Z
[ "python", "naming-conventions" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,265
<p>Because it is a convention, not language syntax. There is a <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Python style guide</a> that people who program in Python follow. This way libraries have a familiar look and feel. Python places a lot of emphasis on readability, and consistency is an important part of this.</p>
1
2009-08-06T17:18:35Z
[ "python", "naming-conventions" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,277
<p>The only case of this I've seen is when you define a function outside of a class definition, and then assign it to the class, e.g.:</p> <pre><code>class Foo(object): def bar(self): # Do something with 'self' def baz(inst): return inst.bar() Foo.baz = baz </code></pre> <p>In this case, <code>self</code> is a little strange to use, because the function could be applied to many classes. Most often I've seen <code>inst</code> or <code>cls</code> used instead.</p>
4
2009-08-06T17:20:54Z
[ "python", "naming-conventions" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,307
<p>As a side observation, note that Pilgrim is committing a common misuse of terms here: a <em>class method</em> is quite a different thing from an <em>instance method</em>, which is what he's talking about here. As <a href="http://en.wikipedia.org/wiki/Method%5F%28computer%5Fscience%29" rel="nofollow">wikipedia</a> puts it, "a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method).". Python's built-ins include a <code>staticmethod</code> type, to make static methods, and a <code>classmethod</code> type, to make class methods, each generally used as a decorator; if you don't use either, a <code>def</code> in a class body makes an instance method. E.g.:</p> <pre><code>&gt;&gt;&gt; class X(object): ... def noclass(self): print self ... @classmethod ... def withclass(cls): print cls ... &gt;&gt;&gt; x = X() &gt;&gt;&gt; x.noclass() &lt;__main__.X object at 0x698d0&gt; &gt;&gt;&gt; x.withclass() &lt;class '__main__.X'&gt; &gt;&gt;&gt; </code></pre> <p>As you see, the instance method <code>noclass</code> gets the instance as its argument, but the class method <code>withclass</code> gets the class instead.</p> <p>So it would be <strong>extremely</strong> confusing and misleading to use <code>self</code> as the name of the first parameter of a class method: the convention in this case is instead to use <code>cls</code>, as in my example above. While this IS just a convention, there is no real good reason for violating it -- any more than there would be, say, for naming a variable <code>number_of_cats</code> if the purpose of the variable is counting dogs!-)</p>
5
2009-08-06T17:27:06Z
[ "python", "naming-conventions" ]
is it ever useful to define a class method with a reference to self not called 'self' in Python?
1,240,229
<p>I'm teaching myself Python and I see the following in <a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> <a href="http://www.diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">section 5.3</a>:</p> <blockquote> <p>By convention, the first argument of any Python class method (the reference to the current instance) is called <code>self</code>. This argument fills the role of the reserved word <code>this</code> in C++ or Java, but <code>self</code> is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but <code>self</code>; this is a very strong convention.</p> </blockquote> <p>Considering that <code>self</code> is <em>not</em> a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it <em>not</em> a keyword?</p>
3
2009-08-06T17:10:36Z
1,240,371
<p>I once had some code like (and I apologize for lack of creativity in the example):</p> <pre><code>class Animal: def __init__(self, volume=1): self.volume = volume self.description = "Animal" def Sound(self): pass def GetADog(self, newvolume): class Dog(Animal): def Sound(this): return self.description + ": " + ("woof" * this.volume) return Dog(newvolume) </code></pre> <p>Then we have output like:</p> <pre><code>&gt;&gt;&gt; a = Animal(3) &gt;&gt;&gt; d = a.GetADog(2) &gt;&gt;&gt; d.Sound() 'Animal: woofwoof' </code></pre> <p>I wasn't sure if <code>self</code> within the <code>Dog</code> class would shadow <code>self</code> within the <code>Animal</code> class, so I opted to make <code>Dog</code>'s reference the word "this" instead. In my opinion and for that particular application, that was more clear to me.</p>
2
2009-08-06T17:40:03Z
[ "python", "naming-conventions" ]
GTK: Modify bg color of a CheckButton
1,240,764
<p>I tried the following, yet the button still has a white background:</p> <pre><code> self.button = gtk.CheckButton() self.button.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STATE_ACTIVE, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STATE_PRELIGHT, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_PRELIGHT, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STATE_SELECTED, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_SELECTED, gtk.gdk.Color(65535,0,0)) self.button.modify_fg(gtk.STATE_INSENSITIVE, gtk.gdk.Color(65535,0,0)) self.button.modify_bg(gtk.STATE_INSENSITIVE, gtk.gdk.Color(65535,0,0)) </code></pre> <p>I also added the CheckButton to an EventBox, and changed the color of that, but all it did is set the background of the space around the button - the button itself was still w/ a white background.</p>
1
2009-08-06T19:07:19Z
1,320,563
<p>So you want the part with the check mark on it to be a different color? Then use this <code>button.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("red"))</code>.</p> <p><img src="http://www.ubuntu-pics.de/bild/22793/screenshot%5F009%5FMCxjbu.png" alt="alt text" /></p>
3
2009-08-24T05:04:35Z
[ "python", "events", "gtk", "colors", "pygtk" ]
GTK: create a colored regular button
1,241,020
<p>How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge of the button that doesn't change. I just want something that looks like this:</p> <p><img src="http://www.kksou.com/php-gtk2/gif/0023.gif" alt="img" title="" /></p> <p>The site claims to have just done modify_bg() on the button. But that doesn't work for me. =(.</p> <p>The right answer probably involves creating a style, or something with a gtkrc file, etc. Can someone point me in that direction?</p>
5
2009-08-06T19:55:17Z
1,241,609
<p>Here's a little example:</p> <pre><code>import gtk win = gtk.Window() win.connect("destroy", gtk.main_quit) btn = gtk.Button("test") #make a gdk.color for red map = btn.get_colormap() color = map.alloc_color("red") #copy the current style and replace the background style = btn.get_style().copy() style.bg[gtk.STATE_NORMAL] = color #set the button's style to the one you created btn.set_style(style) win.add(btn) win.show_all() gtk.main() </code></pre>
14
2009-08-06T21:30:14Z
[ "python", "button", "gtk", "colors", "pygtk" ]
How to filter a dictionary by value?
1,241,029
<p>Newbie question here, so please bear with me.</p> <p>Let's say I have a dictionary looking like this:</p> <pre><code>a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>I want all values that are equal to each other to be moved into another dictionary. </p> <pre><code>matched = {"2323232838": ("first/dir", "hello.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt")} </code></pre> <p>And the remaining unmatched items should be looking like this:</p> <pre><code>remainder = {"2323221383": ("second/dir", "foo.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>Thanks in advance, and if you provide an example, please comment it as much as possible.</p>
4
2009-08-06T19:56:16Z
1,241,064
<p>Iterating over a dictionary is no different from iterating over a list in python:</p> <pre><code>for key in dic: print("dic[%s] = %s" % (key, dic[key])) </code></pre> <p>This will print all of the keys and values of your dictionary.</p>
1
2009-08-06T20:01:37Z
[ "python", "dictionary" ]
How to filter a dictionary by value?
1,241,029
<p>Newbie question here, so please bear with me.</p> <p>Let's say I have a dictionary looking like this:</p> <pre><code>a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>I want all values that are equal to each other to be moved into another dictionary. </p> <pre><code>matched = {"2323232838": ("first/dir", "hello.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt")} </code></pre> <p>And the remaining unmatched items should be looking like this:</p> <pre><code>remainder = {"2323221383": ("second/dir", "foo.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>Thanks in advance, and if you provide an example, please comment it as much as possible.</p>
4
2009-08-06T19:56:16Z
1,241,307
<p>I assume that your unique id will be the key.<br /> Probably not very beautiful, but returns a dict with your unique values: </p> <pre><code>&gt;&gt;&gt; dict_ = {'1': ['first/dir', 'hello.txt'], '3': ['first/dir', 'foo.txt'], '2': ['second/dir', 'foo.txt'], '4': ['second/dir', 'foo.txt']} &gt;&gt;&gt; dict((v[0]+v[1],k) for k,v in dict_.iteritems()) {'second/dir/foo.txt': '4', 'first/dir/hello.txt': '1', 'first/dir/foo.txt': '3'} </code></pre> <p>I've seen you updated your post: </p> <pre><code>&gt;&gt;&gt; a {'324234324': ('third/dir', 'dog.txt'), '2323221383': ('second/dir', 'foo.txt'), '3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt')} &gt;&gt;&gt; dict((v[0]+"/"+v[1],k) for k,v in a.iteritems()) {'second/dir/foo.txt': '2323221383', 'first/dir/hello.txt': '32232334', 'third/dir/dog.txt': '324234324'} </code></pre>
1
2009-08-06T20:39:14Z
[ "python", "dictionary" ]
How to filter a dictionary by value?
1,241,029
<p>Newbie question here, so please bear with me.</p> <p>Let's say I have a dictionary looking like this:</p> <pre><code>a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>I want all values that are equal to each other to be moved into another dictionary. </p> <pre><code>matched = {"2323232838": ("first/dir", "hello.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt")} </code></pre> <p>And the remaining unmatched items should be looking like this:</p> <pre><code>remainder = {"2323221383": ("second/dir", "foo.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>Thanks in advance, and if you provide an example, please comment it as much as possible.</p>
4
2009-08-06T19:56:16Z
1,241,354
<p>The code below will result in two variables, <code>matches</code> and <code>remainders</code>. <code>matches</code> is an array of dictionaries, in which matching items from the original dictionary will have a corresponding element. <code>remainder</code> will contain, as in your example, a dictionary containing all the unmatched items.</p> <p>Note that in your example, there is only one set of matching values: <code>('first/dir', 'hello.txt')</code>. If there were more than one set, each would have a corresponding entry in <code>matches</code>.</p> <pre><code>import itertools # Original dict a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} # Convert dict to sorted list of items a = sorted(a.items(), key=lambda x:x[1]) # Group by value of tuple groups = itertools.groupby(a, key=lambda x:x[1]) # Pull out matching groups of items, and combine items # with no matches back into a single dictionary remainder = [] matched = [] for key, group in groups: group = list(group) if len(group) == 1: remainder.append( group[0] ) else: matched.append( dict(group) ) else: remainder = dict(remainder) </code></pre> <p>Output: </p> <pre><code>&gt;&gt;&gt; matched [ { '3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt') } ] &gt;&gt;&gt; remainder { '2323221383': ('second/dir', 'foo.txt'), '324234324': ('third/dir', 'dog.txt') } </code></pre> <p>As a newbie, you're probably being introduced to a few unfamiliar concepts in the code above. Here are some links:</p>
9
2009-08-06T20:49:46Z
[ "python", "dictionary" ]
How to filter a dictionary by value?
1,241,029
<p>Newbie question here, so please bear with me.</p> <p>Let's say I have a dictionary looking like this:</p> <pre><code>a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>I want all values that are equal to each other to be moved into another dictionary. </p> <pre><code>matched = {"2323232838": ("first/dir", "hello.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt")} </code></pre> <p>And the remaining unmatched items should be looking like this:</p> <pre><code>remainder = {"2323221383": ("second/dir", "foo.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>Thanks in advance, and if you provide an example, please comment it as much as possible.</p>
4
2009-08-06T19:56:16Z
1,241,369
<p>if you know what value you want to filter out:</p> <pre><code>known_tuple = 'first/dir','hello.txt' b = {k:v for k, v in a.items() if v == known_tuple} </code></pre> <p>then <code>a</code> would become:</p> <pre><code>a = dict(a.items() - b.items()) </code></pre> <p>this is py3k notation, but I'm sure something similar can be implemented in legacy versions. If you don't know what the <code>known_tuple</code> is, then you'd need to first find it out. for example like this:</p> <pre><code>c = list(a.values()) for i in set(c): c.remove(i) known_tuple = c[0] </code></pre>
0
2009-08-06T20:52:47Z
[ "python", "dictionary" ]
How to filter a dictionary by value?
1,241,029
<p>Newbie question here, so please bear with me.</p> <p>Let's say I have a dictionary looking like this:</p> <pre><code>a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>I want all values that are equal to each other to be moved into another dictionary. </p> <pre><code>matched = {"2323232838": ("first/dir", "hello.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt")} </code></pre> <p>And the remaining unmatched items should be looking like this:</p> <pre><code>remainder = {"2323221383": ("second/dir", "foo.txt"), "324234324": ("third/dir", "dog.txt")} </code></pre> <p>Thanks in advance, and if you provide an example, please comment it as much as possible.</p>
4
2009-08-06T19:56:16Z
1,241,803
<p>What you're asking for is called an "Inverted Index" -- the distinct items are recorded just once with a list of keys.</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; a = {"2323232838": ("first/dir", "hello.txt"), ... "2323221383": ("second/dir", "foo.txt"), ... "3434221": ("first/dir", "hello.txt"), ... "32232334": ("first/dir", "hello.txt"), ... "324234324": ("third/dir", "dog.txt")} &gt;&gt;&gt; invert = defaultdict( list ) &gt;&gt;&gt; for key, value in a.items(): ... invert[value].append( key ) ... &gt;&gt;&gt; invert defaultdict(&lt;type 'list'&gt;, {('first/dir', 'hello.txt'): ['3434221', '2323232838', '32232334'], ('second/dir', 'foo.txt'): ['2323221383'], ('third/dir', 'dog.txt'): ['324234324']}) </code></pre> <p>The inverted dictionary has the original values associated with a list of 1 or more keys.</p> <p>Now, to get your revised dictionaries from this. </p> <p>Filtering:</p> <pre><code>&gt;&gt;&gt; [ invert[multi] for multi in invert if len(invert[multi]) &gt; 1 ] [['3434221', '2323232838', '32232334']] &gt;&gt;&gt; [ invert[uni] for uni in invert if len(invert[uni]) == 1 ] [['2323221383'], ['324234324']] </code></pre> <p>Expanding</p> <pre><code>&gt;&gt;&gt; [ (i,multi) for multi in invert if len(invert[multi]) &gt; 1 for i in invert[multi] ] [('3434221', ('first/dir', 'hello.txt')), ('2323232838', ('first/dir', 'hello.txt')), ('32232334', ('first/dir', 'hello.txt'))] &gt;&gt;&gt; dict( (i,multi) for multi in invert if len(invert[multi]) &gt; 1 for i in invert[multi] ) {'3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt')} </code></pre> <p>A similar (but simpler) treatment works for the items which occur once.</p>
4
2009-08-06T22:08:42Z
[ "python", "dictionary" ]
Copy constructor in python
1,241,148
<p>Is there a copy constructor in python ? If not what would I do to achieve something similar ?</p> <p>The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.</p>
50
2009-08-06T20:16:48Z
1,241,170
<p>I think you want the <a href="http://docs.python.org/library/copy.html">copy module</a></p> <pre><code>import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y </code></pre> <p>you can control copying in much the same way as you control <a href="http://docs.python.org/library/pickle.html#module-pickle">pickle</a>.</p>
40
2009-08-06T20:21:34Z
[ "python", "constructor", "copy" ]
Copy constructor in python
1,241,148
<p>Is there a copy constructor in python ? If not what would I do to achieve something similar ?</p> <p>The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.</p>
50
2009-08-06T20:16:48Z
1,241,241
<p>For your situation, I would suggest writing a class method (or it could be a static method or a separate function) that takes as an argument an instance of the library's class and returns an instance of your class with all applicable attributes copied over.</p>
10
2009-08-06T20:31:14Z
[ "python", "constructor", "copy" ]
Copy constructor in python
1,241,148
<p>Is there a copy constructor in python ? If not what would I do to achieve something similar ?</p> <p>The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.</p>
50
2009-08-06T20:16:48Z
16,046,733
<p>In python the copy constructor can be defined using default arguments. Lets say you want the normal constructor to run the function non_copy_constructor(self) and the copy constructor should run copy_constructor(self,orig). Then you can do the following:</p> <pre><code>class Foo: def __init__(self,orig=None): if (orig==None): self.non_copy_constructor() else: self.copy_constructor(orig) def non_copy_constructor(self): # do the non-copy constructor stuff def copy_constructor(self,orig): # do the copy constructor a=Foo() # this will call the non-copy constructor b=Foo(a) # this will call the copy constructor </code></pre>
11
2013-04-16T20:43:33Z
[ "python", "constructor", "copy" ]
Copy constructor in python
1,241,148
<p>Is there a copy constructor in python ? If not what would I do to achieve something similar ?</p> <p>The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.</p>
50
2009-08-06T20:16:48Z
27,441,776
<p>A simple example of my usual implementation of a copy constructor:</p> <pre><code>import copy class Foo: def __init__(self, data): self._data = data @classmethod def from_foo(cls, class_instance): data = copy.deepcopy(class_instance._data) # if deepcopy is necessary return cls(data) </code></pre>
4
2014-12-12T10:37:17Z
[ "python", "constructor", "copy" ]
Copy constructor in python
1,241,148
<p>Is there a copy constructor in python ? If not what would I do to achieve something similar ?</p> <p>The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.</p>
50
2009-08-06T20:16:48Z
35,440,728
<p>Building on @Godsmith's <a href="http://stackoverflow.com/a/27441776/623735">train of thought</a> and addressing @Zitrax's need (I think) to do the data copy for all attributes within the constructor:</p> <pre><code>class ConfusionMatrix(pd.DataFrame): def __init__(self, df, *args, **kwargs): try: # Check if `df` looks like a `ConfusionMatrix` # Could check `isinstance(df, ConfusionMatrix)` # But might miss some "ConfusionMatrix-elligible" `DataFrame`s assert((df.columns == df.index).all()) assert(df.values.dtype == int) self.construct_copy(df, *args, **kwargs) return except (AssertionError, AttributeError, ValueError): pass # df is just data, so continue with normal constructor here ... def construct_copy(self, other, *args, **kwargs): # construct a parent DataFrame instance parent_type = super(ConfusionMatrix, self) parent_type.__init__(other) for k, v in other.__dict__.iteritems(): if hasattr(parent_type, k) and hasattr(self, k) and getattr(parent_type, k) == getattr(self, k): continue setattr(self, k, deepcopy(v)) </code></pre> <p>This <a href="https://en.wikipedia.org/wiki/Confusion_matrix" rel="nofollow"><code>ConfusionMatrix</code></a> class inherits a <code>pandas.DataFrame</code> and adds a ton of other attributes and methods that need to be recomputed unless the <code>other</code> matrix data can be copied over. Searching for a solution is how I found this question.</p>
1
2016-02-16T18:50:48Z
[ "python", "constructor", "copy" ]
ValueError: invalid literal for int() with base 10
1,241,395
<p>I received the following error when trying to retrieve data using <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> from a single entry to a single page e.g. foobar.com/page/1 would show all the data from id 1:</p> <pre><code>ValueError: invalid literal for int() with base 10 </code></pre> <p>Here are the files:</p> <p><strong>Views.py</strong></p> <pre><code>class One(webapp.RequestHandler): def get(self, id): id = models.Page.get_by_id(int(str(self.request.get("id")))) page_query = models.Page.get(db.Key.from_path('Page', id)) pages = page_query template_values = { 'pages': pages, } path = os.path.join(os.path.dirname(__file__), 'template/list.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p><strong>Urls.py</strong>:</p> <pre><code>(r'/browse/(\d+)/', One), </code></pre> <p><strong>Error:</strong></p> <pre> Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Volumes/foobar/views.py", line 72, in get id = models.Page.get_by_id(int(str(self.request.get("id")))) ValueError: invalid literal for int() with base 10: '' </pre>
3
2009-08-06T20:56:44Z
1,241,471
<p>Change <code>self.request.get("id")</code> to simply <code>id</code>, which is already being passed to your <code>get</code> handler.</p> <p>The code, as you have it, would only work for URLs like <code>/browse/1/?id=1</code></p>
2
2009-08-06T21:08:02Z
[ "python", "google-app-engine" ]