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
Using numpy to build an array of all combinations of two arrays
1,208,118
<p>I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.</p> <p>My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:</p> <p>First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays</p> <pre><code>from numpy import * def comb(a,b): c = [] for i in a: for j in b: c.append(r_[i,j]) return c </code></pre> <p>Then I used <code>reduce()</code> to apply that to m copies of the same array:</p> <pre><code>def combs(a,m): return reduce(comb,[a]*m) </code></pre> <p>And then I evaluate my function like this:</p> <pre><code>values = combs(np.arange(0,1,0.1),6) for val in values: print F(val) </code></pre> <p>This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 10<sup>6</sup> (a million) points in this example and it took more than 15 seconds just to create the array <code>values</code>.</p> <p>Do you know any more efficient way of doing this with numpy? </p> <p>I can modify the way the function <code>F</code> takes it's arguments if it's necessary.</p>
73
2009-07-30T17:32:27Z
35,608,701
<p><strong><em>In newer version of <code>numpy</code> (>1.8.x), <code>np.meshgrid</code> provides a much faster implementation:</em></strong></p> <p>@pv's solution</p> <pre><code>In [113]: %timeit cartesian(([1, 2, 3], [4, 5], [6, 7])) 10000 loops, best of 3: 135 µs per loop In [114]: cartesian(([1, 2, 3], [4, 5], [6, 7])) Out[114]: array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) </code></pre> <p><code>numpy.meshgrid</code> use to be 2D only, now it is capable of ND. In this case, 3D:</p> <pre><code>In [115]: %timeit np.array(np.meshgrid([1, 2, 3], [4, 5], [6, 7])).T.reshape(-1,3) 10000 loops, best of 3: 74.1 µs per loop In [116]: np.array(np.meshgrid([1, 2, 3], [4, 5], [6, 7])).T.reshape(-1,3) Out[116]: array([[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6], [1, 4, 7], [1, 5, 7], [2, 4, 7], [2, 5, 7], [3, 4, 7], [3, 5, 7]]) </code></pre> <p>Note that the order of the final resultant is slightly different.</p>
15
2016-02-24T17:14:46Z
[ "python", "arrays", "multidimensional-array", "numpy" ]
Dictionary with classes?
1,208,322
<p>In Python is it possible to instantiate a class through a dictionary?</p> <pre><code>shapes = {'1':Square(), '2':Circle(), '3':Triangle()} x = shapes[raw_input()] </code></pre> <p>I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?</p>
7
2009-07-30T18:10:06Z
1,208,348
<p>Almost. What you want is</p> <pre><code>shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance. </code></pre>
22
2009-07-30T18:14:57Z
[ "python", "dictionary", "class" ]
Dictionary with classes?
1,208,322
<p>In Python is it possible to instantiate a class through a dictionary?</p> <pre><code>shapes = {'1':Square(), '2':Circle(), '3':Triangle()} x = shapes[raw_input()] </code></pre> <p>I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?</p>
7
2009-07-30T18:10:06Z
1,209,623
<p>I'd recommend a chooser function:</p> <pre><code>def choose(optiondict, prompt='Choose one:'): print prompt while 1: for key, value in sorted(optiondict.items()): print '%s) %s' % (key, value) result = raw_input() # maybe with .lower() if result in optiondict: return optiondict[result] print 'Not an option' result = choose({'1': Square, '2': Circle, '3': Triangle})() </code></pre>
1
2009-07-30T21:54:08Z
[ "python", "dictionary", "class" ]
how do I use CommaSeparatedIntegerField in django?
1,208,698
<p>There is almost no documentation for it here: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield">http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield</a></p> <p>Maybe someone could, by example, show me how to populate a <code>CommaSeparatedIntegerField</code> in Django?</p> <p>-thanks.</p>
31
2009-07-30T19:11:21Z
1,208,832
<p>Looking at the source for django...</p> <pre><code>class CommaSeparatedIntegerField(CharField): def formfield(self, **kwargs): defaults = { 'form_class': forms.RegexField, 'regex': '^[\d,]+$', 'max_length': self.max_length, 'error_messages': { 'invalid': _(u'Enter only digits separated by commas.'), } } defaults.update(kwargs) return super(CommaSeparatedIntegerField, self).formfield(**defaults) </code></pre> <p>Check out that regex validator. Looks like as long as you give it a list of integers and commas, django won't complain.</p> <p>You can define it just like a charfield basically:</p> <pre><code>class Foo(models.Model): int_list = models.CommaSeparatedIntegerField(max_length=200) </code></pre> <p>And populate it like this:</p> <pre><code>f = Foo(int_list="1,2,3,4,5") </code></pre>
22
2009-07-30T19:34:00Z
[ "python", "django", "django-models" ]
how do I use CommaSeparatedIntegerField in django?
1,208,698
<p>There is almost no documentation for it here: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield">http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield</a></p> <p>Maybe someone could, by example, show me how to populate a <code>CommaSeparatedIntegerField</code> in Django?</p> <p>-thanks.</p>
31
2009-07-30T19:11:21Z
1,209,287
<p>I just happened to have dealt with CommaSeparatedIntegerField in my latest project. I was using MySQL and it seemed like supplying a string of comma separated integer values is very DB friendly e.g. '1,2,3,4,5'. If you want to leave it blank, just pass an empty string.</p> <p>It does act like a CharField, and beaved in a weird way for me.. I ended up with values like "[1, 2, 3, 4, 5]" including the brackets in my database! So watch out!</p>
6
2009-07-30T20:47:03Z
[ "python", "django", "django-models" ]
Django and urls.py: How do I HttpResponseRedirect via a named url?
1,208,802
<p>I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') </code></pre> <p>What I want to accomplish is something like:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName </code></pre> <p>I get syntax errors when I execute this, any ideas?</p>
16
2009-07-30T19:29:30Z
1,208,839
<p>You need to use the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse" rel="nofollow"><code>reverse()</code></a> utils function.</p> <pre><code>from django.core.urlresolvers import reverse def myview(request): return HttpResponseRedirect(reverse('arch-summary', args=[1945])) </code></pre> <p>Where <code>args</code> satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.</p>
27
2009-07-30T19:35:34Z
[ "python", "django", "redirect", "django-urls" ]
Django and urls.py: How do I HttpResponseRedirect via a named url?
1,208,802
<p>I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') </code></pre> <p>What I want to accomplish is something like:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName </code></pre> <p>I get syntax errors when I execute this, any ideas?</p>
16
2009-07-30T19:29:30Z
1,211,218
<p>A more concise way to write that if statement would be <code>if request.session.get('user')</code>. has_key is deprecated nowadays, and .get() returns None (by default, changeable by passing a second parameter). So combining this with Soviut's reply:</p> <pre><code>from django.core.urlresolvers import reverse def login(request): if request.session.get('user'): return HttpResponseRedirect(reverse('my-named-url')) </code></pre>
7
2009-07-31T07:56:54Z
[ "python", "django", "redirect", "django-urls" ]
Django and urls.py: How do I HttpResponseRedirect via a named url?
1,208,802
<p>I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') </code></pre> <p>What I want to accomplish is something like:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName </code></pre> <p>I get syntax errors when I execute this, any ideas?</p>
16
2009-07-30T19:29:30Z
23,734,284
<pre><code>from django.core.urlresolvers import reverse from django.shortcuts import redirect def login(request): if request.session.get('user'): return redirect(reverse('name-of-url')) </code></pre> <p>Also see <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls</a></p>
3
2014-05-19T09:31:56Z
[ "python", "django", "redirect", "django-urls" ]
Django and urls.py: How do I HttpResponseRedirect via a named url?
1,208,802
<p>I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') </code></pre> <p>What I want to accomplish is something like:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName </code></pre> <p>I get syntax errors when I execute this, any ideas?</p>
16
2009-07-30T19:29:30Z
24,950,931
<p>The right answer from <a href="http://web.archive.org/web/20140704183041/https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#redirect" rel="nofollow">Django 1.3 onwards</a>, where the redirect method implicitly does a reverse call, is:</p> <pre><code>from django.shortcuts import redirect def login(request): if request.session.get('user'): return redirect('named_url') </code></pre>
1
2014-07-25T08:06:39Z
[ "python", "django", "redirect", "django-urls" ]
Decoding HTML entities with Python
1,208,916
<p>I'm trying to decode HTML entries from here <a href="http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&amp;hp">NYTimes.com</a> and I cannot figure out what I am doing wrong. </p> <p>Take for example: </p> <pre><code>"U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" </code></pre> <p>I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart_str without any success. </p>
17
2009-07-30T19:47:34Z
1,208,931
<p><strong>Try this:</strong></p> <pre><code>import re def _callback(matches): id = matches.group(1) try: return unichr(int(id)) except: return id def decode_unicode_references(data): return re.sub("&amp;#(\d+)(;|(?=\s))", _callback, data) data = "U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" print decode_unicode_references(data) </code></pre>
6
2009-07-30T19:50:07Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
Decoding HTML entities with Python
1,208,916
<p>I'm trying to decode HTML entries from here <a href="http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&amp;hp">NYTimes.com</a> and I cannot figure out what I am doing wrong. </p> <p>Take for example: </p> <pre><code>"U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" </code></pre> <p>I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart_str without any success. </p>
17
2009-07-30T19:47:34Z
1,209,015
<p>This does work:</p> <pre><code>from BeautifulSoup import BeautifulStoneSoup s = "U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" decoded = BeautifulStoneSoup(s, convertEntities=BeautifulStoneSoup.HTML_ENTITIES) </code></pre> <p>If you want a string instead of a Unicode object, you'll need to decode it to an encoding that supports the characters being used; ISO-8859-1 doesn't:</p> <pre><code>result = decoded.encode("UTF-8") </code></pre> <p>It's unfortunate that you need an external module for something like this; simple HTML/XML entity decoding should be in the standard library, and not require me to use a library with meaningless class names like "BeautifulStoneSoup". (Class and function names should not be "creative", they should be meaningful.)</p>
18
2009-07-30T20:05:12Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
Decoding HTML entities with Python
1,208,916
<p>I'm trying to decode HTML entries from here <a href="http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&amp;hp">NYTimes.com</a> and I cannot figure out what I am doing wrong. </p> <p>Take for example: </p> <pre><code>"U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" </code></pre> <p>I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart_str without any success. </p>
17
2009-07-30T19:47:34Z
1,209,922
<p>Actually what you have are not HTML entities. There are THREE varieties of those &amp;.....; thingies -- for example <code>&amp;#160; &amp;#xa0; &amp;nbsp;</code> all mean U+00A0 NO-BREAK SPACE.</p> <p><code>&amp;#160;</code> (the type you have) is a "numeric character reference" (decimal).<br> <code>&amp;#xa0;</code> is a "numeric character reference" (hexadecimal).<br> <code>&amp;nbsp;</code> is an entity.</p> <p>Further reading: <a href="http://htmlhelp.com/reference/html40/entities/">http://htmlhelp.com/reference/html40/entities/</a></p> <p>Here you will find code for Python2.x that does all three in one scan through the input: <a href="http://effbot.org/zone/re-sub.htm#unescape-html">http://effbot.org/zone/re-sub.htm#unescape-html</a></p>
19
2009-07-30T23:18:53Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
Decoding HTML entities with Python
1,208,916
<p>I'm trying to decode HTML entries from here <a href="http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&amp;hp">NYTimes.com</a> and I cannot figure out what I am doing wrong. </p> <p>Take for example: </p> <pre><code>"U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: Time &amp;#8216;to Go Home&amp;#8217;" </code></pre> <p>I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart_str without any success. </p>
17
2009-07-30T19:47:34Z
20,715,131
<pre><code>&gt;&gt;&gt; from HTMLParser import HTMLParser &gt;&gt;&gt; print HTMLParser().unescape('U.S. Adviser&amp;#8217;s Blunt Memo on Iraq: ' ... 'Time &amp;#8216;to Go Home&amp;#8217;') U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’ </code></pre> <p>The function is undocumented in Python 2. <a href="http://bugs.python.org/issue2927">It is fixed in Python 3.4+</a>: it is exposed as <a href="https://docs.python.org/3/library/html.html#html.unescape"><code>html.unescape()</code> there</a>.</p>
10
2013-12-21T03:37:21Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
Can pydoc generate subdirectories?
1,208,990
<p>Is there any way to get pydoc's writedocs() function to create subdirectories for packages? For instance, let's say I have the following modules to document:</p> <p>foo.py dir/bar.py dir/<strong>init</strong>.py</p> <p>When I run pydoc.writedocs(), I get the following files:</p> <p>foo.html dir.bar.html</p> <p>I would like to get: foo.html dir/bar.html</p> <p>Is there any way to do this?</p>
1
2009-07-30T19:58:51Z
1,209,321
<p><code>pydoc.writedocs</code> just loops calling <code>writedoc</code>, which is documented (and implemented) to "write a file in the current directory". The only way out that I can see is by making a modified version and forcing it (i.e., sigh, monkeypatching it) into the module, or monkeypatching some key aspect of it, namely where 'open' opens for writing the HTML files it's asked to open. Specifically, in your code, you could do something like:</p> <pre><code>import pydoc def monkey_open(name, option): if option == 'w' and name.endswith('.html'): name_pieces = name.split('.') name_pieces[-2:] = '.'.join(name_pieces[-2:]) name = '/'.join(name_pieces) return open(name, option) pydoc.open = monkey_open </code></pre> <p>Not an elegant or extremely robust solution, but "needs must"... pydoc just isn't designed to allow you to do what you want, so the thing needs to be "shoehorned in" a bit.</p>
1
2009-07-30T20:55:50Z
[ "python", "pydoc" ]
Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr?
1,209,155
<p>Today I ran against the fact, that <code>sys.exit()</code> called from a child-thread does not kill the main process. I did not know this before, and this is okay, but I needed long time to realize this. It would have saved <strong>much much time</strong>, if <code>sys.exit(msg)</code> would have printed <code>msg</code> to <code>stderr</code>. But it did not.</p> <p>It turned out that it wasn't a real bug in my application; it called <code>sys.exit(msg)</code> with a meaningful error in a volitional way -- but I just could not see this.</p> <p><a href="http://docs.python.org/library/sys.html#sys.exit">In the docs for <code>sys.exit()</code> it is stated</a>: <em>"[...] any other object is printed to <code>sys.stderr</code> and results in an exit code of 1"</em></p> <p>This is <strong>not true</strong> for a call from a child-thread, where <code>sys.exit()</code> obviously behaves as <a href="http://docs.python.org/library/thread.html#thread.exit"><code>thread.exit()</code></a>: <em>"Raise the SystemExit exception. When not caught, this will cause the thread to exit <strong>silently</strong>"</em></p> <p>I think when a programmer wants <code>sys.exit(msg)</code> to print an error message, then this should just be printed -- independent of the place from where it is called. Why not? I currently don't see any reason. At least there should be a hint in the docs for <code>sys.exit()</code> that the message is not printed from threads.</p> <p>What do you think? Why are error messages concealed from threads? Does this make sense?</p> <p>Best regards,</p> <p>Jan-Philip Gehrcke</p>
8
2009-07-30T20:29:56Z
1,209,215
<p>Not all threads in python are equal. Calling sys.exit from a thread, does not actually exit the system. Thus, calling sys.exit() from a child thread is nonsensical, so it makes sense that it does not behave the way you expect.</p> <p>This <a href="http://docs.python.org/library/threading.html" rel="nofollow">page</a> talks more about threading objects, and the differences between threads and the special "main" thread.</p>
0
2009-07-30T20:38:22Z
[ "python", "multithreading", "exit", "sys" ]
Python: Why does `sys.exit(msg)` called from a thread not print `msg` to stderr?
1,209,155
<p>Today I ran against the fact, that <code>sys.exit()</code> called from a child-thread does not kill the main process. I did not know this before, and this is okay, but I needed long time to realize this. It would have saved <strong>much much time</strong>, if <code>sys.exit(msg)</code> would have printed <code>msg</code> to <code>stderr</code>. But it did not.</p> <p>It turned out that it wasn't a real bug in my application; it called <code>sys.exit(msg)</code> with a meaningful error in a volitional way -- but I just could not see this.</p> <p><a href="http://docs.python.org/library/sys.html#sys.exit">In the docs for <code>sys.exit()</code> it is stated</a>: <em>"[...] any other object is printed to <code>sys.stderr</code> and results in an exit code of 1"</em></p> <p>This is <strong>not true</strong> for a call from a child-thread, where <code>sys.exit()</code> obviously behaves as <a href="http://docs.python.org/library/thread.html#thread.exit"><code>thread.exit()</code></a>: <em>"Raise the SystemExit exception. When not caught, this will cause the thread to exit <strong>silently</strong>"</em></p> <p>I think when a programmer wants <code>sys.exit(msg)</code> to print an error message, then this should just be printed -- independent of the place from where it is called. Why not? I currently don't see any reason. At least there should be a hint in the docs for <code>sys.exit()</code> that the message is not printed from threads.</p> <p>What do you think? Why are error messages concealed from threads? Does this make sense?</p> <p>Best regards,</p> <p>Jan-Philip Gehrcke</p>
8
2009-07-30T20:29:56Z
1,209,358
<p>I agree that the Python docs are incorrect, or maybe more precisely incomplete, regarding sys.exit and SystemExit when called/raised by threads other than the main one; please open a doc issue on the Python online tracker so this can be addressed in a future iteration of the docs (probably a near-future one -- doc fixes are easier and smoother than code fixes;-).</p> <p>The remedy is pretty easy, of course -- just wrap any function you're using as the target of a <code>threading.Thread</code> with a decorator that does a <code>try</code>/<code>except SystemExit, e:</code> around it, and performs the "write to stderr" extra functionality you require (or, maybe better, uses a logging.error call instead) before terminating. But, with the doc issue that you correctly point out, it's hard to think about doing that unless and until one has met with the problem and in fact has had to spend some time in debugging to pin it down, as you've had to do (on the collective behalf of the core python developers -- sorry!).</p>
6
2009-07-30T21:03:33Z
[ "python", "multithreading", "exit", "sys" ]
How do you control MySQL timeouts from SQLAlchemy?
1,209,640
<p>What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The <code>connect_timeout</code> URL parameter seems to be insufficient.</p> <p>I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly. I'm not worried about the queries themselves taking too long. </p> <p>The following script does what you'd expect (i.e., time out after approximately one second) if <em>somehost</em> is unavailable <strong>before</strong> the <code>while</code> loop is ever reached. But if <em>somehost</em> goes down <strong>during</strong> the <code>while</code> loop (e.g., try yanking out its network cable after the loop has started), then the timeout seems to take at least 18 seconds. Is there some additional setting or parameter I'm missing?</p> <p>It's not surprising that the <code>wait_timeout</code> session variable doesn't work, as I think that's a server-side variable. But I threw it in there just to make sure.</p> <pre><code>from sqlalchemy import * from sqlalchemy.exc import * import time import sys engine = create_engine("mysql://user:password@somehost/test?connect_timeout=1") try: engine.execute("set session wait_timeout = 1;") while True: t = time.time() print t engine.execute("show tables;") except DBAPIError: pass finally: print time.time() - t, "seconds to time out" </code></pre>
8
2009-07-30T21:59:19Z
1,309,814
<p>Could this be a bug in the mysql/python connector? <a href="https://bugs.launchpad.net/myconnpy/+bug/328998" rel="nofollow">https://bugs.launchpad.net/myconnpy/+bug/328998</a> which says the time out is hard-coded to 10 seconds.</p> <p>To really see where the breakdown is, you could use a packet sniffer to checkout the conversation between the server and the client. wireshark + tcpdump works great for this kind of thing.</p>
1
2009-08-21T02:26:47Z
[ "python", "mysql", "sqlalchemy" ]
How do you control MySQL timeouts from SQLAlchemy?
1,209,640
<p>What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The <code>connect_timeout</code> URL parameter seems to be insufficient.</p> <p>I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly. I'm not worried about the queries themselves taking too long. </p> <p>The following script does what you'd expect (i.e., time out after approximately one second) if <em>somehost</em> is unavailable <strong>before</strong> the <code>while</code> loop is ever reached. But if <em>somehost</em> goes down <strong>during</strong> the <code>while</code> loop (e.g., try yanking out its network cable after the loop has started), then the timeout seems to take at least 18 seconds. Is there some additional setting or parameter I'm missing?</p> <p>It's not surprising that the <code>wait_timeout</code> session variable doesn't work, as I think that's a server-side variable. But I threw it in there just to make sure.</p> <pre><code>from sqlalchemy import * from sqlalchemy.exc import * import time import sys engine = create_engine("mysql://user:password@somehost/test?connect_timeout=1") try: engine.execute("set session wait_timeout = 1;") while True: t = time.time() print t engine.execute("show tables;") except DBAPIError: pass finally: print time.time() - t, "seconds to time out" </code></pre>
8
2009-07-30T21:59:19Z
1,318,706
<p>I believe you are reaching a totally different error, this is a dreaded "mysql has gone away" error, If I'm right the solution is to update to a newer mysqldb driver as the bug has been patches in the driver.</p> <p>If for some reason you can't/won't update you should try the SA fix for this</p> <pre><code>db= create_engine('mysql://root@localhost/test', pool_recycle=True) </code></pre>
1
2009-08-23T14:30:09Z
[ "python", "mysql", "sqlalchemy" ]
How do you control MySQL timeouts from SQLAlchemy?
1,209,640
<p>What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The <code>connect_timeout</code> URL parameter seems to be insufficient.</p> <p>I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly. I'm not worried about the queries themselves taking too long. </p> <p>The following script does what you'd expect (i.e., time out after approximately one second) if <em>somehost</em> is unavailable <strong>before</strong> the <code>while</code> loop is ever reached. But if <em>somehost</em> goes down <strong>during</strong> the <code>while</code> loop (e.g., try yanking out its network cable after the loop has started), then the timeout seems to take at least 18 seconds. Is there some additional setting or parameter I'm missing?</p> <p>It's not surprising that the <code>wait_timeout</code> session variable doesn't work, as I think that's a server-side variable. But I threw it in there just to make sure.</p> <pre><code>from sqlalchemy import * from sqlalchemy.exc import * import time import sys engine = create_engine("mysql://user:password@somehost/test?connect_timeout=1") try: engine.execute("set session wait_timeout = 1;") while True: t = time.time() print t engine.execute("show tables;") except DBAPIError: pass finally: print time.time() - t, "seconds to time out" </code></pre>
8
2009-07-30T21:59:19Z
1,348,957
<p>this isn't possible due to the way TCP works. if the other computer drops off the network, it will simply stop responding to incoming packets. the "18 seconds" you're seeing is something on your TCP stack timing out due to no response.</p> <p>the only way you can get your desired behavior is to have the computer generate a "i'm dying" message immediately before it dies. which, if the death is unexpected, is completely impossible.</p> <p>have you ever heard of hearbeats? these are packets that high-availability systems send to each other every second or less to let the other one know they still exist. if you want your application to know "immediately" that the server is gone, you first have to decide how long "immediate" is (1 second, 200 ms, etc.) and then designed a system (such as heartbeats) to detect when the other system is no longer there.</p>
5
2009-08-28T19:42:05Z
[ "python", "mysql", "sqlalchemy" ]
outer join modelisation in django
1,209,947
<p>I have a many to many relationship table whith some datas in the jointing base</p> <p>a basic version of my model look like:</p> <pre><code>class FooLine(models.Model): name = models.CharField(max_length=255) class FooCol(models.Model): name = models.CharField(max_length=255) class FooVal(models.Model): value = models.CharField(max_length=255) line = models.ForeignKey(FooLine) col = models.ForeignKey(FooCol) </code></pre> <p>I'm trying to search every values for a certain line with a null if the value is not present (basically i'm trying to display the fooval table with null values for values that haven't been filled) a typical sql would be</p> <pre><code>SELECT value FROM FooCol LEFT OUTER JOIN (FooVal JOIN FooLine ON FooVal.line_id == FooLine.id AND FooLine.name = "FIXME") ON FooCol.id = col_id; </code></pre> <p>Is there any way to modelise above query using django model</p> <p>Thanks</p>
0
2009-07-30T23:29:05Z
1,210,397
<p>Outer joins can be viewed as a hack because SQL lacks "navigation". </p> <p>What you have is a simple if-statement situation.</p> <pre><code>for line in someRangeOfLines: for col in someRangeOfCols: try: cell= FooVal.objects().get( col = col, line = line ) except FooVal.DoesNotExist: cell= None </code></pre> <p>That's what an outer join really is -- an attempted lookup with a NULL replacement.</p> <p>The only optimization is something like the following.</p> <pre><code>matrix = {} for f in FooVal.objects().all(): matrix[(f.line,f.col)] = f for line in someRangeOfLines: for col in someRangeOfCols: cell= matrix.get((line,col),None) </code></pre>
0
2009-07-31T02:33:08Z
[ "python", "django", "request", "outer-join" ]
How to find number of users, number of users with a profile object, and monthly logins in Django
1,210,099
<p>Is there an easy way in Django to find the number of Users, Number of Users with profile objects, and ideally number of logins per month (but could do this with Google Analytics). I can see all the data is there in the admin interface, but I'm unsure of how to get to it in Python land. Has anyone seen any examples of counting number of user objects?</p>
0
2009-07-31T00:25:14Z
1,210,157
<p>Count the number of users:</p> <pre><code>import django.contrib.auth django.contrib.auth.models.User.objects.all().count() </code></pre> <p>You can use the same to count the number of profile objects (assuming every user has at most 1 profile), e.g. if Profile is the profile model:</p> <pre><code>Profile.objects.all().count() </code></pre> <p>To count the number of logins in a month you'd need to create a table logging each login with a time stamp. Then it's a matter of using count() again.</p>
1
2009-07-31T00:48:33Z
[ "python", "django", "admin" ]
Handling Windows-specific exceptions in platform-independent way
1,210,118
<p>Consider the following Python exception:</p> <pre><code> [...] f.extractall() File "C:\Python26\lib\zipfile.py", line 935, in extractall self.extract(zipinfo, path, pwd) File "C:\Python26\lib\zipfile.py", line 923, in extract return self._extract_member(member, path, pwd) File "C:\Python26\lib\zipfile.py", line 957, in _extract_member os.makedirs(upperdirs) File "C:\Python26\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 267] The directory name is invalid: 'C:\\HOME\\as\ \pypm-infinitude\\scratch\\b\\slut-0.9.0.zip.work\\slut-0.9\\aux' </code></pre> <p>I want to handle this particular exception - i.e., WindowsError with error number 267. However, I cannot simply do the following:</p> <pre><code>try: do() except WindowsError, e: ... </code></pre> <p>Because that would not work on Unix systems where WindowsError is not even defined in the exceptions module. </p> <p>Is there an elegant way to handle this error?</p>
5
2009-07-31T00:36:15Z
1,210,148
<p>Here's my current solution, but I slightly despise using non-trivial code in a except block:</p> <pre><code> try: f.extractall() except OSError, e: # http://bugs.python.org/issue6609 if sys.platform.startswith('win'): if isinstance(e, WindowsError) and e.winerror == 267: raise InvalidFile, ('uses Windows special name (%s)' % e) raise </code></pre>
3
2009-07-31T00:45:47Z
[ "python", "windows", "exception", "exception-handling" ]
Handling Windows-specific exceptions in platform-independent way
1,210,118
<p>Consider the following Python exception:</p> <pre><code> [...] f.extractall() File "C:\Python26\lib\zipfile.py", line 935, in extractall self.extract(zipinfo, path, pwd) File "C:\Python26\lib\zipfile.py", line 923, in extract return self._extract_member(member, path, pwd) File "C:\Python26\lib\zipfile.py", line 957, in _extract_member os.makedirs(upperdirs) File "C:\Python26\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 267] The directory name is invalid: 'C:\\HOME\\as\ \pypm-infinitude\\scratch\\b\\slut-0.9.0.zip.work\\slut-0.9\\aux' </code></pre> <p>I want to handle this particular exception - i.e., WindowsError with error number 267. However, I cannot simply do the following:</p> <pre><code>try: do() except WindowsError, e: ... </code></pre> <p>Because that would not work on Unix systems where WindowsError is not even defined in the exceptions module. </p> <p>Is there an elegant way to handle this error?</p>
5
2009-07-31T00:36:15Z
1,210,193
<p>If you need to catch an exception with a name that might not always exist, then create it:</p> <pre><code>if not getattr(__builtins__, "WindowsError", None): class WindowsError(OSError): pass try: do() except WindowsError, e: print "error" </code></pre> <p>If you're on Windows, you'll use the real WindowsError class and catch the exception. If you're not, you'll create a WindowsError class that will never be raised, so the except clause doesn't cause any errors, and the except clause will never be invoked.</p>
10
2009-07-31T01:02:51Z
[ "python", "windows", "exception", "exception-handling" ]
Google app engine ReferenceProperty relationships
1,210,321
<p>I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.</p> <p>I am able to store new Groups nice and fine, but I don't have any idea how to store topics underneath these groups. I want to link from a page with a link "New topic" underneath each group, that takes them to a simple form (1 field for now). Obviously the URL will need to have some sort of reference to the id of the group or something.</p> <p>Here are my models: </p> <pre><code>class Groups(db.Model): group_user = db.UserProperty() group_name = db.StringProperty(multiline=True) group_date = db.DateTimeProperty(auto_now_add=True) class Topics(db.Model): topic_user = db.UserProperty() topic_name = db.StringProperty(multiline=True) topic_date = db.DateTimeProperty(auto_now_add=True) topic_group = db.ReferenceProperty(Groups, collection_name='topics') class Pro(db.Model): pro_user = db.UserProperty() pro_content = db.StringProperty(multiline=True) pro_date = db.IntegerProperty(default=0) pro_topic = db.ReferenceProperty(Topics, collection_name='pros') class Con(db.Model): con_user = db.UserProperty() con_content = db.StringProperty(multiline=True) con_date = db.IntegerProperty(default=0) con_topic = db.ReferenceProperty(Topics, collection_name='cons') </code></pre> <p>And one function for the actual page I want to show the list of Groups, and then underneath their topics:</p> <pre><code>class Summary(webapp.RequestHandler): def get(self): groups_query = Groups.all() groups = groups_query.fetch(1000) template_values = { 'groups': groups, } path = os.path.join(os.path.dirname(__file__), 'summary.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>And finally the html:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="/newgroup"&gt;New Group&lt;/a&gt; &lt;br&gt; {% for group in groups %} &lt;font size="24"&gt;{{ group.group_name|escape }}&lt;/font&gt;&lt;br&gt; by &lt;b&gt;{{ group.group_user }}&lt;/b&gt; at &lt;b&gt;{{ group.group_date }}&lt;/b&gt; {{ group.raw_id }} &lt;br&gt; &lt;a href="/newtopic?id={{group.key.id}}" &gt;New topice &lt;/a&gt; &lt;br&gt; &lt;blockquote&gt; {{ topics.topics_name }} &lt;/blockquote&gt; {% endfor %} &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-07-31T02:02:58Z
1,210,696
<p>Something that has side effects, such as altering the store (by creating a new object for example) should <em>NOT</em> be an HTTP <code>GET</code> -- GET should essentially only do "read" operations. This isn't pedantry, it's a key bit of HTTP semantics -- browsers, caches, proxies, etc, are allowed to act on GET as read-only operations (for example by caching results and not passing a request to the server if they can satisfy it from cache).</p> <p>For modifications, use HTTP verbs such as POST (most popular essentially because all browsers implement it correctly) or for specialized operations PUT (to create new objects) or DELETE (to remove objects). I assume you'll be going to use POST to support a variety of browsers.</p> <p>To get a POST from a browser, you need either Javascript wizardy or a plain old form with method=post -- I'll assume the latter for simplicity.</p> <p>If you're using Django 1.0 (which app engine supports now), it has its own mechanisms to make, validate and accept forms based on models. Other frameworks have their own similarly advanced layers.</p> <p>If you want to avoid "rich" frameworks you'll have to implement by hand templates for your HTML forms, direct them (via some kind of URL dispatching, e.g. in app.yaml) to a handler of yours implementing with a <code>def post(self):</code>, get the data from the request, validate it, form the new object, put it, display some acknowledgment page.</p> <p>What part or parts of the procedure are unclear to you? Your question's title focuses specifically on reference properties but I'm not sure what problem they are giving you in particular -- from the text of your question you appear to be on the right tack about them.</p> <p><strong>Edit</strong>: the OP has now clarified in a comment that his problem is how to make something like:</p> <pre><code>"&lt;a href="/newtopic?id={{group.key.id}}" &gt;New topic &lt;/a&gt;" </code></pre> <p>work. There's more than one way to do that. If the newtopic URL is served by a static form, the handler for the post "action" of that form could get back to that <code>id=</code> via the <code>Referer:</code> header (a notorious but unfixable mis-spelling), but that's a bit clunky and fragile. Better is to have the newtopic URI served by a handler whose <code>def get</code> gets the <code>id=</code> from the request and inserts it in the resulting form template -- for example, in a hidden input field. Have that form's template contain (among the other fields):</p> <pre><code>&lt;INPUT TYPE=hidden NAME=thegroupid VALUE={{ theid }}&gt; &lt;/INPUT&gt; </code></pre> <p>put <code>theid</code> in the context with which you render that template, and it will be in the request that the <code>def post</code> of the action receiving the form finally gets.</p>
2
2009-07-31T04:31:51Z
[ "python", "google-app-engine", "django-models", "model", "django-templates" ]
Google app engine ReferenceProperty relationships
1,210,321
<p>I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.</p> <p>I am able to store new Groups nice and fine, but I don't have any idea how to store topics underneath these groups. I want to link from a page with a link "New topic" underneath each group, that takes them to a simple form (1 field for now). Obviously the URL will need to have some sort of reference to the id of the group or something.</p> <p>Here are my models: </p> <pre><code>class Groups(db.Model): group_user = db.UserProperty() group_name = db.StringProperty(multiline=True) group_date = db.DateTimeProperty(auto_now_add=True) class Topics(db.Model): topic_user = db.UserProperty() topic_name = db.StringProperty(multiline=True) topic_date = db.DateTimeProperty(auto_now_add=True) topic_group = db.ReferenceProperty(Groups, collection_name='topics') class Pro(db.Model): pro_user = db.UserProperty() pro_content = db.StringProperty(multiline=True) pro_date = db.IntegerProperty(default=0) pro_topic = db.ReferenceProperty(Topics, collection_name='pros') class Con(db.Model): con_user = db.UserProperty() con_content = db.StringProperty(multiline=True) con_date = db.IntegerProperty(default=0) con_topic = db.ReferenceProperty(Topics, collection_name='cons') </code></pre> <p>And one function for the actual page I want to show the list of Groups, and then underneath their topics:</p> <pre><code>class Summary(webapp.RequestHandler): def get(self): groups_query = Groups.all() groups = groups_query.fetch(1000) template_values = { 'groups': groups, } path = os.path.join(os.path.dirname(__file__), 'summary.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>And finally the html:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="/newgroup"&gt;New Group&lt;/a&gt; &lt;br&gt; {% for group in groups %} &lt;font size="24"&gt;{{ group.group_name|escape }}&lt;/font&gt;&lt;br&gt; by &lt;b&gt;{{ group.group_user }}&lt;/b&gt; at &lt;b&gt;{{ group.group_date }}&lt;/b&gt; {{ group.raw_id }} &lt;br&gt; &lt;a href="/newtopic?id={{group.key.id}}" &gt;New topice &lt;/a&gt; &lt;br&gt; &lt;blockquote&gt; {{ topics.topics_name }} &lt;/blockquote&gt; {% endfor %} &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-07-31T02:02:58Z
1,210,723
<p>Thankyou for the reply.</p> <p>Yeah I am aware of the get vs post. The class I posted was just to actually print all the Groups().</p> <p>The issue I have is I'm unsure how I use the models to keep data in a sort of hierarchical fashion, with Groups > Topics > Pros/Cons.</p> <p>Grabbing data is simple enough and I am using:</p> <pre><code>class NewGroupSubmit(webapp.RequestHandler): def post(self): group = Groups() if users.get_current_user(): group.group_user = users.get_current_user() group.group_name = self.request.get('groupname') group.put() self.redirect('/summary') </code></pre> <p>I need another function to add a new topic, that stores it within that group. So lets say a group is "Cars" for instance; the topics might be "Ferrari", "Porsche", "BMW", and then pros/cons for each topic. I realise I'm being a little vague, but it's because I'm very new to relational databasing and not quite used to the terminology.</p>
0
2009-07-31T04:43:49Z
[ "python", "google-app-engine", "django-models", "model", "django-templates" ]
Google app engine ReferenceProperty relationships
1,210,321
<p>I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.</p> <p>I am able to store new Groups nice and fine, but I don't have any idea how to store topics underneath these groups. I want to link from a page with a link "New topic" underneath each group, that takes them to a simple form (1 field for now). Obviously the URL will need to have some sort of reference to the id of the group or something.</p> <p>Here are my models: </p> <pre><code>class Groups(db.Model): group_user = db.UserProperty() group_name = db.StringProperty(multiline=True) group_date = db.DateTimeProperty(auto_now_add=True) class Topics(db.Model): topic_user = db.UserProperty() topic_name = db.StringProperty(multiline=True) topic_date = db.DateTimeProperty(auto_now_add=True) topic_group = db.ReferenceProperty(Groups, collection_name='topics') class Pro(db.Model): pro_user = db.UserProperty() pro_content = db.StringProperty(multiline=True) pro_date = db.IntegerProperty(default=0) pro_topic = db.ReferenceProperty(Topics, collection_name='pros') class Con(db.Model): con_user = db.UserProperty() con_content = db.StringProperty(multiline=True) con_date = db.IntegerProperty(default=0) con_topic = db.ReferenceProperty(Topics, collection_name='cons') </code></pre> <p>And one function for the actual page I want to show the list of Groups, and then underneath their topics:</p> <pre><code>class Summary(webapp.RequestHandler): def get(self): groups_query = Groups.all() groups = groups_query.fetch(1000) template_values = { 'groups': groups, } path = os.path.join(os.path.dirname(__file__), 'summary.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>And finally the html:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="/newgroup"&gt;New Group&lt;/a&gt; &lt;br&gt; {% for group in groups %} &lt;font size="24"&gt;{{ group.group_name|escape }}&lt;/font&gt;&lt;br&gt; by &lt;b&gt;{{ group.group_user }}&lt;/b&gt; at &lt;b&gt;{{ group.group_date }}&lt;/b&gt; {{ group.raw_id }} &lt;br&gt; &lt;a href="/newtopic?id={{group.key.id}}" &gt;New topice &lt;/a&gt; &lt;br&gt; &lt;blockquote&gt; {{ topics.topics_name }} &lt;/blockquote&gt; {% endfor %} &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-07-31T02:02:58Z
1,212,047
<p>I'm not quite sure what problem you're having. Everything you list looks fine - the ReferenceProperties are set up according to what one would expect from your dscription. The only problem I can see is that in your template, you're referring to a variable "topics", which isn't defined anywhere, and you're not iterating through the topics for a group anywhere. You can do that like this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="/newgroup"&gt;New Group&lt;/a&gt; &lt;br&gt; {% for group in groups %} &lt;font size="24"&gt;{{ group.group_name|escape }}&lt;/font&gt;&lt;br&gt; by &lt;b&gt;{{ group.group_user }}&lt;/b&gt; at &lt;b&gt;{{ group.group_date }}&lt;/b&gt; {{ group.raw_id }} &lt;br&gt; &lt;a href="/newtopic?id={{group.key.id}}" &gt;New topice &lt;/a&gt; &lt;br&gt; Topics: &lt;ul&gt; {% for topic in group.topics %} &lt;li&gt;{{topic.topic_name}}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>To create a new topic, just use the constructor, passing in the required arguments:</p> <pre><code>mytopic = Topic(topic_name="foo", topic_group=somegroup) </code></pre> <p>Here, somegroup should be either a Group object, or a key for a Group object.</p>
0
2009-07-31T11:32:14Z
[ "python", "google-app-engine", "django-models", "model", "django-templates" ]
Google app engine ReferenceProperty relationships
1,210,321
<p>I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.</p> <p>I am able to store new Groups nice and fine, but I don't have any idea how to store topics underneath these groups. I want to link from a page with a link "New topic" underneath each group, that takes them to a simple form (1 field for now). Obviously the URL will need to have some sort of reference to the id of the group or something.</p> <p>Here are my models: </p> <pre><code>class Groups(db.Model): group_user = db.UserProperty() group_name = db.StringProperty(multiline=True) group_date = db.DateTimeProperty(auto_now_add=True) class Topics(db.Model): topic_user = db.UserProperty() topic_name = db.StringProperty(multiline=True) topic_date = db.DateTimeProperty(auto_now_add=True) topic_group = db.ReferenceProperty(Groups, collection_name='topics') class Pro(db.Model): pro_user = db.UserProperty() pro_content = db.StringProperty(multiline=True) pro_date = db.IntegerProperty(default=0) pro_topic = db.ReferenceProperty(Topics, collection_name='pros') class Con(db.Model): con_user = db.UserProperty() con_content = db.StringProperty(multiline=True) con_date = db.IntegerProperty(default=0) con_topic = db.ReferenceProperty(Topics, collection_name='cons') </code></pre> <p>And one function for the actual page I want to show the list of Groups, and then underneath their topics:</p> <pre><code>class Summary(webapp.RequestHandler): def get(self): groups_query = Groups.all() groups = groups_query.fetch(1000) template_values = { 'groups': groups, } path = os.path.join(os.path.dirname(__file__), 'summary.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>And finally the html:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;a href="/newgroup"&gt;New Group&lt;/a&gt; &lt;br&gt; {% for group in groups %} &lt;font size="24"&gt;{{ group.group_name|escape }}&lt;/font&gt;&lt;br&gt; by &lt;b&gt;{{ group.group_user }}&lt;/b&gt; at &lt;b&gt;{{ group.group_date }}&lt;/b&gt; {{ group.raw_id }} &lt;br&gt; &lt;a href="/newtopic?id={{group.key.id}}" &gt;New topice &lt;/a&gt; &lt;br&gt; &lt;blockquote&gt; {{ topics.topics_name }} &lt;/blockquote&gt; {% endfor %} &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-07-31T02:02:58Z
1,635,487
<p>Just to answer the question for others as you probably figured this out:</p> <pre> class NewTopic(webapp.RequestHandler): def get(self): groupId = self.request.get('group') # either get the actual group object from the DB and initialize topic with topic_group=object as in 'Nick Johnson's answer, or do as follows topic = Topic() topic.name = self.request.get("topicname") topic.reference = groupId topic.put() </pre>
1
2009-10-28T06:26:05Z
[ "python", "google-app-engine", "django-models", "model", "django-templates" ]
help me eliminate a for-loop in python
1,210,509
<p>There has to be a faster way of doing this.</p> <p>There is a lot going on here, but it's fairly straightforward to unpack.</p> <p>Here is the relevant python code (from scipy import *)</p> <pre><code>for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) </code></pre> <p>There are a bunch of arrays.</p> <ul> <li>result -- array of length (wav)</li> <li>laser_flux -- array of length (laser)</li> <li>wav -- array of length (wav)</li> <li>laser_wav -- array of length (laser)</li> </ul> <p>Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav. </p> <p>Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!</p>
0
2009-07-31T03:06:59Z
1,210,527
<p>For one thing, it seems to be slightly quicker to multiply a variable by itself than to use the <code>**</code> power operator:</p> <pre><code>~$ python -m timeit -n 100000 -v "x = 4.1; x * x" raw times: 0.0904 0.0513 0.0493 100000 loops, best of 3: 0.493 usec per loop ~$ python -m timeit -n 100000 -v "x = 4.1; x**2" raw times: 0.101 0.147 0.118 100000 loops, best of 3: 1.01 usec per loop </code></pre>
0
2009-07-31T03:21:01Z
[ "python", "for-loop" ]
help me eliminate a for-loop in python
1,210,509
<p>There has to be a faster way of doing this.</p> <p>There is a lot going on here, but it's fairly straightforward to unpack.</p> <p>Here is the relevant python code (from scipy import *)</p> <pre><code>for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) </code></pre> <p>There are a bunch of arrays.</p> <ul> <li>result -- array of length (wav)</li> <li>laser_flux -- array of length (laser)</li> <li>wav -- array of length (wav)</li> <li>laser_wav -- array of length (laser)</li> </ul> <p>Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav. </p> <p>Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!</p>
0
2009-07-31T03:06:59Z
1,210,530
<p>I'm new to Python, so this may not the most optimal <em>in Python</em>, but I'd use the same technique for Perl, Scheme, etc.</p> <pre><code>def func(x): delta = x - laser_wav return sum(laser_flux * exp(-delta * delta)) result = map(func, wav) </code></pre>
2
2009-07-31T03:23:48Z
[ "python", "for-loop" ]
help me eliminate a for-loop in python
1,210,509
<p>There has to be a faster way of doing this.</p> <p>There is a lot going on here, but it's fairly straightforward to unpack.</p> <p>Here is the relevant python code (from scipy import *)</p> <pre><code>for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) </code></pre> <p>There are a bunch of arrays.</p> <ul> <li>result -- array of length (wav)</li> <li>laser_flux -- array of length (laser)</li> <li>wav -- array of length (wav)</li> <li>laser_wav -- array of length (laser)</li> </ul> <p>Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav. </p> <p>Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!</p>
0
2009-07-31T03:06:59Z
1,210,538
<p>You're going to want to use Numpy arrays (if you're not already) to store your data. Then, you can take advantage of array broadcasting with <code>np.newaxis</code>. For each value in <code>wav</code>, you're going to want to compute a difference between that value and each value in <code>laser_wav</code>. That suggests that you'll want a two-dimensional array, with the two dimensions being the <code>wav</code> dimension and the <code>laser</code> dimension. </p> <p>In the example below, I'll pick the first index as the <code>laser</code> index and the second index as the <code>wav</code> index. With sample data, this becomes:</p> <pre><code>import numpy as np LASER_LEN = 5 WAV_LEN = 10 laser_flux = np.arange(LASER_LEN) wav = np.arange(WAV_LEN) laser_wav = np.array(LASER_LEN) # Tile wav into LASER_LEN rows and tile laser_wav into WAV_LEN columns diff = wav[np.newaxis,:] - laser_wav[:,np.newaxis] exp_arg = -diff ** 2 sum_arg = laser_flux[:,np.newaxis] * np.exp(exp_arg) # Now, the resulting array sum_arg should be of size (LASER_LEN,WAV_LEN) # Since your original sum was along each element of laser_flux/laser_wav, # you'll need to sum along the first axis. result = np.sum(sum_arg, axis=0) </code></pre> <p>Of course, you could just condense this down into a single statement:</p> <pre><code>result = np.sum(laser_flux[:,np.newaxis] * np.exp(-(wav[np.newaxis,:]-laser_wav[:,np.newaxis])**2),axis=0) </code></pre> <p>Edit:</p> <p>As noted in the comments to the question, you can take advantage of the "sum of multiplications" inherent in the definition of linear-algebra style multiplications. This then becomes:</p> <pre><code>result = np.dot(laser_flux, np.exp(-(wav[np.newaxis,:] - laser_wav[:,np.newaxis])**2)) </code></pre>
13
2009-07-31T03:25:57Z
[ "python", "for-loop" ]
help me eliminate a for-loop in python
1,210,509
<p>There has to be a faster way of doing this.</p> <p>There is a lot going on here, but it's fairly straightforward to unpack.</p> <p>Here is the relevant python code (from scipy import *)</p> <pre><code>for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) </code></pre> <p>There are a bunch of arrays.</p> <ul> <li>result -- array of length (wav)</li> <li>laser_flux -- array of length (laser)</li> <li>wav -- array of length (wav)</li> <li>laser_wav -- array of length (laser)</li> </ul> <p>Yes, within the exponential, I am squaring (element by element) the difference between the scalar value and the array of laser_wav. </p> <p>Everything works as expected (including SLOWLY) any help you can give me to eliminate this for-loop would be much appreciated!</p>
0
2009-07-31T03:06:59Z
1,210,618
<p>If raw performance is an issue, you might benefit from rewriting to take advantage of multiple cores, if you have them. </p> <pre><code>from multiprocessing import Pool p = Pool(5) # about the number of cores you have def f(i): delta = wav[i] - laser_wav return sum(laser_flux * exp(-delta*delta) ) result = p.map(f, arange(len(wav)) ) </code></pre>
1
2009-07-31T03:55:19Z
[ "python", "for-loop" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
1,210,671
<p>Is the <a href="http://packages.debian.org/lenny/python-pysqlite2" rel="nofollow">python-pysqlite2</a> package installed?</p> <pre><code>sudo apt-get install python-pysqlite2 </code></pre>
-1
2009-07-31T04:23:44Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
1,210,746
<p>My _sqlite3.so is in /usr/lib/python2.5/lib-dynload/_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/_sqlite3.so.</p> <p>Try the following:</p> <pre><code>find /usr/local -name _sqlite3.so </code></pre> <p>If the file isn't found, something may be wrong with your Python installation. If it is, make sure the path it's installed to is in the Python path. In the Python shell,</p> <pre><code>import sys print sys.path </code></pre> <p>In my case, /usr/lib/python2.5/lib-dynload is in the list, so it's able to find /usr/lib/python2.5/lib-dynload/_sqlite3.so.</p>
8
2009-07-31T04:50:35Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
1,595,484
<p>Checking your settings.py file. Did you not just write "sqlite" instead of "sqlite3" for the database engine?</p>
1
2009-10-20T15:29:22Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
2,747,227
<p>I had the same problem (building <code>python2.5</code> from source on Ubuntu Lucid), and <code>import sqlite3</code> threw this same exception. I've installed <code>libsqlite3-dev</code> from the package manager, recompiled python2.5, and then the import worked.</p>
54
2010-04-30T19:46:42Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
6,715,701
<p>I recently tried installing python 2.6.7 on my Ubuntu 11.04 desktop for some dev work. Came across similar problems to this thread. I mamaged to fix it by:</p> <ol> <li><p>Adjusting the setup.py file to include the correct sqlite dev path. Code snippet from setup.py:</p> <pre><code>def sqlite_incdir: sqlite_dirs_to_check = [ os.path.join(sqlite_incdir, '..', 'lib64'), os.path.join(sqlite_incdir, '..', 'lib'), os.path.join(sqlite_incdir, '..', '..', 'lib64'), os.path.join(sqlite_incdir, '..', '..', 'lib'), '/usr/lib/x86_64-linux-gnu/' ] </code></pre> <p>With the bit that I added being '/usr/lib/x86_64-linux-gnu/'.</p></li> <li><p>After running make I did not get any warnings saying the sqlite support was not built (i.e., it built correctly :P ), but after running <code>make install</code>, sqlite3 still did not import with the same "<code>ImportError: No module named _sqlite3" whe running "import sqlite3</code>".</p> <p>So, the library was compiled, but not moved to the correct installation path, so I copied the <code>.so</code> file (<code>cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/</code> — these are my build paths, you will probably need to adjust them to your setup).</p></li> </ol> <p>Voila! SQLite3 support now works.</p>
6
2011-07-16T06:05:29Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
7,237,237
<p>I have the problem in FreeBSD 8.1:</p> <pre><code>- No module named _sqlite3 - </code></pre> <p>It is solved by stand the port ----------</p> <pre><code>/usr/ports/databases/py-sqlite3 </code></pre> <p>after this one can see:</p> <pre><code>OK ---------- '&gt;&gt;&gt;' import sqlite3 ----- '&gt;&gt;&gt;' sqlite3.apilevel ----- '2.0' </code></pre>
3
2011-08-29T23:40:25Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
18,912,070
<p>You need to install <a href="https://pypi.python.org/pypi/pysqlite" rel="nofollow">pysqlite</a> in your python environment:</p> <pre><code> $ pip install pysqlite </code></pre>
-3
2013-09-20T08:25:58Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
19,748,196
<p>This is what I did to get it to work.</p> <p>I am using pythonbrew(which is using pip) with python 2.7.5 installed.</p> <p>I first did what Zubair(above) said and ran this command:</p> <pre><code>sudo apt-get install libsqlite3-dev </code></pre> <p>Then I ran this command:</p> <pre><code>pip install pysqlite </code></pre> <p>This fixed the database problem and I got confirmation of this when I ran:</p> <pre><code>python manager.py syncdb </code></pre>
8
2013-11-02T23:40:35Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
20,963,270
<p>you must be in centos or redhat and compile python yourself, it is python‘s bug do this in your python source code dir and do this below</p> <pre><code>curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1 </code></pre>
0
2014-01-07T03:13:31Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
24,449,632
<p>it's seems your makefile didn't include the appropriate <code>.so</code> file. I corrected this problem with the steps below:</p> <ol> <li>Install <code>sqlite-devel</code> (or <code>libsqlite3-dev</code> on some Debian-based systems)</li> <li>re-configured and re-compiled Python with <code>./configure --enable-loadable-sqlite-extensions &amp;&amp; make &amp;&amp; make install</code></li> </ol>
16
2014-06-27T10:28:29Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
25,339,281
<p>This worked for me in Redhat Centos 6.5:</p> <pre><code>yum install sqlite-devel pip install pysqlite </code></pre>
3
2014-08-16T10:31:24Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
34,129,584
<ol> <li><p>Install the <code>sqlite-devel</code> package:</p> <p><code>yum install sqlite-devel -y</code></p></li> <li><p>Recompile python from the source:</p> <pre><code>./configure make make altinstall </code></pre></li> </ol>
7
2015-12-07T08:50:12Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
36,790,974
<p>I also had this problem for django 1.9, python3.5 and ubuntu 14.04 I just added sudo before every command and that's solved my problem example </p> <pre><code>sudo python manage.py migrate sudo python manage.py runserver </code></pre>
-1
2016-04-22T10:13:00Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
38,842,600
<p>I had the same problem with Python 3.5 on Ubuntu while using <a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a>.</p> <p>If you're installing the python using <a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a>, it's listed as one of the <a href="https://github.com/yyuu/pyenv/wiki/Common-build-problems" rel="nofollow">common build problems</a>. To solve it, remove the installed python version, install the requirements (for this particular case <code>libsqlite3-dev</code>), then reinstall the python version. </p>
0
2016-08-09T05:17:17Z
[ "python", "django", "sqlite", "debian" ]
No module named _sqlite3
1,210,664
<p>I am trying to run a <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29">Django</a> app on my <a href="http://en.wikipedia.org/wiki/Virtual_private_server">VPS</a> running <a href="http://en.wikipedia.org/wiki/Debian#Releases">Debian</a> 5. When I run a demo app, it comes back with this error:</p> <pre><code> File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in &lt;module&gt; raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 </code></pre> <p>Looking at the Python install, it gives the same error:</p> <pre><code>Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 &gt;&gt;&gt; </code></pre> <p>Reading on the web, I learn that Python 2.5 should come with all the necessary <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running? </p>
55
2009-07-31T04:21:03Z
40,106,999
<p>Download sqlite3:</p> <pre><code>wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz </code></pre> <p>Follow these steps to install:</p> <pre><code>$tar xvfz sqlite-autoconf-3071502.tar.gz $cd sqlite-autoconf-3071502 $./configure --prefix=/usr/local $make install </code></pre>
-1
2016-10-18T11:27:16Z
[ "python", "django", "sqlite", "debian" ]
Django .."join" query?
1,210,711
<p>guys, how or where is the "join" query in Django?</p> <p>i think that Django dont have "join"..but how ill make join?</p> <p>Thanks </p>
4
2009-07-31T04:38:14Z
1,210,718
<p>Look into <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#relationships" rel="nofollow">model relationships</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/relations/#ref-models-relations" rel="nofollow">accessing related objects</a>.</p>
1
2009-07-31T04:42:01Z
[ "python", "django" ]
Django .."join" query?
1,210,711
<p>guys, how or where is the "join" query in Django?</p> <p>i think that Django dont have "join"..but how ill make join?</p> <p>Thanks </p>
4
2009-07-31T04:38:14Z
1,211,756
<p>SQL Join queries are a hack because SQL doesn't have objects or navigation among objects.</p> <p>Objects don't need "joins". Just access the related objects.</p>
-9
2009-07-31T10:09:20Z
[ "python", "django" ]
Django .."join" query?
1,210,711
<p>guys, how or where is the "join" query in Django?</p> <p>i think that Django dont have "join"..but how ill make join?</p> <p>Thanks </p>
4
2009-07-31T04:38:14Z
1,211,769
<p>If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.</p>
4
2009-07-31T10:13:25Z
[ "python", "django" ]
usage of generators as a progression notifier
1,211,035
<p>I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant...</p> <p>Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes).</p> <p>I use this module from a GUI written in wxpython and a console script. When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit... So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished.</p> <p>by doing that here's what it looks like:</p> <pre><code>dlg = wx.ProgressDialog("Movie processing", "Movie is being written...", maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame, parent=self, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT) state = self.engine.processMovie() f = state.next() while f != None: c, s = dlg.Update(f, "Processing frame %d"%f) if not c:break f = state.next() dlg.Destroy() </code></pre> <p>That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to.</p> <p>For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress...</p> <p>Anyone with another design that the one I came up with? (using threads, globals, processes, etc)</p> <p>There must be a design somewhere that does this job cleany I think :-)</p>
2
2009-07-31T06:53:59Z
1,211,093
<p>Using a generator is fine for this, but the whole point of using generators is so you can builtin syntax:</p> <pre><code>for f in self.engine.processMovie(): c, s = dlg.Update(f, "Processing frame %d"%f) if not c: break </code></pre> <p>If you don't care about that, then you can either say:</p> <pre><code>for f in self.engine.processMovie(): pass </code></pre> <p>or expose a function (eg. engine.processMovieFull) to do that for you.</p> <p>You could also use a plain callback:</p> <pre><code>def update_state(f): c, s = dlg.Update(f, "Processing frame %d"%f) return c self.engine.processMovie(progress=update_state) </code></pre> <p>... but that's not as nice if you want to process the data piecemeal; callback models prefer to do all the work at once--that's the real benefit of generators.</p>
2
2009-07-31T07:09:38Z
[ "python", "progress-bar", "generator" ]
usage of generators as a progression notifier
1,211,035
<p>I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant...</p> <p>Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes).</p> <p>I use this module from a GUI written in wxpython and a console script. When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit... So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished.</p> <p>by doing that here's what it looks like:</p> <pre><code>dlg = wx.ProgressDialog("Movie processing", "Movie is being written...", maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame, parent=self, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT) state = self.engine.processMovie() f = state.next() while f != None: c, s = dlg.Update(f, "Processing frame %d"%f) if not c:break f = state.next() dlg.Destroy() </code></pre> <p>That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to.</p> <p>For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress...</p> <p>Anyone with another design that the one I came up with? (using threads, globals, processes, etc)</p> <p>There must be a design somewhere that does this job cleany I think :-)</p>
2
2009-07-31T06:53:59Z
1,211,100
<p>First of all, if you use a generator, you might as well use it as an iterator:</p> <pre><code>state = self.engine.processMovie() for f in state: c, s = dlg.Update(f, "Processing frame %d"%f) if not c: break dlg.Destroy() </code></pre> <p>And don't yield <code>None</code>; stop yielding when you're done and leave the function; alternatively raise <code>StopIteration</code>. This is the correct way of ending generation (and when using a <code>for</code> loop, it's necessary).</p> <p>Other than that, I like the idea. In my opinion, this is a very valid use of generators.</p> <p>You might want to make the <code>33</code> configurable (i.e. passable to <code>processMovie</code> as a parameter); 33 seems like an arbitrary choice, and if your process a two-hour movie, there's no need to update the progress bar every 33 frames I guess.</p>
0
2009-07-31T07:11:52Z
[ "python", "progress-bar", "generator" ]
usage of generators as a progression notifier
1,211,035
<p>I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant...</p> <p>Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to several minutes).</p> <p>I use this module from a GUI written in wxpython and a console script. When I looked at how to implement progress dialogs in wxpython, I saw that I must get somehow a progress value to update my dialog, which is pure logic you'll admit... So I decided to use the number of frame processed in my engine functions, yield the current frame number every 33 frames and yield None when the processing is finished.</p> <p>by doing that here's what it looks like:</p> <pre><code>dlg = wx.ProgressDialog("Movie processing", "Movie is being written...", maximum = self.engine.endProcessingFrame,self.engine.startProcessingFrame, parent=self, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH | wx.PD_CAN_ABORT) state = self.engine.processMovie() f = state.next() while f != None: c, s = dlg.Update(f, "Processing frame %d"%f) if not c:break f = state.next() dlg.Destroy() </code></pre> <p>That works very well, there is absolutely no noticeable speed loss, but I would like to be able to call processMovie() function without having to deal with generators if I don't want to.</p> <p>For instance my console script which uses the engine module doesn't care of the progress, I could use it but it is destined to be executed in an environment where there is no display so I really don't care about the progress...</p> <p>Anyone with another design that the one I came up with? (using threads, globals, processes, etc)</p> <p>There must be a design somewhere that does this job cleany I think :-)</p>
2
2009-07-31T06:53:59Z
1,211,427
<p>This sounds like a perfect case for events. The process sends a "status update event", and anyone who wants to know (in this case the dialog) listens to that event.</p>
1
2009-07-31T09:02:56Z
[ "python", "progress-bar", "generator" ]
downloading files to users machine?
1,211,363
<p>I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.</p> <p>any ideas?</p>
0
2009-07-31T08:47:34Z
1,211,370
<p>You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be.</p> <p>You can do one of two things:</p> <ul> <li>count on the browser to cache the media file</li> <li>serve the media via some 3rd party plugin (Flash, for example)</li> </ul>
4
2009-07-31T08:49:37Z
[ "python", "django", "web-applications" ]
downloading files to users machine?
1,211,363
<p>I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.</p> <p>any ideas?</p>
0
2009-07-31T08:47:34Z
1,211,405
<p>I have no experience with this, but you could try your luck with <a href="http://www.w3.org/TR/webstorage/" rel="nofollow">DOM storage</a> in newer browsers:</p> <ul> <li><p><a href="http://msdn.microsoft.com/en-us/library/cc197062%28VS.85%29.aspx" rel="nofollow">IE8</a></p></li> <li><p><a href="https://developer.mozilla.org/en/DOM/Storage" rel="nofollow">FF>=2</a></p></li> <li><p>Opera > 9.5, as I have read somewhere</p></li> <li><p>Safari and Chrome should implement it, too, I guess</p></li> </ul> <p><a href="http://ejohn.org/blog/dom-storage/" rel="nofollow">Here's</a> an article by John Resig about that.</p> <p>However, if questions contain something like 'without the user's knowledge' or 'without the user having to agree', typically the one asking really should reconsider his/her thoughts about the visitors and what is or isn't good for them.</p> <p>Cheers,</p>
0
2009-07-31T08:56:13Z
[ "python", "django", "web-applications" ]
downloading files to users machine?
1,211,363
<p>I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.</p> <p>any ideas?</p>
0
2009-07-31T08:47:34Z
1,211,434
<p>Don't do this.</p> <p>Most files are cached anyway.</p> <p>But if you really want to add this (because users asked for it), make it optional (default off).</p>
2
2009-07-31T09:04:04Z
[ "python", "django", "web-applications" ]
wxPython: Changing the color scheme of a wx.stc.StyledTextCtrl
1,211,380
<p>I have a PyShell, which is supposed to be derived from <code>wx.stc.StyledTextCtrl</code>. How do I change the color scheme it uses?</p>
1
2009-07-31T08:51:06Z
1,272,807
<p>You can use styledTextCtrl.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, "fore:#CDCDCD") (Bunch of .StyleSetSpec properties) ... ... ... styCtrl.SetCaretForeground("BLUE") styCtrl.SetSelBackground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)) styCtrl.SetSelForeground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)) ... (Bunch of Set*() commands)</p> <p>Don't know if there is a way to load a pre-defined color scheme. You could define it in YAML and load it up via the commands above and more.</p>
0
2009-08-13T15:43:17Z
[ "python", "user-interface", "wxpython", "color-scheme" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
1,211,512
<p>Proprietary TestTrack (<a href="http://www.seapine.com/ttpro.html" rel="nofollow">http://www.seapine.com/ttpro.html</a>) has a client edition that will those things. We use it at work and I'm very happy using it.</p> <p>Maybe you can check out this wikipedia article for hints <a href="http://en.wikipedia.org/wiki/Comparison_of_issue_tracking_systems" rel="nofollow">http://en.wikipedia.org/wiki/Comparison_of_issue_tracking_systems</a> </p>
0
2009-07-31T09:18:50Z
[ "python", "windows", "bug-tracking", "non-web" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
1,213,232
<p>Trac might be a bit too over engineered, but you could still run it locally via tracd on localhost.</p> <p>It's:</p> <ul> <li>opensource.</li> <li>pure Python</li> <li>uses sqlite</li> </ul> <p>But as I said, might be too complex for your use case.</p> <p>Link: <a href="http://trac.edgewall.org">http://trac.edgewall.org</a></p>
8
2009-07-31T15:34:22Z
[ "python", "windows", "bug-tracking", "non-web" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
1,214,018
<p>Do yourself a favor. Get over this "must not be web based" obsession, Install a local WAMP stack on your PC or on a LAN server. Now, you can install your own <a href="http://lifehacker.com/software/wikipedia/geek-to-live-set-up-your-personal-wikipedia-163707.php" rel="nofollow">wiki</a>. And something like Trac. I'd like to find an implementation of google code's bugtracker and integrated wiki thats runnable locally - <a href="http://trac.edgewall.org/wiki/TracDownload" rel="nofollow">Trac</a> seems to be the closest.</p> <p>You have also installed a local SVN server? Even for personal projects the ability to track changes over time. revert etc. and integration with Trac are too good to pass up even for purely 1 man projects.</p>
-12
2009-07-31T18:09:02Z
[ "python", "windows", "bug-tracking", "non-web" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
1,508,002
<p>Maybe <a href="http://www.fossil-scm.org/" rel="nofollow">Fossil</a> is of any use to you?</p> <p>It is actually a DVCS but it also integrates a bugtracker and wiki, very much like trac (although I like trac, don't get me wrong). And its webbased, on the other hand the installation is supossedly dead simple.</p>
2
2009-10-02T06:30:43Z
[ "python", "windows", "bug-tracking", "non-web" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
1,508,055
<p>I'm surprised nobody has mentioned <a href="http://roundup.sourceforge.net/">Roundup</a>.</p> <p>It meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac).</p> <p>Roundup is:</p> <ul> <li>Open source</li> <li>Pure Python</li> <li>Supports SQLite</li> <li>Not fancy, focuses on solid bug tracking</li> </ul> <p>And as a significant point of differentiation, it has command-line and email interfaces in addition to a web interface.</p> <p>It's very easy to get started - I suggest you take it for a spin.</p>
8
2009-10-02T06:50:29Z
[ "python", "windows", "bug-tracking", "non-web" ]
Simple non-web based bug tracker
1,211,463
<p>There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.</p> <ul> <li>very preferably open-source</li> <li>pure Python or (at least) Windows executable</li> <li>no need for a database server (sqlite is obviously fine)</li> <li>Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.</li> </ul> <p>Any suggestions?</p>
9
2009-07-31T09:10:19Z
2,016,533
<p>If you don't need to share your bug tracker system with a team (i.e., it's okay to have it isolated to your computer) I would recommend using <a href="http://www.tiddlywiki.com/">Tiddlywiki</a>. Technically it's web-based, but it's entirely encapsulated within a single HTML document and requires no database or server whatsoever (only a web browser) so I think it follows the spirit of what you are wanting. It's extremely customizable since it's 100% HTML/CSS/javascript. I have been using a tiddlywiki as a project notebook for years, keeping track of my to-do list, bug list, and general project documentation in one centralized, cross-referenced place. You can also find all sorts of tiddlywikis that you can download pre-configured for productivity (for example, <a href="http://www.getteamtasks.com/">TeamTasks</a>, <a href="http://monkeygtd.tiddlyspot.com/">MonkeyGTD</a>, or <a href="http://www.checkettsweb.com/tw/gtd_tiddlywiki.htm">GTDTiddlyWiki Plus</a>).</p>
6
2010-01-06T21:50:14Z
[ "python", "windows", "bug-tracking", "non-web" ]
Python: high precision time.sleep
1,211,806
<p>can you tell me how can I get a high precision sleep-function in Python2.6 on Win32 and on Linux?</p>
27
2009-07-31T10:25:43Z
1,211,827
<p>You can use floating-point numbers in <a href="http://docs.python.org/library/time.html#time.sleep"><code>sleep()</code></a>:</p> <blockquote> <p>The argument may be a floating point number to indicate a more precise sleep time.</p> </blockquote> <p>So</p> <pre><code>time.sleep(0.5) </code></pre> <p>will sleep for half a second.</p> <p>In practice, however, it's unlikely that you will get much more than millisecond precision with sleep because operating systems usually only support millisecond sleeps and because very short amounts of time quickly get unreliable.</p>
45
2009-07-31T10:32:42Z
[ "python" ]
Python: high precision time.sleep
1,211,806
<p>can you tell me how can I get a high precision sleep-function in Python2.6 on Win32 and on Linux?</p>
27
2009-07-31T10:25:43Z
1,212,070
<p>Here is a similar question:</p> <p><a href="http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep">how-accurate-is-pythons-time-sleep</a></p> <p>On <strong>linux</strong> if you need high accuracy you might want to look into using ctypes to call <a href="http://linux.die.net/man/2/nanosleep">nanosleep()</a> or <a href="http://linux.die.net/man/2/clock%5Fnanosleep">clock_nanosleep()</a>. I'm not sure of all the implications of trying that though.</p>
7
2009-07-31T11:38:35Z
[ "python" ]
m2crypto throws "TypeError: in method 'x509_req_set_pubkey'"
1,211,843
<p>Guys, my little code snippet throws the following Traceback:</p> <pre><code>..++++++++++++ ..++++++++++++ Traceback (most recent call last): File "csr.py", line 48, in &lt;module&gt; csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(EVP.PKey(keypair)) File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey return m2.x509_req_set_pubkey( self.req, pkey.pkey ) TypeError: in method 'x509_req_set_pubkey', argument 2 of type 'EVP_PKEY *' </code></pre> <p>I do not understand whats going on here... here are my two python modules:</p> <pre><code>from config import * from keypair import * from M2Crypto import X509 class CSR(object): def __init__(self): pass def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None): # create a certificate signing request object cert_request = X509.Request() # set certificate version to 3 cert_request.set_version(3) # which rsa public key should be used? cert_request.set_pubkey(EVP.PKey(keypair)) # create an subject for the certificate request cert_request.set_subject_name(cert_name) if cert_extension_stack != None: # add the extensions to the request cert_request.add_extensions(cert_extension_stack) # sign the request using the RSA key pair cert_request.sign(keypair, 'sha1') return cert_request if __name__ == "__main__": csr = CSR() cert_name = X509.X509_Name() keyp = Keypair() keyp.create_keypair() keyp.save_keypair("host.key") pubkey = keyp.get_keypair() cert_name.C = "GB" cert_name.ST = "Greater Manchester" cert_name.L = "Salford" cert_name.O = "COMODO CA Limited" cert_name.CN = "COMODO Certification Authority" cert_name.OU = "Information Technology" cert_name.Email = "contact@comodo.com" csr.create_cert_signing_request(pubkey, cert_name) from M2Crypto import X509, m2, RSA, EVP from config import * class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): self.keypair.save_key(filename, None) def load_keypair(self, filename): self.keypair = EVP.load_key(filename) def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": key = Keypair() key.create_keypair() key.save_keypair("test.key") print key.get_keypair() print key.get_public_key() </code></pre> <p>I really would be happy if someone could give me a helping hand on this! </p>
0
2009-07-31T10:37:51Z
1,212,261
<p>If I change <strong>"cert_request.set_pubkey(EVP.PKey(keypair))"</strong> to <strong>"cert_request.set_pubkey(keypair)"</strong> I receive the following Traceback instead. This confuses me even more... </p> <pre><code>Traceback (most recent call last): File "csr.py", line 48, in &lt;module&gt; csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(keypair) File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey return m2.x509_req_set_pubkey( self.req, pkey.pkey ) AttributeError: 'CSR' object has no attribute 'pkey' </code></pre>
0
2009-07-31T12:25:09Z
[ "python", "m2crypto" ]
Text formatting in different versions of Python
1,212,108
<p>I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.</p> <p>In python &lt; 2.6, it's done like this:</p> <pre><code>n = 3 print "%s * %s = %s" % (n, n, n*n) </code></pre> <p>whereas in python >= 2.6 the <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow">best way to do it</a> is:</p> <pre><code>n = 3 print "{0} * {0} = {1}".format(n, n*n) </code></pre> <p>But how about when you want the script to be runned in any python version? What's better, to write python&lt;2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?</p> <p>Is there any other option to write code for the actual python versions without loosing compatibility with olders?</p> <p>Thanks</p>
2
2009-07-31T11:48:35Z
1,212,140
<p>str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0.</p> <p>In Python 2.6 both methods will still work, of course. </p> <p>It all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then stick with the old formatting.</p> <p>However, if there is some must-have feature in Python 3.0 that you require for your project, then its not unreasonable to require your users to use a specific version of the interpreter. Keep in mind though that Python 3.0 breaks some pre 3.0 code.</p> <p>So in summary, if you're targeting Python 3.0, use str.format(). If you're targeting Pyhon &lt;3.0, use % formatting.</p>
3
2009-07-31T11:57:31Z
[ "python", "formatting" ]
Text formatting in different versions of Python
1,212,108
<p>I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.</p> <p>In python &lt; 2.6, it's done like this:</p> <pre><code>n = 3 print "%s * %s = %s" % (n, n, n*n) </code></pre> <p>whereas in python >= 2.6 the <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow">best way to do it</a> is:</p> <pre><code>n = 3 print "{0} * {0} = {1}".format(n, n*n) </code></pre> <p>But how about when you want the script to be runned in any python version? What's better, to write python&lt;2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?</p> <p>Is there any other option to write code for the actual python versions without loosing compatibility with olders?</p> <p>Thanks</p>
2
2009-07-31T11:48:35Z
1,212,602
<p>What about the good old tuple or string concatenation?</p> <pre><code>print n, "*", n, "=", n*n #or print str(n) + " * " + str(n) + " = " + str(n*n) </code></pre> <p>it's not as fancy, but should work in any version.</p> <p>if it's too verbose, maybe a custom function could help:</p> <pre><code>def format(fmt, values, sep="%%"): return "".join(str(j) for i in zip(fmt.split(sep), values) for j in i) #usage format("%% * %% = %%", [n, n, n*n]) </code></pre>
1
2009-07-31T13:41:49Z
[ "python", "formatting" ]
Text formatting in different versions of Python
1,212,108
<p>I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.</p> <p>In python &lt; 2.6, it's done like this:</p> <pre><code>n = 3 print "%s * %s = %s" % (n, n, n*n) </code></pre> <p>whereas in python >= 2.6 the <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow">best way to do it</a> is:</p> <pre><code>n = 3 print "{0} * {0} = {1}".format(n, n*n) </code></pre> <p>But how about when you want the script to be runned in any python version? What's better, to write python&lt;2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?</p> <p>Is there any other option to write code for the actual python versions without loosing compatibility with olders?</p> <p>Thanks</p>
2
2009-07-31T11:48:35Z
1,214,844
<p>You should have a look at the <a href="http://docs.python.org/3.1/library/string.html#template-strings" rel="nofollow">string.Template (link for 3.1)</a> way to format a string, the API is stable across all versions >=2.5. I think that concatenation is the simple way to achieve portability for both old and new Python versions. Obviously it's slow, verbose and less pythonic than alternatives.</p>
0
2009-07-31T20:53:08Z
[ "python", "formatting" ]
How to create a property with its name in a string?
1,212,434
<p>Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:</p> <pre><code>blah = property(get_blah, set_blah, del_blah, "bleh blih") </code></pre> <p>where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:</p> <pre><code>setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) </code></pre> <p>But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <code>&lt;property object at 0xbb1aa0&gt;</code>. How should I define it so it works?</p>
3
2009-07-31T13:06:47Z
1,212,553
<p>One way is to write into locals():</p> <pre><code>class X: for attr in ["a","b","c"]: def getter(self, name=attr): return name+"_value" locals()[attr] = property(getter, None, None, attr) x = X() print x.a print x.b print x.c </code></pre> <p>gives</p> <pre><code>a_value b_value c_value </code></pre>
1
2009-07-31T13:30:55Z
[ "python", "properties", "setattr" ]
How to create a property with its name in a string?
1,212,434
<p>Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:</p> <pre><code>blah = property(get_blah, set_blah, del_blah, "bleh blih") </code></pre> <p>where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:</p> <pre><code>setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) </code></pre> <p>But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <code>&lt;property object at 0xbb1aa0&gt;</code>. How should I define it so it works?</p>
3
2009-07-31T13:06:47Z
1,212,561
<p>If I understand what you're trying to do, you could accomplish it by overriding the class's <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattr%5F%5F" rel="nofollow"><strong>getattr</strong></a> and <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fsetattr%5F%5F" rel="nofollow"><strong>setattr</strong></a> methods.</p> <p>For example:</p> <pre><code>class Something(object): def __getattr__(self, name): # The name of the property retrieved is a string called name return "You're getting %s" % name something = Something() print something.foo print something.bar </code></pre> <p>Will print:</p> <pre><code>You're getting foo You're getting bar </code></pre> <p>This way you can have a generic getter and setter that has the name of the property in a string and does something with it accordingly.</p>
1
2009-07-31T13:33:37Z
[ "python", "properties", "setattr" ]
How to create a property with its name in a string?
1,212,434
<p>Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:</p> <pre><code>blah = property(get_blah, set_blah, del_blah, "bleh blih") </code></pre> <p>where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this:</p> <pre><code>setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) </code></pre> <p>But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is <code>&lt;property object at 0xbb1aa0&gt;</code>. How should I define it so it works?</p>
3
2009-07-31T13:06:47Z
1,212,588
<p>As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!).</p> <p>How about this version:</p> <pre><code>setattr(MyClass, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) </code></pre> <p>you can also do this:</p> <pre><code>setattr(type(self), "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) </code></pre>
2
2009-07-31T13:38:45Z
[ "python", "properties", "setattr" ]
How to get information about a function and call it
1,212,649
<p>I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(</p>
2
2009-07-31T13:48:56Z
1,212,657
<p>Python supports <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping" rel="nofollow">duck typing</a> - simply call the method on the instance.</p>
1
2009-07-31T13:49:57Z
[ "python" ]
How to get information about a function and call it
1,212,649
<p>I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(</p>
2
2009-07-31T13:48:56Z
1,212,662
<p>Try <code>hasattr</code></p> <pre><code>&gt;&gt;&gt; help(hasattr) Help on built-in function hasattr in module __builtin__: hasattr(...) hasattr(object, name) -&gt; bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.) </code></pre> <p>For more advanced introspection read about the <code>inspect</code> module.</p> <p>But first, tell us why you need this. There's a 99% chance that a better way exists...</p>
3
2009-07-31T13:50:45Z
[ "python" ]
How to get information about a function and call it
1,212,649
<p>I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(</p>
2
2009-07-31T13:48:56Z
1,212,817
<p>Are you trying to align argument values with a function that has a unknown signature?</p> <p>How will you match up argument values and parameter variables? Guess?</p> <p>You'd have to use some kind of name matching.</p> <p>For example something like this.</p> <pre><code>someObject.someMethod( thisParam=aValue, thatParam=anotherValue ) </code></pre> <p>Oh. Wait. That's already a first-class part of Python.</p> <p>But what if the method doesn't exist (for inexplicable reasons).</p> <pre><code>try: someObject.someMethod( thisParam=aValue, thatParam=anotherValue ) except AttributeError: method doesn't exist. </code></pre>
0
2009-07-31T14:22:20Z
[ "python" ]
How to get information about a function and call it
1,212,649
<p>I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(</p>
2
2009-07-31T13:48:56Z
1,212,911
<pre><code>class Test(object): def say_hello(name,msg = "Hello"): return name +' '+msg def foo(obj,method_name): import inspect # dir gives info about attributes of an object if method_name in dir(obj): attr_info = eval('inspect.getargspec(obj.%s)'%method_name) # here you can implement logic to call the method # using attribute information return 'Done' else: return 'Method: %s not found for %s'%(method_name,obj.__str__) if __name__=='__main__': o1 = Test() print(foo(o1,'say_hello')) print(foo(o1,'say_bye')) </code></pre> <p>I think <strong><code>inspect</code></strong> module will be of very much help to you. Main functions used in above code are <strong><code>dir,eval,inspect.getargspec</code></strong>. You can get related help in python docs.</p>
0
2009-07-31T14:38:19Z
[ "python" ]
Python Interpreter blocks Multithreaded DNS requests?
1,212,716
<p>I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:</p> <p>from threading import Thread import socket</p> <pre><code>class Connection(Thread): def __init__(self, name, url): Thread.__init__(self) self._url = url self._name = name def run(self): print "Connecting...", self._name try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.connect((self._url, 80)) except socket.gaierror: pass #not interested in it print "finished", self._name if __name__ == '__main__': conns = [] # all invalid addresses to see how they fail / check times conns.append(Connection("conn1", "www.2eg11erdhrtj.com")) conns.append(Connection("conn2", "www.e2ger2dh2rtj.com")) conns.append(Connection("conn3", "www.eg2de3rh1rtj.com")) conns.append(Connection("conn4", "www.ege2rh4rd1tj.com")) conns.append(Connection("conn5", "www.ege52drhrtj1.com")) for conn in conns: conn.start() </code></pre> <p>I dont know exactly how long the timeout is, but when running this the following happens:</p> <ol> <li>All Threads start and I get my printouts</li> <li>Every xx seconds, one thread displays finished, instead of all at once</li> <li>The Threads finish sequentially, not all at once (timeout = same for all!)</li> </ol> <p>So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.</p> <p>Does anyone know a way around this?</p> <p>(<strong>asyncore</strong> doesnt help, and I'd prefer not to use <strong>twisted</strong> for now) Isn't it possible to get this simple little thing done with python?</p> <p>Greetings, Tom</p> <h1>edit:</h1> <p>I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.</p> <p>Can anyone explain this?</p>
7
2009-07-31T14:03:56Z
1,212,821
<p>On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends).</p> <p>So if you can't switch operating systems, you'll have to use a different (thread-safe) resolver library, such as twisted's.</p>
15
2009-07-31T14:23:30Z
[ "python", "multithreading", "network-programming" ]
Python Interpreter blocks Multithreaded DNS requests?
1,212,716
<p>I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:</p> <p>from threading import Thread import socket</p> <pre><code>class Connection(Thread): def __init__(self, name, url): Thread.__init__(self) self._url = url self._name = name def run(self): print "Connecting...", self._name try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.connect((self._url, 80)) except socket.gaierror: pass #not interested in it print "finished", self._name if __name__ == '__main__': conns = [] # all invalid addresses to see how they fail / check times conns.append(Connection("conn1", "www.2eg11erdhrtj.com")) conns.append(Connection("conn2", "www.e2ger2dh2rtj.com")) conns.append(Connection("conn3", "www.eg2de3rh1rtj.com")) conns.append(Connection("conn4", "www.ege2rh4rd1tj.com")) conns.append(Connection("conn5", "www.ege52drhrtj1.com")) for conn in conns: conn.start() </code></pre> <p>I dont know exactly how long the timeout is, but when running this the following happens:</p> <ol> <li>All Threads start and I get my printouts</li> <li>Every xx seconds, one thread displays finished, instead of all at once</li> <li>The Threads finish sequentially, not all at once (timeout = same for all!)</li> </ol> <p>So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.</p> <p>Does anyone know a way around this?</p> <p>(<strong>asyncore</strong> doesnt help, and I'd prefer not to use <strong>twisted</strong> for now) Isn't it possible to get this simple little thing done with python?</p> <p>Greetings, Tom</p> <h1>edit:</h1> <p>I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.</p> <p>Can anyone explain this?</p>
7
2009-07-31T14:03:56Z
1,234,581
<p>if it's suitable you could use the <code>multiprocessing</code> module to enable process-based parallelism</p> <pre><code>import multiprocessing, socket NUM_PROCESSES = 5 def get_url(url): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.connect((url, 80)) except socket.gaierror: pass #not interested in it return 'finished ' + url def main(url_list): pool = multiprocessing.Pool( NUM_PROCESSES ) for output in pool.imap_unordered(get_url, url_list): print output if __name__=="__main__": main(""" www.2eg11erdhrtj.com www.e2ger2dh2rtj.com www.eg2de3rh1rtj.com www.ege2rh4rd1tj.com www.ege52drhrtj1.com """.split()) </code></pre>
2
2009-08-05T17:15:36Z
[ "python", "multithreading", "network-programming" ]
Python Interpreter blocks Multithreaded DNS requests?
1,212,716
<p>I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:</p> <p>from threading import Thread import socket</p> <pre><code>class Connection(Thread): def __init__(self, name, url): Thread.__init__(self) self._url = url self._name = name def run(self): print "Connecting...", self._name try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.connect((self._url, 80)) except socket.gaierror: pass #not interested in it print "finished", self._name if __name__ == '__main__': conns = [] # all invalid addresses to see how they fail / check times conns.append(Connection("conn1", "www.2eg11erdhrtj.com")) conns.append(Connection("conn2", "www.e2ger2dh2rtj.com")) conns.append(Connection("conn3", "www.eg2de3rh1rtj.com")) conns.append(Connection("conn4", "www.ege2rh4rd1tj.com")) conns.append(Connection("conn5", "www.ege52drhrtj1.com")) for conn in conns: conn.start() </code></pre> <p>I dont know exactly how long the timeout is, but when running this the following happens:</p> <ol> <li>All Threads start and I get my printouts</li> <li>Every xx seconds, one thread displays finished, instead of all at once</li> <li>The Threads finish sequentially, not all at once (timeout = same for all!)</li> </ol> <p>So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.</p> <p>Does anyone know a way around this?</p> <p>(<strong>asyncore</strong> doesnt help, and I'd prefer not to use <strong>twisted</strong> for now) Isn't it possible to get this simple little thing done with python?</p> <p>Greetings, Tom</p> <h1>edit:</h1> <p>I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.</p> <p>Can anyone explain this?</p>
7
2009-07-31T14:03:56Z
4,210,277
<p>Send DNS requests asynchronously using <a href="http://twistedmatrix.com/trac/wiki/TwistedNames" rel="nofollow">Twisted Names</a>: </p> <pre><code>import sys from twisted.internet import reactor from twisted.internet import defer from twisted.names import client from twisted.python import log def process_names(names): log.startLogging(sys.stderr, setStdout=False) def print_results(results): for name, (success, result) in zip(names, results): if success: print "%s -&gt; %s" % (name, result) else: print &gt;&gt;sys.stderr, "error: %s failed. Reason: %s" % ( name, result) d = defer.DeferredList(map(client.getHostByName, names), consumeErrors=True) d.addCallback(print_results) d.addErrback(defer.logError) d.addBoth(lambda _: reactor.stop()) reactor.callWhenRunning(process_names, """ google.com www.2eg11erdhrtj.com www.e2ger2dh2rtj.com www.eg2de3rh1rtj.com www.ege2rh4rd1tj.com www.ege52drhrtj1.com """.split()) reactor.run() </code></pre>
1
2010-11-17T23:29:20Z
[ "python", "multithreading", "network-programming" ]
Detecting when a python script is being run interactively in ipython
1,212,779
<p>Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable?</p> <p>Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts interactively for debugging and profiling, usually in ipython. When I'm running interactively, I want to suppress the calls to exit. </p> <p><strong>Clarification</strong>: </p> <p>Suppose I have a script, myscript.py, that looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... exit(exit_status) </code></pre> <p>Sometimes, I want to run the script within an IPython session that I have already started, saying something like:</p> <pre><code>In [nnn]: %run -p -D myscript.pstats myscript.py </code></pre> <p>At the end of the script, the exit() call will cause ipython to hang while it asks me if I really want to exit. This is a minor annoyance while debugging (too minor for me to care), but it can mess up profiling results: the exit prompt gets included in the profile results (making the analysis harder if I start a profiling session before going off to lunch). </p> <p>What I'd like is something that allows me modify my script so it looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... if is_python_running_interactively(): print "The exit_status was %d" % (exit_status,) else: exit(exit_status) </code></pre>
5
2009-07-31T14:15:58Z
1,212,807
<p>When invoked interactively, python will run the script in $PYTHONSTARTUP, so you could simply have that environment variable invoke a script which sets a global</p>
2
2009-07-31T14:21:01Z
[ "python", "interactive", "ipython" ]
Detecting when a python script is being run interactively in ipython
1,212,779
<p>Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable?</p> <p>Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts interactively for debugging and profiling, usually in ipython. When I'm running interactively, I want to suppress the calls to exit. </p> <p><strong>Clarification</strong>: </p> <p>Suppose I have a script, myscript.py, that looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... exit(exit_status) </code></pre> <p>Sometimes, I want to run the script within an IPython session that I have already started, saying something like:</p> <pre><code>In [nnn]: %run -p -D myscript.pstats myscript.py </code></pre> <p>At the end of the script, the exit() call will cause ipython to hang while it asks me if I really want to exit. This is a minor annoyance while debugging (too minor for me to care), but it can mess up profiling results: the exit prompt gets included in the profile results (making the analysis harder if I start a profiling session before going off to lunch). </p> <p>What I'd like is something that allows me modify my script so it looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... if is_python_running_interactively(): print "The exit_status was %d" % (exit_status,) else: exit(exit_status) </code></pre>
5
2009-07-31T14:15:58Z
1,212,907
<p>I stumbed on the following and it seems to do the trick for me:</p> <pre><code>def in_ipython(): try: __IPYTHON__ except NameError: return False else: return True </code></pre>
11
2009-07-31T14:37:48Z
[ "python", "interactive", "ipython" ]
Detecting when a python script is being run interactively in ipython
1,212,779
<p>Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable?</p> <p>Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts interactively for debugging and profiling, usually in ipython. When I'm running interactively, I want to suppress the calls to exit. </p> <p><strong>Clarification</strong>: </p> <p>Suppose I have a script, myscript.py, that looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... exit(exit_status) </code></pre> <p>Sometimes, I want to run the script within an IPython session that I have already started, saying something like:</p> <pre><code>In [nnn]: %run -p -D myscript.pstats myscript.py </code></pre> <p>At the end of the script, the exit() call will cause ipython to hang while it asks me if I really want to exit. This is a minor annoyance while debugging (too minor for me to care), but it can mess up profiling results: the exit prompt gets included in the profile results (making the analysis harder if I start a profiling session before going off to lunch). </p> <p>What I'd like is something that allows me modify my script so it looks like:</p> <pre><code>#!/usr/bin/python ...do useful stuff... if is_python_running_interactively(): print "The exit_status was %d" % (exit_status,) else: exit(exit_status) </code></pre>
5
2009-07-31T14:15:58Z
6,675,649
<p>Docs say that <code>sys.ps1</code> doesn't exist in noninteractive mode. Additionally, one can use <code>sys.flags</code> (for python 2.6+) to detect if we have used <code>python -i &lt;whatever&gt;</code>.</p> <p>This scripts detects if we run interactively, non-interactively, and in post-mortem mode (which may be attributed to interactive mode if python interpreter is called using <code>python -i</code> implicitly and user thinks he landed into "interactive" console):</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sys # IPython recognition is missing; test here if __IPYTHON__ exists, etc. if hasattr(sys, 'ps1'): print "Running interactively." else: print "Not running interactively..." if sys.flags.interactive: print "... but I'm in interactive postmortem mode." </code></pre> <p>IPython support can be added as described by Mr Fooz.</p>
3
2011-07-13T07:44:04Z
[ "python", "interactive", "ipython" ]
Threaded application + IntegrityError
1,212,864
<p><br /> I have python threaded application + Postgres. I am using Django's ORM to save to Postgres..<br /> I have concurrent save calls. Occasionally 2 threads save with the same primary key which leads to an issue. </p> <p>Postgres log:<br /> ERROR: duplicate key value violates unique constraint "store_pkey"<br /> STATEMENT: INSERT INTO "store" ("store_id", "address") VALUES (E'HAN277', E'101 Ocean Street') </p> <p>Code:<br /> In the code I see an IntegrityError. I tried different ways to handle this. </p> <p>a.<br /> try:<br /> a.save()<br /> except IntegrityError:<br /> pass </p> <p>This causes InternalError </p> <p>b. Tried to do transaction roll back.. but not sure.. As far as I understand you need to distinct save calls to have transactions</p> <pre><code> sid = transaction.savepoint() try: row.save() except IntegrityError, e: transaction.savepoint_rollback(sid) pass transaction.commit() </code></pre> <p>The first savepoint fails with</p> <p>AttributeError: 'NoneType' object has no attribute 'cursor'</p> <p>a. I read somewhere django is not 100% thread safe. Is it a good choice in my usecase. I was already using Django for other application and need an ORM.. So naturally I chose Django<br /> b. How to handle this situation.. Any comments. </p> <p>Thanks and regards, Ramya </p>
1
2009-07-31T14:31:12Z
1,213,201
<p>Just to make sure, you're using strings for primary keys if I understand correctly?</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'cursor'</p> </blockquote> <p>This means there's an error in some Python code. Have you tried using another version or revision of Django or searching the Django trac for your bug? It isn't so uncommon to be affected by some bug if you're using version from trunk.</p> <p>As an alternative you could also try to deploy Django using multiple processes instead of multiple threads if that's an option.</p> <p>However, you might still want to find out why you're getting duplicate requests as it might uncover some other bug.</p>
2
2009-07-31T15:30:22Z
[ "python", "django", "postgresql", "thread-safety" ]
pygtk: Draw lines onto a gtk.gdk.Pixbuf
1,213,090
<p>I'm using pygtk with PIL. I've already figured out a way to convert PIL <code>Image</code>s to <code>gtk.gdk.Pixbuf</code>s. What I do to display the pixbuf is I create a <code>gtk.gdk.Image</code>, and then use <code>img.set_from_pixbuf</code>. I now want to draw a few lines onto this image. Apparently I need a <code>Drawable</code> to do that. I've started looking through the docs but already I have 8-10 windows open and it is not being straightforward at all. </p> <p>So - what magic do I need to type to get a Drawable representing my picture, draw some things on to it, and then turn it into a <code>gdk.Image</code> so I can display it on my app?</p>
3
2009-07-31T15:10:41Z
1,213,148
<p>Have you tried cairo context? sorry i seem cant comment on your post. hence i posted it here.</p> <p>I haven't tried this myself but I believe that cairo is your friend when it comes to drawing in gtk. you can set the source of your cairo context as pixbuf so i think this is usable for you.</p> <p><a href="http://www.pygtk.org/docs/pygtk/class-gdkcairocontext.html" rel="nofollow">gdkcairocontext</a></p>
1
2009-07-31T15:20:58Z
[ "python", "gtk", "drawing", "pygtk" ]
pygtk: Draw lines onto a gtk.gdk.Pixbuf
1,213,090
<p>I'm using pygtk with PIL. I've already figured out a way to convert PIL <code>Image</code>s to <code>gtk.gdk.Pixbuf</code>s. What I do to display the pixbuf is I create a <code>gtk.gdk.Image</code>, and then use <code>img.set_from_pixbuf</code>. I now want to draw a few lines onto this image. Apparently I need a <code>Drawable</code> to do that. I've started looking through the docs but already I have 8-10 windows open and it is not being straightforward at all. </p> <p>So - what magic do I need to type to get a Drawable representing my picture, draw some things on to it, and then turn it into a <code>gdk.Image</code> so I can display it on my app?</p>
3
2009-07-31T15:10:41Z
1,213,220
<p>Oh my god. So painful. Here it is:</p> <pre><code> w,h = pixbuf.get_width(), pixbuf.get_height() drawable = gtk.gdk.Pixmap(None, w, h, 24) gc = drawable.new_gc() drawable.draw_pixbuf(gc, pixbuf, 0, 0, 0, 0, -1, -1) #---ACTUAL DRAWING CODE--- gc.set_foreground(gtk.gdk.Color(65535, 0, 0)) drawable.draw_line(gc, 0, 0, w, h) #------------------------- cmap = gtk.gdk.Colormap(gtk.gdk.visual_get_best(), False) pixbuf.get_from_drawable(drawable, cmap, 0, 0, 0, 0, w, h) </code></pre> <p>It actually draws a black line ATM, not a red one, so I have some work left to do...</p>
3
2009-07-31T15:32:50Z
[ "python", "gtk", "drawing", "pygtk" ]
pygtk: Draw lines onto a gtk.gdk.Pixbuf
1,213,090
<p>I'm using pygtk with PIL. I've already figured out a way to convert PIL <code>Image</code>s to <code>gtk.gdk.Pixbuf</code>s. What I do to display the pixbuf is I create a <code>gtk.gdk.Image</code>, and then use <code>img.set_from_pixbuf</code>. I now want to draw a few lines onto this image. Apparently I need a <code>Drawable</code> to do that. I've started looking through the docs but already I have 8-10 windows open and it is not being straightforward at all. </p> <p>So - what magic do I need to type to get a Drawable representing my picture, draw some things on to it, and then turn it into a <code>gdk.Image</code> so I can display it on my app?</p>
3
2009-07-31T15:10:41Z
1,213,535
<p>I was doing something similar (drawing to a gdk.Drawable), and I found that set_foreground doesn't work. To actually draw using the color I wanted, I had to use the following:</p> <pre><code># Red! gc.set_rgb_fg_color(gtk.gdk.Color(0xff, 0x0, 0x0)) </code></pre>
4
2009-07-31T16:25:41Z
[ "python", "gtk", "drawing", "pygtk" ]
pygtk: Draw lines onto a gtk.gdk.Pixbuf
1,213,090
<p>I'm using pygtk with PIL. I've already figured out a way to convert PIL <code>Image</code>s to <code>gtk.gdk.Pixbuf</code>s. What I do to display the pixbuf is I create a <code>gtk.gdk.Image</code>, and then use <code>img.set_from_pixbuf</code>. I now want to draw a few lines onto this image. Apparently I need a <code>Drawable</code> to do that. I've started looking through the docs but already I have 8-10 windows open and it is not being straightforward at all. </p> <p>So - what magic do I need to type to get a Drawable representing my picture, draw some things on to it, and then turn it into a <code>gdk.Image</code> so I can display it on my app?</p>
3
2009-07-31T15:10:41Z
1,485,053
<pre><code>image = gtk.Image() pixmap,mask = pixbuf.render_pixmap_and_mask() # Function call cm = pixmap.get_colormap() red = cm.alloc_color('red') gc = pixmap.new_gc(foreground=red) pixmap.draw_line(gc,0,0,w,h) image.set_from_pixmap(pixmap,mask) </code></pre> <p>Should do the trick.</p>
1
2009-09-28T01:42:54Z
[ "python", "gtk", "drawing", "pygtk" ]
pygtk: Draw lines onto a gtk.gdk.Pixbuf
1,213,090
<p>I'm using pygtk with PIL. I've already figured out a way to convert PIL <code>Image</code>s to <code>gtk.gdk.Pixbuf</code>s. What I do to display the pixbuf is I create a <code>gtk.gdk.Image</code>, and then use <code>img.set_from_pixbuf</code>. I now want to draw a few lines onto this image. Apparently I need a <code>Drawable</code> to do that. I've started looking through the docs but already I have 8-10 windows open and it is not being straightforward at all. </p> <p>So - what magic do I need to type to get a Drawable representing my picture, draw some things on to it, and then turn it into a <code>gdk.Image</code> so I can display it on my app?</p>
3
2009-07-31T15:10:41Z
6,578,903
<p>You should connect to the <code>expose-event</code> (GTK 2) or <code>draw</code> (GTK 3) signal. In that handler, simply use <code>image.window</code> to get the widget's <code>gtk.gdk.Window</code>; this is a subclass of <code>gtk.gdk.Drawable</code>, so you can draw on it.</p>
1
2011-07-05T06:51:48Z
[ "python", "gtk", "drawing", "pygtk" ]
Handling Swing focus events with Jython
1,213,295
<p>Jython 2.5</p> <p>I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instance)</p> <pre><code>from javax.swing import * from java.awt import * class Test(JFrame): def __init__(self): JFrame.__init__(self, 'JDesktopPane and JInternalFrame Demo', size=(600, 300), defaultCloseOperation=JFrame.EXIT_ON_CLOSE) self.desktop = JDesktopPane() self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...) frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1) panel = JPanel() self.label = JLabel('Hello from Jython') panel.add(self.label) self.textfield1 = JTextField('Type something here',15) # self.textfield1.addFocusListener(event.FocusListener()) # ??? panel.add(self.textfield1) self.textfield2 = JTextField('and click Copy', 15) panel.add(self.textfield2) copyButton = JButton('Copy',actionPerformed=self.noAction) panel.add(copyButton) frame.add(panel) frame.pack() self.desktop.add(frame) frame.setSelected(1) frame.moveToFront() def noAction (self, event): pass if __name__ == '__main__': test = Test() test.setLocation(100, 100) test.show() </code></pre>
2
2009-07-31T15:45:09Z
1,213,341
<p>I was just trying to figure this out yesterday myself...tested and works:</p> <pre><code>from javax.swing import * from java.awt import * class Test(JFrame): def __init__(self): JFrame.__init__(self, 'JDesktopPane and JInternalFrame Demo', size=(600, 300), defaultCloseOperation=JFrame.EXIT_ON_CLOSE) self.desktop = JDesktopPane() self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...) frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1) panel = JPanel() self.label = JLabel('Hello from Jython') panel.add(self.label) self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus) panel.add(self.textfield1) self.textfield2 = JTextField('and click Copy', 15) panel.add(self.textfield2) copyButton = JButton('Copy',actionPerformed=self.noAction) panel.add(copyButton) frame.add(panel) frame.pack() self.desktop.add(frame) frame.setSelected(1) frame.moveToFront() def myOnFocus(self,event): print "testing..." def noAction (self, event): pass if __name__ == '__main__': test = Test() test.setLocation(100, 100) test.show() </code></pre>
1
2009-07-31T15:50:57Z
[ "python", "swing", "jython" ]
Handling Swing focus events with Jython
1,213,295
<p>Jython 2.5</p> <p>I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instance)</p> <pre><code>from javax.swing import * from java.awt import * class Test(JFrame): def __init__(self): JFrame.__init__(self, 'JDesktopPane and JInternalFrame Demo', size=(600, 300), defaultCloseOperation=JFrame.EXIT_ON_CLOSE) self.desktop = JDesktopPane() self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...) frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1) panel = JPanel() self.label = JLabel('Hello from Jython') panel.add(self.label) self.textfield1 = JTextField('Type something here',15) # self.textfield1.addFocusListener(event.FocusListener()) # ??? panel.add(self.textfield1) self.textfield2 = JTextField('and click Copy', 15) panel.add(self.textfield2) copyButton = JButton('Copy',actionPerformed=self.noAction) panel.add(copyButton) frame.add(panel) frame.pack() self.desktop.add(frame) frame.setSelected(1) frame.moveToFront() def noAction (self, event): pass if __name__ == '__main__': test = Test() test.setLocation(100, 100) test.show() </code></pre>
2
2009-07-31T15:45:09Z
6,683,088
<p>Cool'n simple. Thank you! I think that the idiom is</p> <pre><code>{var} = {constructor}({param}, {event}={function}) tf = JTextField('1.23', focusLost=tf_focus_lost) </code></pre> <p>Other alternative:</p> <pre><code>from java.awt.event import FocusListener class Enfoque(FocusListener): '''Add dynamically''' # Left unimplemented # def focusGained(self, event): # print 'tf_b Enfoque.focusGained' def focusLost(self,event): print 'tf_b Enfoque.focusLost' enf = Enfoque() tf_b = JTextField('2.34') tf_b.addFocusListener(enf) </code></pre>
1
2011-07-13T17:33:09Z
[ "python", "swing", "jython" ]
how can I get the uuid module for python 2.4.3
1,213,328
<p>I have an older version of python on the server i'm using and cannot upgrade it. is there a way to get the uuid module?</p>
1
2009-07-31T15:49:14Z
1,213,340
<p>Get it from <a href="http://pypi.python.org/pypi/uuid/" rel="nofollow">pypi</a> -- just download and install, it will work with Python 2.3 or better.</p> <p><strong>Edit</strong>: to install, first unpack the <code>.tar.gz</code> you just downloaded, i.e., from a terminal, cd to the directory you downloaded it to, then <code>tar xzvf uuid-1.30.tar.gz</code>, then <code>cd uuid-1.30</code>, and <code>sudo python setup.py install</code> (the <code>sudo</code> may or may not be needed depending on how your Linux system is set up; if it is needed, it will probably ask you for your password unless you've done another <code>sudo</code> very recently).</p>
4
2009-07-31T15:50:54Z
[ "python" ]
how can I get the uuid module for python 2.4.3
1,213,328
<p>I have an older version of python on the server i'm using and cannot upgrade it. is there a way to get the uuid module?</p>
1
2009-07-31T15:49:14Z
1,400,264
<p>To continue where Alex left off..</p> <ul> <li>Download the uuid-1.30.tar.gz from Alex's pypi link.</li> <li>unzip and untar.</li> <li>place the uuid.py to your application's python path (e.g., same dir with your own .py files)</li> </ul>
1
2009-09-09T14:59:05Z
[ "python" ]
"Connection Reset" error on Django Admin file upload
1,213,427
<p>WheneverI try to upload an mp3 file through a CMS I built with the Django Admin contrib pacakage, the server takes a couple minutes, then gives me a "Connection was reset" error. </p> <p>I'm running Django on a CentOS server using NGINX which is proxying Apache with mod_wsgi for python. Could this be a server settings issue?</p>
0
2009-07-31T16:05:44Z
19,777,706
<p>The problem is in the max body size</p> <p>If you are using NGinx, add <code>client_max_body_size 35m</code></p> <p>And if you are using Apache you have to increase this size too.</p>
1
2013-11-04T21:41:29Z
[ "python", "django", "apache", "nginx", "centos" ]
Is it possible to utilize a python module that isnt installed into the python directories in linux?
1,213,448
<p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
3
2009-07-31T16:08:45Z
1,213,470
<p>There are several ways to do this. The fastest is the simple command:</p> <pre><code>export PYTHONPATH=path/to/module/directory </code></pre> <p>Alternatively, you can use virtualenv. Just sudo apt-get install python-virtualenv (?). It's a very common development tool used for using modules that you don't necessarily want installed in your local Python installation.</p>
5
2009-07-31T16:12:09Z
[ "python", "linux" ]
Is it possible to utilize a python module that isnt installed into the python directories in linux?
1,213,448
<p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
3
2009-07-31T16:08:45Z
1,213,494
<p>Yes, there's no need to install most Python modules. uuid.py is simple enough you don't need to build or install it at all. Just <a href="http://pypi.python.org/pypi/uuid/" rel="nofollow">download it</a>, unpack it, and place the uuid.py file in your directory with your code. "import uuid" will work (the current working directory is in the Python path). This hack works fine up until you are doing serious application deployment management.</p> <p>BTW, I believe the uuid module is installed already with Python 2.5 and above.</p>
0
2009-07-31T16:16:54Z
[ "python", "linux" ]
Is it possible to utilize a python module that isnt installed into the python directories in linux?
1,213,448
<p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
3
2009-07-31T16:08:45Z
1,214,006
<p>Python looks for modules to import by means of the <code>sys.path</code> variable. You can change this in your program to point to new modules your program needs. By default this will include the programs own directory as well as the python system directories, but you can certainly add just about anything to it.</p> <p><a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">Link to the docs!</a></p>
0
2009-07-31T18:05:30Z
[ "python", "linux" ]
Is it possible to utilize a python module that isnt installed into the python directories in linux?
1,213,448
<p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
3
2009-07-31T16:08:45Z
1,214,488
<p>To follow up on this in the future this is addressed in [PEP 370][1] a good blog article explain how it works here [<a href="http://jessenoller.com/2009/07/19/pep-370-per-user-site-packages-and-environment-stew/" rel="nofollow">http://jessenoller.com/2009/07/19/pep-370-per-user-site-packages-and-environment-stew/</a>][2].</p> <p>To install packages you can as well have a look to [virtualenv][3] and [pip][4] which give you the ultimate way to have a clean environment.</p>
0
2009-07-31T19:42:13Z
[ "python", "linux" ]
Is it possible to utilize a python module that isnt installed into the python directories in linux?
1,213,448
<p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
3
2009-07-31T16:08:45Z
1,238,116
<p>If it's a single module I would consider including it on my project path. If it's something more complex (like a package, binary files, etc) and I don't want to modify the project sys.path (for example because it's the source of Django and I don't want to mess with updates) I install the package somewhere and then I add the path to a .pth file on my project directory (the current directory is always on the Python Path.) This way you don't have to be playing with your PYTHONPATH or project sys.path.</p> <p>You can check the format of the pth files here:</p> <p><a href="http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/" rel="nofollow">http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/</a></p>
1
2009-08-06T10:31:48Z
[ "python", "linux" ]
What is the most compatible way to install python modules on a Mac?
1,213,690
<p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p> <p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p> <p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p> <p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p> <p>Bonus questions: </p> <p>Do you use Apple's python, or some other version? Do you compile everything from source or is there a package manger that works well (Fink?).</p> <p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
108
2009-07-31T16:58:55Z
1,213,732
<p>Have you looked into <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">easy_install</a> at all? It won't synchronize your macports or anything like that, but it will automatically download the latest package and all necessary dependencies, i.e.</p> <pre><code>easy_install nose </code></pre> <p>for the nose unit testing package, or</p> <pre><code>easy_install trac </code></pre> <p>for the <code>trac</code> bug tracker.</p> <p>There's a bit more information on their <a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">EasyInstall</a> page too.</p>
3
2009-07-31T17:07:50Z
[ "python", "osx", "module", "packages", "macports" ]
What is the most compatible way to install python modules on a Mac?
1,213,690
<p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p> <p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p> <p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p> <p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p> <p>Bonus questions: </p> <p>Do you use Apple's python, or some other version? Do you compile everything from source or is there a package manger that works well (Fink?).</p> <p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
108
2009-07-31T16:58:55Z
1,213,753
<p>When you install modules with MacPorts, it does not go into Apple's version of Python. Instead those modules are installed onto the MacPorts version of Python selected.</p> <p>You can change which version of Python is used by default using a mac port called <a href="http://trac.macports.org/browser/trunk/dports/sysutils/python%5Fselect/Portfile" rel="nofollow">python_select</a>. instructions <a href="http://bar4mi.tistory.com/tag/python%5Fselect" rel="nofollow">here</a>.</p> <p>Also, there's <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">easy_install</a>. Which will use python to install python modules. </p>
2
2009-07-31T17:10:58Z
[ "python", "osx", "module", "packages", "macports" ]
What is the most compatible way to install python modules on a Mac?
1,213,690
<p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p> <p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p> <p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p> <p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p> <p>Bonus questions: </p> <p>Do you use Apple's python, or some other version? Do you compile everything from source or is there a package manger that works well (Fink?).</p> <p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
108
2009-07-31T16:58:55Z
1,213,795
<p>The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this:</p> <pre><code>easy_install django </code></pre> <p>easy_install uses the <a href="http://pypi.python.org">Python Package Index</a> which is an amazing resource for python developers. Have a look around to see what packages are available.</p> <p>A better option is <a href="http://pypi.python.org/pypi/pip">pip</a>, which is gaining traction, as it attempts to <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">fix a lot of the problems</a> associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command:</p> <pre><code>easy_install pip </code></pre> <p>After that, use:</p> <pre><code>pip install django </code></pre> <p>At some point you will probably want to learn a bit about <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs.</p> <p>Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the <a href="http://trac.macports.org/browser/trunk/dports/lang/python26/Portfile">macports</a> python 2.6.</p>
122
2009-07-31T17:20:22Z
[ "python", "osx", "module", "packages", "macports" ]