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
Python: Which modules for a discussion site?
1,297,350
<p>A site should be ready in 6 days. I am not allowed to use any framework such as Django. I am going to use:</p> <p><strong>Python modules</strong></p> <ol> <li>HTMLGen to generate HTML code from class-based description</li> <li>SQLObject, relational tables onto Python's class model</li> <li>?</li> </ol> <p><strong>Other</strong></p> <ol> <li>Python 2.5</li> <li><a href="http://varlena.com/GeneralBits/110.php" rel="nofollow">A variant of the Postgres schema</a></li> <li><a href="http://stackoverflow.com/questions/1295641/automatically-generated-test-data-to-a-db-from-a-schema">Super Smack</a> for testing the schema</li> </ol> <p><strong>Which modules would you use in the limited time?</strong></p> <p><strong>Plan</strong></p> <ol> <li>To generate class model with SQLOject from the <a href="http://varlena.com/GeneralBits/110.php" rel="nofollow">schema</a> </li> <li>then generate HTML code from the gererated class model with HTMLGen. (changed to Jinja2)</li> <li>?</li> </ol>
1
2009-08-19T01:00:44Z
1,297,409
<p>How about Jinja for templating? It will be much faster than working with autogenerated html. <a href="http://pypi.python.org/pypi/Jinja2/2.0" rel="nofollow">http://pypi.python.org/pypi/Jinja2/2.0</a></p>
3
2009-08-19T01:30:11Z
[ "python", "postgresql", "module", "website" ]
Python: Which modules for a discussion site?
1,297,350
<p>A site should be ready in 6 days. I am not allowed to use any framework such as Django. I am going to use:</p> <p><strong>Python modules</strong></p> <ol> <li>HTMLGen to generate HTML code from class-based description</li> <li>SQLObject, relational tables onto Python's class model</li> <li>?</li> </ol> <p><strong>Other</strong></p> <ol> <li>Python 2.5</li> <li><a href="http://varlena.com/GeneralBits/110.php" rel="nofollow">A variant of the Postgres schema</a></li> <li><a href="http://stackoverflow.com/questions/1295641/automatically-generated-test-data-to-a-db-from-a-schema">Super Smack</a> for testing the schema</li> </ol> <p><strong>Which modules would you use in the limited time?</strong></p> <p><strong>Plan</strong></p> <ol> <li>To generate class model with SQLOject from the <a href="http://varlena.com/GeneralBits/110.php" rel="nofollow">schema</a> </li> <li>then generate HTML code from the gererated class model with HTMLGen. (changed to Jinja2)</li> <li>?</li> </ol>
1
2009-08-19T01:00:44Z
1,297,960
<p>I think <a href="http://turbogears.org/" rel="nofollow">TurboGears</a> started out as a project to collect best-of-breed packages together with some glue code to stitch them together. I think the latest incarnation uses Pylons, but perhaps only for the controller. At the very least, you can see the <a href="http://en.wikipedia.org/wiki/Turbogears" rel="nofollow">TurboGears Wikipedia entry</a> to see what components they selected (see the subsections <a href="http://en.wikipedia.org/wiki/Turbogears#TurboGears%5F1.x%5Fcomponents" rel="nofollow">TurboGears 1.x components</a> and <a href="http://en.wikipedia.org/wiki/Turbogears#TurboGears%5F2.x%5Fcomponents" rel="nofollow">TurboGears 2.x components</a>), since they've obviously had some experience with this kind of thing. There's nothing "discussion" specific, but really you just want a templating library, a database library or ORM, a WSGI implementation with a router/controller and perhaps some AJAXy or other presentation widgets.</p>
1
2009-08-19T05:39:34Z
[ "python", "postgresql", "module", "website" ]
Django RSS Feed Problems
1,297,426
<p>I'm working on a blogging application, and trying to made just a simple RSS feed system function. However, I'm running into an odd bug that doesn't make a lot of sense to me. I understand what's likely going on, but I don't understand why. My RSS Feed class is below:</p> <pre><code>class RSSFeed(Feed): title = settings.BLOG_NAME description = "Recent Posts" def items(self): return Story.objects.all().order_by('-created')[:10] def link(self, obj): return obj.get_absolute_url() </code></pre> <p>However I received the following error (full stack trace at <a href="http://dpaste.com/82510/" rel="nofollow">http://dpaste.com/82510/</a>):</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'startswith' </code></pre> <p>That leads me to believe that it's not receiving any objects whatsoever. However, I can drop to a shell and grab those Story objects, and I can iterate through them returning the absolute url without any problems. So it would seem both portions of the Feed work, just not when it's in feed form. Furthermore, I added some logging, and can confirm that the items function is <em>never</em> entered when visiting the feeds link. I'm hoping I'm just overlooking something simple. Thanks in advance for any/all help.</p>
3
2009-08-19T01:40:49Z
1,297,451
<p>Changing to:</p> <pre><code>class RSSFeed(Feed): title = settings.BLOG_NAME link = "/blog/" description = "Recent Posts" def items(self): return Story.objects.all().order_by('-created')[:10] </code></pre> <p>Fixed it. Not sure I totally understand it.. but whatev. :)</p>
4
2009-08-19T01:51:59Z
[ "python", "django", "django-rss" ]
Django RSS Feed Problems
1,297,426
<p>I'm working on a blogging application, and trying to made just a simple RSS feed system function. However, I'm running into an odd bug that doesn't make a lot of sense to me. I understand what's likely going on, but I don't understand why. My RSS Feed class is below:</p> <pre><code>class RSSFeed(Feed): title = settings.BLOG_NAME description = "Recent Posts" def items(self): return Story.objects.all().order_by('-created')[:10] def link(self, obj): return obj.get_absolute_url() </code></pre> <p>However I received the following error (full stack trace at <a href="http://dpaste.com/82510/" rel="nofollow">http://dpaste.com/82510/</a>):</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'startswith' </code></pre> <p>That leads me to believe that it's not receiving any objects whatsoever. However, I can drop to a shell and grab those Story objects, and I can iterate through them returning the absolute url without any problems. So it would seem both portions of the Feed work, just not when it's in feed form. Furthermore, I added some logging, and can confirm that the items function is <em>never</em> entered when visiting the feeds link. I'm hoping I'm just overlooking something simple. Thanks in advance for any/all help.</p>
3
2009-08-19T01:40:49Z
1,303,273
<p>have you defined</p> <pre><code>def get_absolute_url(self): </code></pre> <p>in the model?</p> <p>also, it's nice to </p> <pre><code>if not obj: raise FeedDoesNotExist </code></pre> <p>to avoid errors when feed result is not present</p>
1
2009-08-20T00:02:14Z
[ "python", "django", "django-rss" ]
Read WordPerfect files with Python?
1,297,466
<p>I really need to work with information contained in <a href="https://en.wikipedia.org/wiki/WordPerfect#Summary" rel="nofollow">WordPerfect&nbsp;12</a> files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that seems to explain how to convert WordPerfect to text, but I didn't understand much about how it works.</p> <p><a href="http://mail.python.org/pipermail/python-list/2000-February/023093.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2000-February/023093.html</a></p> <p>How do I accomplish this?</p>
1
2009-08-19T02:00:11Z
1,297,581
<p>OpenOffice.org should read WordPerfect files, I think.</p> <p>And you can <a href="http://udk.openoffice.org/python/scriptingframework/index.html" rel="nofollow">script OpenOffice with Python</a>.</p>
2
2009-08-19T02:39:00Z
[ "python", "wordperfect" ]
Read WordPerfect files with Python?
1,297,466
<p>I really need to work with information contained in <a href="https://en.wikipedia.org/wiki/WordPerfect#Summary" rel="nofollow">WordPerfect&nbsp;12</a> files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that seems to explain how to convert WordPerfect to text, but I didn't understand much about how it works.</p> <p><a href="http://mail.python.org/pipermail/python-list/2000-February/023093.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2000-February/023093.html</a></p> <p>How do I accomplish this?</p>
1
2009-08-19T02:00:11Z
1,297,599
<p>The relevant part of your link is this:</p> <pre><code>os.system( "%s %s %s" % ( WPD_TO_TEXT_CMD, "/tmp/tmpfile", "/tmp/tmpfile.txt" ) ) </code></pre> <p>Which is making a system call to an outside program called "wp2txt". Googling for that program produces active hits.</p>
3
2009-08-19T02:44:23Z
[ "python", "wordperfect" ]
Read WordPerfect files with Python?
1,297,466
<p>I really need to work with information contained in <a href="https://en.wikipedia.org/wiki/WordPerfect#Summary" rel="nofollow">WordPerfect&nbsp;12</a> files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that seems to explain how to convert WordPerfect to text, but I didn't understand much about how it works.</p> <p><a href="http://mail.python.org/pipermail/python-list/2000-February/023093.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2000-February/023093.html</a></p> <p>How do I accomplish this?</p>
1
2009-08-19T02:00:11Z
1,415,786
<p>OK, here's what I did. I read the file in binary mode, converted by the data into a string representation of the hex values, and used unofficial WordPerfect documentation to create regular expressions to swap out all the hex strings representing non-text formatting codes and meta data, then converted everything back into text.</p> <p>A dirty piece of hacking, but it got the job done.</p>
1
2009-09-12T18:28:05Z
[ "python", "wordperfect" ]
Python sendto() not working on 3.1 (works on 2.6)
1,297,505
<p>For some reason, the following seems to work perfectly on my ubuntu machine running python 2.6 and returns an error on my windows xp box running python 3.1</p> <pre><code>from socket import socket, AF_INET, SOCK_DGRAM data = 'UDP Test Data' port = 12345 hostname = '192.168.0.1' udp = socket(AF_INET,SOCK_DGRAM) udp.sendto(data, (hostname, port)) </code></pre> <p>Below is the error that the python 3.1 throws:</p> <pre><code>Traceback (most recent call last): File "sendto.py", line 6, in &lt;module&gt; udp.sendto(data, (hostname, port)) TypeError: sendto() takes exactly 3 arguments (2 given) </code></pre> <p>I have consulted the documentation for python 3.1 and the sendto() only requires two parameters. Any ideas as to what may be causing this?</p>
4
2009-08-19T02:14:45Z
1,297,536
<p>Related issue on the Python bugtracker: <a href="http://bugs.python.org/issue5421" rel="nofollow">http://bugs.python.org/issue5421</a></p>
4
2009-08-19T02:26:57Z
[ "python", "windows", "ubuntu", "udp", "sendto" ]
Python sendto() not working on 3.1 (works on 2.6)
1,297,505
<p>For some reason, the following seems to work perfectly on my ubuntu machine running python 2.6 and returns an error on my windows xp box running python 3.1</p> <pre><code>from socket import socket, AF_INET, SOCK_DGRAM data = 'UDP Test Data' port = 12345 hostname = '192.168.0.1' udp = socket(AF_INET,SOCK_DGRAM) udp.sendto(data, (hostname, port)) </code></pre> <p>Below is the error that the python 3.1 throws:</p> <pre><code>Traceback (most recent call last): File "sendto.py", line 6, in &lt;module&gt; udp.sendto(data, (hostname, port)) TypeError: sendto() takes exactly 3 arguments (2 given) </code></pre> <p>I have consulted the documentation for python 3.1 and the sendto() only requires two parameters. Any ideas as to what may be causing this?</p>
4
2009-08-19T02:14:45Z
1,297,541
<p>In Python 3, the string (first) argument must be of type bytes or buffer, not str. You'll get that error message if you supply the optional flags parameter. Change data to:</p> <p>d<code>ata = b'UDP Test Data'</code></p> <p>You might want to file a bug report about that at the python.org bug tracker. [EDIT: already filed as noted by Dav]</p> <p>...</p> <pre><code>&gt;&gt;&gt; data = 'UDP Test Data' &gt;&gt;&gt; udp.sendto(data, (hostname, port)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sendto() takes exactly 3 arguments (2 given) &gt;&gt;&gt; udp.sendto(data, 0, (hostname, port)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sendto() argument 1 must be bytes or buffer, not str &gt;&gt;&gt; data = b'UDP Test Data' &gt;&gt;&gt; udp.sendto(data, 0, (hostname, port)) 13 &gt;&gt;&gt; udp.sendto(data, (hostname, port)) 13 </code></pre>
6
2009-08-19T02:27:37Z
[ "python", "windows", "ubuntu", "udp", "sendto" ]
Writing a tail -f python script that doesn't utilize 100% CPU
1,297,563
<p>Here's a simple implementation of tail -f written in python. The problem with this is with the looping nature, this script likes to hog a lot of the CPU time. If it's something one would like to run as a forked process/daemon, it would be an inefficient start.</p> <p>What's a solution to have a CPU efficient tail -f written in Python?</p> <pre><code> # CPU inefficient tail -f def main(): filename = '/tmp/foo' file = open(filename, 'r') st_results = os.stat(filename) st_size = st_results[6] file.seek(st_size) lastmatch = 0 while 1: where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: print line, </code></pre>
2
2009-08-19T02:33:32Z
1,297,591
<p>I don't know of an implementation that's going to be extremely efficient AND portable between Windows on one side, and just about every other system on the other. Just about everywhere, I'd use the <code>select</code> module of the standard library (which can be based on system level functionality such as select, kqueue, etc) to get woken up when and only when there are changes to a file, without polling; but on Windows select can only work on sockets. So, on Windows, I'd use directory change notifications instead (e.g. via ctypes or win32).</p>
0
2009-08-19T02:41:07Z
[ "python", "algorithm" ]
Python class method - Is there a way to make the calls shorter?
1,297,583
<p>I am playing around with Python, and I've created a class in a different package from the one calling it. In this class, I've added a class method which is being called from my main function. Again, they are in separate packages. The line to call the class method is much longer than I thought it would be from the examples I've seen in other places. These examples tend to call class methods from within the same package - thus shortening the calling syntax.</p> <p>Here's an example that I hope helps:</p> <p>In a 'config' package:</p> <pre><code>class TestClass : memberdict = { } @classmethod def add_key( clazz, key, value ) : memberdict[ key ] = value </code></pre> <p>Now in a different package named 'test':</p> <pre><code>import sys import config.TestClass def main() : config.TestClass.TestClass.add_key( "mykey", "newvalue" ) return 0 if __name__ == "__main__" : sys.exit( main() ) </code></pre> <p>You can see how 'config.TestClass.TestClass.add_key' is much more verbose than normal class method calls. Is there a way to make it shorter? Maybe 'TestClass.add_key'? Am I defining something in a strange way (Case of the class matching the python file name?)</p>
4
2009-08-19T02:39:34Z
1,297,590
<pre><code>from config.TestClass import TestClass TestClass.add_key( "mykey", "newvalue" ) </code></pre>
13
2009-08-19T02:40:27Z
[ "python", "class-method" ]
Why there is a difference in "import" vs. "import *"?
1,297,766
<pre><code>"""module a.py""" test = "I am test" _test = "I am _test" __test = "I am __test" </code></pre> <p>=============</p> <pre><code>~ $ python Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from a import * &gt;&gt;&gt; test 'I am test' &gt;&gt;&gt; _test Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name '_test' is not defined &gt;&gt;&gt; __test Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name '__test' is not defined &gt;&gt;&gt; import a &gt;&gt;&gt; a.test 'I am test' &gt;&gt;&gt; a._test 'I am _test' &gt;&gt;&gt; a.__test 'I am __test' &gt;&gt;&gt; </code></pre>
6
2009-08-19T04:08:36Z
1,297,784
<p>Variables with a leading "_" (underbar) are not <em>public names</em> and will not be imported when <code>from x import *</code> is used.</p> <p>Here, <code>_test</code> and <code>__test</code> are not <em>public</em> names.</p> <p>From the <a href="http://docs.python.org/reference/simple_stmts.html#the-import-statement" rel="nofollow">import</a> statement description:</p> <blockquote> <p>If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace of the import statement..</p> <p>The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. <strong>If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_').</strong> __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).</p> </blockquote>
21
2009-08-19T04:18:00Z
[ "python", "import" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
1,297,901
<p>Then what you need is not Django. What you need is exactly what <a href="http://code.google.com/p/micropy/" rel="nofollow">micropy</a> does.</p>
3
2009-08-19T05:09:31Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
1,297,911
<p>This is a simple CMS implemented in Django, as a single file. It was written by <a href="http://news.e-scribe.com/395">Paul Bissex</a>. Some of it has been "golfed" and could do with a bit of expansion, but it's still relatively easy to read.</p> <p>The source has vanished from his pastebin, but I saved it:</p> <pre><code>#!/usr/bin/env python """ jngo -- The unhealthily compressed Django application. Usage: ./jngo.py Assuming a working install of Django (http://djangoproject.com/) and SQLite (http://sqlite.org), this script can be executed directly without any other preparations -- you don't have to do `setup.py install`, it doesn't need to be on your Python path, you don't need to set DJANGO_SETTINGS_MODULE, you don't need a webserver. You don't even need content -- the first time it's run, it will create a SQLite database in the same directory as the script and populate it with sample pages. Features: * Editable content on all pages * Dynamically generated navigation buttons * Optional private-access pages * Optional per-page comments * RSS feed of latest comments, with autodiscovery Author: Paul Bissex &lt;pb@e-scribe.com&gt; URL: http://news.e-scribe.com/ License: MIT FAQS: Q: Should I use this as an example of excellent Django coding practices? A: Um, no. This is pretty much the opposite of excellent Django coding practices. Q: Why did you do such a terrible thing? A: At first, it was just a perverse experiment. It ended up being a good way to refresh my memory on some Django internals, by trying all kinds of things that broke in weird ways. """ #--- Settings --- NAME = ROOT_URLCONF = "jngo" DEBUG = TEMPLATE_DEBUG = True SITE_ID = 3000 HOSTNAME_AND_PORT = "127.0.0.1:8000" DATABASE_ENGINE = "sqlite3" DATABASE_NAME = NAME + ".db" INSTALLED_APPS = ["django.contrib.%s" % app for app in "auth admin contenttypes sessions sites flatpages comments".split()] TEMPLATE_LOADERS = ('django.template.loaders.app_directories.load_template_source', NAME + '.template_loader') MIDDLEWARE_CLASSES = ('django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware') TEMPLATE_CONTEXT_PROCESSORS = (NAME + '.context_processor', "django.core.context_processors.auth", "django.core.context_processors.request") #--- Template loader and templates --- def template_loader(t, _): from django.template import TemplateDoesNotExist try: return { 'base.html': """&lt;html&gt;&lt;head&gt;&lt;title&gt;{{ flatpage.title }}&lt;/title&gt;&lt;link rel='alternate' type='application/rss+xml' href='/feed/'&gt;&lt;style type="text/css"&gt;body { margin: 15px 50px; background: #eee; color: #343; font-family: sans-serif; } ul { padding: 0; } li { display: inline; background: #383; padding: 4px 8px; margin: 3px; } li:hover { background: #252; } dd { border-bottom: 1px dotted #666; } a { color: #383; text-decoration: none; } li a { color: #fff; } .anav { background: #141; } .rnav a { color: #ff4; } .error { color: #e22; } #footer { border-top: 1px dotted #555; font-size: 80%; color: #555; margin-top: 15px } #comments { background: #ddd; margin-top: 20px; padding: 10px; } dt { font-weight: bold; margin-top: 1em; }&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;ul&gt;{% for nav in navs %}&lt;li class="{% ifequal nav.url flatpage.url %}anav {% endifequal %}{% if nav.registration_required %}rnav {% endif %}"&gt;&lt;a href="{{ nav.url }}"&gt;{{ nav.title }}&lt;/a&gt;&lt;/li&gt;{% endfor %}&lt;/ul&gt;{% block content %}{% endblock %}&lt;div id="footer"&gt;{% if request.user.is_staff %}&lt;a href="javascript:(function(){if(typeof%20ActiveXObject!='undefined'){var%20x=new%20ActiveXObject('Microsoft.XMLHTTP')}else%20if(typeof%20XMLHttpRequest!='undefined'){var%20x=new%20XMLHttpRequest()}else{return;}x.open('GET',location.href,false);x.send(null);try{var%20type=x.getResponseHeader('x-object-type');var%20id=x.getResponseHeader('x-object-id');}catch(e){return;}document.location='/admin/'+type.split('.').join('/')+'/'+id+'/';})()"&gt;Edit this page&lt;/a&gt; (as staff user &lt;a href="/admin/"&gt;{{ request.user }}&lt;/a&gt;)&lt;br&gt;{% endif %}Powered by &lt;a href="http://djangoproject.com/"&gt;Django&lt;/a&gt; {{ version }}&lt;br&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;""", 'flatpages/default.html': """{% extends "base.html" %}{% load comments %}{% block content %}&lt;h1&gt;{{ flatpage.title }}&lt;/h1&gt;{{ flatpage.content }}{% if flatpage.enable_comments %}&lt;div id="comments"&gt;{% get_free_comment_list for flatpages.flatpage flatpage.id as comments %}&lt;h3&gt;Comments!&lt;/h3&gt;&lt;dl&gt;{% for comment in comments %}{% include "comment.html" %}{% endfor %}&lt;/dl&gt;{% free_comment_form for flatpages.flatpage flatpage.id %}&lt;/div&gt;{% endif %}{% endblock %}""", 'comments/free_preview.html': """{% extends "base.html" %}{% block content %}&lt;h1&gt;Comment preview&lt;/h1&gt;&lt;dl&gt;{% include "comment.html" %}&lt;/dl&gt;&lt;form action='.' method='post'&gt;&lt;input type='hidden' name='gonzo' value='{{ hash }}'&gt;&lt;input type='hidden' name='options' value='{{ options }}'&gt;&lt;input type='hidden' name='comment' value='{{ comment.comment }}'&gt;&lt;input type='hidden' name='person_name' value='{{ comment.person_name }}'&gt;&lt;input type='hidden' name='target' value='{{ target }}'&gt;&lt;input type='submit' name='post' value='Post comment'&gt;&lt;/form&gt;{% endblock %}""", 'comments/posted.html': """{% extends "base.html" %}{% block content %}&lt;h1&gt;Comment posted&lt;/h1&gt;&lt;p&gt;Thanks for posting!&lt;/p&gt; &lt;p&gt;&lt;a href='{{ object.get_absolute_url }}'&gt;Continue&lt;/a&gt;&lt;/p&gt;{% endblock %}""", 'comment.html': """&lt;dt&gt;{{ comment.person_name }} said:&lt;/dt&gt; &lt;dd&gt;{{ comment.comment }}&lt;/dd&gt;""", 'registration/login.html': """{% extends "base.html" %}{% block content %}{% if form.has_errors %}&lt;h2 class="error"&gt;Wrong!&lt;/h2&gt;{% endif %}&lt;p&gt;This page is top secret, so you need to log in.&lt;/p&gt;&lt;form method="post" action="."&gt;Username: {{ form.username }}&lt;br&gt;Password: {{ form.password }}&lt;br&gt;&lt;input type="submit" value="login"&gt;&lt;input type="hidden" name="next" value="{{ next }}"&gt;&lt;/form&gt;{% endblock %}""" }[t], '' except KeyError: raise TemplateDoesNotExist template_loader.is_usable = True #--- Context processor --- def context_processor(request): from django.contrib.flatpages.models import FlatPage navs = FlatPage.objects.all().values("url", "title", "registration_required") from django import get_version return { 'navs': navs, 'version': get_version() } #--- RSS Feed (hacky wrapper function needed because of jngo's one-file setup) --- def feed(*args, **kwargs): from django.contrib.comments.feeds import LatestFreeCommentsFeed return LatestFreeCommentsFeed(*args, **kwargs) #--- URLconf --- from django.conf.urls.defaults import * urlpatterns = patterns("", (r"^admin/", include("django.contrib.admin.urls")), (r"^comments/", include("django.contrib.comments.urls.comments")), (r"^accounts/login/$", "django.contrib.auth.views.login"), (r"^(feed)/$", "django.contrib.syndication.views.feed", {'feed_dict': {'feed': feed}}), ) #--- Execution --- if __name__ == "__main__": import os, sys from django.core.management import call_command here = os.path.dirname(__file__) sys.path.append(here) os.environ["DJANGO_SETTINGS_MODULE"] = NAME if not os.path.isfile(os.path.join(here, DATABASE_NAME)): from django.contrib.auth.create_superuser import createsuperuser from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site call_command("syncdb") createsuperuser() site_obj = Site.objects.create(id=SITE_ID, domain=HOSTNAME_AND_PORT) FlatPage.objects.create(url="/", title="Home", content="Welcome to %s!" % NAME).sites.add(site_obj) FlatPage.objects.create(url="/stuff/", enable_comments=True, title="Stuff", content="This is a page about stuff.").sites.add(site_obj) FlatPage.objects.create(url="/topsecret/", title="Top Secret", content="Now you know.", registration_required=True).sites.add(site_obj) call_command("runserver", HOSTNAME_AND_PORT) </code></pre>
8
2009-08-19T05:14:57Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
1,297,931
<p>You might want to consider Simon Willison's library:</p> <ul> <li><a href="http://blog.simonwillison.net/post/57956850422/djng" rel="nofollow">djng—a Django powered microframework</a></li> </ul> <p>From the <a href="http://github.com/simonw/djng/tree/master" rel="nofollow">readme</a>:</p> <blockquote> <p>djng is a micro-framework that depends on a macro-framework (Django).</p> <p>My definition of a micro-framework: something that lets you create an entire Python web application in a single module:</p> <pre><code>import djng def index(request): return djng.Response('Hello, world') if __name__ == '__main__': djng.serve(index, '0.0.0.0', 8888) </code></pre> <p>[...]</p> </blockquote>
11
2009-08-19T05:27:30Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
1,298,303
<p>You also may want to take a look at <a href="http://webpy.org/" rel="nofollow">web.py</a>. (<a href="http://webpy.org/tutorial3.en" rel="nofollow">Tutorial</a>)</p> <p>It's another compact, but powerful web framework.</p> <p>Sample from the main page:</p> <pre><code>import web urls = ('/(.*)', 'hello') app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'world' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() </code></pre>
1
2009-08-19T07:27:16Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
1,298,381
<p>Well, the easiest way to do that is to mimic the django project arbo in one file. So in one module, assure there is :</p> <pre><code>Root_module : Root_module.settings Root_module.urls Root_module.app_in_the_module Root_module.app_in_the_module.models Root_module.app_in_the_module.views </code></pre> <p>Then code is as a normal Django project. What you must know is that Django does not need anything to be in a specific place. Standard names and paths are at beat, convention, at worst, shortcut to prevent you from defining a setting.</p> <p>If you know Django very well, you don't even need to mimic the arbo, just write you django app making all the data from the above modules interconnected the way they should be.</p>
1
2009-08-19T07:50:39Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
2,709,778
<p>Getting started with Django can be pretty easy too. Here's a 10-line single-file Django webapp:</p> <pre><code>import os from django.conf.urls.defaults import patterns from django.http import HttpResponse filepath, extension = os.path.splitext(__file__) ROOT_URLCONF = os.path.basename(filepath) def yoohoo(request): return HttpResponse('Yoohoo!') urlpatterns = patterns('', (r'^hello/$', yoohoo)) </code></pre> <p>Check out my blog post <a href="http://olifante.blogs.com/covil/2010/04/minimal-django.html">Minimal Django</a> for details.</p>
9
2010-04-25T20:11:01Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
9,896,862
<p>Most of the single file django examples found over the web lack support for model since django somehow require models to be declared in models.py file in each <code>INSTALLED_APP</code>. Finally I found an example that include support for model:-</p> <p><a href="http://fahhem.com/blog/2011/10/django-models-without-apps-or-everything-django-truly-in-a-single-file/" rel="nofollow">http://fahhem.com/blog/2011/10/django-models-without-apps-or-everything-django-truly-in-a-single-file/</a></p> <p>The link to the django wiki on models creation also worth reading. And the full code which also include admin:-</p> <p><a href="https://gist.github.com/2219751" rel="nofollow">https://gist.github.com/2219751</a></p>
2
2012-03-27T20:07:24Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
28,638,323
<p><a href="http://stackoverflow.com/a/1297911/4794">John's answer</a> quoting the <a href="http://news.e-scribe.com/395" rel="nofollow">jngo app</a> by Paul Bissex is impressive, but it's sadly broken under Django 1.7.</p> <p>I did a bunch of digging and <a href="https://github.com/donkirkby/udjango" rel="nofollow">created 𝜇Django</a> to show how to run a model class with a SQLite database in a single Python file. I plan to use it for posting questions about Django model classes. If you want some of the other parts from jngo, you might be able to graft them onto this. Fahrzin Hemmati has posted <a href="http://blog.fahhem.com/2011/10/django-models-without-apps-or-everything-django-truly-in-a-single-file/" rel="nofollow">an example</a> that seems similar and includes the full Django: web server, models, management commands. I haven't tried it out, yet.</p> <pre><code># Tested with Django 1.9.2 import sys import django from django.apps import apps from django.apps.config import AppConfig from django.conf import settings from django.db import connections, models, DEFAULT_DB_ALIAS from django.db.models.base import ModelBase NAME = 'udjango' def main(): setup() class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) syncdb(Person) p1 = Person(first_name='Jimmy', last_name='Jones') p1.save() p2 = Person(first_name='Bob', last_name='Brown') p2.save() print ', '.join([p.first_name for p in Person.objects.all()]) def setup(): DB_FILE = NAME + '.db' with open(DB_FILE, 'w'): pass # wipe the database settings.configure( DEBUG=True, DATABASES={ DEFAULT_DB_ALIAS: { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_FILE}}, LOGGING={'version': 1, 'disable_existing_loggers': False, 'formatters': { 'debug': { 'format': '%(asctime)s[%(levelname)s]' '%(name)s.%(funcName)s(): %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}}, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'debug'}}, 'root': { 'handlers': ['console'], 'level': 'WARN'}, 'loggers': { "django.db": {"level": "WARN"}}}) app_config = AppConfig(NAME, sys.modules['__main__']) apps.populate([app_config]) django.setup() original_new_func = ModelBase.__new__ @staticmethod def patched_new(cls, name, bases, attrs): if 'Meta' not in attrs: class Meta: app_label = NAME attrs['Meta'] = Meta return original_new_func(cls, name, bases, attrs) ModelBase.__new__ = patched_new def syncdb(model): """ Standard syncdb expects models to be in reliable locations. Based on https://github.com/django/django/blob/1.9.3 /django/core/management/commands/migrate.py#L285 """ connection = connections[DEFAULT_DB_ALIAS] with connection.schema_editor() as editor: editor.create_model(model) main() </code></pre>
0
2015-02-20T21:14:20Z
[ "python", "django", "web-applications" ]
How do I write a single-file Django application?
1,297,873
<p>I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:</p> <pre><code>$ python myapp.py </code></pre> <p>You can assume I won't render HTML, so I don't need templates (I'll return <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> or some other auto-generated string).</p>
11
2009-08-19T04:58:30Z
28,651,818
<p>Tested with Django 1.7</p> <pre><code>#!/usr/bin/env python import os import sys from django.conf import settings from django.conf.urls import patterns, include, url from django.http import HttpResponse filename = os.path.splitext(os.path.basename(__file__))[0] urlpatterns = patterns('', url(r'^$', '%s.home' % filename, name='home'), ) def home(request): return HttpResponse('hello') if __name__ == "__main__": settings.configure( DEBUG=True, MIDDLEWARE_CLASSES = [], ROOT_URLCONF = filename ) from django.core.management import execute_from_command_line execute_from_command_line([sys.argv[0], 'runserver']) </code></pre>
2
2015-02-21T21:55:11Z
[ "python", "django", "web-applications" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
1,298,176
<p>It's a little bit of a simplification to say the class browser only shows one method. It actually shows a lot of methods in a much more organized way than raw source code usually does. Consider in which of these you think you'd have an easier time finding what you wanted:</p> <pre><code>class Thing def foo blah blah blah blah.each do |blah| blah blah blah blah blah.collect {|blah, blah| blah blah blah} end end def bar(blah) blah blah blah blah.each do |blah| blah blah blah blah blah.collect {|blah, blah| blah blah blah} end end end class Fob def foo blah blah blah blah.each do |blah| blah blah blah blah blah.collect {|blah, blah| blah blah blah} end end def bar(blah) blah blah blah blah.each do |blah| blah blah blah blah blah.collect {|blah, blah| blah blah blah} end end end </code></pre> <p>Or:</p> <pre><code>Classes Methods Thing -&gt; foo -&gt; blah blah blah Fob bar blah.each do |blah| blah blah blah blah blah.collect {|blah, blah| blah blah blah} end </code></pre> <p>And an actual Smalltalk class browser is a lot more powerful than my silly little plaintext mockup, whereas Ruby source actually looks a lot like that. A class browser encourages you to think of classes as actual entities with autonomous behaviors rather than a bunch of abstract text.</p>
1
2009-08-19T06:49:11Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
1,298,447
<p>I have a love/hate relationship with the Smalltalk browsers (Squeak in my case). At times I think they are the best things since sliced bread, and at others they make me grind my teeth. The problem with Smalltalk is that the browsers are basically all you have. You can of course write your own, but very few people go that route. Whereas with file-based languages, I have a choice of ways of looking at the code, using completely different editors or environments if I wish. However, one way of looking at the code I've never wanted is one that only lets me see one method at a time. </p>
0
2009-08-19T08:12:01Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
1,299,109
<p>The Smalltalk browser has two parts: the top one shows the packages, classes, protocols and methods/messages, the bottom one shows the content of one method. This is very usefull if you design/code your program thinking more on signatures and names, rather than as a web of lines of codes.</p> <p>If you concentrate on signature, this could lead to a more "object oriented" style, where the system is designed as a collaboration of objects sending messages to each other. In this paradigm, the methods names are somehow more important than how they are implemented.</p> <p>If you have a very large screen (I got one myself :-)) you would open several smalltalk browsers allowing you to browse (and code) in several different packages and classes. Moreover, you would probably also have a worspace and a xUnit to test and play with your objects.</p> <p>I suggest you look at the Whisker editor created for Squeak. It proposes a quite nice balance between names and signatures navigation, and lines of code exploration. You would need to try it, as the screenshot does not show the dynamic of it, and how you navigate thru the "boxes" of codes.</p> <p><a href="http://www.mindspring.com/~dway/smalltalk/whisker.html">http://www.mindspring.com/~dway/smalltalk/whisker.html</a></p>
5
2009-08-19T10:50:19Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
1,302,807
<p>VisualAge for Java used the Smalltalk Browser model for coding, and I thought they (IBM) did a great job of taking a typical file based language and lifting it up to a higher conceptual mode. Instantiations even had a great add-on to bring good refactoring tools to VAJ (people either don't know or forget for which language refactoring tools were introduced first...take a guess ;) Of course I had cut my teeth on Smalltalk, then moved to C++ for a number of years (too many) and was pleased to see anything Smalltalk-like. When I saw that IBM was seriously moving on Eclipse I was flabbergasted.</p> <p>But most of my co-workers at the time did not like not being able to see the entire text of the .java file at once. I would ask, "why not just have only one method in a class so that you can see it all of the class file at once?" Then someone would reply, "Then I wouldn't be able to decompose my code very well at all!" To which I would reply, "If your code is decomposed well, why do you need to see every method at once?" And then I would get a response about things being slower somehow...</p> <p>Development environments that throw in your face the fact that the code database is a system of text files and force you to work with the code that way have always seemed retarded to me...particularly in the in the case of OO languages.</p> <p>Having said that, there are a number of things that I don't like about the traditional Smalltalk browser. I've often wanted a better way of navigating across the browser instances that I've opened and visited. Whenever you work with code there is invariably a context of methods and classes that you are working with (modifying and/or viewing) - it should be simpler to navigate around the context that dynamically develops while you work. I would also like to be able to easily compose a view of 2-3 method bodies together at one time - something that a code-folding editor can sort of give you, at least for one file...</p>
2
2009-08-19T21:47:58Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
1,334,764
<p>Eclipse offers a Smalltalk like browser, the Java browsing perspective. Even though being a Smalltalker myself, I almost never use it. Why? The powerful part if the Smalltalk IDE is the debugger not the browser. When coding Smalltalk, I do everything test-first and then fix all missing methods in the debugger <em>while</em> running the test. Having this for any other language would be like ... WOW JUST WOW, so go ahead and do this :)</p>
3
2009-08-26T13:40:15Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
How useful would be a Smalltalk source code browser for other programming languages?
1,298,020
<p>I'm working on an IDE for python, ruby and php.</p> <p>Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. </p> <p>I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display <strong>a lot</strong> of lines at ones.</p> <p>I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke.</p> <p>But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention.</p>
4
2009-08-19T06:01:43Z
22,278,806
<p>OK so this is ancient-but I simply can't believe no one thought of <em>opening several browsers.</em> I don't think I've ever seen anyone programming in a Smalltalk system with just the one. Class browsers, hierarchy browsers, protocol browsers... Yes, each one shows a single methods source at any one time but just point each one at a different method!</p>
2
2014-03-09T05:31:02Z
[ "php", "python", "ruby", "ide", "smalltalk" ]
--home or --prefix in python package install?
1,298,036
<p>When you build and install a python package, you have two choices: --home and --prefix. I never really got the difference between the two (I always use --home) but if I understood correctly one is deprecated and the other is "the way to go"™.</p> <p>Am I wrong ?</p>
4
2009-08-19T06:06:25Z
1,299,203
<p>According to the <a href="http://docs.python.org/install/index.html#alternate-installation" rel="nofollow">Installing Python Modules</a> documentation, the "standard" way is to specify neither, and to let Python install it in either <code>/usr/local/lib/pythonX.Y/site-packages</code> on *nix or <code>C:\Python\</code> on Windows.</p> <p>But, if you <em>do</em> decide to go for an alternate method, you can specify <code>--home</code> to name the base installation directory, typically when you want to store multiple packages in just your own directory, usually on a multi-user machine when you don't have admin access, or perhaps for just testing before a system-wide install. <code>--home</code> is not deprecated; in fact, it was only added to Windows as of Python 2.4.</p> <p>The <code>--prefix</code> option is more strange, because this lets you use one version of Python to <em>build</em> the module you're installing, while letting you <em>install</em> the module to a different location from normal. Another example is when you have to write to a directory with one name, while reading from it with another name (some network shares are set up this way).</p> <p>So the <code>--home</code> prefix specifies <code>home/lib/python</code>, <code>home/bin</code>, <code>home/share</code>, while the <code>--prefix</code> option specifies <code>prefix/lib/pythonX.Y/site-packages/</code>, <code>prefix/bin</code>, <code>prefix/share</code> on *nix and <code>prefix/Scripts</code> and <code>prefix/Data</code> on Windows.</p>
3
2009-08-19T11:07:14Z
[ "python", "installation" ]
Is there an easy way to use a python tempfile in a shelve (and make sure it cleans itself up)?
1,298,037
<p>Basically, I want an infinite size (more accurately, hard-drive rather than memory bound) dict in a python program I'm writing. It seems like the tempfile and shelve modules are naturally suited for this, however, I can't see how to use them together in a safe manner. I want the tempfile to be deleted when the shelve is GCed (or at guarantee deletion after the shelve is out of use, regardless of when), but the only solution I can come up with for this involves using tempfile.TemporaryFile() to open a file handle, getting the filename from the handle, using this filename for opening a shelve, keeping the reference to the file handle to prevent it from getting GCed (and the file deleted), and then putting a wrapper on the shelve that stores this reference. Anyone have a better solution than this convoluted mess?</p> <p>Restrictions: Can only use the standard python library and must be fully cross platform.</p>
1
2009-08-19T06:07:17Z
1,298,162
<p>I would rather inherit from shelve.Shelf, and override the close method (*) to unlink the files. Notice that, depending on the specific dbm module being used, you may have more than one file that contains the shelf. One solution could be to create a temporary directory, rather than a temporary file, and remove anything in the directory when done. The other solution would be to bind to a specific dbm module (say, bsddb, or dumbdbm), and remove specifically those files that these libraries create.</p> <p>(*) notice that the close method of a shelf is also called when the shelf is garbage collected. The only case how you could end up with garbage files is when the interpreter crashes or gets killed.</p>
1
2009-08-19T06:46:26Z
[ "python", "shelve", "temporary-files" ]
Unescape/unquote binary strings in (extended) url encoding in python
1,298,319
<p>for analysis I'd have to unescape URL-encoded binary strings (non-printable characters most likely). The strings sadly come in the extended URL-encoding form, e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. </p> <p>How do I get this into binary data in python? (urllib.unquote only handles the "%HH"-form)</p>
0
2009-08-19T07:33:14Z
1,298,400
<p>I guess you will have to write the decoder function by yourself. Here is an implementation to get you started:</p> <pre><code>def decode(file): while True: c = file.read(1) if c == "": # End of file break if c != "%": # Not an escape sequence yield c continue c = file.read(1) if c != "u": # One hex-byte yield chr(int(c + file.read(1), 16)) continue # Two hex-bytes yield chr(int(file.read(2), 16)) yield chr(int(file.read(2), 16)) </code></pre> <p>Usage:</p> <pre><code>input = open("/path/to/input-file", "r") output = open("/path/to/output-file", "wb") output.writelines(decode(input)) output.close() input.close() </code></pre>
1
2009-08-19T07:57:10Z
[ "python", "binary", "urlencode" ]
Unescape/unquote binary strings in (extended) url encoding in python
1,298,319
<p>for analysis I'd have to unescape URL-encoded binary strings (non-printable characters most likely). The strings sadly come in the extended URL-encoding form, e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. </p> <p>How do I get this into binary data in python? (urllib.unquote only handles the "%HH"-form)</p>
0
2009-08-19T07:33:14Z
1,298,424
<p>Here is a regex-based approach:</p> <pre><code># the replace function concatenates the two matches after # converting them from hex to ascii repfunc = lambda m: chr(int(m.group(1), 16))+chr(int(m.group(2), 16)) # the last parameter is the text you want to convert result = re.sub('%u(..)(..)', repfunc, '%u616f') print result </code></pre> <p>gives</p> <pre><code>ao </code></pre>
0
2009-08-19T08:06:15Z
[ "python", "binary", "urlencode" ]
Unescape/unquote binary strings in (extended) url encoding in python
1,298,319
<p>for analysis I'd have to unescape URL-encoded binary strings (non-printable characters most likely). The strings sadly come in the extended URL-encoding form, e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here. </p> <p>How do I get this into binary data in python? (urllib.unquote only handles the "%HH"-form)</p>
0
2009-08-19T07:33:14Z
1,301,097
<blockquote> <p>The strings sadly come in the extended URL-encoding form, e.g. "%u616f"</p> </blockquote> <p>Incidentally that's not anything to do with URL-encoding. It's an arbitrary made-up format produced by the JavaScript escape() function and pretty much nothing else. If you can, the best thing to do would be to change the JavaScript to use the encodeURIComponent function instead. This will give you a proper, standard URL-encoded UTF-8 string.</p> <blockquote> <p>e.g. "%u616f". I want to store them in a file that then contains the raw binary values, eg. 0x61 0x6f here.</p> </blockquote> <p>Are you sure 0x61 0x6f (the letters "ao") is the byte stream you want to store? That would imply UTF-16BE encoding; are you treating all your strings that way?</p> <p>Normally you'd want to turn the input into Unicode then write it out using an appropriate encoding, such as UTF-8 or UTF-16LE. Here's a quick way of doing it, relying on the hack of making Python read '%u1234' as the string-escaped format u'\u1234':</p> <pre><code>&gt;&gt;&gt; ex= 'hello %e9 %u616f' &gt;&gt;&gt; ex.replace('%u', r'\u').replace('%', r'\x').decode('unicode-escape') u'hello \xe9 \u616f' &gt;&gt;&gt; print _ hello é 慯 &gt;&gt;&gt; _.encode('utf-8') 'hello \xc2\xa0 \xe6\x85\xaf' </code></pre>
3
2009-08-19T16:28:12Z
[ "python", "binary", "urlencode" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,298,685
<p>You can try to separate key hashing from the content filling with <a href="http://docs.python.org/library/stdtypes.html#dict.fromkeys" rel="nofollow"><code>dict.fromkeys</code></a> classmethod. It'll create a <code>dict</code> of a known size with all values defaulting to either <code>None</code> or a value of your choice. After that you could iterate over it to fill with the values. It'll help you to time the actual hashing of all keys. Not sure if you'd be able significantly increase the speed though.</p>
3
2009-08-19T09:14:37Z
[ "python", "performance", "dictionary" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,298,705
<p>If your datas need/can be stored on disc perhaps you can store your datas in a <a href="http://docs.python.org/library/bsddb.html" rel="nofollow">BSDDB database</a> or use <a href="http://docs.python.org/library/pickle.html#module-cPickle" rel="nofollow">Cpickle</a> to load/store your dictionnary</p>
2
2009-08-19T09:17:32Z
[ "python", "performance", "dictionary" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,298,734
<p>If you know C, you can take a look at <a href="http://svn.python.org/view/python/trunk/Objects/dictobject.c?revision=74197&amp;view=markup">dictobject.c</a> and <a href="http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?revision=53782&amp;view=markup">the Notes on Optimizing Dictionaries</a>. There you'll notice the parameter PyDict_MINSIZE:</p> <blockquote> <p>PyDict_MINSIZE. Currently set to 8.</p> </blockquote> <p>This parameter is defined in <a href="http://svn.python.org/view/python/trunk/Include/dictobject.h?revision=70546&amp;view=markup">dictobject.h</a>. So you <em>could</em> change it when compiling Python but this probably is a bad idea.</p>
5
2009-08-19T09:22:38Z
[ "python", "performance", "dictionary" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,298,739
<p>I tried :</p> <pre><code>a = dict.fromkeys((range(4000000))) </code></pre> <p>It creates a dictionary with 4 000 000 entries in about 3 seconds. After that, setting values are really fast. So I guess dict.fromkey is definitly the way to go.</p>
7
2009-08-19T09:24:25Z
[ "python", "performance", "dictionary" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,298,905
<p>With performance issues it's always best to measure. Here are some timings:</p> <pre><code> d = {} for i in xrange(4000000): d[i] = None # 722ms d = dict(itertools.izip(xrange(4000000), itertools.repeat(None))) # 634ms dict.fromkeys(xrange(4000000)) # 558ms s = set(xrange(4000000)) dict.fromkeys(s) # Not including set construction 353ms </code></pre> <p>The last option doesn't do any resizing, it just copies the hashes from the set and increments references. As you can see, the resizing isn't taking a lot of time. It's probably your object creation that is slow. </p>
21
2009-08-19T10:05:42Z
[ "python", "performance", "dictionary" ]
How to set initial size for a dictionary in Python?
1,298,636
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming as the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject(object): def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
12
2009-08-19T09:06:30Z
1,302,843
<p>Do you initialize all keys with new "empty" instances of the same type? Is it not possible to write a defaultdict or something that will create the object when it is accessed?</p>
1
2009-08-19T21:56:33Z
[ "python", "performance", "dictionary" ]
How can I call the svn.client.svn_client_list2 with python SVN API SWIG bindings?
1,298,869
<h1>The question</h1> <p>How do I call <a href="http://svn.collab.net/svn-doxygen/group__List.html#ga1" rel="nofollow"><code>svn_client_list2</code></a> C API function from python via SVN API SWIG bindings?</p> <h1>Problem description</h1> <p>I can find that function from the <code>svn.client</code> module, but <strong>calling it is the problem</strong>, because the callback function it uses is a typedef <a href="http://svn.collab.net/svn-doxygen/group__List.html#ga0" rel="nofollow"><code>svn_client_list_func_t</code></a> and I don't know how to use that typedef in python. </p> <p>Although I can find a class for it from <code>svn.client.svn_client_list_func_t</code> along with <code>svn.client.svn_client_list_func_tPtr</code>, but I can't find an example of how to use it.</p> <h2>Incorrect usage of svn.client.svn_client_list2</h2> <p>If you call the <code>svn.client.svn_client_list2</code> function with a normal python function as callback parameter it gives you an error.</p> <p><code></p> <pre><code>import svn.core, svn.client path = svn.core.svn_path_canonicalize("/path/to/a/working_copy/") pool = svn.core.Pool() ctx = svn.client.svn_client_create_context(pool) revision = svn.core.svn_opt_revision_t() SVN_DIRENT_ALL = 0xffffffffl def _handle_list(path, dirent, abs_path, pool): print(path, dirent, abs_path, pool) svn.client.svn_client_list2(path, revision, revision, svn.core.svn_depth_infinity, SVN_DIRENT_ALL, True, _handle_list, ctx, pool) </code> </code> `TypeError: argument number 7: a 'svn_client_list_func_t *' is expected, 'function()' is received` </pre> <h2>Incorrect usage of svn.client.svn_client_list_func_t</h2> <p>Trying to initialize the <code>svn.client.svn_client_list_func_t</code> will result to an exception.</p> <p><code></p> <pre><code>callback_function = svn.client.svn_client_list_func_t() </code></pre> <p></code></p> <p><code>RuntimeError: No constructor defined</code></p> <p>Ideas how I can proceed?</p>
0
2009-08-19T09:56:02Z
1,375,441
<p>It looks like you can't really do this at the moment. When I dug into bit into the SWIG bindings code and documentation it says that when you're using target language functions as the callback function, you need a typemap for it as it says in the <a href="http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn30" rel="nofollow">SWIG documentation</a>:</p> <blockquote>Although SWIG does not normally allow callback functions to be written in the target language, this can be accomplished with the use of typemaps and other advanced SWIG features.</blockquote> <p>It looked like it was missing for Python...</p>
0
2009-09-03T19:29:19Z
[ "python" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
1,299,266
<p>Yes, the MySQLDb egg was compiled against a different version of libmysqlclient than the version present in the system. You need to either get a proper egg (uninstalling the previous) or to build MySQLDb from scratch to compile it against the library present in your system.</p> <p>I don't know why but I think your colleague might be interested in this question:</p> <p><a href="http://stackoverflow.com/questions/1297917/configuring-django-to-use-remote-mysql-server">http://stackoverflow.com/questions/1297917/configuring-django-to-use-remote-mysql-server</a></p>
0
2009-08-19T11:18:35Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
1,303,895
<p>It might be best if you install mysql and it's Python bindings from scratch, I use the following steps whenever I need MySQLdb on OS X 10.4 or 10.5:</p> <ol> <li><p>Install <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">MySQL</a> for your system, the dmg installer should be sufficient</p></li> <li><p>The default location of MySQL will be somewhere around: <code> /usr/local/mysql-5.0.45-osx10.4-i686</code>. From <code>/usr/local/mysql/lib</code>, create a soft link:</p> <p><code>ln -s ../../mysql-5.0.45-osx10.4-i686/lib mysql</code></p></li> <li><p>Download the <a href="http://sourceforge.net/projects/mysql-python/files/" rel="nofollow">MySQLdb source</a> and unpack it</p></li> <li><p>Edit the file <code>site.cfg</code> under your unpacked MySQLdb directory, comment out the <code>registry_key</code> and set <code>mysql_config</code> to:</p> <p><code>mysql_config = /usr/local/mysql-5.0.45-osx10.4-i686/bin/mysql_config</code></p></li> <li><p>Carry on with the regular Python packages build from within MySQLdb directory:</p> <p><code>sudo python setup.py install</code></p></li> <li><p>If everything is fine above, test MySQLdb in a new terminal:</p> <p><code>python -c "import MySQLdb"</code></p></li> </ol> <p>The above should return nothing if successful. The above example shows OS 10.4 and MySQL 5.0, substitute them with the your proper tools version.</p>
6
2009-08-20T04:06:41Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
4,293,013
<p>I had trouble with Thierry's solution on 32-bit Python (2.6.5) on OS X 10.6.</p> <p>Upgrading to Python 2.7 64-bit version fixed the problem for me.</p>
0
2010-11-27T17:44:14Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
4,537,783
<p>Thiery's instructions worked just fine for me with the MySQL 10.6 dmg and MySQLdb ver 1.2.3</p> <p>It helps to start with a clean slate, so make sure you uninstall early versions of MySQL. Look at this post for uninstallation help <a href="http://stackoverflow.com/questions/1436425/how-do-you-uninstall-mysql-from-mac-os-x">How do you uninstall MySQL from Mac OS X? </a></p> <p>Thanks!</p>
0
2010-12-27T09:41:06Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
10,572,999
<p>It was Complicated and hard but it worked on <strong>MacOSX Lion</strong>.</p> <p>you will be using :</p> <pre><code>Xcode Brew Port Pip </code></pre> <p>make sure that you have Xcode(4.X) installed , and your mac is configured to find the executables because it will be used by <strong>Macports</strong> during the process of installing mysql-python.</p> <p>Make sure that Xcode Command line Tools are installed </p> <p>start Xcode app >> preferences >> download >> Components tab >> Command Line Tools >> click install </p> <p>run the following commands from the terminal.</p> <p><code>xcodebuild -version</code></p> <p>if you ran into this <strong>error</strong></p> <p><code>/usr/bin/xcodebuild -version Error: No developer directory found at /Developer</code></p> <p>Try to Run</p> <p><code>/usr/bin/xcode-select</code><br> this will update the developer directory path.</p> <p>Then you need to switch manually to the new Xcode install dir in /Applications:</p> <pre><code>sudo /usr/bin/xcode-select -switch /Applications/Xcode.app </code></pre> <p><a href="http://trac.macports.org/ticket/27820" rel="nofollow">Ref</a></p> <p><strong>Uninstall</strong> mysql [<em>Backup you data before doing so !</em>].</p> <pre><code>sudo rm /usr/local/mysql sudo rm -rf /usr/local/mysql* sudo rm -rf /Library/StartupItems/MySQLCOM sudo rm -rf /Library/PreferencePanes/My* edit /etc/hostconfig and remove the line MYSQLCOM=-YES- sudo rm -rf /Library/Receipts/mysql* sudo rm -rf /Library/Receipts/MySQL* sudo rm -rf /var/db/receipts/com.mysql.* </code></pre> <p>Use <a href="https://github.com/mxcl/homebrew" rel="nofollow">brew</a> to install Mysql again:</p> <pre><code>brew install mysql </code></pre> <p>you might run into this error.</p> <pre><code>Error: Cannot write to /usr/local/Cellar </code></pre> <p>the <strong><a href="http://stackoverflow.com/a/5112493/1340281">fix</a></strong>.</p> <p>you should be ready to go now.</p> <pre><code>sudo port install py27-mysql pip install mysql-python python -c "import MySQLdb" </code></pre> <p>if you don't see any errors MySQLdb is installed.</p>
1
2012-05-13T15:38:51Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
12,278,125
<pre><code>sudo apt-get install python-mysqldb </code></pre> <p>make sure it should installed properly</p> <p>or you can use another alternative like <code>easy_install</code> </p>
-1
2012-09-05T09:15:46Z
[ "python", "mysql", "django" ]
Django - MySQLdb: Symbol not found: _mysql_affected_rows
1,299,013
<p>A colleague got this error message when trying to use MySQLdb from Django:</p> <pre><code>[...] ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/roy/.python-eggs/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so Expected in: dynamic lookup </code></pre> <p>He's using OS X 10.5, Python 2.5 (arriving with OS X), MySQL 5.1 &amp; MySQLdb 1.2.3c1.</p> <p>Any idea how to attack this?</p>
7
2009-08-19T10:31:47Z
17,581,431
<p>Try to run:</p> <pre><code>easy_install -U distribute pip install --upgrade mysql-python </code></pre> <p>Note: If you have any errors of missing symbols while compiling, you need to have mysql development libs to compile it.</p> <p>On Linux it's easy to install it:</p> <pre><code>sudo apt-get install mysql-devel </code></pre> <p>or:</p> <pre><code>sudo yum install mysql-devel </code></pre> <p>On Mac you probably need to download <a href="http://dev.mysql.com/downloads/connector/c/#downloads" rel="nofollow">MySQL Connector</a> and then you may have to pass in a --with-mysql-libs option to point to the directory when the C libraries are unpacked to. Or you can try to put the libraries in the default directory: /usr/lib64/mysql</p>
0
2013-07-10T21:43:48Z
[ "python", "mysql", "django" ]
How to check if python is installed in windows from java?
1,299,018
<p>How can I check from inside a java program if python is installed in windows? Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).</p>
3
2009-08-19T10:32:51Z
1,299,042
<p>Have you tried querying the registry to check if it is installed? It is stored in </p> <p><code>software\python\pythoncore</code></p> <p>If the user has a (relatively) new version of python, that is installed with the MSI-package, you can use the <a href="http://msdn.microsoft.com/en-us/library/aa370101%28VS.85%29.aspx" rel="nofollow">MsiEnumProducts Function</a> to check if python is installed.</p>
1
2009-08-19T10:38:31Z
[ "java", "python", "installation" ]
How to check if python is installed in windows from java?
1,299,018
<p>How can I check from inside a java program if python is installed in windows? Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).</p>
3
2009-08-19T10:32:51Z
1,299,046
<p>Most Python installers add keys to the Windows registry. Here's <a href="http://effbot.org/zone/python-register.htm" rel="nofollow">an article</a> about how to add that information, you can use it to see how to read the information.</p>
2
2009-08-19T10:38:46Z
[ "java", "python", "installation" ]
How to check if python is installed in windows from java?
1,299,018
<p>How can I check from inside a java program if python is installed in windows? Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).</p>
3
2009-08-19T10:32:51Z
1,299,061
<p>exec(String command) Executes the specified string command in a separate process. Check for Python from command</p>
0
2009-08-19T10:41:30Z
[ "java", "python", "installation" ]
How to check if python is installed in windows from java?
1,299,018
<p>How can I check from inside a java program if python is installed in windows? Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).</p>
3
2009-08-19T10:32:51Z
1,299,062
<p>Use the Java Runtime to exec the following command "python --version".</p> <p>If it works, you have Python, and the standard output is the version number.</p> <p>If it doesn't work, you don't have Python.</p>
2
2009-08-19T10:41:31Z
[ "java", "python", "installation" ]
How to check if python is installed in windows from java?
1,299,018
<p>How can I check from inside a java program if python is installed in windows? Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).</p>
3
2009-08-19T10:32:51Z
19,837,856
<p>this would work</p> <ul> <li>Process process = Runtime.getRuntime().exec("cmd /c C:\Python27\python --version");</li> </ul>
-1
2013-11-07T13:59:39Z
[ "java", "python", "installation" ]
Handling international dates in python
1,299,377
<p>I have a date that is either formatted in German for e.g, </p> <pre><code>2. Okt. 2009 </code></pre> <p>and also perhaps as </p> <pre><code>2. Oct. 2009 </code></pre> <p>How do I parse this into an ISO datetime (or python <code>datetime</code>)?</p> <p>Solved by using this snippet:</p> <pre><code>for l in locale.locale_alias: worked = False try: locale.setlocale(locale.LC_TIME, l) worked = True except: worked = False if worked: print l </code></pre> <p>And then plugging in the appropriate for the parameter l in setlocale.</p> <p>Can parse using </p> <pre><code>import datetime print datetime.datetime.strptime("09. Okt. 2009", "%d. %b. %Y") </code></pre>
4
2009-08-19T11:37:46Z
1,299,387
<p><a href="http://docs.python.org/library/locale.html">http://docs.python.org/library/locale.html</a></p> <p>The <code>datetime</code> module is already locale aware.</p> <p>It's something like the following</p> <pre><code># German locale loc= locale.setlocale(locale.LC_TIME,("de","de")) try: date= datetime.date.strptime( input, "%d. %b. %Y" ) except: # English locale loc= locale.setlocale(locale.LC_TIME,("en","us")) date= datetime.date.strptime( input, "%d. %b. %Y" ) </code></pre>
7
2009-08-19T11:40:23Z
[ "python", "datetime", "internationalization" ]
Handling international dates in python
1,299,377
<p>I have a date that is either formatted in German for e.g, </p> <pre><code>2. Okt. 2009 </code></pre> <p>and also perhaps as </p> <pre><code>2. Oct. 2009 </code></pre> <p>How do I parse this into an ISO datetime (or python <code>datetime</code>)?</p> <p>Solved by using this snippet:</p> <pre><code>for l in locale.locale_alias: worked = False try: locale.setlocale(locale.LC_TIME, l) worked = True except: worked = False if worked: print l </code></pre> <p>And then plugging in the appropriate for the parameter l in setlocale.</p> <p>Can parse using </p> <pre><code>import datetime print datetime.datetime.strptime("09. Okt. 2009", "%d. %b. %Y") </code></pre>
4
2009-08-19T11:37:46Z
1,300,274
<p>Very minor point about your code snippet : I'm no python expert but I'd consider the whole flag to check for success + silently swallowing all exceptions to be bad form.</p> <p>try/expect/else does what you want in a cleaner way, I think :</p> <pre><code>for l in locale.locale_alias: try: locale.setlocale(locale.LC_TIME, l) except locale.Error: # the doc says setlocale should throw this on failure pass else: print l </code></pre>
1
2009-08-19T14:16:26Z
[ "python", "datetime", "internationalization" ]
Beginner at testing Python code, need help!
1,299,672
<p>I don't do tests, but I'd like to start. I have some questions :</p> <ol> <li>Is it ok to use the <code>unittest</code> module for that? From what I understand, the <code>unittest</code> module will run any method starting with <code>test</code>.</li> <li>if I have a separate directory for the tests ( consider a directory named <code>tests</code> ), how would I import the code I'm testing? Do I need to use the <code>imp</code> module? Here's the directory structure :</li> </ol> <p>src/</p> <p>tests/</p>
3
2009-08-19T12:39:53Z
1,299,684
<p>It's fine to use <code>unittest</code>. This module will run methods beginning with <code>test</code> for classes which inherit from <code>unittest.TestCase</code>.</p> <p>There's no need to use the <code>imp</code> module - your test module would just import the code under test as normal. You might need to add the <code>src</code> directory to your path:</p> <pre><code>import sys sys.path.append('../src') # OnLinux - use r'..\src' for Windows </code></pre> <p>This code would be in your test module(s) before any import of your modules.</p> <p>A better approach is to use the OS environment variable <code>PYTHONPATH</code>.</p> <p>(Windows) <code>SET PYTHONPATH=path\to\module; python test.py</code></p> <p>(Linux) <code>PYTHONPATH=path/to/module; python test.py</code></p> <p>An alternative to <code>unittest</code> is <a href="http://code.google.com/p/python-nose/" rel="nofollow">nose</a>.</p>
4
2009-08-19T12:43:02Z
[ "python", "testing" ]
Beginner at testing Python code, need help!
1,299,672
<p>I don't do tests, but I'd like to start. I have some questions :</p> <ol> <li>Is it ok to use the <code>unittest</code> module for that? From what I understand, the <code>unittest</code> module will run any method starting with <code>test</code>.</li> <li>if I have a separate directory for the tests ( consider a directory named <code>tests</code> ), how would I import the code I'm testing? Do I need to use the <code>imp</code> module? Here's the directory structure :</li> </ol> <p>src/</p> <p>tests/</p>
3
2009-08-19T12:39:53Z
1,299,705
<p>I had a bit of problem with the whole seperate directory for tests issue. </p> <p>The way I solved it was by having a test runner in the source directory with the following code:</p> <pre><code>import sys, os, re, unittest # Run all tests in t/ def regressionTest(): path = os.path.abspath(os.path.dirname(sys.argv[0])) + '/t' files = os.listdir(path) test = re.compile("^t_.+\.py$", re.IGNORECASE) files = filter(test.search, files) filenameToModuleName = lambda f: 't.'+os.path.splitext(f)[0] moduleNames = map(filenameToModuleName, files) modules = map(__import__, moduleNames) modules = map(lambda name: sys.modules[name], moduleNames) load = unittest.defaultTestLoader.loadTestsFromModule return unittest.TestSuite(map(load, modules)) suite = regressionTest() if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>Then I had a folder named <code>t</code> containing all my tests, named <code>t_&lt;something&gt;.py</code>.</p> <p>If you need help on getting started with unit testing in Python, I can recommend <a href="http://docs.python.org/library/unittest.html" rel="nofollow">the official documentation</a> and <a href="http://diveintopython.net/unit_testing/index.html" rel="nofollow">Dive Into Python</a> among other things.</p>
2
2009-08-19T12:47:36Z
[ "python", "testing" ]
Beginner at testing Python code, need help!
1,299,672
<p>I don't do tests, but I'd like to start. I have some questions :</p> <ol> <li>Is it ok to use the <code>unittest</code> module for that? From what I understand, the <code>unittest</code> module will run any method starting with <code>test</code>.</li> <li>if I have a separate directory for the tests ( consider a directory named <code>tests</code> ), how would I import the code I'm testing? Do I need to use the <code>imp</code> module? Here's the directory structure :</li> </ol> <p>src/</p> <p>tests/</p>
3
2009-08-19T12:39:53Z
1,300,554
<p>Another good way to start tests with your Python code is use the <a href="http://docs.python.org/library/doctest.html" rel="nofollow">doctest</a> module, whereby you include tests inside method and class comments. The neat bit is that these serve as code examples, and therefore, partial documentation. Extremely easy to do, too.</p>
5
2009-08-19T15:05:28Z
[ "python", "testing" ]
Beginner at testing Python code, need help!
1,299,672
<p>I don't do tests, but I'd like to start. I have some questions :</p> <ol> <li>Is it ok to use the <code>unittest</code> module for that? From what I understand, the <code>unittest</code> module will run any method starting with <code>test</code>.</li> <li>if I have a separate directory for the tests ( consider a directory named <code>tests</code> ), how would I import the code I'm testing? Do I need to use the <code>imp</code> module? Here's the directory structure :</li> </ol> <p>src/</p> <p>tests/</p>
3
2009-08-19T12:39:53Z
1,301,545
<p>As mentioned by Sebastian P., Mark Pilgrim's <em><a href="http://www.diveintopython.org/" rel="nofollow">Dive Into Python</a></em> has great chapters on <a href="http://www.diveintopython.org/unit%5Ftesting/index.html" rel="nofollow">unit testing</a> and <a href="http://www.diveintopython.org/unit%5Ftesting/stage%5F1.html" rel="nofollow">test-driven development</a> using Python's unittest module. I used these chapters to get started with testing, myself.</p> <p>I wrote a blog post describing <a href="http://igotgenes.blogspot.com/2008/12/robust-imports-in-python-guaranteed.html" rel="nofollow">my approach to importing modules for testing</a>. Note that it solves the shortcoming of Vinay Sajip's approach, which will not work if you call the testing module from anywhere but the directory in which it resides. A reader posted a nice solution in the comments of my blog post as well.</p> <p>S. Lott hints at a method using <code>PYTHONPATH</code> in Vinay's post; I hope he will expound on it.</p>
2
2009-08-19T17:50:17Z
[ "python", "testing" ]
Error while importing SQLObject on Windows
1,299,849
<p>I am getting following error while importing SQLObject on Window. Does anyone knows what is this error about and how to solve it?</p> <p>==============================</p> <pre><code> from sqlobject import * File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\__init__.py", line 5, in &lt;module&gt; from main import * File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\main.py", line 32, in &lt;module&gt; import dbconnection File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\dbconnection.py", line 17, in &lt;module&gt; from joins import sorter File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\joins.py", line 5, in &lt;module&gt; import events File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\events.py", line 3, in &lt;module&gt; from sqlobject.include.pydispatch import dispatcher File "c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg\sqlobject\include\pydispatch\dispatcher.py", line 30, in &lt;module&gt; import saferef, robustapply, errors EOFError: EOF read where object expected </code></pre>
0
2009-08-19T13:14:48Z
1,300,442
<p>Looks like your <code>c:\python26\lib\site-packages\sqlobject-0.10.4-py2.6.egg</code> file may be truncated or otherwise damaged. How does it compare to a freshly downloaded one (in terms of both length and checksum)?</p>
0
2009-08-19T14:44:14Z
[ "python", "windows", "sqlobject" ]
upload file with Python Mechanize
1,299,855
<p>When I run the following script:</p> <pre><code>from mechanize import Browser br = Browser() br.open(url) br.select_form(name="edit_form") br['file'] = 'file.txt' br.submit() </code></pre> <p>I get: <em>ValueError: value attribute is readonly</em></p> <p>And I still get the same error when I add:</p> <pre><code>br.form.set_all_readonly(False) </code></pre> <p>So, how can I use Python Mechanize to interact with a HTML form to upload a file?</p> <p>Richard</p>
6
2009-08-19T13:15:20Z
1,299,896
<p><a href="http://twill.idyll.org/" rel="nofollow"><code>twill</code></a> is built on <code>mechanize</code> and makes scripting web forms a breeze. See <a href="http://stackoverflow.com/questions/1294862/python-www-macro">python-www-macro</a>.</p> <pre><code>&gt;&gt;&gt; from twill import commands &gt;&gt;&gt; print commands.formfile.__doc__ &gt;&gt; formfile &lt;form&gt; &lt;field&gt; &lt;filename&gt; [ &lt;content_type&gt; ] Upload a file via an "upload file" form field. &gt;&gt;&gt; </code></pre>
2
2009-08-19T13:24:04Z
[ "python", "file", "forms", "upload", "mechanize" ]
upload file with Python Mechanize
1,299,855
<p>When I run the following script:</p> <pre><code>from mechanize import Browser br = Browser() br.open(url) br.select_form(name="edit_form") br['file'] = 'file.txt' br.submit() </code></pre> <p>I get: <em>ValueError: value attribute is readonly</em></p> <p>And I still get the same error when I add:</p> <pre><code>br.form.set_all_readonly(False) </code></pre> <p>So, how can I use Python Mechanize to interact with a HTML form to upload a file?</p> <p>Richard</p>
6
2009-08-19T13:15:20Z
1,305,860
<p>This is how to do it properly with Mechanize:</p> <pre><code>br.form.add_file(open(filename), 'text/plain', filename) </code></pre>
11
2009-08-20T12:30:32Z
[ "python", "file", "forms", "upload", "mechanize" ]
Apache/Django freezing after a few requests
1,300,213
<p>I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04.</p> <p>I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the browser spinner would just keep spinning).</p> <p>It works for about 10 mintues, then just stops. Apache is still able to serve static files. Just nothing through Django.</p> <p>I've checked the apache error logs, and I don't see any entries that could be related. I'm not sure if this is a WSGI, Django, Apache, or Postgres issue?</p> <p>Any ideas?</p> <p>Thanks for your help!</p>
1
2009-08-19T14:09:48Z
1,300,283
<p>It sounds a lot like there's something happening between django and your newly housed database.</p> <p>Just to eliminate apache from the mix, you should run it as the dev server (on some random port to stop people using it) and see if you still have issues. If you do, it's the database. If it behaves, it could be apache.</p> <p>Edit, <a href="http://code.djangoproject.com/ticket/900" rel="nofollow">This looks interesting</a>. You can test that by applying his patch (commenting out the <code>.close()</code>) but there are other similar bugs floating around.</p>
0
2009-08-19T14:18:39Z
[ "python", "django", "postgresql", "apache2", "mod-wsgi" ]
Apache/Django freezing after a few requests
1,300,213
<p>I'm running Django through mod_wsgi and Apache (2.2.8) on Ubuntu 8.04.</p> <p>I've been running Django on this setup for about 6 months without any problems. Yesterday, I moved my database (postgres 8.3) to its own server, and my Django site started refusing to load (the browser spinner would just keep spinning).</p> <p>It works for about 10 mintues, then just stops. Apache is still able to serve static files. Just nothing through Django.</p> <p>I've checked the apache error logs, and I don't see any entries that could be related. I'm not sure if this is a WSGI, Django, Apache, or Postgres issue?</p> <p>Any ideas?</p> <p>Thanks for your help!</p>
1
2009-08-19T14:09:48Z
2,368,542
<p>Found it! I'm using eventlet in some other code and I imported one of my modules into a django model. So eventlet was taking over and putting everything to "sleep".</p>
0
2010-03-03T03:24:35Z
[ "python", "django", "postgresql", "apache2", "mod-wsgi" ]
HTTPResponse - Return organised data (table?)
1,300,310
<p>My Webservice is currently returning a HTTPResponse which contains thousands of data from a mySQL database (via a Objects.filter). It's currently just displating them in a very boring way!</p> <p>I'm looking to organised this data in some way. What would be ideal is two things:</p> <p>The possibility of having a table and maybe having some kind of scroll bar?</p> <p>Does anyone have any idea what I'm referring to or what package would help me?</p>
0
2009-08-19T14:22:21Z
1,300,421
<p>Do you need to return pure HTML (as opposed to, say, JSON and Javascript to show it)? If so, the <code>&lt;table&gt;</code> <a href="http://www.w3schools.com/html/html%5Ftables.asp" rel="nofollow">tag</a> of HTML seems to be what you want; and <a href="http://www.htmlcodetutorial.com/help/ftopic2394.html" rel="nofollow">this</a> is a way to have a scrollbar on the table.</p>
1
2009-08-19T14:40:09Z
[ "python", "django" ]
Python re question - sub challenge
1,300,350
<p>I want to add a href links to all words prefixed with # or ! or @ If this is the text</p> <p>Check the #bamboo and contact @Fred re #bamboo #garden</p> <p>should be converted to:</p> <pre><code>Check the &lt;a href="/what/bamboo"&gt;#bamboo&lt;/a&gt; and contact &lt;a href="/who/fred"&gt;@Fred&lt;/a&gt; re &lt;a href="/what/bamboo"&gt;#bamboo&lt;/a&gt; &lt;a href="/what/garden"&gt;#garden&lt;/a&gt; </code></pre> <p>Note that # and @ go to different places.</p> <p>This is as far as I have got, just doing the hashes...</p> <pre><code>matched = re.sub("[#](?P&lt;keyword&gt;\w+)", \ '&lt;a href="/what/(?P=keyword)"&gt;(?P=keyword)&lt;/a&gt;', \ text) </code></pre> <p>Any re gurus able to point me in the right direction. Do I need to do separate matches for each symbol?</p>
1
2009-08-19T14:27:28Z
1,300,406
<p>I'd do it with a single match and a function picking the "place". I.e.:</p> <pre><code>import re places = {'#': 'what', '@': 'who', '!': 'why', } def replace(m): all = m.group(0) first, rest = all[0], all[1:] return '&lt;a href="/%s/%s"&gt;%s&lt;/a&gt;' % ( places[first], rest, all) markedup = re.sub(r'[#!@]\w+', replace, text) </code></pre>
5
2009-08-19T14:37:05Z
[ "python", "regex" ]
How to map one class against multiple tables with SQLAlchemy?
1,300,433
<p>Lets say that I have a database structure with three tables that look like this:</p> <pre><code>items - item_id - item_handle attributes - attribute_id - attribute_name item_attributes - item_attribute_id - item_id - attribute_id - attribute_value </code></pre> <p>I would like to be able to do this in SQLAlchemy:</p> <pre><code>item = Item('item1') item.foo = 'bar' session.add(item) session.commit() item1 = session.query(Item).filter_by(handle='item1').one() print item1.foo # =&gt; 'bar' </code></pre> <p>I'm new to SQLAlchemy and I found this in the documentation (<a href="http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables">http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables</a>): </p> <pre><code>j = join(items, item_attributes, items.c.item_id == item_attributes.c.item_id). \ join(attributes, item_attributes.c.attribute_id == attributes.c.attribute_id) mapper(Item, j, properties={ 'item_id': [items.c.item_id, item_attributes.c.item_id], 'attribute_id': [item_attributes.c.attribute_id, attributes.c.attribute_id], }) </code></pre> <p>It only adds item_id and attribute_id to Item and its not possible to add attributes to Item object.</p> <p>Is what I'm trying to achieve possible with SQLAlchemy? Is there a better way to structure the database to get the same behaviour of "dynamic columns"?</p>
9
2009-08-19T14:42:39Z
1,300,603
<p>This is called the <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model">entity-attribute-value</a> pattern. There is an example about this under the SQLAlchemy examples directory: <a href="http://www.sqlalchemy.org/trac/browser/examples/vertical/">vertical/</a>.</p> <p>If you are using PostgreSQL, then there is also the <code>hstore</code> contrib module that can store a string to string mapping. If you are interested then I have some code for a custom type that makes it possible to use that to store extended attributes via SQLAlchemy.</p> <p>Another option to store custom attributes is to serialize them to a text field. In that case you will lose the ability to filter by attributes.</p>
8
2009-08-19T15:13:25Z
[ "python", "database", "database-design", "sqlalchemy" ]
How to map one class against multiple tables with SQLAlchemy?
1,300,433
<p>Lets say that I have a database structure with three tables that look like this:</p> <pre><code>items - item_id - item_handle attributes - attribute_id - attribute_name item_attributes - item_attribute_id - item_id - attribute_id - attribute_value </code></pre> <p>I would like to be able to do this in SQLAlchemy:</p> <pre><code>item = Item('item1') item.foo = 'bar' session.add(item) session.commit() item1 = session.query(Item).filter_by(handle='item1').one() print item1.foo # =&gt; 'bar' </code></pre> <p>I'm new to SQLAlchemy and I found this in the documentation (<a href="http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables">http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables</a>): </p> <pre><code>j = join(items, item_attributes, items.c.item_id == item_attributes.c.item_id). \ join(attributes, item_attributes.c.attribute_id == attributes.c.attribute_id) mapper(Item, j, properties={ 'item_id': [items.c.item_id, item_attributes.c.item_id], 'attribute_id': [item_attributes.c.attribute_id, attributes.c.attribute_id], }) </code></pre> <p>It only adds item_id and attribute_id to Item and its not possible to add attributes to Item object.</p> <p>Is what I'm trying to achieve possible with SQLAlchemy? Is there a better way to structure the database to get the same behaviour of "dynamic columns"?</p>
9
2009-08-19T14:42:39Z
2,890,682
<p>The link to vertical/vertical.py is broken. The example had been renamed to <code>dictlike-polymorphic.py</code> and <code>dictlike.py.</code></p> <p>I am pasting in the contents of <code>dictlike.py</code>:</p> <pre><code>"""Mapping a vertical table as a dictionary. This example illustrates accessing and modifying a "vertical" (or "properties", or pivoted) table via a dict-like interface. These are tables that store free-form object properties as rows instead of columns. For example, instead of:: # A regular ("horizontal") table has columns for 'species' and 'size' Table('animal', metadata, Column('id', Integer, primary_key=True), Column('species', Unicode), Column('size', Unicode)) A vertical table models this as two tables: one table for the base or parent entity, and another related table holding key/value pairs:: Table('animal', metadata, Column('id', Integer, primary_key=True)) # The properties table will have one row for a 'species' value, and # another row for the 'size' value. Table('properties', metadata Column('animal_id', Integer, ForeignKey('animal.id'), primary_key=True), Column('key', UnicodeText), Column('value', UnicodeText)) Because the key/value pairs in a vertical scheme are not fixed in advance, accessing them like a Python dict can be very convenient. The example below can be used with many common vertical schemas as-is or with minor adaptations. """ class VerticalProperty(object): """A key/value pair. This class models rows in the vertical table. """ def __init__(self, key, value): self.key = key self.value = value def __repr__(self): return '&lt;%s %r=%r&gt;' % (self.__class__.__name__, self.key, self.value) class VerticalPropertyDictMixin(object): """Adds obj[key] access to a mapped class. This is a mixin class. It can be inherited from directly, or included with multiple inheritence. Classes using this mixin must define two class properties:: _property_type: The mapped type of the vertical key/value pair instances. Will be invoked with two positional arugments: key, value _property_mapping: A string, the name of the Python attribute holding a dict-based relationship of _property_type instances. Using the VerticalProperty class above as an example,:: class MyObj(VerticalPropertyDictMixin): _property_type = VerticalProperty _property_mapping = 'props' mapper(MyObj, sometable, properties={ 'props': relationship(VerticalProperty, collection_class=attribute_mapped_collection('key'))}) Dict-like access to MyObj is proxied through to the 'props' relationship:: myobj['key'] = 'value' # ...is shorthand for: myobj.props['key'] = VerticalProperty('key', 'value') myobj['key'] = 'updated value'] # ...is shorthand for: myobj.props['key'].value = 'updated value' print myobj['key'] # ...is shorthand for: print myobj.props['key'].value """ _property_type = VerticalProperty _property_mapping = None __map = property(lambda self: getattr(self, self._property_mapping)) def __getitem__(self, key): return self.__map[key].value def __setitem__(self, key, value): property = self.__map.get(key, None) if property is None: self.__map[key] = self._property_type(key, value) else: property.value = value def __delitem__(self, key): del self.__map[key] def __contains__(self, key): return key in self.__map # Implement other dict methods to taste. Here are some examples: def keys(self): return self.__map.keys() def values(self): return [prop.value for prop in self.__map.values()] def items(self): return [(key, prop.value) for key, prop in self.__map.items()] def __iter__(self): return iter(self.keys()) if __name__ == '__main__': from sqlalchemy import (MetaData, Table, Column, Integer, Unicode, ForeignKey, UnicodeText, and_, not_) from sqlalchemy.orm import mapper, relationship, create_session from sqlalchemy.orm.collections import attribute_mapped_collection metadata = MetaData() # Here we have named animals, and a collection of facts about them. animals = Table('animal', metadata, Column('id', Integer, primary_key=True), Column('name', Unicode(100))) facts = Table('facts', metadata, Column('animal_id', Integer, ForeignKey('animal.id'), primary_key=True), Column('key', Unicode(64), primary_key=True), Column('value', UnicodeText, default=None),) class AnimalFact(VerticalProperty): """A fact about an animal.""" class Animal(VerticalPropertyDictMixin): """An animal. Animal facts are available via the 'facts' property or by using dict-like accessors on an Animal instance:: cat['color'] = 'calico' # or, equivalently: cat.facts['color'] = AnimalFact('color', 'calico') """ _property_type = AnimalFact _property_mapping = 'facts' def __init__(self, name): self.name = name def __repr__(self): return '&lt;%s %r&gt;' % (self.__class__.__name__, self.name) mapper(Animal, animals, properties={ 'facts': relationship( AnimalFact, backref='animal', collection_class=attribute_mapped_collection('key')), }) mapper(AnimalFact, facts) metadata.bind = 'sqlite:///' metadata.create_all() session = create_session() stoat = Animal(u'stoat') stoat[u'color'] = u'reddish' stoat[u'cuteness'] = u'somewhat' # dict-like assignment transparently creates entries in the # stoat.facts collection: print stoat.facts[u'color'] session.add(stoat) session.flush() session.expunge_all() critter = session.query(Animal).filter(Animal.name == u'stoat').one() print critter[u'color'] print critter[u'cuteness'] critter[u'cuteness'] = u'very' print 'changing cuteness:' metadata.bind.echo = True session.flush() metadata.bind.echo = False marten = Animal(u'marten') marten[u'color'] = u'brown' marten[u'cuteness'] = u'somewhat' session.add(marten) shrew = Animal(u'shrew') shrew[u'cuteness'] = u'somewhat' shrew[u'poisonous-part'] = u'saliva' session.add(shrew) loris = Animal(u'slow loris') loris[u'cuteness'] = u'fairly' loris[u'poisonous-part'] = u'elbows' session.add(loris) session.flush() q = (session.query(Animal). filter(Animal.facts.any( and_(AnimalFact.key == u'color', AnimalFact.value == u'reddish')))) print 'reddish animals', q.all() # Save some typing by wrapping that up in a function: with_characteristic = lambda key, value: and_(AnimalFact.key == key, AnimalFact.value == value) q = (session.query(Animal). filter(Animal.facts.any( with_characteristic(u'color', u'brown')))) print 'brown animals', q.all() q = (session.query(Animal). filter(not_(Animal.facts.any( with_characteristic(u'poisonous-part', u'elbows'))))) print 'animals without poisonous-part == elbows', q.all() q = (session.query(Animal). filter(Animal.facts.any(AnimalFact.value == u'somewhat'))) print 'any animal with any .value of "somewhat"', q.all() # Facts can be queried as well. q = (session.query(AnimalFact). filter(with_characteristic(u'cuteness', u'very'))) print 'just the facts', q.all() metadata.drop_all() </code></pre>
5
2010-05-23T04:36:12Z
[ "python", "database", "database-design", "sqlalchemy" ]
Best Python Library for Downloading and Extracting Addresses
1,300,479
<p>I've just been given a project which involves the following steps</p> <ol> <li>Grab an email from a POP3 address</li> <li>Open an attachment from the email</li> <li>Extract the To: email address</li> <li>Add this to a global suppression list </li> </ol> <p>I'd like to try and do this in Python even though I could it in PHP in half the time (this is because I dont know anywhere near as much Python as PHP) </p> <p>My question would be.</p> <p>Can anyone recommend a Python library for interacting with email in the way described above?</p> <p>Many thanks in advance</p>
0
2009-08-19T14:51:12Z
1,300,517
<p>Two bits from the standard library: <a href="http://docs.python.org/library/poplib.html" rel="nofollow">poplib</a> to grab the email via POP3, <a href="http://docs.python.org/library/email.html" rel="nofollow">email</a> to slice and dice it as you wish.</p>
2
2009-08-19T14:59:24Z
[ "python", "email", "pop3" ]
Python - substr
1,300,610
<p>I need to be able to get the last digit of a number.</p> <p>i.e., I need 2 to be returned from: 12.</p> <p>Like this in PHP: <code>$minute = substr(date('i'), -1)</code> but I need this in Python.</p> <p>Any ideas</p>
1
2009-08-19T15:14:28Z
1,300,619
<pre><code>last_digit = str(number)[-1] </code></pre>
10
2009-08-19T15:16:16Z
[ "php", "python", "substr" ]
Python - substr
1,300,610
<p>I need to be able to get the last digit of a number.</p> <p>i.e., I need 2 to be returned from: 12.</p> <p>Like this in PHP: <code>$minute = substr(date('i'), -1)</code> but I need this in Python.</p> <p>Any ideas</p>
1
2009-08-19T15:14:28Z
1,300,625
<p>Use the <strong>%</strong> operator:</p> <pre><code> x = 12 % 10 # returns 2 y = 25 % 10 # returns 5 z = abs(-25) % 10 # returns 5 </code></pre>
8
2009-08-19T15:16:43Z
[ "php", "python", "substr" ]
Python - substr
1,300,610
<p>I need to be able to get the last digit of a number.</p> <p>i.e., I need 2 to be returned from: 12.</p> <p>Like this in PHP: <code>$minute = substr(date('i'), -1)</code> but I need this in Python.</p> <p>Any ideas</p>
1
2009-08-19T15:14:28Z
1,300,675
<p>Python distinguishes between strings and numbers (and actually also between numbers of different kinds, i.e., int vs float) so the best solution depends on what type you start with (str or int?) and what type you want as a result (ditto).</p> <p>Int to int: <code>abs(x) % 10</code></p> <p>Int to str: <code>str(x)[-1]</code></p> <p>Str to int: <code>int(x[-1])</code></p> <p>Str to str: <code>x[-1]</code></p>
2
2009-08-19T15:23:38Z
[ "php", "python", "substr" ]
Multidimensional list(array) reassignment problem
1,300,648
<p>Good day coders and codereses,</p> <p>I am writing a piece of code that goes through a pile of statistical data and returns what I ask from it. To complete its task the method reads from one multidimensional array and writes into another one. The piece of code giving me problems is:</p> <pre><code>writer.variables[variable][:, :, :, :] = reader.variables[variable][offset:, 0, 0:5, 3] </code></pre> <p>The size of both slices is <code>27:1:6:1</code> but it throws up an exception:</p> <pre><code>ValueError: total size of new array must be unchanged </code></pre> <p>I am flabbergasted.</p> <p>Thank you.</p>
1
2009-08-19T15:20:52Z
1,300,692
<p>The size of a slice with <code>0:5</code> is not 6 as you say: it's 5. The upper limit is excluded in slicing (as it most always is, in Python). Don't know whether that's your actual problem or just a typo in your question...</p>
2
2009-08-19T15:25:59Z
[ "python", "list", "numpy", "scipy", "netcdf" ]
Writing Python/Django view to "join" across three models/tables
1,300,657
<p>Just begin my Python/Django experience and i have a problem :-)</p> <p>So i have a model.py like this:</p> <pre><code>from django.db import models class Priority(models.Model): name = models.CharField(max_length=100) class Projects(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=150) priority = models.ForeignKey(Priority) class Tasks(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=40) priority = models.ForeignKey(Priority) </code></pre> <p>In the priority table i plan to store data like 1.High, 2.Medium , 3.Low and in Tasks table priority will be stored as id (1, 2 or 3)</p> <p>And the question is how to write a view that display all my tasks but with Priority named? For example:</p> <pre><code>name: Task 1 description: Description 1 priority: **High** </code></pre>
1
2009-08-19T15:21:39Z
1,300,701
<p>There are many ways of accomplishing what you need. One of the easiest would be to keep a dictionary of number to string. Like this: 1->High, 2->Medium, 3->High.</p> <p>Keep this dictionary outside of your view functions so that you can access it from any of your view functions that need to get the priority.</p> <p>You could also simply write a switch that determines what to display in the template.</p>
0
2009-08-19T15:27:21Z
[ "python", "django-views" ]
Writing Python/Django view to "join" across three models/tables
1,300,657
<p>Just begin my Python/Django experience and i have a problem :-)</p> <p>So i have a model.py like this:</p> <pre><code>from django.db import models class Priority(models.Model): name = models.CharField(max_length=100) class Projects(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=150) priority = models.ForeignKey(Priority) class Tasks(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=40) priority = models.ForeignKey(Priority) </code></pre> <p>In the priority table i plan to store data like 1.High, 2.Medium , 3.Low and in Tasks table priority will be stored as id (1, 2 or 3)</p> <p>And the question is how to write a view that display all my tasks but with Priority named? For example:</p> <pre><code>name: Task 1 description: Description 1 priority: **High** </code></pre>
1
2009-08-19T15:21:39Z
1,300,789
<p>Your view doesn't have to do much.</p> <pre><code>tasks = Tasks.objects.all() </code></pre> <p>Provide this to your template.</p> <p>Your template can then do something like the following.</p> <pre><code>{% for t in tasks %} name: {{t.name}} description: {{t.description}} priority: **{{t.priority.name}}** {% endfor %} </code></pre>
2
2009-08-19T15:37:20Z
[ "python", "django-views" ]
Hierarchical data output from App Engine Datastore to JSON?
1,300,694
<p>I have a large hierarchical dataset in the App Engine Datastore. The hierarchy is preserved by storing the data in Entity groups, so that I can pull a whole tree by simply knowing the top element key like so:</p> <p><code>query = db.Query().ancestor(db.get(key))</code></p> <p>The question: How do I now output this data as JSON and preserve the hierarchy?</p> <p>Google has a utility class called GqlEncoder that add support for datastore query results to simplejson, but it basically flattens the data, destroying the hierarchy.</p> <p>Any suggestions?</p>
1
2009-08-19T15:26:07Z
1,300,783
<p>I imagine you're referring to <a href="http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55" rel="nofollow">this code</a> and the "flattening" you mention is done by lines 51-52:</p> <pre><code> if isinstance(obj, db.GqlQuery): return list(obj) </code></pre> <p>while the rest of the code is fine for your purpose. So, how would you like to represent a GQL query, since you don't what a JS array (Python list) of the objects it contains? It's not clear, besides the entity group (which you're recovering entirely), what gives it hierarchy; is it an issue of "parent"?</p> <p>Anyway, once that's clarified, copying and editing that file into your own code seems best (it's not designed to let you override just that one tidbit).</p>
1
2009-08-19T15:36:49Z
[ "python", "json", "google-app-engine", "gae-datastore" ]
Load blob image data into QPixmap
1,300,908
<p>I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:</p> <pre><code>def dump_image(imgfile): i = open(imgfile, 'rb') i.seek(0) w = i.read() i.close() return cPickle.dumps(w,1) blob = dump_image(imgfile) hex_str = blob.encode('hex') # x"%s"%hex_str will be the string inserted into the SQL command </code></pre> <p>This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:</p> <p>(1) Hex str in database -- cPickle&amp;StringIO --> PIL Image Object </p> <pre><code>def load_image(s): o = cPickle.loads(s) c = StringIO.StringIO() c.write(o) c.seek(0) im = Image.open(c) return im </code></pre> <p>(2) PIL Image Object -->Temporary image file</p> <p>(3) Temporary image file --> QPixmap</p> <p>This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use <a href="http://docs.huihoo.com/pyqt/pyqt4/html/qpixmap.html#loadFromData" rel="nofollow">QPixmap::loadFromData()</a> to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.</p> <p>TIA,</p> <p>Bing</p>
4
2009-08-19T15:52:53Z
1,300,979
<p>You can use the QImage.fromData static method to load an image from a string and then convert it to a pixmap:</p> <pre><code> image_data = get_image_data_from_blob() qimg = QtGui.QImage.fromData(image_data) pixmap = QtGui.QPixmap.fromImage(qimg) </code></pre>
6
2009-08-19T16:05:42Z
[ "python", "image", "pyqt", "blob", "qpixmap" ]
Load blob image data into QPixmap
1,300,908
<p>I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:</p> <pre><code>def dump_image(imgfile): i = open(imgfile, 'rb') i.seek(0) w = i.read() i.close() return cPickle.dumps(w,1) blob = dump_image(imgfile) hex_str = blob.encode('hex') # x"%s"%hex_str will be the string inserted into the SQL command </code></pre> <p>This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:</p> <p>(1) Hex str in database -- cPickle&amp;StringIO --> PIL Image Object </p> <pre><code>def load_image(s): o = cPickle.loads(s) c = StringIO.StringIO() c.write(o) c.seek(0) im = Image.open(c) return im </code></pre> <p>(2) PIL Image Object -->Temporary image file</p> <p>(3) Temporary image file --> QPixmap</p> <p>This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use <a href="http://docs.huihoo.com/pyqt/pyqt4/html/qpixmap.html#loadFromData" rel="nofollow">QPixmap::loadFromData()</a> to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.</p> <p>TIA,</p> <p>Bing</p>
4
2009-08-19T15:52:53Z
1,301,997
<p>The approach suggested by Ants Aasma works and actually it is also OK to just use the following code: </p> <pre><code>image_data = cPickle.loads(str(s)) # s is fetched from DB qp = QPixmap() qp.loadFromData(image_data) </code></pre> <p>Thanks a lot for all the help and information.</p>
1
2009-08-19T19:02:15Z
[ "python", "image", "pyqt", "blob", "qpixmap" ]
Load blob image data into QPixmap
1,300,908
<p>I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:</p> <pre><code>def dump_image(imgfile): i = open(imgfile, 'rb') i.seek(0) w = i.read() i.close() return cPickle.dumps(w,1) blob = dump_image(imgfile) hex_str = blob.encode('hex') # x"%s"%hex_str will be the string inserted into the SQL command </code></pre> <p>This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:</p> <p>(1) Hex str in database -- cPickle&amp;StringIO --> PIL Image Object </p> <pre><code>def load_image(s): o = cPickle.loads(s) c = StringIO.StringIO() c.write(o) c.seek(0) im = Image.open(c) return im </code></pre> <p>(2) PIL Image Object -->Temporary image file</p> <p>(3) Temporary image file --> QPixmap</p> <p>This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use <a href="http://docs.huihoo.com/pyqt/pyqt4/html/qpixmap.html#loadFromData" rel="nofollow">QPixmap::loadFromData()</a> to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.</p> <p>TIA,</p> <p>Bing</p>
4
2009-08-19T15:52:53Z
2,213,246
<p>After a good hour and a half of googleing to solve a similar problem, I ended up loading JPEGs in a compiled .exe with QT. I am using python3.1, and therefore could not use some of the previously mentioned solutions :</p> <ul> <li>tips working for py2exe (because I am using cxfreeze instead of py2exe, as py2exe works only for python2),</li> <li>tips that require PIL (also only for python2, afaik).</li> </ul> <p>While the solutions posted here didn't work, something very similar did : I simply copied the <code>[PythonDir]\Lib\site-packages\PyQt4\plugins\imageformats</code> to my exe's folder and removed the <code>qt.conf</code> file that I created in that folder following other solutions. That's all (I think :p).</p> <p>After that, it worked whether I loaded the jpg using <code>QPixmap</code>'s constructor or loading a <code>QImage</code> first. It also worked with no special option needed for both the <code>setup.py</code> and the <code>cxfreeze.bat</code> methods of compiling to exe using cxfreeze.</p> <p>(this solution was posted by jbz on <a href="http://www.thetoryparty.com/wp/2009/08/27/pyqt-and-py2app-seriously-i-dont-know-what-to-do-with-you-when-youre-like-this/" rel="nofollow">http://www.thetoryparty.com/wp/2009/08/27/pyqt-and-py2app-seriously-i-dont-know-what-to-do-with-you-when-youre-like-this/</a>)</p> <p>This question is a bit old, but as the problem seems to be still there, I hope this answer will help python3.1 users out there.</p>
0
2010-02-06T13:32:12Z
[ "python", "image", "pyqt", "blob", "qpixmap" ]
mod_python problem?
1,301,000
<p>I have been working on a website using mod_python, python, and SQL Alchemy when I ran into a strange problem: When I query the database for all of the records, it returns the correct result set; however, when I refresh the page, it returns me a result set with that same result set appended to it. I get more result sets "stacked" on top of eachother as I refresh the page more.</p> <p><strong>For example:</strong></p> <p>First page load: 10 results</p> <p>Second page load: 20 results (two of each)</p> <p>Third page load: 30 results (three of each)</p> <p><em>etc...</em></p> <p>Is this some underlying problem with mod_python? I don't recall running into this when using mod_wsgi.</p>
0
2009-08-19T16:08:45Z
1,301,029
<p>Not that I've ever heard of, but it's impossible to tell without some code to look at.</p> <p>Maybe you initialised your result set list as a global, or shared member, and then appended results to it when the application was called without resetting it to empty? A classic way of re-using lists accidentally is to put one in a default argument value to a function. </p> <p>(The same could happen in mod_wsgi of course.)</p>
0
2009-08-19T16:13:55Z
[ "python", "sqlalchemy", "mod-python" ]
mod_python problem?
1,301,000
<p>I have been working on a website using mod_python, python, and SQL Alchemy when I ran into a strange problem: When I query the database for all of the records, it returns the correct result set; however, when I refresh the page, it returns me a result set with that same result set appended to it. I get more result sets "stacked" on top of eachother as I refresh the page more.</p> <p><strong>For example:</strong></p> <p>First page load: 10 results</p> <p>Second page load: 20 results (two of each)</p> <p>Third page load: 30 results (three of each)</p> <p><em>etc...</em></p> <p>Is this some underlying problem with mod_python? I don't recall running into this when using mod_wsgi.</p>
0
2009-08-19T16:08:45Z
1,301,471
<p>I don't know about any of the technologies you are using. However, before you think that might be a possible bug in the packages you are using, you have to consider one thing.</p> <p><a href="http://en.wikipedia.org/wiki/Occam%27s%5Frazor" rel="nofollow">Occam's razor.</a></p> <p>Basically, "when you have two competing theories that make exactly the same predictions, the simpler one is the better."</p> <p>Your two possible major theories here is that there is a bug in the components you are using (that many others use) or there is a bug in your code. Chances are (and I'm sorry) there is a bug in your code. </p> <p>I use this idea with my own code and every time there was a problem it did turn out to be my code. </p> <p>Hopefully others can direct you to the bug and you might want to post the problem code. You may not be clearing a result set or something -- a variable -- is being held on longer than you expect.</p>
0
2009-08-19T17:34:23Z
[ "python", "sqlalchemy", "mod-python" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,301,206
<p>It may be proven through profiling that this isn't quite the fastest but...</p> <pre><code>import collections a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } dicts = [a,b] totals = collections.defaultdict(list) avg = {} for D in dicts: for key,value in D.iteritems(): totals[key].append(value) for key,values in totals.iteritems(): avg[key] = sum(values) / len(values) </code></pre> <p>I'm <em>guessing</em> that allowing Python to use the built-ins <code>sum()</code> and <code>len()</code> is going to gain some performance over calculating the mean as you see new values, but I could sure be wrong about that.</p>
2
2009-08-19T16:48:07Z
[ "python", "dictionary" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,301,211
<p>This works:</p> <pre><code>import collections data= [ {'x': 1.0, 'y': 0.5, 'z': 0.25 }, {'w': 0.5, 'x': 0.2 } ] tally = collections.defaultdict(lambda: (0.0, 0)) for d in data: for k,v in d.items(): sum, count = tally[k] tally[k] = (sum+v, count+1) results = {} for k, v in tally.items(): t = tally[k] results[k] = t[0]/t[1] print results </code></pre> <p>I don't know if it's faster than yours, since you haven't posted your code.</p> <pre><code>{'y': 0.5, 'x': 0.59999999999999998, 'z': 0.25, 'w': 0.5} </code></pre> <p>I tried in tally to avoid storing all the values again, simply accumulating the sum and count I'd need to compute the average at the end. Often, the time bottleneck in a Python program is in the memory allocator, and using less memory can help a lot with speed.</p>
2
2009-08-19T16:48:34Z
[ "python", "dictionary" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,301,218
<pre><code>&gt;&gt;&gt; def avg(items): ... return sum(items) / len(items) ... &gt;&gt;&gt; hashes = [a, b] &gt;&gt;&gt; dict([(k, avg([h.get(k) or 0 for h in hashes])) for k in set(sum((h.keys() for h in hashes), []))]) {'y': 0.25, 'x': 0.59999999999999998, 'z': 0.125, 'w': 0.25} </code></pre> <p>Explanation:</p> <ol> <li><p>The set of keys in all of the hashes, no repeats.</p> <pre><code>set(sum((h.keys() for h in hashes), [])) </code></pre></li> <li><p>The average value for each key in the above set, using 0 if the value doesn't exist in a particular hash.</p> <pre><code>(k, avg([h.get(k) or 0 for h in hashes])) </code></pre></li> </ol>
1
2009-08-19T16:49:44Z
[ "python", "dictionary" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,301,527
<p>It is possible that your bottleneck might be due to excessive memory use. Consider using iteritems to leverage the power of generators.</p> <p>Since you say your data is sparse, that will probably not be the most efficient. Consider this alternate usage of iterators:</p> <pre><code>dicts = ... #Assume this is your dataset totals = {} lengths = {} means = {} for d in dicts: for key,value in d.iteritems(): totals.setdefault(key,0) lengths.setdefault(key,0) totals[key] += value length[key] += 1 for key,value in totals.iteritems(): means[key] = value / lengths[key] </code></pre> <p>Here totals, lengths, and means are the only data structures you create. This ought to be fairly speedy, since it avoids having to create auxiliary lists and only loops through each dictionary exactly once per key it contains.</p> <p>Here's a second approach that I doubt will be an improvement in performance over the first, but it theoretically could, depending on your data and machine, since it will require less memory allocation:</p> <pre><code>dicts = ... #Assume this is your dataset key_set = Set([]) for d in dicts: key_set.update(d.keys()) means = {} def get_total(dicts, key): vals = (dict[key] for dict in dicts if dict.has_key(key)) return sum(vals) def get_length(dicts, key): vals = (1 for dict in dicts if dict.has_key(key)) return sum(vals) def get_mean(dicts,key): return get_total(dicts,key)/get_length(dicts,key) for key in key_set: means[key] = get_mean(dicts,key) </code></pre> <p>You do end up looping through all dictionaries twice for each key, but need no intermediate data structures other than the key_set.</p>
0
2009-08-19T17:45:58Z
[ "python", "dictionary" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,301,644
<p><a href="http://www.scipy.org/doc/api%5Fdocs/SciPy.sparse.sparse.html" rel="nofollow">scipy.sparse</a> supports sparse matrices -- the <a href="http://www.scipy.org/doc/api%5Fdocs/SciPy.sparse.sparse.dok%5Fmatrix.html" rel="nofollow"><code>dok_matrix</code></a> form seems reasonably suited to your needs (you'll have to use integer coordinates, though, so a separate pass will be needed to collect and put in any arbitrary but definite order the string keys you currently have). If you have a huge number of very large and sparse "arrays", the performance gains might possibly be worth the complications.</p>
0
2009-08-19T18:05:44Z
[ "python", "dictionary" ]
Fastest ways to key-wise add a list of dicts together in python
1,301,149
<p>Say I have a bunch of dictionaries </p> <pre><code>a = {'x': 1.0, 'y': 0.5, 'z': 0.25 } b = {'w': 0.5, 'x': 0.2 } </code></pre> <p>There's only two there, but the question is regarding an arbitary amount.</p> <p>What's the fastest way to find the mean value for each key? The dicts are quite sparse, so there will be a lot of cases where lots of keys aren't present in various dicts.</p> <p>The result I'm looking for is a new dictionary which has all the keys and the mean values for each one. The values are always floats, I'm happy to dip into ctypes. The approach I have is slower than I'd like, possibly because in my case I'm using defaultdicts which means I'm actually initialising values even if they're not there. If this is the cause of the slowness I'm happy to refactor, just want to make sure I'm not missing anything obvious.</p> <p>Edit: I think I was misleading with what the result should be, if the value isn't present it should act as 0.0, so the result for the above example would be:</p> <pre><code>{'w':0.25,'x':0.6,'y':0.25,'z':0.125} </code></pre> <p>So the division is by the total number of unique keys.</p> <p>The main thing I'm wondering is if there's a sneaky way to divide the whole dict by the length in one step, or do the additions in one step. Basically a very fast vector addition and division. I've looked briefly at numpy arrays, but they don't seem to apply to dicts and if I converted the dicts to lists I'd have to remove the sparseness property (by explicitly setting absent values to 0).</p>
3
2009-08-19T16:38:40Z
1,302,027
<p>It's simple but this could work:</p> <pre><code>a = { 'x': 1.0, 'y': 0.5, 'z': 0.25 } b = { 'w': 0.5, 'x': 0.2 } ds = [a, b] result = {} for d in ds: for k, v in d.iteritems(): result[k] = v + result.get(k, 0) n = len(ds) result = dict((k, amt/n) for k, amt in result.iteritems()) print result </code></pre> <p>I have no idea how it compares to your method since you didn't post any code.</p>
0
2009-08-19T19:07:34Z
[ "python", "dictionary" ]
How to sort digits in a number?
1,301,156
<p>I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's constant</a>.</p> <p>It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.</p>
2
2009-08-19T16:39:13Z
1,301,168
<pre><code>&gt;&gt;&gt; x = [4,5,81,5,28958,28] # first list &gt;&gt;&gt; print sorted(x) [4, 5, 5, 28, 81, 28958] &gt;&gt;&gt; x [4, 5, 81, 5, 28958, 28] &gt;&gt;&gt; x.sort() # sort the list in place &gt;&gt;&gt; x [4, 5, 5, 28, 81, 28958] &gt;&gt;&gt; x.append(1) # add to the list &gt;&gt;&gt; x [4, 5, 5, 28, 81, 28958, 1] &gt;&gt;&gt; sorted(x) [1, 4, 5, 5, 28, 81, 28958] </code></pre> <p>As many others have pointed out, you can sort a number forwards like:</p> <pre><code>&gt;&gt;&gt; int(''.join(sorted(str(2314)))) 1234 </code></pre> <p>That's pretty much the most standard way.</p> <p>Reverse a number? Doesn't work well in a number with trailing zeros.</p> <pre><code>&gt;&gt;&gt; y = int(''.join(sorted(str(2314)))) &gt;&gt;&gt; y 1234 &gt;&gt;&gt; int(str(y)[::-1]) 4321 </code></pre> <p>The <code>[::-1]</code> notation indicates that the iterable is to be traversed in reverse order.</p>
2
2009-08-19T16:41:17Z
[ "python", "numbers" ]
How to sort digits in a number?
1,301,156
<p>I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's constant</a>.</p> <p>It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.</p>
2
2009-08-19T16:39:13Z
1,301,246
<p>Sort the digits in ascending and descending orders:</p> <pre><code>ascending = "".join(sorted(str(number))) descending = "".join(sorted(str(number), reverse=True)) </code></pre> <p>Like this:</p> <pre><code>&gt;&gt;&gt; number = 5896 &gt;&gt;&gt; ascending = "".join(sorted(str(number))) &gt;&gt;&gt; &gt;&gt;&gt; descending = "".join(sorted(str(number), reverse=True)) &gt;&gt;&gt; ascending '5689' &gt;&gt;&gt; descending '9865' </code></pre> <p>And if you need them to be numbers again (not just strings), call <code>int()</code> on them:</p> <pre><code>&gt;&gt;&gt; int(ascending) 5689 &gt;&gt;&gt; int(descending) 9865 </code></pre>
10
2009-08-19T16:55:37Z
[ "python", "numbers" ]
How to sort digits in a number?
1,301,156
<p>I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's constant</a>.</p> <p>It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.</p>
2
2009-08-19T16:39:13Z
1,301,313
<p>I don't know the python syntax, but thinking the generically, I would convert the input string into a character array, they do a sort on the character array, and lastly pipe it out.</p>
1
2009-08-19T17:07:59Z
[ "python", "numbers" ]
How to sort digits in a number?
1,301,156
<p>I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's constant</a>.</p> <p>It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.</p>
2
2009-08-19T16:39:13Z
1,303,841
<p>As Mark Rushakoff already mentioned (but didn't solve) in his answer, <code>str(n)</code> doesn't handle numeric <code>n</code> with leading zeros, which you need for <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's operation</a>. hughdbrown's answer similarly doesn't work with leading zeros.</p> <p>One way to make sure you have a four-character string is to use the <code>zfill</code> string method. For example:</p> <pre><code>&gt;&gt;&gt; n = 2 &gt;&gt;&gt; str(n) '2' &gt;&gt;&gt; str(n).zfill(4) '0002' </code></pre> <p>You should also be aware that in versions of Python prior to 3, a leading zero in a numeric literal indicated octal:</p> <pre><code>&gt;&gt;&gt; str(0043) '35' &gt;&gt;&gt; str(0378) File "&lt;stdin&gt;", line 1 str(0378) ^ SyntaxError: invalid token </code></pre> <p>In Python 3, <code>0043</code> is not a valid numeric literal at all.</p>
2
2009-08-20T03:46:54Z
[ "python", "numbers" ]
How to sort digits in a number?
1,301,156
<p>I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing <a href="http://en.wikipedia.org/wiki/6174" rel="nofollow">Kaprekar's constant</a>.</p> <p>It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well.</p>
2
2009-08-19T16:39:13Z
1,338,221
<p>Here's an answer to the title question in Perl, with a bias toward sorting 4-digit numbers for the Kaprekar algorithm. In the example, replace 'shift' with the number to sort. It sorts digits in a 4-digit number with leading 0's ($asc is sorted in ascending order, $dec is descending), and outputs a number with leading 0's:</p> <pre><code>my $num = sprintf("%04d", shift); my $asc = sprintf("%04d", join('', sort {$a &lt;=&gt; $b} split('', $num))); my $dec = sprintf("%04d", join('', sort {$b &lt;=&gt; $a} split('', $num))); </code></pre>
0
2009-08-27T00:05:21Z
[ "python", "numbers" ]
unable to import libxml2mod from the python script
1,301,167
<pre><code>File "/usr/local/lib/python2.5/site-packages/libxml2.py", line 1, in &lt;module&gt; import libxml2mod ImportError: /usr/local/lib/python2.5/site-packages/libxml2mod.so: undefined symbol:xmlTextReaderSetup &gt;&gt;&gt; import libxml2mod &gt;&gt;&gt; import libxml2 &gt;&gt;&gt; </code></pre> <p>on Python Prompt it works fine !!</p> <p>can anyone has idea why my program is not working from .py file as import is working perfect from python prompt.</p>
0
2009-08-19T16:40:58Z
1,302,196
<p>I can only suggest that your paths are different for some reason. Either that, or you are not using the same python interpreter in both cases.</p> <p>I have experienced this when I happen to have a couple of interpreters, and the wrong one is either default, or specified in the #! section of the script.</p>
2
2009-08-19T19:37:30Z
[ "python", "importerror" ]
What regex can I use to capture groups from this string?
1,301,257
<p>Assume the following strings:</p> <ul> <li><code>A01B100</code></li> <li><code>A01.B100</code></li> <li><code>A01</code></li> <li><code>A01............................B100</code> ( whatever between A and B )</li> </ul> <p>The thing is, the numbers should be <code>\d+</code>, and in all of the strings A will always be present, while B may not. A will always be followed by one or more digits, and so will B, if present. What regex could I use to capture A and B's digit?</p> <p>I have the following regex:</p> <pre><code>(A(\d+)).*?(B?(\d+)?) </code></pre> <p>but this only works for the first and the third case.</p>
1
2009-08-19T16:58:06Z
1,301,281
<pre><code>(?ms)^A(\d+)(?:[^\n\r]*B(\d+))?$ </code></pre> <p>Assuming one string per line:</p> <ul> <li><p>the [^\n\r]* is a non-greedy match for any characters (except newlines) after Axx, meaing it could gobble an intermediate Byy before the last B:</p> <p>A01...B01...B23</p></li> </ul> <p>would be matched, with 01 and 23 detected.</p>
1
2009-08-19T17:02:59Z
[ "python", "regex" ]
What regex can I use to capture groups from this string?
1,301,257
<p>Assume the following strings:</p> <ul> <li><code>A01B100</code></li> <li><code>A01.B100</code></li> <li><code>A01</code></li> <li><code>A01............................B100</code> ( whatever between A and B )</li> </ul> <p>The thing is, the numbers should be <code>\d+</code>, and in all of the strings A will always be present, while B may not. A will always be followed by one or more digits, and so will B, if present. What regex could I use to capture A and B's digit?</p> <p>I have the following regex:</p> <pre><code>(A(\d+)).*?(B?(\d+)?) </code></pre> <p>but this only works for the first and the third case.</p>
1
2009-08-19T16:58:06Z
1,301,291
<pre><code>A\d+.*(B\d+)? </code></pre> <p>OK, so that provides something which passes all test cases... BUT it has some false positives.</p> <pre><code>A\d+(.*B\d+)? </code></pre> <p>It seems other characters should only appear if B(whatever) is after them, so use the above instead.</p> <pre><code>#perl test case hackup @array = ('A01B100', 'A01.B100', 'A01', 'A01............................B100', 'A01FAIL', 'NEVER'); for (@array) { print "$_\n" if $_ =~ /^A\d+(.*B\d+)?$/; } </code></pre>
0
2009-08-19T17:04:41Z
[ "python", "regex" ]
What regex can I use to capture groups from this string?
1,301,257
<p>Assume the following strings:</p> <ul> <li><code>A01B100</code></li> <li><code>A01.B100</code></li> <li><code>A01</code></li> <li><code>A01............................B100</code> ( whatever between A and B )</li> </ul> <p>The thing is, the numbers should be <code>\d+</code>, and in all of the strings A will always be present, while B may not. A will always be followed by one or more digits, and so will B, if present. What regex could I use to capture A and B's digit?</p> <p>I have the following regex:</p> <pre><code>(A(\d+)).*?(B?(\d+)?) </code></pre> <p>but this only works for the first and the third case.</p>
1
2009-08-19T16:58:06Z
1,301,293
<pre><code>import re m = re.match(r"A(?P&lt;d1&gt;\d+)\.*(B(?P&lt;d2&gt;\d+))?", "A01.B100") print m.groupdict() </code></pre>
0
2009-08-19T17:04:45Z
[ "python", "regex" ]
What regex can I use to capture groups from this string?
1,301,257
<p>Assume the following strings:</p> <ul> <li><code>A01B100</code></li> <li><code>A01.B100</code></li> <li><code>A01</code></li> <li><code>A01............................B100</code> ( whatever between A and B )</li> </ul> <p>The thing is, the numbers should be <code>\d+</code>, and in all of the strings A will always be present, while B may not. A will always be followed by one or more digits, and so will B, if present. What regex could I use to capture A and B's digit?</p> <p>I have the following regex:</p> <pre><code>(A(\d+)).*?(B?(\d+)?) </code></pre> <p>but this only works for the first and the third case.</p>
1
2009-08-19T16:58:06Z
1,301,306
<ul> <li>Must <code>A</code> precede <code>B</code>? Assuming yes.</li> <li>Can <code>B</code> appear more than once? Assuming no. </li> <li>Can <code>B</code> appear except as part of a <code>B</code>-number group? Assuming no.</li> </ul> <p>Then,</p> <pre><code>A\d+.*?(B\d+)? </code></pre> <p>using the lazy .*? or</p> <pre><code>A\d+[^B]*(B\d+)? </code></pre> <p>which is more efficient but requires that <code>B</code> be a single character.</p> <p>EDIT: Upon further reflection, I have parenthesized the patterns in a less-than-perfect way. The following patterns should require fewer assumptions:</p> <pre><code>A\d+(.*?B\d+)? a\d+([^B]*B\d+)? </code></pre>
3
2009-08-19T17:06:38Z
[ "python", "regex" ]
How can I make a Django query for the first occurrence of a foreign key in a column?
1,301,270
<p>Basically, I have a table with a bunch of foreign keys and I'm trying to query only the first occurrence of a particular key by the "created" field. Using the Blog/Entry example, if the Entry model has a foreign key to Blog and a foreign key to User, then how can I construct a query to select all Entries in which a particular User has written the first one for the various Blogs?</p> <pre><code>class Blog(models.Model): ... class User(models.Model): ... class Entry(models.Model): blog = models.Foreignkey(Blog) user = models.Foreignkey(User) </code></pre> <p>I assume there's some magic I'm missing to select the first entries of a blog and that I can simple filter further down to a particular user by appending:</p> <pre><code>query = Entry.objects.magicquery.filter(user=user) </code></pre> <p>But maybe there's some other more efficient way. Thanks!</p>
1
2009-08-19T17:01:11Z
1,301,376
<p><code>query = Entry.objects.filter(user=user).order_by('id')[0]</code></p> <p>Basically order by id (lowest to highest), and slice it to get only the first hit from the QuerySet.</p> <p>I don't have a Django install available right now to test my line, so please check the documentation if somehow I have a type above:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields" rel="nofollow">order by</a></p> <p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets" rel="nofollow">limiting querysets</a></p> <p>By the way, interesting note on 'limiting queysets" manual section:</p> <blockquote> <p>To retrieve a single object rather than a list (e.g. SELECT foo FROM bar LIMIT 1), use a simple index instead of a slice. For example, this returns the first Entry in the database, after ordering entries alphabetically by headline:</p> <p><code>Entry.objects.order_by('headline')[0]</code></p> </blockquote> <p>EDIT: Ok, this is the best I could come up so far (after yours and mine comment). It doesn't return Entry objects, but its ids as <code>entry_id</code>.</p> <p><code>query = Entry.objects.values('blog').filter(user=user).annotate(Count('blog')).annotate(entry_id=Min('id'))</code></p> <p>I'll keep looking for a better way.</p>
1
2009-08-19T17:16:42Z
[ "python", "django", "foreign-keys" ]
How can I make a Django query for the first occurrence of a foreign key in a column?
1,301,270
<p>Basically, I have a table with a bunch of foreign keys and I'm trying to query only the first occurrence of a particular key by the "created" field. Using the Blog/Entry example, if the Entry model has a foreign key to Blog and a foreign key to User, then how can I construct a query to select all Entries in which a particular User has written the first one for the various Blogs?</p> <pre><code>class Blog(models.Model): ... class User(models.Model): ... class Entry(models.Model): blog = models.Foreignkey(Blog) user = models.Foreignkey(User) </code></pre> <p>I assume there's some magic I'm missing to select the first entries of a blog and that I can simple filter further down to a particular user by appending:</p> <pre><code>query = Entry.objects.magicquery.filter(user=user) </code></pre> <p>But maybe there's some other more efficient way. Thanks!</p>
1
2009-08-19T17:01:11Z
1,303,400
<p>Can't test it in this particular moment</p> <pre><code>Entry.objects.filter(user=user).distinct("blog").order_by("id") </code></pre>
0
2009-08-20T00:47:16Z
[ "python", "django", "foreign-keys" ]
Python2.6 xmpp Jabber Error
1,301,303
<p>I am using xmpp with python and I want create a simple client to communicate with a gmail id. </p> <pre><code>#!/usr/bin/python import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login,pwd, 'botty') cnx.send( xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" ) ) </code></pre> <p>When I run the last line I get an exception</p> <blockquote> <p>IOError: Disconnected from server.</p> </blockquote> <p>Also when I run the other statements I get debug messages in the console.</p> <p>What could be the issue and how can I resolve it ?</p>
4
2009-08-19T17:06:20Z
1,301,357
<p>I think you need to call <code>sendInitPresence</code> before sending the first message:</p> <pre><code>... cnx.auth(login,pwd, 'botty') cnx.sendInitPresence() cnx.send( xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" ) ) </code></pre>
0
2009-08-19T17:13:15Z
[ "python", "xmpp" ]
Python2.6 xmpp Jabber Error
1,301,303
<p>I am using xmpp with python and I want create a simple client to communicate with a gmail id. </p> <pre><code>#!/usr/bin/python import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login,pwd, 'botty') cnx.send( xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" ) ) </code></pre> <p>When I run the last line I get an exception</p> <blockquote> <p>IOError: Disconnected from server.</p> </blockquote> <p>Also when I run the other statements I get debug messages in the console.</p> <p>What could be the issue and how can I resolve it ?</p>
4
2009-08-19T17:06:20Z
1,318,431
<p>Try this code snippet. I didn't handle the error conditions for simplicity's sake.</p> <pre><code>import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' jid = xmpp.protocol.JID(login) cl = xmpp.Client(jid.getDomain(), debug=[]) if cl.connect(('talk.google.com',5223)): print "Connected" else: print "Connectioned failed" if cl.auth(jid.getNode(), pwd): cl.sendInitPresence() cl.send(xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" )) else: print "Authentication failed" </code></pre> <p><br/> To switch off the debugging messages, pass <strong>debug=[]</strong> for the 2nd parameter on the Client class's constructor:</p> <pre><code>cl = xmpp.Client(jid.getDomain(), debug=[]) </code></pre>
1
2009-08-23T12:14:06Z
[ "python", "xmpp" ]
Python2.6 xmpp Jabber Error
1,301,303
<p>I am using xmpp with python and I want create a simple client to communicate with a gmail id. </p> <pre><code>#!/usr/bin/python import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login,pwd, 'botty') cnx.send( xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" ) ) </code></pre> <p>When I run the last line I get an exception</p> <blockquote> <p>IOError: Disconnected from server.</p> </blockquote> <p>Also when I run the other statements I get debug messages in the console.</p> <p>What could be the issue and how can I resolve it ?</p>
4
2009-08-19T17:06:20Z
1,541,802
<p><a href="https://svn.tchoy.net/svn/jTalk/trunk/pyTalk/ConnectorThread.py">Here</a> is how it did on <a href="http://pytalk.trunat.fr/">my PyTalk client</a>.</p> <p><strong>Don't forget the @gmail.com in the userID.</strong></p> <p>I think you should try to connect talk.google.com on the 5222 port.</p> <p>Also try to specify a ressource for the auth.</p> <pre><code>import xmpp import sys userID = 'Your.Login@gmail.com' password = 'YourPassword' ressource = 'Script' jid = xmpp.protocol.JID(userID) jabber = xmpp.Client(jid.getDomain(), debug=[]) connection = jabber.connect(('talk.google.com',5222)) if not connection: sys.stderr.write('Could not connect\n') else: sys.stderr.write('Connected with %s\n' % connection) auth = jabber.auth(jid.getNode(), password, ressource) if not auth: sys.stderr.write("Could not authenticate\n") else: sys.stderr.write('Authenticate using %s\n' % auth) jabber.sendInitPresence(requestRoster=1) jabber.send(xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" )) </code></pre> <p>By the way, it looks very close from Philip Answer</p>
6
2009-10-09T04:31:51Z
[ "python", "xmpp" ]