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
Should I create mapper objects or use the declarative syntax in SQLAlchemy?
1,453,219
<p>There are two (three, but I'm not counting <a href="http://elixir.ematia.de/trac/wiki">Elixir</a>, as its not "official") ways to define a persisting object with <a href="http://www.sqlalchemy.org">SQLAlchemy</a>:</p> <h3><a href="http://www.sqlalchemy.org/docs/05/mappers.html">Explicit syntax for mapper objects</a></h3> <pre><code>from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.orm import mapper metadata = MetaData() users_table = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), ) class User(object): def __init__(self, name): self.name = name def __repr__(self): return "&lt;User('%s')&gt;" % (self.name) mapper(User, users_table) # &amp;lt;Mapper at 0x...; User&amp;gt; </code></pre> <h3><a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html">Declarative syntax</a></h3> <pre><code>from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) def __init__(self, name): self.name = name def __repr__(self): return "&lt;User('%s')&gt;" % (self.name) </code></pre> <p>I can see that while using the mapper objects, I separate completely the ORM definition from the business logic, while using the declarative syntax, whenever I modify the business logic class, I can edit right there the database class (which ideally should be edited little).</p> <p>What I'm not completely sure, is which approach is more maintainable for a business application?</p> <p>I haven't been able to find a comparative between the two mapping methods, to be able to decide which one is a better fit for my project.</p> <p>I'm leaning towards using the "normal" way (i.e. not the declarative extension) as it allows me to "hide", and keep out of the business view all the ORM logic, but I'd like to hear compelling arguments for both approaches.</p>
32
2009-09-21T07:19:43Z
1,454,641
<p>I've found that using mapper objects are much simpler then declarative syntax if you use <a href="http://packages.python.org/sqlalchemy-migrate/">sqlalchemy-migrate</a> to version your database schema (and this is a must-have for a business application from my point of view). If you are using mapper objects you can simply copy/paste your table declarations to migration versions, and use simple api to modify tables in the database. Declarative syntax makes this harder because you have to filter away all helper functions from your class definitions after copying them to the migration version.</p> <p>Also, it seems to me that complex relations between tables are expressed more clearly with mapper objects syntax, but this may be subjective.</p>
5
2009-09-21T13:56:29Z
[ "python", "sqlalchemy" ]
Python HTTPS client with basic authentication via proxy
1,453,264
<p>From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows.</p> <p>I have been playing around with urllib2, however did not succeed so far.</p> <p>I have a solution running, calling wget via os.system():</p> <pre><code>wget_cmd = r'\path\to\wget.exe -q -e "https_proxy = http://fqdn.to.proxy:port" --no-check-certificate --http-user="username" --http-password="password" -O path\to\output https://fqdn.to.site/content' </code></pre> <p>I would like to get rid of the os.system(). Is that possible in Python?</p>
3
2009-09-21T07:35:48Z
1,453,303
<p>Try this (notice that you'll have to fill in the realm of your server also):</p> <pre><code>import urllib2 authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password(realm='Fill In Realm Here', uri='https://fqdn.to.site/content', user='username', passwd='password') proxy_support = urllib2.ProxyHandler({"https" : "http://fqdn.to.proxy:port"}) opener = urllib2.build_opener(proxy_support, authinfo) fp = opener.open("https://fqdn.to.site/content") open(r"path\to\output", "wb").write(fp.read()) </code></pre>
3
2009-09-21T07:50:23Z
[ "python", "proxy", "https", "basic-authentication" ]
Python HTTPS client with basic authentication via proxy
1,453,264
<p>From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows.</p> <p>I have been playing around with urllib2, however did not succeed so far.</p> <p>I have a solution running, calling wget via os.system():</p> <pre><code>wget_cmd = r'\path\to\wget.exe -q -e "https_proxy = http://fqdn.to.proxy:port" --no-check-certificate --http-user="username" --http-password="password" -O path\to\output https://fqdn.to.site/content' </code></pre> <p>I would like to get rid of the os.system(). Is that possible in Python?</p>
3
2009-09-21T07:35:48Z
1,453,341
<p>Proxy and https wasn't working <a href="http://bugs.python.org/issue1424152" rel="nofollow">for a long time</a> with urllib2. It will be fixed in the next released version of python 2.6 (v2.6.3).</p> <p>In the meantime you can reimplement the correct support, that's what we did for mercurial: <a href="http://hg.intevation.org/mercurial/crew/rev/59acb9c7d90f" rel="nofollow">http://hg.intevation.org/mercurial/crew/rev/59acb9c7d90f</a></p>
3
2009-09-21T08:02:17Z
[ "python", "proxy", "https", "basic-authentication" ]
Python HTTPS client with basic authentication via proxy
1,453,264
<p>From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows.</p> <p>I have been playing around with urllib2, however did not succeed so far.</p> <p>I have a solution running, calling wget via os.system():</p> <pre><code>wget_cmd = r'\path\to\wget.exe -q -e "https_proxy = http://fqdn.to.proxy:port" --no-check-certificate --http-user="username" --http-password="password" -O path\to\output https://fqdn.to.site/content' </code></pre> <p>I would like to get rid of the os.system(). Is that possible in Python?</p>
3
2009-09-21T07:35:48Z
3,468,220
<p>You could try this too: <a href="http://code.google.com/p/python-httpclient/" rel="nofollow">http://code.google.com/p/python-httpclient/</a></p> <p>(It also supports the verification of the server certificate.)</p>
0
2010-08-12T13:36:27Z
[ "python", "proxy", "https", "basic-authentication" ]
Django: use archive_index with date_field from a related model
1,453,465
<p>Hello (please excuse me for my ugly english :p),</p> <p>Imagine these two simple models :</p> <pre><code>from django.contrib.contenttypes import generic from django.db import models class SomeModel(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object id')) content_object = generic.GenericForeignKey('content_type', 'object_id') published_at = models.DateTimeField('Publication date') class SomeOtherModel(models.Model): related = generic.GenericRelation(SomeModel) </code></pre> <p>I would like to use the archive_index generic view with SomeOtherModel, but it doesn't work :</p> <pre><code>from django.views.generic.date_based import archive_index archive_index(request, SometherModel.objects.all(), 'related__published_at') </code></pre> <p>The error comes from archive_index at line 28 (using django 1.1) :</p> <pre><code>date_list = queryset.dates(date_field, 'year')[::-1] </code></pre> <p>The raised exception is :</p> <pre><code>SomeOtherModel has no field named 'related__published_at' </code></pre> <p>Have you any idea to fix it ?</p> <p>Thank you very much :)</p>
1
2009-09-21T08:45:44Z
1,455,589
<p>From digging through the Django source code, the generic view <code>archive_index</code> does not appear to support related fields that are <code>GenericRelation</code>s.</p> <p>This is because the queryset method <code>dates</code> does not support generic relations. Consider filing this as a bug / feature request on the Django bug tracker.</p>
1
2009-09-21T17:01:03Z
[ "python", "django", "django-models", "django-views", "django-generic-views" ]
How to markup form fields with <div class='field_type'> in Django
1,453,488
<p>I wasn't able to find a way to identify the type of a field in a django template. My solution was to create a simple filter to access the field and widget class names. I've included the code below in case it's helpful for someone else.</p> <p>Is there a better approach?</p> <pre><code>## agency/tagutils/templatetags/fieldtags.py ############################################################### from django import template register = template.Library() @register.filter(name='field_type') def field_type(value): return value.field.__class__.__name__ @register.filter(name='widget_type') def widget_type(value): return value.field.widget.__class__.__name__ ## client/project/settings.py ############################################################### INSTALLED_APPS = ( # ... 'agency.tagutils', ) ## client/project/templates/project/field_snippet.html ############################################################### {% load fieldtags %} &lt;div class="field {{ field|field_type }} {{ field|widget_type }} {{ field.name }}"&gt; {{ field.errors }} &lt;div class="form_label"&gt; {{ field.label_tag }} &lt;/div&gt; &lt;div class="form_field"&gt; {{ field }} &lt;/div&gt; &lt;/div&gt; ## sample output html ############################################################### &lt;div class="field CharField TextInput family_name"&gt; &lt;div class="form_label"&gt; &lt;label for="id_family_name"&gt;Family name&lt;/label&gt; &lt;/div&gt; &lt;div class="form_field"&gt; &lt;input id="id_family_name" type="text" name="family_name" maxlength="64" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
6
2009-09-21T08:53:04Z
1,504,903
<pre><code>class MyForm(forms.Form): myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'})) </code></pre> <p>or, with a ModelForm</p> <pre><code>class MyForm(forms.ModelForm): class Meta: model = MyModel widgets = { 'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}), } </code></pre> <p>or, when you don't want to redefine the widget</p> <pre><code>class MyForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'}) </code></pre> <p>render normally with {{ form }}</p>
16
2009-10-01T16:08:35Z
[ "python", "django", "django-forms", "django-templates", "django-models" ]
How to filter query in sqlalchemy by year (datetime column)
1,453,591
<p>I have table in sqlalchemy 0.4 that with types.DateTime column:</p> <pre><code>Column("dfield", types.DateTime, index=True) </code></pre> <p>I want to select records, that has specific year in this column, using model. How to do this? I though it should be done like this:</p> <pre><code>selected_year = 2009 my_session = model.Session() my_query = my_session.query(model.MyRecord).filter(model.dfield.??? == selected_year) # process data in my_query </code></pre> <p>Part with ??? is for me unclear.</p>
12
2009-09-21T09:23:09Z
1,453,610
<p>sqlalchemy.extract('year', model.MyRecord.dfield) == selected_year</p>
18
2009-09-21T09:27:11Z
[ "python", "sqlalchemy" ]
Django: queryset filter for *all* values from a ManyToManyField
1,453,662
<p>Hi (sorry for my bad english :p)</p> <p>Imagine these models :</p> <pre><code>class Fruit(models.Model): # ... class Basket(models.Model): fruits = models.ManyToManyField(Fruit) </code></pre> <p>Now I would like to retrieve Basket instances related to <em>all</em> fruits. The problem is that the code bellow returns Basket instances related to <em>any</em> fruits :</p> <pre><code>baskets = Basket.objects.filter(fruits__in=Fruit.objects.all()) # This doesn't work: baskets = Basket.objects.filter(fruits=Fruit.objects.all()) </code></pre> <p>Any solution do resolve this problem ?</p> <p>Thank you very much. :)</p>
2
2009-09-21T09:43:44Z
1,453,736
<p>I don't have a dataset handy to test this, but I think it should work:</p> <pre><code>Basket.objects.annotate(num_fruits=Count('fruits')).filter(num_fruits=len(Fruit.objects.all())) </code></pre> <p>It annotates every basket object with the count of related fruits and filters out those baskets that have a fruit count that equals the total amount of fruits.</p> <p>Note: you need Django 1.1 for this to work.</p>
5
2009-09-21T10:02:33Z
[ "python", "sql", "django", "django-models", "django-queryset" ]
ctypes memory management: how and when free the allocated resources?
1,453,776
<p>I'm writing a small wrapper for a C library in Python with Ctypes, and I don't know if the structures allocated from Python will be automatically freed when they're out of scope.</p> <p>Example:</p> <pre><code>from ctypes import * mylib = cdll.LoadLibrary("mylib.so") class MyPoint(Structure): _fields_ = [("x", c_int), ("y", c_int)] def foo(): p = MyPoint() #do something with the point foo() </code></pre> <p>Will that point still be "alive" after foo returns? Do I have to call <code>clib.free(pointer(p))</code>? or does ctypes provide a function to free memory allocated for C structures?</p>
7
2009-09-21T10:12:19Z
1,453,822
<p>In this case your <code>MyPoint</code> instance is a Python object allocated on the Python heap, so there should be no need to treat it differently from any other Python object. If, on the other hand, you got the <code>MyPoint</code> instance by calling say <code>allocate_point()</code> in <code>mylib.so</code>, then you would need to free it using whatever function is provided for doing so, e.g. <code>free_point(p)</code> in <code>mylib.so</code>.</p>
3
2009-09-21T10:24:42Z
[ "python", "c", "memory", "ctypes" ]
python error "list indices must be integers" , they ARE integers
1,453,882
<p>I am having a problem. I have an array of 31 elements called colors. I also have another array with integer numbers that vary between 0 and 31, this is called c. I want to produce a new array where the values in c are now the corresponding values in colors.</p> <p>I write:</p> <blockquote> <blockquote> <p>newarray=colors[c]</p> </blockquote> </blockquote> <p>but get the error message "list indices must be integers" but c is an array of integers. I am new to python and have not got time to do the tutorials as I just need it for a specific plotting task. Could anyone give me a hand?</p> <p>Thanks</p>
4
2009-09-21T10:39:25Z
1,453,925
<p>array of integers != integer</p> <p>list indices must be integers - you've given a list of integers.</p> <p>You probably want a list comprehension:</p> <pre><code>newarray = [ colors[i] for i in c ] </code></pre> <p>But you really ought to learn the language properly before using it. It's not like python takes a long time to learn.</p> <p>EDIT:</p> <p>If you're still getting the same error then your assertion that <code>c</code> is a list of integers is incorrect.</p> <p>Please try:</p> <pre><code>print type(c) print type(c[0]) print type(colors) print type(colors[0]) </code></pre> <p>Then we can work out what types you have got. Also a <a href="http://www.yoda.arachsys.com/csharp/complete.html">short but complete example</a> would help, and probably teach you a lot about your problem.</p> <p>EDIT2:</p> <p>So if <code>c</code> is actually a list of string, you should probably have mentioned this, strings don't get automatically converted to integers, unlike some other scripting languages.</p> <pre><code>newarray = [ colors[int(i)] for i in c ] </code></pre> <p>EDIT3:</p> <p>Here is some minimal code that demonstrates a couple of bug fixes:</p> <pre><code>x=["1\t2\t3","4\t5\t6","1\t2\t0","1\t2\t31"] a=[y.split('\t')[0] for y in x] b=[y.split('\t')[1] for y in x] c=[y.split('\t')[2] for y in x] # this line is probably the problem colors=['#FFFF00']*32 newarray=[colors[int(i)] for i in c] print newarray </code></pre> <p>a) <code>colors</code> needs to be 32 entries long. b) the elements from c (<code>i</code>) in the list comprehension need to be converted to integers (<code>int(i)</code>).</p>
12
2009-09-21T10:47:02Z
[ "python" ]
python error "list indices must be integers" , they ARE integers
1,453,882
<p>I am having a problem. I have an array of 31 elements called colors. I also have another array with integer numbers that vary between 0 and 31, this is called c. I want to produce a new array where the values in c are now the corresponding values in colors.</p> <p>I write:</p> <blockquote> <blockquote> <p>newarray=colors[c]</p> </blockquote> </blockquote> <p>but get the error message "list indices must be integers" but c is an array of integers. I am new to python and have not got time to do the tutorials as I just need it for a specific plotting task. Could anyone give me a hand?</p> <p>Thanks</p>
4
2009-09-21T10:39:25Z
1,453,933
<p>Python does not support arbitrary list indexing. You can use single integer index like c[4] or slice like c[4:10]. <a href="http://www.scipy.org/SciPy" rel="nofollow">SciPy</a> library has richer indexing capabilities. Or just use list comprehensions as Douglas Leeder advices.</p>
1
2009-09-21T10:48:52Z
[ "python" ]
python error "list indices must be integers" , they ARE integers
1,453,882
<p>I am having a problem. I have an array of 31 elements called colors. I also have another array with integer numbers that vary between 0 and 31, this is called c. I want to produce a new array where the values in c are now the corresponding values in colors.</p> <p>I write:</p> <blockquote> <blockquote> <p>newarray=colors[c]</p> </blockquote> </blockquote> <p>but get the error message "list indices must be integers" but c is an array of integers. I am new to python and have not got time to do the tutorials as I just need it for a specific plotting task. Could anyone give me a hand?</p> <p>Thanks</p>
4
2009-09-21T10:39:25Z
1,454,335
<p>Okay, I think I know what you are after...</p> <p>So you have your list of 31 colours. Say for argument it is a list of 31 strings like this...</p> <pre><code>colours = [ "Black", "DarkBlue", "DarkGreen", ... "White" ] </code></pre> <p>And 'c' is an array of numbers in the range 0 to 31, but in random order...</p> <pre><code>import random c = [x for x in xrange(32)] random.shuffle(c) # 'c' now has numbers 0 to 31 in random order # c = [ 2, 31, 0, ... 1] </code></pre> <p>And what you want to do is map the values in c as an index into the list of colors so that you end up with a list of colors in as indexed by c and in that order...</p> <pre><code>mapped = [color[idx] for idx in c] # mapped has the colors in the same order as indexed by 'c' # mapped = ["DarkGreen", "White", "Black", ... "DarkBlue"] </code></pre> <p>If that ain't what you want then you need to revise your question!</p> <p>I think you've got a basic problem in that your list of colours should have 32 elements (colours) in it, not 31, if the list 'c' is a random shuffle of all numbers in the range 0 to 31 (that's 32 numbers, you see).</p>
1
2009-09-21T12:45:21Z
[ "python" ]
python error "list indices must be integers" , they ARE integers
1,453,882
<p>I am having a problem. I have an array of 31 elements called colors. I also have another array with integer numbers that vary between 0 and 31, this is called c. I want to produce a new array where the values in c are now the corresponding values in colors.</p> <p>I write:</p> <blockquote> <blockquote> <p>newarray=colors[c]</p> </blockquote> </blockquote> <p>but get the error message "list indices must be integers" but c is an array of integers. I am new to python and have not got time to do the tutorials as I just need it for a specific plotting task. Could anyone give me a hand?</p> <p>Thanks</p>
4
2009-09-21T10:39:25Z
1,454,429
<p>This is your code: (from your comment)</p> <pre><code>from pylab import* f=open("transformdata.txt") x=f.readlines() a=[y.split('\t')[0] for y in x] b=[y.split('\t')[1] for y in x] c=[y.split('\t')[2] for y in x] # this line is probably the problem subplot(111,projection="hammer") colors=['#FFFF00']*31 newarray=[colors [i] for i in c] p=plot([a],[b],"o",mfc=color) show() </code></pre> <p>Without knowing exactly what your data is, or what you're trying to accomplish, I'd suggest trying this:</p> <pre><code>c=[int(y.split('\t')[2]) for y in x] </code></pre>
2
2009-09-21T13:07:29Z
[ "python" ]
Is it possible to use django Piston on Google AppEngine?
1,453,909
<p>I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine)</p> <p>I was wondering if anyone patched\forked piston to get it working on AppEngine?</p>
5
2009-09-21T10:44:35Z
1,454,771
<p><a href="http://bitbucket.org/gumptioncom/django-piston-app-engine/" rel="nofollow" rel="nofollow">http://bitbucket.org/gumptioncom/django-piston-app-engine/</a></p>
5
2009-09-21T14:20:20Z
[ "python", "django", "google-app-engine", "django-piston" ]
Is it possible to use django Piston on Google AppEngine?
1,453,909
<p>I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine)</p> <p>I was wondering if anyone patched\forked piston to get it working on AppEngine?</p>
5
2009-09-21T10:44:35Z
1,491,297
<p>It turns out the problem with Piston and AppEngine is mainly when it comes to the authentication code. So, I managed to port Piston to AppEngine doing the following:</p> <ol> <li>I'm using the <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">app-engine-patch</a> project which integrates django's authentication framework with Google AppEngine</li> <li>I forked Piston and removed all the OAuth authentication code and models (in authentication.py). Its probably not too complicated to convert the model and auth code but as I don't need it I didn't bother...</li> </ol>
2
2009-09-29T08:37:24Z
[ "python", "django", "google-app-engine", "django-piston" ]
Is it possible to use django Piston on Google AppEngine?
1,453,909
<p>I haven't been able to do so due to all sort of missing dependencies (mainly, I think the problem is in the authentication code which relies on django stuff that is not available on AppEngine)</p> <p>I was wondering if anyone patched\forked piston to get it working on AppEngine?</p>
5
2009-09-21T10:44:35Z
1,561,747
<p>I've forked django-oauth, to make it compatible with app-engine-patch. So it could eventually be used with <a href="http://bitbucket.org/gumptioncom/django-piston-app-engine/" rel="nofollow">django-piston-app-engine</a>.</p> <p><a href="http://bitbucket.org/mtourne/django-oauth-appengine/" rel="nofollow">http://bitbucket.org/mtourne/django-oauth-appengine/</a></p>
1
2009-10-13T17:31:20Z
[ "python", "django", "google-app-engine", "django-piston" ]
Python: Does a dict value pointer store its key?
1,454,437
<p>I'm wondering if there is a built-in way to do this... Take this simple code for example:</p> <pre><code>D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] </code></pre> <p>I believe <code>object_a</code> is just pointing at the <code>objectA()</code> created on the first line, and knows nothing about the dictionary <code>D</code>, but my question is, does Python store the Key of the dictionary value? Is there a way to get the Key <code>'one'</code> if all you have is the variable <code>object_a</code> (without looping over the dictionary, of course)?</p> <p>If not, I can store the value <code>'one'</code> inside <code>objectA()</code>, but I'm just curious if Python already stores that info.</p>
2
2009-09-21T13:09:43Z
1,454,441
<p>I think no.</p> <p>Consider the case of adding a single object to a (large) number of different dictionaries. It would become quite expensive for Python to track that for you, it would cost a lot for a feature not used by most.</p>
7
2009-09-21T13:10:53Z
[ "python", "dictionary" ]
Python: Does a dict value pointer store its key?
1,454,437
<p>I'm wondering if there is a built-in way to do this... Take this simple code for example:</p> <pre><code>D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] </code></pre> <p>I believe <code>object_a</code> is just pointing at the <code>objectA()</code> created on the first line, and knows nothing about the dictionary <code>D</code>, but my question is, does Python store the Key of the dictionary value? Is there a way to get the Key <code>'one'</code> if all you have is the variable <code>object_a</code> (without looping over the dictionary, of course)?</p> <p>If not, I can store the value <code>'one'</code> inside <code>objectA()</code>, but I'm just curious if Python already stores that info.</p>
2
2009-09-21T13:09:43Z
1,454,475
<p>The <code>dict</code> mapping is not trivially "reversible" as you describe.</p> <ol> <li><p>The key must be immutable. It must be immutable so that it can be hashed for lookup and not suffer spontaneous changes.</p></li> <li><p>The value does not have to be immutable, it is not hashed for quick lookup. </p></li> </ol> <p>You cannot simply go from value back to key without (1) creating an immutable value and (2) populating some other kind of mapping with the "reversed" value -> key mapping.</p>
3
2009-09-21T13:19:59Z
[ "python", "dictionary" ]
Python: Does a dict value pointer store its key?
1,454,437
<p>I'm wondering if there is a built-in way to do this... Take this simple code for example:</p> <pre><code>D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] </code></pre> <p>I believe <code>object_a</code> is just pointing at the <code>objectA()</code> created on the first line, and knows nothing about the dictionary <code>D</code>, but my question is, does Python store the Key of the dictionary value? Is there a way to get the Key <code>'one'</code> if all you have is the variable <code>object_a</code> (without looping over the dictionary, of course)?</p> <p>If not, I can store the value <code>'one'</code> inside <code>objectA()</code>, but I'm just curious if Python already stores that info.</p>
2
2009-09-21T13:09:43Z
1,454,702
<blockquote> <p>Is there a way to get the Key 'one' if all you have is the variable object_a (without looping over the dictionary, of course)?</p> </blockquote> <p>No, Python imposes no such near-useless redundancy on you. If <code>objA</code> is a factory callable:</p> <pre><code>d = {'zap': objA()} a = d['zap'] </code></pre> <p>and</p> <pre><code>b = objA() </code></pre> <p>just as well as</p> <pre><code>L = [objA()] c = L[0] </code></pre> <p>all result in exactly the same kind of references in <code>a</code>, <code>b</code> and <code>c</code>, to exactly equivalent objects (if that's what <code>objA</code> gives you in the first place), without one bit wasted (neither in said objects nor in any redundant and totally hypothetical auxiliary structure) to record "this is/was a value in list L and/or dict d at these index/key" ((or indices/keys since of cource there could be many)).</p>
2
2009-09-21T14:08:40Z
[ "python", "dictionary" ]
Python: Does a dict value pointer store its key?
1,454,437
<p>I'm wondering if there is a built-in way to do this... Take this simple code for example:</p> <pre><code>D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] </code></pre> <p>I believe <code>object_a</code> is just pointing at the <code>objectA()</code> created on the first line, and knows nothing about the dictionary <code>D</code>, but my question is, does Python store the Key of the dictionary value? Is there a way to get the Key <code>'one'</code> if all you have is the variable <code>object_a</code> (without looping over the dictionary, of course)?</p> <p>If not, I can store the value <code>'one'</code> inside <code>objectA()</code>, but I'm just curious if Python already stores that info.</p>
2
2009-09-21T13:09:43Z
1,456,611
<p>Like others have said, there is no built-in way to do this, since it takes up memory and is not usually needed.</p> <blockquote> <p>If not, I can store the value 'one' inside objectA(), but I'm just curious if Python already stores that info.</p> </blockquote> <p>Just wanted to add that it should be pretty easy to add a more general solution which does this automatically. For example:</p> <pre><code>def MakeDictReversible(dict): for k, v in dict.iteritems(): v.dict_key = k </code></pre> <p>This function just embeds every object in the dictionary with a member "dict_key", which is the dictionary key used to store the object.</p> <p>Of course, this code can only work once (i.e., run this on two different dictionaries which share an object, and the object's "dict_key" member will be overwritten by the second dictionary).</p>
0
2009-09-21T20:17:35Z
[ "python", "dictionary" ]
do properties work on django model fields?
1,454,727
<p>I think the best way to ask this question is with some code... can I do this? (<strong>edit</strong>: ANSWER: no)</p> <del><pre><code> class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self.foo def set_foo(self, input): self.foo = input foo = property(get_foo, set_foo) </code></pre> </del> <p><del>or do I have to do it like this:</del></p> <h2>Yes, you have to do it like this:</h2> <pre><code>class MyModel(models.Model): _foo = models.CharField(max_length = 20, db_column='foo') bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self._foo def set_foo(self, input): self._foo = input foo = property(get_foo, set_foo) </code></pre> <p><strong>note</strong>: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reason</p>
25
2009-09-21T14:13:17Z
1,454,856
<p>A model field is already property, so I would say you have to do it the second way to avoid a name clash.</p> <p>When you define foo = property(..) it actually overrides the foo = models.. line, so that field will no longer be accessible.</p> <p>You will need to use a different name for the property and the field. In fact, if you do it the way you have it in example #1 you will get an infinite loop when you try and access the property as it now tries to return itself.</p> <p>EDIT: Perhaps you should also consider not using _foo as a field name, but rather foo, and then define another name for your property because properties cannot be used in QuerySet, so you'll need to use the actual field names when you do a filter for example.</p>
12
2009-09-21T14:39:02Z
[ "python", "django", "properties", "models" ]
do properties work on django model fields?
1,454,727
<p>I think the best way to ask this question is with some code... can I do this? (<strong>edit</strong>: ANSWER: no)</p> <del><pre><code> class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self.foo def set_foo(self, input): self.foo = input foo = property(get_foo, set_foo) </code></pre> </del> <p><del>or do I have to do it like this:</del></p> <h2>Yes, you have to do it like this:</h2> <pre><code>class MyModel(models.Model): _foo = models.CharField(max_length = 20, db_column='foo') bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self._foo def set_foo(self, input): self._foo = input foo = property(get_foo, set_foo) </code></pre> <p><strong>note</strong>: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reason</p>
25
2009-09-21T14:13:17Z
12,358,707
<p>As mentioned, a correct alternative to implementing your own django.db.models.Field class, one should use - <strong>db_column</strong> argument and a custom (or hidden) class attribute. I am just rewriting the code in the edit by @Jiaaro following more strict conventions for OOP in python (e.g. if _foo should be actually hidden):</p> <pre><code>class MyModel(models.Model): __foo = models.CharField(max_length = 20, db_column='foo') bar = models.CharField(max_length = 20) @property def foo(self): if self.bar: return self.bar else: return self.__foo @foo.setter def foo(self, value): self.__foo = value </code></pre> <p>*__foo* will be resolved into *<em>MyModel</em>_foo* (as seen by <em>dir(..)</em>) thus hidden (<a href="http://docs.python.org/tutorial/classes.html#private-variables-and-class-local-references">private</a>). Note that this form also permits using of <a href="http://docs.python.org/library/functions.html#property">@property decorator</a> which would be ultimately a nicer way to write readable code.</p> <p>Again, django will create *_MyModel table with two fields <em>foo</em> and <em>bar</em>.</p>
10
2012-09-10T20:08:16Z
[ "python", "django", "properties", "models" ]
do properties work on django model fields?
1,454,727
<p>I think the best way to ask this question is with some code... can I do this? (<strong>edit</strong>: ANSWER: no)</p> <del><pre><code> class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self.foo def set_foo(self, input): self.foo = input foo = property(get_foo, set_foo) </code></pre> </del> <p><del>or do I have to do it like this:</del></p> <h2>Yes, you have to do it like this:</h2> <pre><code>class MyModel(models.Model): _foo = models.CharField(max_length = 20, db_column='foo') bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: return self.bar else: return self._foo def set_foo(self, input): self._foo = input foo = property(get_foo, set_foo) </code></pre> <p><strong>note</strong>: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reason</p>
25
2009-09-21T14:13:17Z
33,899,883
<p>The previous solutions suffer because @property causes problems in admin, and .filter(_foo). </p> <p>A better solution would be to override <strong>setattr</strong> except that this can cause problems initializing the ORM object from the DB. However, there is a trick to get around this, and it's universal.</p> <pre><code>class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def __setattr__(self, attrname, val): setter_func = 'setter_' + attrname if attrname in self.__dict__ and callable(getattr(self, setter_func, None)): super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val)) else: super(MyModel, self).__setattr__(attrname, val) def setter_foo(self, val): return val.upper() </code></pre> <p>The secret is '<strong>attrname in self.__dict__</strong>'. When the model initializes either from new or hydrated from the <strong>__dict__</strong>!</p>
2
2015-11-24T17:16:12Z
[ "python", "django", "properties", "models" ]
Allowing user to rollback from db audit trail with SQLAlchemy
1,454,874
<p>I'm starting to use SQLAlchemy for a new project where I was planning to implement an audit trail similar to the one proposed on this quiestions:<sub></p> <ul> <li><a href="http://stackoverflow.com/questions/328898/implementing-audit-trail-for-objects-in-c">http://stackoverflow.com/questions/328898/implementing-audit-trail-for-objects-in-c</a></li> <li><a href="http://stackoverflow.com/questions/315240/audit-trails-and-implementing-sox-hipaa-etc-best-practices-for-sensitive-data">http://stackoverflow.com/questions/315240/audit-trails-and-implementing-sox-hipaa-etc-best-practices-for-sensitive-data</a></li> <li><a href="http://stackoverflow.com/questions/1051449/ideas-on-database-design-for-capturing-audit-trails">http://stackoverflow.com/questions/1051449/ideas-on-database-design-for-capturing-audit-trails</a></li> <li><a href="http://stackoverflow.com/questions/60920/what-is-the-best-implementation-for-db-audit-trail">http://stackoverflow.com/questions/60920/what-is-the-best-implementation-for-db-audit-trail</a></li> <li><a href="http://stackoverflow.com/questions/711597/is-this-the-best-approach-to-creating-an-audit-trail">http://stackoverflow.com/questions/711597/is-this-the-best-approach-to-creating-an-audit-trail</a></li> <li><a href="http://stackoverflow.com/questions/23770/good-strategy-for-leaving-an-audit-trail-change-history-for-db-applications">http://stackoverflow.com/questions/23770/good-strategy-for-leaving-an-audit-trail-change-history-for-db-applications</a></li> <li><a href="http://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver">http://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver</a>.</li> <li><a href="http://stackoverflow.com/questions/1051449/ideas-on-database-design-for-capturing-audit-trails">http://stackoverflow.com/questions/1051449/ideas-on-database-design-for-capturing-audit-trails</a></sub></li> </ul> <p>As I will already have the full history of the "interesting" objects, I was thinking in allowing users to rollback to a given version, giving them the possibility to have unlimited <code>undo</code>.</p> <p>Would this be possible to be done in a clean way with SQLAlchemy?</p> <p>What would be the <em>correct</em> way to expose this feature in the internal API (business logic and ORM)?</p> <p>I was something along the ways of <code>user.rollback(ver=42)</code>.</p>
4
2009-09-21T14:42:21Z
1,455,056
<p>Although I haven't used SQLAlchemy specifically, I can give you some general tips that can be easily implemented in any ORM:</p> <ul> <li>Separate out the versioned item into two tables, say <code>Document</code> and <code>DocumentVersion</code>. <code>Document</code> stores information that will never change between versions, and <code>DocumentVersion</code> stores information that does change.</li> <li>Give each <code>DocumentVersion</code> a "parent" reference. Make a foreign key to the same table, pointing to the previous version of the document.</li> <li>Roll back to previous versions by updating a reference from <code>Document</code> to the "current" version. Don't delete versions from the bottom of the chain.</li> <li>When they make newer versions after rolling back, it will create another branch of versions.</li> </ul> <p>Example, create A, B, C, rollback to B, create D, E:</p> <pre><code>(A) | (B) | \ (C) (D) | (E) </code></pre>
7
2009-09-21T15:18:37Z
[ "python", "sqlalchemy", "audit", "rollback" ]
Flow control in threading.Thread
1,454,941
<p>I Have run into a few examples of managing threads with the threading module (using Python 2.6).</p> <p>What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.</p> <p>Maybe this is not the preferred way of working with threads? Please enlighten me:</p> <pre><code>#!/usr/bin/env python import Queue import time import urllib2 import threading import datetime hosts = ["http://example.com/", "http://www.google.com"] queue = Queue.Queue() class ThreadUrl(threading.Thread): """Threaded Url Grab""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue host = self.queue.get() #grabs urls of hosts and prints first 1024 bytes of page url = urllib2.urlopen(host) print url.read(10) #signals to queue job is done self.queue.task_done() start = time.time() def main(): #spawn a pool of threads, and pass them queue instance for i in range(1): t = ThreadUrl(queue) t.setDaemon(True) t.start() for host in hosts: queue.put(host) queue.join() main() print "Elapsed time: %s" % (time.time() - start) </code></pre>
3
2009-09-21T14:56:40Z
1,454,967
<p>The method run() is called behind the scene by "threading.Thread" (Google inheritance and polymorphism concepts of OOP). The invocation will be done just after t.start() has called.</p> <p>If you have an access to threading.py (find it in python folder). You will see a class name Thread. In that class, there is a method called "start()". start() called '_start_new_thread(self.&#95;&#95;bootstrap, ())' a low-level thread start-up which will run a wrapper method called '&#95;&#95;bootstrap()' by a new thread. '&#95;&#95;bootstrap()', then, called '&#95;&#95;bootstrap_inner()' which do some more preparation before, finally, call 'run()'.</p> <p>Read the source, you can learn a lot. :D</p>
4
2009-09-21T15:00:47Z
[ "python", "multithreading", "control", "flow" ]
Flow control in threading.Thread
1,454,941
<p>I Have run into a few examples of managing threads with the threading module (using Python 2.6).</p> <p>What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.</p> <p>Maybe this is not the preferred way of working with threads? Please enlighten me:</p> <pre><code>#!/usr/bin/env python import Queue import time import urllib2 import threading import datetime hosts = ["http://example.com/", "http://www.google.com"] queue = Queue.Queue() class ThreadUrl(threading.Thread): """Threaded Url Grab""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue host = self.queue.get() #grabs urls of hosts and prints first 1024 bytes of page url = urllib2.urlopen(host) print url.read(10) #signals to queue job is done self.queue.task_done() start = time.time() def main(): #spawn a pool of threads, and pass them queue instance for i in range(1): t = ThreadUrl(queue) t.setDaemon(True) t.start() for host in hosts: queue.put(host) queue.join() main() print "Elapsed time: %s" % (time.time() - start) </code></pre>
3
2009-09-21T14:56:40Z
1,454,989
<p><code>t.start()</code> creates a new thread in the OS and when this thread begins it will call the thread's <code>run()</code> method (or a different function if you provide a <code>target</code> in the <code>Thread</code> constructor)</p>
0
2009-09-21T15:04:43Z
[ "python", "multithreading", "control", "flow" ]
Flow control in threading.Thread
1,454,941
<p>I Have run into a few examples of managing threads with the threading module (using Python 2.6).</p> <p>What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.</p> <p>Maybe this is not the preferred way of working with threads? Please enlighten me:</p> <pre><code>#!/usr/bin/env python import Queue import time import urllib2 import threading import datetime hosts = ["http://example.com/", "http://www.google.com"] queue = Queue.Queue() class ThreadUrl(threading.Thread): """Threaded Url Grab""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue host = self.queue.get() #grabs urls of hosts and prints first 1024 bytes of page url = urllib2.urlopen(host) print url.read(10) #signals to queue job is done self.queue.task_done() start = time.time() def main(): #spawn a pool of threads, and pass them queue instance for i in range(1): t = ThreadUrl(queue) t.setDaemon(True) t.start() for host in hosts: queue.put(host) queue.join() main() print "Elapsed time: %s" % (time.time() - start) </code></pre>
3
2009-09-21T14:56:40Z
1,455,015
<p>Per the <a href="http://docs.python.org/library/threading.html#threading.Thread.start">pydoc</a>:</p> <blockquote> <p><code>Thread.start()</code></p> <p>Start the thread’s activity.</p> <p>It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.</p> <p>This method will raise a RuntimeException if called more than once on the same thread object.</p> </blockquote> <p>The way to think of python <code>Thread</code> objects is that they take some chunk of python code that is written synchronously (either in the <code>run</code> method or via the <code>target</code> argument) and wrap it up in C code that knows how to make it run asynchronously. The beauty of this is that you get to treat <code>start</code> like an opaque method: you don't have any business overriding it unless you're rewriting the class in C, but you get to treat <code>run</code> very concretely. This can be useful if, for example, you want to test your thread's logic synchronously. All you need is to call <code>t.run()</code> and it will execute just as any other method would.</p>
7
2009-09-21T15:11:17Z
[ "python", "multithreading", "control", "flow" ]
How to define properties in __init__
1,454,984
<p>I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour.</p> <pre><code>class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): setattr(self, p, property(lambda : p) ) def PropNames(self): # The names of all the properties return ['Apple', 'Pear'] # normal property Air = property(lambda s : "Air") if __name__ == "__main__": b = Basket() print b.Air # outputs: "Air" print b.Apple # outputs: &lt;property object at 0x...&gt; print b.Pear # outputs: &lt;property object at 0x...&gt; </code></pre> <p>How could I get this to work?</p>
4
2009-09-21T15:04:02Z
1,455,009
<p>You need to set the properties on the class (ie: <code>self.__class__</code>), not on the object (ie: <code>self</code>). For example:</p> <pre><code>class Basket(object): def __init__(self): # add all the properties setattr(self.__class__, 'Apple', property(lambda s : 'Apple') ) setattr(self.__class__, 'Pear', property(lambda s : 'Pear') ) # normal property Air = property(lambda s : "Air") if __name__ == "__main__": b = Basket() print b.Air # outputs: "Air" print b.Apple # outputs: "Apple" print b.Pear # outputs: "Pear" </code></pre> <p>For what it's worth, your usage of <code>p</code> when creating lamdas in the loop, doesn't give the behavior that you would expect. Since the value of <code>p</code> is changed while going through the loop, the two properties set in the loop both return the same value: the last value of <code>p</code>.</p>
9
2009-09-21T15:10:31Z
[ "python", "properties", "constructor" ]
How to define properties in __init__
1,454,984
<p>I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour.</p> <pre><code>class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): setattr(self, p, property(lambda : p) ) def PropNames(self): # The names of all the properties return ['Apple', 'Pear'] # normal property Air = property(lambda s : "Air") if __name__ == "__main__": b = Basket() print b.Air # outputs: "Air" print b.Apple # outputs: &lt;property object at 0x...&gt; print b.Pear # outputs: &lt;property object at 0x...&gt; </code></pre> <p>How could I get this to work?</p>
4
2009-09-21T15:04:02Z
1,455,051
<p>This does what you wanted:</p> <pre><code>class Basket(object): def __init__(self): # add all the properties def make_prop( name ): def getter( self ): return "I'm a " + name return property(getter) for p in self.PropNames(): setattr(Basket, p, make_prop(p) ) def PropNames(self): # The names of all the properties return ['Apple', 'Pear', 'Bread'] # normal property Air = property(lambda s : "I'm Air") if __name__ == "__main__": b = Basket() print b.Air print b.Apple print b.Pear </code></pre> <p>Another way to do it would be a metaclass ... but they confuse a lot of people ^^.</p> <p>Because I'm bored:</p> <pre><code>class WithProperties(type): """ Converts `__props__` names to actual properties """ def __new__(cls, name, bases, attrs): props = set( attrs.get('__props__', () ) ) for base in bases: props |= set( getattr( base, '__props__', () ) ) def make_prop( name ): def getter( self ): return "I'm a " + name return property( getter ) for prop in props: attrs[ prop ] = make_prop( prop ) return super(WithProperties, cls).__new__(cls, name, bases, attrs) class Basket(object): __metaclass__ = WithProperties __props__ = ['Apple', 'Pear'] Air = property(lambda s : "I'm Air") class OtherBasket(Basket): __props__ = ['Fish', 'Bread'] if __name__ == "__main__": b = Basket() print b.Air print b.Apple print b.Pear c = OtherBasket() print c.Air print c.Apple print c.Pear print c.Fish print c.Bread </code></pre>
3
2009-09-21T15:18:10Z
[ "python", "properties", "constructor" ]
How to define properties in __init__
1,454,984
<p>I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour.</p> <pre><code>class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): setattr(self, p, property(lambda : p) ) def PropNames(self): # The names of all the properties return ['Apple', 'Pear'] # normal property Air = property(lambda s : "Air") if __name__ == "__main__": b = Basket() print b.Air # outputs: "Air" print b.Apple # outputs: &lt;property object at 0x...&gt; print b.Pear # outputs: &lt;property object at 0x...&gt; </code></pre> <p>How could I get this to work?</p>
4
2009-09-21T15:04:02Z
1,455,178
<p>Why are you defining properties at <code>__init__</code> time? It's confusing and clever, so you better have a really good reason. The loop problem that Stef pointed out is just one example of why this should be avoided.</p> <p>If you need to redifine which properties a subclass has, you can just do <code>del self.&lt;property name&gt;</code> in the subclass <code>__init__</code> method, or define new properties in the subclass.</p> <p>Also, some style nitpicks:</p> <ul> <li>Indent to 4 spaces, not 2</li> <li>Don't mix quote types unnecessarily</li> <li>Use underscores instead of camel case for method names. <code>PropNames</code> -> <code>prop_names</code></li> <li><code>PropNames</code> doesn't really need to be a method</li> </ul>
1
2009-09-21T15:39:25Z
[ "python", "properties", "constructor" ]
What's a Django/Python solution for providing a one-time url for people to download files?
1,455,109
<p>I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy person downloading the file won't be able to download the file more than once. It would be nice to host the file on Amazon S3 to save on bandwidth where our server is co-located.</p> <p>My thought for the codes would be to pre-generate the unique codes that will get printed on the cards and store those in a database that could also have a field that stores the number of times the file was downloaded. This way we could set how many attempts we would allow the user for downloading the file.</p> <p>The part that I need direction on is how do I hide/mask the original file location so people can't steal that url and then download the file as many times as they want. I've done Google searches and I'm either not searching using the right keywords or there aren't very many libraries or snippets out there already for this type of thing.</p> <p>I'm guessing that I might be able to rig something up using <code>django.views.static.serve</code> that acts as a sort of proxy between the actual file and the user downloading the file. The only drawback to this method I would think is that I would need to use the actual web server and wouldn't be able to store the file on Amazon S3.</p> <p>Any suggestions or thoughts are greatly appreciated.</p>
4
2009-09-21T15:27:59Z
1,455,194
<p>You can just use something simple such as <a href="http://tn123.ath.cx/mod%5Fxsendfile/" rel="nofollow">mod_xsendfile</a>. This functionality is also available in other popular webservers such <a href="http://blog.lighttpd.net/articles/2006/07/02/x-sendfile" rel="nofollow">lighttpd</a> or <a href="http://kovyrin.net/2006/11/01/nginx-x-accel-redirect-php-rails/" rel="nofollow">nginx</a>.</p> <p>It works like this: when enabled your application (e.g. a trivial PHP script) can send a special response header, causing the webserver to serve a static file.</p> <p>If you want it to work with S3 you will need to handle each and every request this way, meaning the traffic will go through your site, from there to AWS, back to your site and back to the client. Does S3 support symbolic links / aliases? If so you might just redirect a valid user to one of the symbolic URLs and delete that symlink after a couple of hours.</p>
2
2009-09-21T15:41:59Z
[ "python", "django", "url", "proxy", "download" ]
What's a Django/Python solution for providing a one-time url for people to download files?
1,455,109
<p>I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy person downloading the file won't be able to download the file more than once. It would be nice to host the file on Amazon S3 to save on bandwidth where our server is co-located.</p> <p>My thought for the codes would be to pre-generate the unique codes that will get printed on the cards and store those in a database that could also have a field that stores the number of times the file was downloaded. This way we could set how many attempts we would allow the user for downloading the file.</p> <p>The part that I need direction on is how do I hide/mask the original file location so people can't steal that url and then download the file as many times as they want. I've done Google searches and I'm either not searching using the right keywords or there aren't very many libraries or snippets out there already for this type of thing.</p> <p>I'm guessing that I might be able to rig something up using <code>django.views.static.serve</code> that acts as a sort of proxy between the actual file and the user downloading the file. The only drawback to this method I would think is that I would need to use the actual web server and wouldn't be able to store the file on Amazon S3.</p> <p>Any suggestions or thoughts are greatly appreciated.</p>
4
2009-09-21T15:27:59Z
1,455,393
<p>Neat idea. However, I would warn against the single-download method, because there is no guarantee that their first download attempt will be successful. Perhaps use a time-expiration method instead?</p> <p>But it is certainly possible to do this with Django. Here is an outline of the basic approach:</p> <ul> <li>Set up a django url for serving these files</li> <li>Use a GET parameter which is a unique string to identify which file to get.</li> <li>Keep a database table which has a <code>FileField</code> for the file to download. This table maps the unique strings to the location of the file on the file system.</li> <li>To serve the file as a download, set the response headers in the view like this:</li> </ul> <p>(<code>path</code> is the location of the file to serve)</p> <pre><code>with open(path, 'rb') as f: response = HttpResponse(f.read()) response['Content-Type'] = 'application/octet-stream'; response['Content-Disposition'] = 'attachment; filename="%s"' % 'insert_filename_here' return response </code></pre> <p>Since we are using this Django page to serve the file, the user cannot find out the original file location.</p>
3
2009-09-21T16:20:04Z
[ "python", "django", "url", "proxy", "download" ]
How to set ignorecase flag for part of regular expression in Python?
1,455,160
<p>Is it possible to implement in Python something like this simple one:</p> <pre><code>#!/usr/bin/perl my $a = 'Use HELLO1 code'; if($a =~ /(?i:use)\s+([A-Z0-9]+)\s+(?i:code)/){ print "$1\n"; } </code></pre> <p>Letters of token in the middle of string are always capital. Letters of the rest of words can have any case (USE, use, Use, CODE, code, Code and so on)</p>
2
2009-09-21T15:35:55Z
1,455,195
<p><a href="http://docs.python.org/library/re.html" rel="nofollow">According to the docs</a>, this is not possible. The <code>(?x)</code> syntax only allows you to modify a flag for the whole expression. Therefore, you must split this into three regexp and apply them one after the other <em>or</em> do the "ignore case" manually: <code>/[uU][sS][eE]...</code></p>
2
2009-09-21T15:41:59Z
[ "python", "regex" ]
How to set ignorecase flag for part of regular expression in Python?
1,455,160
<p>Is it possible to implement in Python something like this simple one:</p> <pre><code>#!/usr/bin/perl my $a = 'Use HELLO1 code'; if($a =~ /(?i:use)\s+([A-Z0-9]+)\s+(?i:code)/){ print "$1\n"; } </code></pre> <p>Letters of token in the middle of string are always capital. Letters of the rest of words can have any case (USE, use, Use, CODE, code, Code and so on)</p>
2
2009-09-21T15:35:55Z
1,455,303
<p>As far as I could find, the python regular expression engine does not support partial ignore-case. Here is a solution using a case-insensitive regular expression, which then tests if the token is uppercase afterward.</p> <pre><code>#! /usr/bin/env python import re token_re = re.compile(r'use\s+([a-z0-9]+)\s+code', re.IGNORECASE) def find_token(s): m = token_re.search(s) if m is not None: token = m.group(1) if token.isupper(): return token if __name__ == '__main__': for s in ['Use HELLO1 code', 'USE hello1 CODE', 'this does not match', ]: print s, '-&gt;', print find_token(s) </code></pre> <p>Here is the program's output:</p> <pre><code>Use HELLO1 code -&gt; HELLO1 USE hello1 CODE -&gt; None this does not match -&gt; None </code></pre>
7
2009-09-21T16:01:10Z
[ "python", "regex" ]
Python-based Gallery web applications?
1,455,224
<p>I'm trying to cut my last dependencies on PHP and MySQL. The last stumbling block is a image gallery I set up for a client a while ago. The whole website is built around <a href="http://www.djangoproject.com/">Django</a> and <a href="http://zine.pocoo.org/">Zine</a>, except for the image gallery, which is based on <a href="http://www.plogger.org/">plogger</a>. I'd love to replace plogger with a Python solution. Requirements include:</p> <ul> <li>good admin interface with batch upload (my client thinks FTP is some kind of disease)</li> <li>uses a templating system (e.g. Jinja)</li> <li>WSGI interface</li> <li>supports PostgreSQL</li> <li>bonus points if it is a Django app</li> </ul> <p>I looked at <a href="http://code.google.com/p/django-photologue/">django-photologue</a>, which seems to be a good base for building a gallery app. But it isn't really a drop-in gallery app, which is what I'm looking for.</p>
6
2009-09-21T15:46:55Z
1,455,282
<p>There is <a href="http://code.google.com/p/django-photo-gallery">django-photo-gallery</a>, <a href="http://bitbucket.org/kmike/django-photo-albums/">django photo album</a> and another <a href="http://www.ohloh.net/p/django-photo-gallery">django-photo-gallery</a> (don't know if its the same one.)</p> <p>Anything else, and you'll have to make your own.</p>
7
2009-09-21T15:58:34Z
[ "python", "web-applications", "gallery" ]
refer to map via. maps() action in python/ pylonshq
1,455,446
<p>I just started to learn python, and i'm totally new and n00b. Normally i work with php. I choose to use this framework: <a href="http://pylonshq.com/" rel="nofollow">http://pylonshq.com/</a></p> <p>I have created an map called ajax in my controller map. now i just need my "htaccees" file to find the ajax map. </p> <p>I want the file to go into the map /ajax/ where the file ajax_load.py is.</p> <p>Right now, it looks like below. But i can't make it work :/</p> <blockquote> <p>map.connect('/ajax/{action}/', controller='ajax.ajax_load')</p> </blockquote> <p>I hope someone can help me ! </p>
1
2009-09-21T16:28:15Z
1,468,043
<p>solution :</p> <p><a href="http://pylonshq.com/docs/en/0.9.7/configuration/" rel="nofollow">http://pylonshq.com/docs/en/0.9.7/configuration/</a></p> <p>this is how it works-><br /> $ paster controller ajax/ajax_load</p>
0
2009-09-23T19:13:20Z
[ "python", "pylons" ]
FFMPEG and Pythons subprocess
1,455,532
<p>I'm trying to write a gui for <code>FFMPEG</code>. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so:</p> <p>Calling <code>subprocess.Popen()</code></p> <pre><code># Convert - Calls FFMPEG with current settings. (in a seperate # thread.) def convert(self): # Check if options are valid if self.input == "" or self.output == "": return False # Make the command string ffmpegString = self.makeString() # Try to open with these settings try: self.ffmpeg = subprocess.Popen(ffmpegString, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: self.error.append("OSError: ") except ValueError: self.error.append("ValueError: Couldn't call FFMPEG with these parameters") # Convert process should be running now. </code></pre> <p>And reading <code>stdout</code>:</p> <pre><code>convert = Convert() convert.input = "test.ogv" convert.output = "test.mp4" convert.output_size = (0, 0) convert.convert() while 1: print convert.ffmpeg.stdout.readline() </code></pre> <p>This works but, ffmpeg's status doesn't show. I'm assuming it has something to do with way ffmpeg refreshes it. Is there a way to access it?</p>
6
2009-09-21T16:49:40Z
1,455,541
<p><strong>FFMPEG:</strong></p> <p>FFMPEG output all the status text (what you see when you run it manually on the command line) on the stderr interface. In order to capture output from ffmpeg, you need to be watching the stderr interface - or redirecting it like the example.</p> <p><strong>Check for output on stderr:</strong></p> <p><em>Here is another way to try and read from stderr, instead of redirecting it when calling Popen</em></p> <p>The <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">Popen class</a> in Python has an file object called stderr, you would access it in the same way that you are accessing stdout. I'm thinking your loop would look something like this:</p> <pre><code>while 1: print convert.ffmpeg.stdout.readline() print convert.ffmpeg.stderr.readline() </code></pre> <p><em>Disclaimer: I haven't tested this in Python, but I made a comparable application using Java.</em></p>
-1
2009-09-21T16:53:00Z
[ "python", "ffmpeg", "subprocess" ]
FFMPEG and Pythons subprocess
1,455,532
<p>I'm trying to write a gui for <code>FFMPEG</code>. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so:</p> <p>Calling <code>subprocess.Popen()</code></p> <pre><code># Convert - Calls FFMPEG with current settings. (in a seperate # thread.) def convert(self): # Check if options are valid if self.input == "" or self.output == "": return False # Make the command string ffmpegString = self.makeString() # Try to open with these settings try: self.ffmpeg = subprocess.Popen(ffmpegString, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: self.error.append("OSError: ") except ValueError: self.error.append("ValueError: Couldn't call FFMPEG with these parameters") # Convert process should be running now. </code></pre> <p>And reading <code>stdout</code>:</p> <pre><code>convert = Convert() convert.input = "test.ogv" convert.output = "test.mp4" convert.output_size = (0, 0) convert.convert() while 1: print convert.ffmpeg.stdout.readline() </code></pre> <p>This works but, ffmpeg's status doesn't show. I'm assuming it has something to do with way ffmpeg refreshes it. Is there a way to access it?</p>
6
2009-09-21T16:49:40Z
1,455,726
<p>I've often noticed problems reading standard output (or even standard error!) with subprocess, due to buffering issues that are hard to defeat. My favorite solution, when I do need to read such stdout/stderr from the subprocess, is to switch to using, instead of <code>subprocess</code>, <a href="http://pexpect.sourceforge.net/pexpect.html"><code>pexpect</code></a> (or, on Windows, <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/"><code>wexpect</code></a>).</p>
8
2009-09-21T17:26:42Z
[ "python", "ffmpeg", "subprocess" ]
FFMPEG and Pythons subprocess
1,455,532
<p>I'm trying to write a gui for <code>FFMPEG</code>. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so:</p> <p>Calling <code>subprocess.Popen()</code></p> <pre><code># Convert - Calls FFMPEG with current settings. (in a seperate # thread.) def convert(self): # Check if options are valid if self.input == "" or self.output == "": return False # Make the command string ffmpegString = self.makeString() # Try to open with these settings try: self.ffmpeg = subprocess.Popen(ffmpegString, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: self.error.append("OSError: ") except ValueError: self.error.append("ValueError: Couldn't call FFMPEG with these parameters") # Convert process should be running now. </code></pre> <p>And reading <code>stdout</code>:</p> <pre><code>convert = Convert() convert.input = "test.ogv" convert.output = "test.mp4" convert.output_size = (0, 0) convert.convert() while 1: print convert.ffmpeg.stdout.readline() </code></pre> <p>This works but, ffmpeg's status doesn't show. I'm assuming it has something to do with way ffmpeg refreshes it. Is there a way to access it?</p>
6
2009-09-21T16:49:40Z
2,358,686
<p>I think you can't use readline because ffmpeg never prints one line, the status is updated by writing \r (carrige return) and then writing the line again.</p> <pre><code>size= 68kB time=0.39 bitrate=1412.1kbits/s \rsize= 2786kB time=16.17 bitrate=1411.2kbits/s \rsize= 5472kB time=31.76 bitrate=1411.2kbits/s \r\n </code></pre> <p>If you examine the row above you'll notice that there is only one \n and that gets printed when the file is done converting.</p>
2
2010-03-01T20:05:47Z
[ "python", "ffmpeg", "subprocess" ]
FFMPEG and Pythons subprocess
1,455,532
<p>I'm trying to write a gui for <code>FFMPEG</code>. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so:</p> <p>Calling <code>subprocess.Popen()</code></p> <pre><code># Convert - Calls FFMPEG with current settings. (in a seperate # thread.) def convert(self): # Check if options are valid if self.input == "" or self.output == "": return False # Make the command string ffmpegString = self.makeString() # Try to open with these settings try: self.ffmpeg = subprocess.Popen(ffmpegString, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: self.error.append("OSError: ") except ValueError: self.error.append("ValueError: Couldn't call FFMPEG with these parameters") # Convert process should be running now. </code></pre> <p>And reading <code>stdout</code>:</p> <pre><code>convert = Convert() convert.input = "test.ogv" convert.output = "test.mp4" convert.output_size = (0, 0) convert.convert() while 1: print convert.ffmpeg.stdout.readline() </code></pre> <p>This works but, ffmpeg's status doesn't show. I'm assuming it has something to do with way ffmpeg refreshes it. Is there a way to access it?</p>
6
2009-09-21T16:49:40Z
3,536,518
<p>Since ffmpeg writes the data unflushed to stderr you have to set the stderr file descriptor to non-blocking using fcntl.</p> <pre> fcntl.fcntl( pipe.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(pipe.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, ) </pre> <p>and then loop using select to read the data</p> <pre> while True: readx = select.select([pipe.stderr.fileno()], [], [])[0] if readx: chunk = pipe.stderr.read() </pre> <p>for full example go <a href="http://derrickpetzold.com/index.php/capturing-output-from-ffmpeg-python/" rel="nofollow">here</a>.</p>
1
2010-08-21T05:50:50Z
[ "python", "ffmpeg", "subprocess" ]
FFMPEG and Pythons subprocess
1,455,532
<p>I'm trying to write a gui for <code>FFMPEG</code>. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so:</p> <p>Calling <code>subprocess.Popen()</code></p> <pre><code># Convert - Calls FFMPEG with current settings. (in a seperate # thread.) def convert(self): # Check if options are valid if self.input == "" or self.output == "": return False # Make the command string ffmpegString = self.makeString() # Try to open with these settings try: self.ffmpeg = subprocess.Popen(ffmpegString, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: self.error.append("OSError: ") except ValueError: self.error.append("ValueError: Couldn't call FFMPEG with these parameters") # Convert process should be running now. </code></pre> <p>And reading <code>stdout</code>:</p> <pre><code>convert = Convert() convert.input = "test.ogv" convert.output = "test.mp4" convert.output_size = (0, 0) convert.convert() while 1: print convert.ffmpeg.stdout.readline() </code></pre> <p>This works but, ffmpeg's status doesn't show. I'm assuming it has something to do with way ffmpeg refreshes it. Is there a way to access it?</p>
6
2009-09-21T16:49:40Z
31,144,059
<p>Simply add ,universal_newlines=True to your subprocess.Popen line.</p> <pre><code>cmd="ffmpeg -i in.mp4 -y out.avi" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True) for line in process.stdout: print(line) </code></pre> <p>For now you got line in cycle like:</p> <pre><code>frame= 1900 fps=453 q=18.6 Lsize= 3473kB time=00:01:16.08 bitrate= 373.9kbits/s </code></pre> <p>Use the time= value to determine progress in percentage.</p>
2
2015-06-30T16:55:17Z
[ "python", "ffmpeg", "subprocess" ]
Python code does not work as expected when I run script as a Windows Service
1,455,592
<p>Here is the code to get Desktop path on Windows Vista. </p> <pre><code>import pythoncom import win32com.client pythoncom.CoInitialize() shell = win32com.client.Dispatch("WScript.Shell") desktop_path = shell.SpecialFolders("Desktop") </code></pre> <p>Code works fine when I tried on python interpreter but its not working when I execute the same code from Python script, which runs as a windows service. Function returns desktop path as empty string. </p> <p>Any idea what is wrong here? Is there any other alternative to get Desktop path when python script runs as Windows Service?</p>
3
2009-09-21T17:01:53Z
1,455,611
<p>Most likely, your service is running under an account which doesn't have a user desktop folder. Also note that by default, services have no access to the GUI - if your app has one, you have to mark your service as being allowed to interact with the desktop (user session, not folder).</p>
3
2009-09-21T17:05:22Z
[ "python", "windows", "windows-vista", "service" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
1,455,620
<p>This doesn't use string formatting, but you should be able to do:</p> <pre><code>print 'this is a tuple ', (1, 2, 3) </code></pre> <p>If you really want to use string formatting:</p> <pre><code>print 'this is a tuple %s' % str((1, 2, 3)) # or print 'this is a tuple %s' % ((1, 2, 3),) </code></pre> <p>Note, this assumes you are using a Python version earlier than 3.0.</p>
4
2009-09-21T17:06:49Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
1,455,623
<pre><code>&gt;&gt;&gt; thetuple = (1, 2, 3) &gt;&gt;&gt; print "this is a tuple: %s" % (thetuple,) this is a tuple: (1, 2, 3) </code></pre> <p>Making a singleton tuple with the tuple of interest as the only item, i.e. the <code>(thetuple,)</code> part, is the key bit here.</p>
112
2009-09-21T17:07:07Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
1,455,632
<pre><code>&gt;&gt;&gt; tup = (1, 2, 3) &gt;&gt;&gt; print "Here it is: %s" % (tup,) Here it is: (1, 2, 3) &gt;&gt;&gt; </code></pre> <p>Note that <code>(tup,)</code> is a tuple containing a tuple. The outer tuple is the argument to the % operator. The inner tuple is its content, which is actually printed.</p> <p><code>(tup)</code> is an expression in brackets, which when evaluated results in <code>tup</code>.</p> <p><code>(tup,)</code> with the trailing comma is a tuple, which contains <code>tup</code> as is only member.</p>
16
2009-09-21T17:08:40Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
1,455,635
<pre><code>t = (1, 2, 3) # the comma (,) concatenates the strings and adds a space print "this is a tuple", (t) # format is the most flexible way to do string formatting print "this is a tuple {0}".format(t) # classic string formatting # I use it only when working with older Python versions print "this is a tuple %s" % repr(t) print "this is a tuple %s" % str(t) </code></pre>
2
2009-09-21T17:09:10Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
1,456,418
<p>I think the best way to do this is:</p> <pre><code>t = (1,2,3) print "This is a tuple: %s" % str(t) </code></pre> <p>If you're familiar with <a href="http://en.wikipedia.org/wiki/Printf#printf%5Fformat%5Fplaceholders" rel="nofollow">printf</a> style formatting, then Python supports its own version. In Python, this is done using the "%" operator applied to strings (an overload of the modulo operator), which takes any string and applies printf-style formatting to it.</p> <p>In our case, we are telling it to print "This is a tuple: ", and then adding a string "%s", and for the actual string, we're passing in a string representation of the tuple (by calling str(t)).</p> <p>If you're not familiar with printf style formatting, I highly suggest learning, since it's very standard. Most languages support it in one way or another.</p>
0
2009-09-21T19:38:45Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
11,130,859
<p>Note that the <code>%</code> syntax is obsolete. Use <code>str.format</code>, which is simpler and more readable:</p> <pre><code>t = 1,2,3 print 'This is a tuple {0}'.format(t) </code></pre>
18
2012-06-21T02:41:20Z
[ "python" ]
Printing tuple with string formatting in Python
1,455,602
<p>So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.</p> <pre><code>tup = (1,2,3) print "this is a tuple %something" % (tup) </code></pre> <p>and this should print tuple representation with brackets, like</p> <blockquote> <p>This is a tuple (1,2,3)</p> </blockquote> <p>But I get <code>TypeError: not all arguments converted during string formatting</code> instead.</p> <p>How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)</p>
59
2009-09-21T17:03:45Z
26,249,755
<p>Please note a trailing comma will be added if the tuple only has one item. e.g:</p> <pre><code>t = (1,) print 'this is a tuple {}'.format(t) </code></pre> <p>and you'll get:</p> <pre><code>'this is a tuple (1,)' </code></pre> <p>in some cases e.g. you want to get a quoted list to be used in mysql query string like </p> <pre><code>SELECT name FROM students WHERE name IN ('Tom', 'Jerry'); </code></pre> <p>you need to consider to remove the tailing comma use replace(',)', ')') after formatting because it's possible that the tuple has only 1 item like ('Tom',), so the tailing comma needs to be removed:</p> <pre><code>query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')') </code></pre> <p>Please suggest if you have decent way of removing this comma in the output.</p>
-1
2014-10-08T05:27:29Z
[ "python" ]
Could not get out of python loop
1,455,630
<p>I want to get out of loop when there is no data but loop seems to be stopping at <code>recvfrom</code></p> <pre><code>image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...' </code></pre>
1
2009-09-21T17:08:23Z
1,455,653
<p>What is the blocking mode of your socket?</p> <p>If you are in blocking mode (which I think is the default), your program would stop until data is available... You would then not get to the next line after the recv() until data is coming. </p> <p>If you switch to non-blocking mode, however (see socket.setblocking(flag)), I think that it will raise an exception you would have to catch rather than null-check.</p>
0
2009-09-21T17:12:07Z
[ "python", "sockets", "loops" ]
Could not get out of python loop
1,455,630
<p>I want to get out of loop when there is no data but loop seems to be stopping at <code>recvfrom</code></p> <pre><code>image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...' </code></pre>
1
2009-09-21T17:08:23Z
1,455,662
<p>Try setting to a <a href="http://docs.python.org/library/socket.html#socket.socket.setblocking" rel="nofollow">non-blocking socket</a>. You would do this before the loop starts. You can also try a <a href="http://docs.python.org/library/socket.html#socket.socket.settimeout" rel="nofollow">socket with a timeout</a>.</p>
5
2009-09-21T17:14:29Z
[ "python", "sockets", "loops" ]
Could not get out of python loop
1,455,630
<p>I want to get out of loop when there is no data but loop seems to be stopping at <code>recvfrom</code></p> <pre><code>image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...' </code></pre>
1
2009-09-21T17:08:23Z
1,455,688
<p>You might want to set socket.setdefaulttimeout(n) to get out of the loop if no data is returned after specified time period.</p>
0
2009-09-21T17:19:00Z
[ "python", "sockets", "loops" ]
Could not get out of python loop
1,455,630
<p>I want to get out of loop when there is no data but loop seems to be stopping at <code>recvfrom</code></p> <pre><code>image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...' </code></pre>
1
2009-09-21T17:08:23Z
1,455,709
<p><code>recvfrom</code> may indeed stop (waiting for data) unless you've set your socket to non-blocking or timeout mode. Moreover, if the socket gets closed by your counterpart, the indication of "socket was closed, nothing more to receive" is <strong>not</strong> a value of <code>None</code> for <code>data</code> -- it's an empty string, <code>''</code>. So you could change your test to <code>if not data: break</code> for more generality.</p>
2
2009-09-21T17:23:18Z
[ "python", "sockets", "loops" ]
How to build sqlite for Python 2.4?
1,455,642
<p>I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:</p> <blockquote> <p>error: command 'gcc' failed with exit status 1</p> </blockquote> <p>As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).</p> <p>Does anybody know how to build sqlite for Python 2.4?</p> <p>As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.</p> <p>Thank you in advance.</p>
0
2009-09-21T17:09:59Z
1,455,663
<p>If you don't have root privileges, I would recommend installing a more recent version of Python in your home directory and then adding your local version to your <code>PATH</code>. It seems easier to go that direction than to try to make sqlite work with an old version of Python.</p> <p>You will also be doing yourself a favor by using a recent version of Python, because you'll have access to the numerous recent improvements in the language.</p>
0
2009-09-21T17:15:01Z
[ "python", "sqlite", "pysqlite" ]
How to build sqlite for Python 2.4?
1,455,642
<p>I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:</p> <blockquote> <p>error: command 'gcc' failed with exit status 1</p> </blockquote> <p>As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).</p> <p>Does anybody know how to build sqlite for Python 2.4?</p> <p>As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.</p> <p>Thank you in advance.</p>
0
2009-09-21T17:09:59Z
1,455,666
<p>You can download and install Python to your home directory. </p> <pre><code>$ cd $ mkdir opt $ mkdir downloads $ cd downloads $ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz $ tar xvzf Python-2.6.2.tgz $ cd Python-2.6.2 $ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4 $ make $ make install </code></pre> <p>Then, (if you are using bash) in your .bash_profile do</p> <pre><code>export PATH=$HOME/opt/bin/:$PATH export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH </code></pre> <p>Then, source the file to make it available</p> <pre><code>$ cd $ source .bash_profile $ python -V </code></pre> <p>where python -V will return the python version. If the correct version appears, any packages that you run with Python's setup.py util (assuming the developer followed the correct conventions) will install in ~/opt/lib/python2.x/site-packages directory.</p>
1
2009-09-21T17:16:00Z
[ "python", "sqlite", "pysqlite" ]
How to build sqlite for Python 2.4?
1,455,642
<p>I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:</p> <blockquote> <p>error: command 'gcc' failed with exit status 1</p> </blockquote> <p>As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).</p> <p>Does anybody know how to build sqlite for Python 2.4?</p> <p>As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.</p> <p>Thank you in advance.</p>
0
2009-09-21T17:09:59Z
1,455,689
<p>Download pysqlite <a href="http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.5/pysqlite-2.5.5.tar.gz" rel="nofollow">here</a>, cd into the directory you downloaded to, unpack the tarball:</p> <pre><code>$ tar xzf pysqlite-2.5.5.tar.gz </code></pre> <p>then just do (if your permissions are set right for this; may need <code>sudo</code> otherwise):</p> <pre><code>$ cd pysqlite-2.5.5 $ python2.4 setup.py install </code></pre> <p>one error does appear in the copious output:</p> <pre><code> File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/pysqlite2/test/py25tests.py", line 48 with self.con: ^ SyntaxError: invalid syntax </code></pre> <p>since as clearly shown that file is for py 2.5 tests only (<code>with</code> statement not present in 2.4!-). Nevertheless the install is successful:</p> <pre><code>$ python2.4 -c'import pysqlite2' $ </code></pre> <p>All this is on Mac OS X 10.5 but using python2.4 separately installed from the system-supplied Python 2.5.</p> <p>The error you report doesn't tell us much -- maybe you're missing the headers or libraries for sqlite itself? Can you show us other output lines around that single error msg...?</p>
1
2009-09-21T17:19:01Z
[ "python", "sqlite", "pysqlite" ]
How to build sqlite for Python 2.4?
1,455,642
<p>I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:</p> <blockquote> <p>error: command 'gcc' failed with exit status 1</p> </blockquote> <p>As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).</p> <p>Does anybody know how to build sqlite for Python 2.4?</p> <p>As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.</p> <p>Thank you in advance.</p>
0
2009-09-21T17:09:59Z
2,805,287
<p>I had the same trouble with gcc failing with Ubuntu Karmic. I fixed this by installing the python-dev package. In my case, I'm working with python2.4, so I installed the python2.4-dev package. The python-dev package should work for python2.6.</p>
0
2010-05-10T18:20:56Z
[ "python", "sqlite", "pysqlite" ]
Can I "embed" a Python back-end in an AIR application?
1,455,722
<p>I'm trying to find out if there is a way I could embed a Python back-end into an AIR application? I'm looking to employ an approach similar to the one outlined <a href="http://www.adobe.com/devnet/flex/articles/flex%5Fui%5F04.html" rel="nofollow">here</a> to implement the business logic for my application, but additionally, I would like to provide the user with a single binary which they can load. I don't want the user to have to fire up a seperate server process to make this work. Is this possible in some way or am I out of luck?</p>
0
2009-09-21T17:25:44Z
1,455,746
<p>Probably. We are using a J2EE server side which uses SOAP webservices to talk to our AIR application on the frontend. You should be able to do the same because soap doesn't care which technology sits on either side of it.</p> <p>You can always have the application launch from a single binary which first fires up the server, then the client, if both are expected to sit on the users system. Also it gives you flexibility to have a more service oriented model later, if you want to. Without knowing what your app does, it is hard to know if that makes sense or not.</p> <p>For setting up the python side of SOAP webservices, here's a useful link to a <a href="http://diveintopython.net/soap_web_services/index.html" rel="nofollow">diveintopython article</a>. Then, if you have your server running with the wsdl, <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=data_4.html" rel="nofollow">FlexBuilder can generate the AIR side of the webservices for you</a>.</p>
1
2009-09-21T17:30:19Z
[ "python", "flex", "air" ]
Can I "embed" a Python back-end in an AIR application?
1,455,722
<p>I'm trying to find out if there is a way I could embed a Python back-end into an AIR application? I'm looking to employ an approach similar to the one outlined <a href="http://www.adobe.com/devnet/flex/articles/flex%5Fui%5F04.html" rel="nofollow">here</a> to implement the business logic for my application, but additionally, I would like to provide the user with a single binary which they can load. I don't want the user to have to fire up a seperate server process to make this work. Is this possible in some way or am I out of luck?</p>
0
2009-09-21T17:25:44Z
1,456,111
<p>You cannot embed your Python server in an AIR application. So basically you are out of luck.</p> <p>The simplest solution probably is to run a server on a central location that all your users can connect to from their AIR apps. That means that all/most of the data will be on your server, and not on the users computer, I don't know if that is a big issue but I guess it is.</p> <p>Also depending on your target systems you could create the program you want yourself without (fully) depending on AIR. You can generate executables for windows and osx from Flash CS3/4 or you can use a special (commercial) executable-maker that provides some more functionality. Wrapping this exe and your python program in a meta-executable that launches both should be possible with some work. Of course you won't have the benefits if the AIR installer etc in this case.</p>
1
2009-09-21T18:41:50Z
[ "python", "flex", "air" ]
Can I "embed" a Python back-end in an AIR application?
1,455,722
<p>I'm trying to find out if there is a way I could embed a Python back-end into an AIR application? I'm looking to employ an approach similar to the one outlined <a href="http://www.adobe.com/devnet/flex/articles/flex%5Fui%5F04.html" rel="nofollow">here</a> to implement the business logic for my application, but additionally, I would like to provide the user with a single binary which they can load. I don't want the user to have to fire up a seperate server process to make this work. Is this possible in some way or am I out of luck?</p>
0
2009-09-21T17:25:44Z
1,456,734
<p>OK, so since it didn't seem possible to go that way around, I came up with an alternative that seems to work for what I want.</p> <p>Instead of trying to embed Python inside AIR, I've gone the other way around: I'm building my Python code into a stand-alone executable using PyInstaller and bundling the AIR application as a resource. The Python code then starts up it's webserver and fires off the AIR app which can then connect to the (local) remote services as required.</p>
1
2009-09-21T20:43:08Z
[ "python", "flex", "air" ]
How to encrypt using public key?
1,455,782
<pre><code>msg = "this is msg to encrypt" pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file. encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding) </code></pre> <p>Now I am trying to give file containing radix64 format public key as a parameter in this method and unable to get expected result i.e encryption using radix64 format public key.</p> <p>Is there any other method in the Python API which can encrypt msg using public key after trying some mechanism?</p> <p>I am getting my public key from public key server with some HTML wrapping and in radix64 format. How can I convert the public key so that it can be accepted by any encryption method?</p>
4
2009-09-21T17:36:19Z
1,456,131
<p>Did you ask this question before? See my answer to this question,</p> <p><a href="http://stackoverflow.com/questions/1387867/how-to-convert-base64-radix64-public-key-to-a-pem-format-in-python">http://stackoverflow.com/questions/1387867/how-to-convert-base64-radix64-public-key-to-a-pem-format-in-python</a></p>
1
2009-09-21T18:44:35Z
[ "python", "encryption", "encoding" ]
How to encrypt using public key?
1,455,782
<pre><code>msg = "this is msg to encrypt" pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file. encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding) </code></pre> <p>Now I am trying to give file containing radix64 format public key as a parameter in this method and unable to get expected result i.e encryption using radix64 format public key.</p> <p>Is there any other method in the Python API which can encrypt msg using public key after trying some mechanism?</p> <p>I am getting my public key from public key server with some HTML wrapping and in radix64 format. How can I convert the public key so that it can be accepted by any encryption method?</p>
4
2009-09-21T17:36:19Z
1,502,121
<p>There is an error somewhere in the public key. It appears to be a PGP public key but with different line lengths, so it can't be used directly as an RSA public key.</p>
0
2009-10-01T05:59:43Z
[ "python", "encryption", "encoding" ]
How to encrypt using public key?
1,455,782
<pre><code>msg = "this is msg to encrypt" pub_key = M2Crypto.RSA.load_pub_key('mykey.py') // This method is taking PEM file. encrypted = pub_key.public_encrypt(msg, M2Crypto.RSA.pkcs1_padding) </code></pre> <p>Now I am trying to give file containing radix64 format public key as a parameter in this method and unable to get expected result i.e encryption using radix64 format public key.</p> <p>Is there any other method in the Python API which can encrypt msg using public key after trying some mechanism?</p> <p>I am getting my public key from public key server with some HTML wrapping and in radix64 format. How can I convert the public key so that it can be accepted by any encryption method?</p>
4
2009-09-21T17:36:19Z
7,424,450
<p>In case someone searches for this question, I was getting the same error message: </p> <pre><code>M2Crypto.RSA.RSAError: no start line </code></pre> <p>In my case, it turned out that my keys were of type unicode. This was solved by converting the key back to ascii:</p> <pre><code>key.encode('ascii') </code></pre>
5
2011-09-15T00:05:41Z
[ "python", "encryption", "encoding" ]
Can we run google app engine on ubuntu/windows and serve web application
1,455,800
<p>I see google provide SDK and utilties to develop and run the web application in development (developer-pc) and port them to google app engine live (at google server).</p> <p>Can we use google app engine to run the local web application without using google infrastructure? </p> <p>Basically I want a decent job scheduler and persistent job queue for python (I am not using google infrastructure). I see google provides task queue implementation along with their app engine sdk.</p> <p>Can I use google app engine SDK to development my full fledged python application for task queue?</p>
4
2009-09-21T17:41:39Z
1,455,828
<p>I don't believe so. According to the App Engine terms of service:</p> <blockquote> <p>7.1. Google gives you a personal, worldwide, royalty-free, non-assignable and non-exclusive license to use the software provided to you by Google as part of the Service as provided to you by Google (referred to as the "Google App Engine Software" below). This license is for the sole purpose of enabling you to use and enjoy the benefit of the <strong>Service as provided by Google</strong>, in the manner permitted by the Terms.</p> </blockquote> <p>(emphasis mine)</p> <p>You'd want to check with a lawyer, but to me this sounds like the dev_appserver.py server is only to be used for development of applications which are then deployed to the GAE "service", not for running your own servers internally.</p> <p>I also suspect that running a production service off dev_appserver.py would be inadvisable for performance reasons. Without special effort, threaded Python web servers can generally only accomodate one request at a time, which limits your performance and scalability. This is due to an implementation detail of CPython, called the GIL. See <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock</a> for a detailed explanation.</p>
-1
2009-09-21T17:47:51Z
[ "python", "google-app-engine", "task" ]
Can we run google app engine on ubuntu/windows and serve web application
1,455,800
<p>I see google provide SDK and utilties to develop and run the web application in development (developer-pc) and port them to google app engine live (at google server).</p> <p>Can we use google app engine to run the local web application without using google infrastructure? </p> <p>Basically I want a decent job scheduler and persistent job queue for python (I am not using google infrastructure). I see google provides task queue implementation along with their app engine sdk.</p> <p>Can I use google app engine SDK to development my full fledged python application for task queue?</p>
4
2009-09-21T17:41:39Z
1,455,832
<p>You can run App Engine apps on top of <a href="http://code.google.com/p/appscale/" rel="nofollow">appscale</a> which in turn does run on Eucalyptus, Xen, and other clustering solutions you can deploy on Ubuntu (not sure about there being any Windows support) -- looks like it may require substantial system installation, configuration, and administration work to get started (sorry, no first-hand experience yet), but once you've done that investment it appears it may be smoother going forwards. (Automation of task queues is a relatively recent addition to appscale, but it's apparently working and can be patched in from a bazaar branch until it gets fully integrated into the trunk of the appscale project).</p> <p><strong>Edit</strong>: since there seems to be some confusion about licensing of this code, I'll point out that the App Engine SDK, as per <a href="http://code.google.com/p/googleappengine/" rel="nofollow">its site</a>, is under Apache License 2.0, and appscale's under the New BSD License. Both are extremely permissive and liberal open-source licenses that basically allow you all sorts of reuses, remixes, mashups, redistributions, etc, etc.</p> <p><strong>Edit</strong>: Nick also suggests mentioning <a href="http://code.google.com/p/twistedae/" rel="nofollow">TwistedAE</a>, another effort to build an open source way (also Apache License 2.0) to deploy App Engine apps on your own infrastructure; I have no direct experience with it, and it IS still pre-alpha, but it does seem very promising and well worth keeping an eye on (tx Nick!).</p>
8
2009-09-21T17:48:18Z
[ "python", "google-app-engine", "task" ]
Given a class type how do I create an instance in Python?
1,455,835
<p>Let's say I have this :</p> <pre><code>class whatever(object): def __init__(self): pass </code></pre> <p>and this function:</p> <pre><code>def create_object(type_name): # create an object of type_name </code></pre> <p>I'd like to be able to call the <code>create_object</code> like this:</p> <pre><code>inst = create_object(whatever) </code></pre> <p>and get back an instance of <code>whatever</code>. I think this should be doable without using <code>eval</code>, I'd like to know how to do this. Please notice that I'm <strong>NOT</strong> using a string as a parameter for <code>create_object</code>.</p>
0
2009-09-21T17:49:28Z
1,455,851
<p>The most obvious way:</p> <pre><code>def create_object(type_name): return type_name() </code></pre>
7
2009-09-21T17:51:23Z
[ "python", "oop" ]
Given a class type how do I create an instance in Python?
1,455,835
<p>Let's say I have this :</p> <pre><code>class whatever(object): def __init__(self): pass </code></pre> <p>and this function:</p> <pre><code>def create_object(type_name): # create an object of type_name </code></pre> <p>I'd like to be able to call the <code>create_object</code> like this:</p> <pre><code>inst = create_object(whatever) </code></pre> <p>and get back an instance of <code>whatever</code>. I think this should be doable without using <code>eval</code>, I'd like to know how to do this. Please notice that I'm <strong>NOT</strong> using a string as a parameter for <code>create_object</code>.</p>
0
2009-09-21T17:49:28Z
1,455,857
<p>If I understand correctly, what you want is:</p> <pre><code>def create_object(type_name, *args): # create an object of type_name return type_name(*args) inst = create_object(whatever) </code></pre> <p>I don't really know <em>why</em> you want to do this, but would be interesting to hear from you what are your reasons to need such a construct.</p>
2
2009-09-21T17:52:20Z
[ "python", "oop" ]
Given a class type how do I create an instance in Python?
1,455,835
<p>Let's say I have this :</p> <pre><code>class whatever(object): def __init__(self): pass </code></pre> <p>and this function:</p> <pre><code>def create_object(type_name): # create an object of type_name </code></pre> <p>I'd like to be able to call the <code>create_object</code> like this:</p> <pre><code>inst = create_object(whatever) </code></pre> <p>and get back an instance of <code>whatever</code>. I think this should be doable without using <code>eval</code>, I'd like to know how to do this. Please notice that I'm <strong>NOT</strong> using a string as a parameter for <code>create_object</code>.</p>
0
2009-09-21T17:49:28Z
1,455,859
<pre><code>def create_object(type_name): return type_name() </code></pre> <p>you can of course skip the function altogether and create the instance of <code>whatever</code> like this:</p> <pre><code>inst = whatever() </code></pre>
2
2009-09-21T17:52:26Z
[ "python", "oop" ]
Given a class type how do I create an instance in Python?
1,455,835
<p>Let's say I have this :</p> <pre><code>class whatever(object): def __init__(self): pass </code></pre> <p>and this function:</p> <pre><code>def create_object(type_name): # create an object of type_name </code></pre> <p>I'd like to be able to call the <code>create_object</code> like this:</p> <pre><code>inst = create_object(whatever) </code></pre> <p>and get back an instance of <code>whatever</code>. I think this should be doable without using <code>eval</code>, I'd like to know how to do this. Please notice that I'm <strong>NOT</strong> using a string as a parameter for <code>create_object</code>.</p>
0
2009-09-21T17:49:28Z
1,455,863
<pre><code>def create_object(typeobject): return typeobject() </code></pre> <p>As you so explicitly say that the arg to <code>create_object</code> is NOT meant to be a string, I assume it's meant to be the type object itself, just like in the <code>create_object(whatever)</code> example you give, in which <code>whatever</code> is indeed the type itself.</p>
5
2009-09-21T17:52:57Z
[ "python", "oop" ]
Built-in tree view for Django-Admin sites?
1,456,047
<p>Why is there no built-in tree view in the Python Django framework? Isn't there an easy way to visualize a model when a class has an 1:n relation to itself?</p> <p>I know about some fancy google code projects to achieve that but I think there must be some common sense among the Django community to handle this common case. Any ideas?</p>
3
2009-09-21T18:26:20Z
1,456,289
<p>The core devs are pretty strongly against adding extra stuff to Django unless there's a clear universal requirement - especially if there are perfectly good third-party projects that provide this functionality. </p> <p>This is absolutely the case with tree views. It's very far from something that everyone wants to do, and there are at least three projects that provide trees, including the relevant tools to build representations of the trees in views and the admin.</p> <p>I suggest you look into them - my favourite is <a href="http://code.google.com/p/django-mptt" rel="nofollow">django-mptt</a>.</p>
2
2009-09-21T19:15:23Z
[ "python", "django", "tree", "view" ]
Built-in tree view for Django-Admin sites?
1,456,047
<p>Why is there no built-in tree view in the Python Django framework? Isn't there an easy way to visualize a model when a class has an 1:n relation to itself?</p> <p>I know about some fancy google code projects to achieve that but I think there must be some common sense among the Django community to handle this common case. Any ideas?</p>
3
2009-09-21T18:26:20Z
9,965,582
<p>check out:</p> <p><a href="http://stackoverflow.com/questions/5229508/tree-structure-of-parent-child-relation-in-django-templates">tree structure of parent child relation in django templates</a></p> <p><a href="http://code.google.com/p/django-treeview/" rel="nofollow">http://code.google.com/p/django-treeview/</a></p> <p>An alternative would be to implement your tree in JavaScript. Django and JavaScript play nicely so that could work fine. There are plenty of JavaScript trees out there, just ask google</p>
0
2012-04-01T15:24:13Z
[ "python", "django", "tree", "view" ]
Built-in tree view for Django-Admin sites?
1,456,047
<p>Why is there no built-in tree view in the Python Django framework? Isn't there an easy way to visualize a model when a class has an 1:n relation to itself?</p> <p>I know about some fancy google code projects to achieve that but I think there must be some common sense among the Django community to handle this common case. Any ideas?</p>
3
2009-09-21T18:26:20Z
26,561,147
<p>Another option is a prove of concept application for Django - <a href="https://pypi.python.org/pypi/django-admirarchy" rel="nofollow">django-admirarchy</a>. It renders hierachies level by level (like Norton Commander and Co).</p>
1
2014-10-25T09:47:26Z
[ "python", "django", "tree", "view" ]
Dealing with db.Timeout on Google App Engine
1,456,070
<p>I'm testing my application (on <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes).</p> <p>I keep getting db.Timeout <em>very often</em> though.</p> <p>How do I deal with this? I was going to surround all my queries with really brutal code like this:</p> <pre> querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( """xxx""" ).get() querySucceeded = True #only get here if above line doesn't raise exc except : querySucceeded = False </pre> <p>Is this ok? Do you agree? What's a better way to deal with db.Timeouts?</p> <h3>Edit:</h3> <p>I now use this for any get queries</p> <pre> """ Query gets single result """ def queryGet( gql ) : querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( gql ).get() querySucceeded = True #only get here if above line doesn't raise except : querySucceeded = False return result </pre> <p>I have similar functions for fetch and count.</p>
4
2009-09-21T18:33:05Z
1,457,225
<p>Queries will occasionally fail. You can either show an error message to the user, or retry, as you're doing above. If you retry, however, you should use thread.sleep to add increasing amounts of delay (starting at, say, 50ms) on each retry - retries are more likely to succeed if they're not retried as fast as possible.</p> <p>40 queries per request is a <em>lot</em>, though. You should consider refactoring your code - it must be possible to eliminate most of those!</p>
6
2009-09-21T22:28:41Z
[ "python", "google-app-engine" ]
Dealing with db.Timeout on Google App Engine
1,456,070
<p>I'm testing my application (on <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes).</p> <p>I keep getting db.Timeout <em>very often</em> though.</p> <p>How do I deal with this? I was going to surround all my queries with really brutal code like this:</p> <pre> querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( """xxx""" ).get() querySucceeded = True #only get here if above line doesn't raise exc except : querySucceeded = False </pre> <p>Is this ok? Do you agree? What's a better way to deal with db.Timeouts?</p> <h3>Edit:</h3> <p>I now use this for any get queries</p> <pre> """ Query gets single result """ def queryGet( gql ) : querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( gql ).get() querySucceeded = True #only get here if above line doesn't raise except : querySucceeded = False return result </pre> <p>I have similar functions for fetch and count.</p>
4
2009-09-21T18:33:05Z
1,475,218
<p>See the new ROTModel in GAE-Utilities. The second discussion below shows how it does retries. It's a subclass of db.Model, so your classes can inherit from ROTModel instead, and take advantage of it's retries. </p> <p><a href="http://code.google.com/p/gaeutilities" rel="nofollow">http://code.google.com/p/gaeutilities</a></p> <p><a href="http://groups.google.com/group/google-appengine/browse%5Fthread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a" rel="nofollow">http://groups.google.com/group/google-appengine/browse_thread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a</a></p>
1
2009-09-25T03:00:33Z
[ "python", "google-app-engine" ]
Dealing with db.Timeout on Google App Engine
1,456,070
<p>I'm testing my application (on <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes).</p> <p>I keep getting db.Timeout <em>very often</em> though.</p> <p>How do I deal with this? I was going to surround all my queries with really brutal code like this:</p> <pre> querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( """xxx""" ).get() querySucceeded = True #only get here if above line doesn't raise exc except : querySucceeded = False </pre> <p>Is this ok? Do you agree? What's a better way to deal with db.Timeouts?</p> <h3>Edit:</h3> <p>I now use this for any get queries</p> <pre> """ Query gets single result """ def queryGet( gql ) : querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( gql ).get() querySucceeded = True #only get here if above line doesn't raise except : querySucceeded = False return result </pre> <p>I have similar functions for fetch and count.</p>
4
2009-09-21T18:33:05Z
1,733,871
<p>Here's a decorator to retry on db.Timeout, adapted from one from Kay framework:</p> <pre><code>import logging, time from google.appengine.ext import db def retry_on_timeout(retries=3, interval=1.0, exponent=2.0): """A decorator to retry a given function performing db operations.""" def _decorator(func): def _wrapper(*args, **kwargs): count = 0 while True: try: return func(*args, **kwargs) except db.Timeout, e: logging.debug(e) if count &gt;= retries: raise e else: sleep_time = (exponent ** count) * interval logging.warning("Retrying function %r in %d secs" % (func, sleep_time)) time.sleep(sleep_time) count += 1 return _wrapper return _decorator </code></pre> <p>To use it, simply decorate any function that performs db operations and you'd like to do retries:</p> <pre><code>@retry_on_timeout() def do_the_stuff(models): return db.put(models) </code></pre>
7
2009-11-14T10:13:08Z
[ "python", "google-app-engine" ]
Dealing with db.Timeout on Google App Engine
1,456,070
<p>I'm testing my application (on <a href="http://en.wikipedia.org/wiki/Google%5FApp%5FEngine" rel="nofollow">Google App Engine</a> live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes).</p> <p>I keep getting db.Timeout <em>very often</em> though.</p> <p>How do I deal with this? I was going to surround all my queries with really brutal code like this:</p> <pre> querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( """xxx""" ).get() querySucceeded = True #only get here if above line doesn't raise exc except : querySucceeded = False </pre> <p>Is this ok? Do you agree? What's a better way to deal with db.Timeouts?</p> <h3>Edit:</h3> <p>I now use this for any get queries</p> <pre> """ Query gets single result """ def queryGet( gql ) : querySucceeded = False while not querySucceeded : try : result = db.GqlQuery( gql ).get() querySucceeded = True #only get here if above line doesn't raise except : querySucceeded = False return result </pre> <p>I have similar functions for fetch and count.</p>
4
2009-09-21T18:33:05Z
1,959,830
<p>Take a look at this this python Autoretry Datastore Timeouts recipe. Similar to moraes answer, but you only need to call it once at initialization time, rather than decorate functions that perform datastore operations.</p> <p><a href="http://appengine-cookbook.appspot.com/recipe/autoretry-datastore-timeouts/" rel="nofollow">http://appengine-cookbook.appspot.com/recipe/autoretry-datastore-timeouts</a></p>
2
2009-12-24T21:38:58Z
[ "python", "google-app-engine" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,389
<p>No, there is really no way to do this without creating two dictionaries. How would it be possible to implement this with just one dictionary while continuing to offer comparable performance?</p> <p>You are better off creating a custom type that encapsulates two dictionaries and exposes the functionality you want.</p>
3
2009-09-21T19:31:28Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,390
<p>Two hash maps is actually probably the fastest-performing solution assuming you can spare the memory. I would wrap those in a single class - the burden on the programmer is in ensuring that two the hash maps sync up correctly.</p>
5
2009-09-21T19:31:29Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,392
<p>I would just populate a second hash, with</p> <pre><code>reverse_map = dict((reversed(item) for item in forward_map.items())) </code></pre>
14
2009-09-21T19:31:55Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,461
<p>In your special case you can store both in one dictionary:</p> <pre><code>relation = {} relation['Alice'] = 'Bob' relation['Bob'] = 'Alice' </code></pre> <p>Since what you are describing is a symmetric relationship. <code>A -&gt; B =&gt; B -&gt; A</code></p>
26
2009-09-21T19:47:24Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,482
<p>You have two separate issues.</p> <ol> <li><p>You have a "Conversation" object. It refers to two Persons. Since a Person can have multiple conversations, you have a many-to-many relationship.</p></li> <li><p>You have a Map from Person to a list of Conversations. A Conversion will have a pair of Persons.</p></li> </ol> <p>Do something like this</p> <pre><code>from collections import defaultdict switchboard= defaultdict( list ) x = Conversation( "Alice", "Bob" ) y = Conversation( "Alice", "Charlie" ) for c in ( x, y ): switchboard[c.p1].append( c ) switchboard[c.p2].append( c ) </code></pre>
5
2009-09-21T19:50:07Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,456,583
<p>Here is a <a href="http://www.aminus.net/geniusql/browser/trunk/geniusql/objects.py#L32" rel="nofollow">simple bijective Dictionary implementation</a>, although I don't know if it will meet your performance requirements.</p> <p>(Link from <a href="http://paddy3118.blogspot.com/2009/04/bimap-bi-directional-mappingdictionary.html" rel="nofollow">this blog article on boost Bimap for Python</a>, which has some nice discussion of the topic.)</p>
1
2009-09-21T20:12:20Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
1,457,749
<p>The kjbuckets C extension module provides a "graph" data structure which I believe gives you what you want.</p>
0
2009-09-22T01:48:12Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
13,276,237
<p>You can create your own dictionary type by subclassing <code>dict</code> and adding the logic that you want. Here's a basic example:</p> <pre><code>class TwoWayDict(dict): def __setitem__(self, key, value): # Remove any previous connections with these values if key in self: del self[key] if value in self: del self[value] dict.__setitem__(self, key, value) dict.__setitem__(self, value, key) def __delitem__(self, key): dict.__delitem__(self, self[key]) dict.__delitem__(self, key) def __len__(self): """Returns the number of connections""" return dict.__len__(self) // 2 </code></pre> <p>And it works like so:</p> <pre><code>&gt;&gt;&gt; d = TwoWayDict() &gt;&gt;&gt; d['foo'] = 'bar' &gt;&gt;&gt; d['foo'] 'bar' &gt;&gt;&gt; d['bar'] 'foo' &gt;&gt;&gt; len(d) 1 &gt;&gt;&gt; del d['foo'] &gt;&gt;&gt; d['bar'] Traceback (most recent call last): File "&lt;stdin&gt;", line 7, in &lt;module&gt; KeyError: 'bar' </code></pre> <p>I'm sure I didn't cover all the cases, but that should get you started.</p>
48
2012-11-07T18:53:25Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
14,129,446
<p>You may be able to use a <code>DoubleDict</code> as shown in <a href="http://code.activestate.com/recipes/578224/" rel="nofollow">recipe 578224</a> on the <a href="http://code.activestate.com/recipes/langs/python/" rel="nofollow">Python Cookbook</a>.</p>
1
2013-01-02T21:27:01Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
18,045,091
<p>Another possible solution is to implement a subclass of <code>dict</code>, that holds the original dictionary and keeps track of a reversed version of it. Keeping two seperate dicts can be useful if keys and values are overlapping. </p> <pre><code>class TwoWayDict(dict): def __init__(self, my_dict): dict.__init__(self, my_dict) self.rev_dict = {v : k for k,v in my_dict.iteritems()} def __setitem__(self, key, value): dict.__setitem__(self, key, value) self.rev_dict.__setitem__(value, key) def pop(self, key): self.rev_dict.pop(self[key]) dict.pop(self, key) # The above is just an idea other methods # should also be overridden. </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; d = {'a' : 1, 'b' : 2} # suppose we need to use d and its reversed version &gt;&gt;&gt; twd = TwoWayDict(d) # create a two-way dict &gt;&gt;&gt; twd {'a': 1, 'b': 2} &gt;&gt;&gt; twd.rev_dict {1: 'a', 2: 'b'} &gt;&gt;&gt; twd['a'] 1 &gt;&gt;&gt; twd.rev_dict[2] 'b' &gt;&gt;&gt; twd['c'] = 3 # we add to twd and reversed version also changes &gt;&gt;&gt; twd {'a': 1, 'c': 3, 'b': 2} &gt;&gt;&gt; twd.rev_dict {1: 'a', 2: 'b', 3: 'c'} &gt;&gt;&gt; twd.pop('a') # we pop elements from twd and reversed version changes &gt;&gt;&gt; twd {'c': 3, 'b': 2} &gt;&gt;&gt; twd.rev_dict {2: 'b', 3: 'c'} </code></pre>
0
2013-08-04T16:33:56Z
[ "python" ]
Two way/reverse map
1,456,373
<p>I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. </p> <p>Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. </p> <p>Or suggest another data structure.</p> <p>There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her. </p>
50
2009-09-21T19:27:35Z
34,081,276
<p>There's the collections-extended library on pypi: <a href="https://pypi.python.org/pypi/collections-extended/0.6.0" rel="nofollow">https://pypi.python.org/pypi/collections-extended/0.6.0</a></p> <p>Using the bijection class is as easy as:</p> <pre><code>RESPONSE_TYPES = bijection({ 0x03 : 'module_info', 0x09 : 'network_status_response', 0x10 : 'trust_center_device_update' }) &gt;&gt;&gt; RESPONSE_TYPES[0x03] 'module_info' &gt;&gt;&gt; RESPONSE_TYPES.inverse['network_status_response'] 0x09 </code></pre>
0
2015-12-04T05:08:12Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,645
<p>The random module defines choice(), which does what you want:</p> <pre><code>import random words = [line.strip() for line in open('/etc/dictionaries-common/words')] print(random.choice(words)) </code></pre> <p>Note also that this assumes that each word is by itself on a line in the file. If the file is very big, or if you perform this operation frequently, you may find that constantly rereading the file impacts your application's performance negatively.</p>
17
2009-09-21T20:24:48Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,646
<p>This article may help</p> <p><a href="http://www.bryceboe.com/2009/03/23/random-lines-from-a-file/" rel="nofollow">http://www.bryceboe.com/2009/03/23/random-lines-from-a-file/</a></p>
2
2009-09-21T20:25:12Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,650
<p>You could do this without using <code>fileinput</code>:</p> <pre><code>import random data = open("/etc/dictionaries-common/words").readlines() print random.choice(data) </code></pre> <p>I have also used <code>data</code> instead of <code>file</code> because <code>file</code> is a predefined type in Python.</p>
1
2009-09-21T20:25:45Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,654
<p>Efficiency and verbosity aren't the same thing in this case. It's tempting to go for the most beautiful, pythonic approach that does everything in one or two lines but for file I/O, stick with classic fopen-style, low-level interaction, even if it does take up a few more lines of code.</p> <p>I could copy and paste some code and claim it to be my own (others can if they want) but have a look at this: <a href="http://mail.python.org/pipermail/tutor/2007-July/055635.html" rel="nofollow">http://mail.python.org/pipermail/tutor/2007-July/055635.html</a></p>
0
2009-09-21T20:26:12Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,723
<p>There are a few different ways to optimize this problem. You can optimize for speed, or for space.</p> <p>If you want a quick but memory-hungry solution, read in the entire file using file.readlines() and then use random.choice()</p> <p>If you want a memory-efficient solution, first check the number of lines in the file by calling somefile.readline() repeatedly until it returns "", then generate a random number smaller then the number of lines (say, n), seek back to the beginning of the file, and finally call somefile.readline() n times. The next call to somefile.readline() will return the desired random line. This approach wastes no memory holding "unnecessary" lines. Of course, if you plan on getting lots of random lines from the file, this will be horribly inefficient, and it's better to just keep the entire file in memory, like in the first approach.</p>
0
2009-09-21T20:40:10Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,750
<p>Pythonizing my answer from <a href="http://stackoverflow.com/questions/232237/whats-the-best-way-to-return-a-random-line-in-a-text-file-using-c">What’s the best way to return a random line in a text file using C?</a> :</p> <pre><code>import random def select_random_line(filename): selection = None count = 0 for line in file(filename, "r"): if random.randint(0, count) == 0: selection = line.strip() count = count + 1 return selection print select_random_line("/etc/dictionaries-common/words") </code></pre> <p>Edit: the original version of my answer used <code>readlines</code>, which didn't work as I thought and was totally unnecessary. This version will iterate through the file instead of reading it all into memory, and do it in a single pass, which should make it much more efficient than any answer I've seen thus far.</p> <h3>Generalized version</h3> <pre><code>import random def choose_from(iterable): """Choose a random element from a finite `iterable`. If `iterable` is a sequence then use `random.choice()` for efficiency. Return tuple (random element, total number of elements) """ selection, i = None, None for i, item in enumerate(iterable): if random.randint(0, i) == 0: selection = item return selection, (i+1 if i is not None else 0) </code></pre> <h3>Examples</h3> <pre><code>print choose_from(open("/etc/dictionaries-common/words")) print choose_from(dict(a=1, b=2)) print choose_from(i for i in range(10) if i % 3 == 0) print choose_from(i for i in range(10) if i % 11 == 0 and i) # empty print choose_from([0]) # one element chunk, n = choose_from(urllib2.urlopen("http://google.com")) print (chunk[:20], n) </code></pre> <h3>Output</h3> <pre> ('yeps\n', 98569) ('a', 2) (6, 4) (None, 0) (0, 1) ('window._gjp && _gjp(', 10) </pre>
3
2009-09-21T20:45:21Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,456,761
<p>Another solution is to use <a href="http://docs.python.org/library/linecache.html#linecache.getline">getline</a></p> <pre><code>import linecache import random line_number = random.randint(0, total_num_lines) linecache.getline('/etc/dictionaries-common/words', line_number) </code></pre> <p>From the documentation:</p> <blockquote> <p>The linecache module allows one to get any line from any file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file</p> </blockquote> <p>EDIT: You can calculate the total number once and store it, since the dictionary file is unlikely to change.</p>
9
2009-09-21T20:47:46Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,457,124
<pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.choice(list(open('/etc/dictionaries-common/words'))) 'jaundiced\n' </code></pre> <p>It is efficient human-time-wise. </p> <p>btw, your implementation coincides with the one from stdlib's <a href="http://svn.python.org/view/python/trunk/Lib/random.py?view=markup"><code>random.py</code></a>:</p> <pre><code> def choice(self, seq): """Choose a random element from a non-empty sequence.""" return seq[int(self.random() * len(seq))] </code></pre> <h3>Measure time performance</h3> <p>I was wondering what is the relative performance of the presented solutions. <code>linecache</code>-based is the obvious favorite. How much slower is the <code>random.choice</code>'s one-liner compared to honest algorithm implemented in <code>select_random_line()</code>?</p> <pre><code># nadia_known_num_lines 9.6e-06 seconds 1.00 # nadia 0.056 seconds 5843.51 # jfs 0.062 seconds 1.10 # dcrosta_no_strip 0.091 seconds 1.48 # dcrosta 0.13 seconds 1.41 # mark_ransom_no_strip 0.66 seconds 5.10 # mark_ransom_choose_from 0.67 seconds 1.02 # mark_ransom 0.69 seconds 1.04 </code></pre> <p>(Each function is called 10 times (cached performance)).</p> <p>These result show that simple solution (<code>dcrosta</code>) is faster in this case than a more deliberate one (<code>mark_ransom</code>).</p> <h3>Code that was used for comparison (<a href="http://gist.github.com/192338">as a gist</a>):</h3> <pre><code>import linecache import random from timeit import default_timer WORDS_FILENAME = "/etc/dictionaries-common/words" def measure(func): measure.func_to_measure.append(func) return func measure.func_to_measure = [] @measure def dcrosta(): words = [line.strip() for line in open(WORDS_FILENAME)] return random.choice(words) @measure def dcrosta_no_strip(): words = [line for line in open(WORDS_FILENAME)] return random.choice(words) def select_random_line(filename): selection = None count = 0 for line in file(filename, "r"): if random.randint(0, count) == 0: selection = line.strip() count = count + 1 return selection @measure def mark_ransom(): return select_random_line(WORDS_FILENAME) def select_random_line_no_strip(filename): selection = None count = 0 for line in file(filename, "r"): if random.randint(0, count) == 0: selection = line count = count + 1 return selection @measure def mark_ransom_no_strip(): return select_random_line_no_strip(WORDS_FILENAME) def choose_from(iterable): """Choose a random element from a finite `iterable`. If `iterable` is a sequence then use `random.choice()` for efficiency. Return tuple (random element, total number of elements) """ selection, i = None, None for i, item in enumerate(iterable): if random.randint(0, i) == 0: selection = item return selection, (i+1 if i is not None else 0) @measure def mark_ransom_choose_from(): return choose_from(open(WORDS_FILENAME)) @measure def nadia(): global total_num_lines total_num_lines = sum(1 for _ in open(WORDS_FILENAME)) line_number = random.randint(0, total_num_lines) return linecache.getline(WORDS_FILENAME, line_number) @measure def nadia_known_num_lines(): line_number = random.randint(0, total_num_lines) return linecache.getline(WORDS_FILENAME, line_number) @measure def jfs(): return random.choice(list(open(WORDS_FILENAME))) def timef(func, number=1000, timer=default_timer): """Return number of seconds it takes to execute `func()`.""" start = timer() for _ in range(number): func() return (timer() - start) / number def main(): # measure time times = dict((f.__name__, timef(f, number=10)) for f in measure.func_to_measure) # print from fastest to slowest maxname_len = max(map(len, times)) last = None for name in sorted(times, key=times.__getitem__): print "%s %4.2g seconds %.2f" % (name.ljust(maxname_len), times[name], last and times[name] / last or 1) last = times[name] if __name__ == "__main__": main() </code></pre>
9
2009-09-21T22:00:26Z
[ "python" ]
Return a random word from a word list in python
1,456,617
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
6
2009-09-21T20:19:28Z
1,457,149
<p>I don't have code for you but as far as an algorithm goes:</p> <ol> <li>Find the file's size</li> <li>Do a random seek with the seek() function</li> <li>Find the next (or previous) whitespace character</li> <li>Return the word that starts after that whitespace character</li> </ol>
1
2009-09-21T22:06:06Z
[ "python" ]
Convert SCCS repository to SVN
1,456,757
<p>I'm investigating migrating a source code repository currently kept under SCCS on an aging Digital UNIX box to Subversion on a Windows box. My initial searching has led me to a python script, <a href="http://sccs2svn.berlios.de/" rel="nofollow">sccs2svn</a>, which looks like it would do the job - with some restrictions. A <code>du -sk</code> on the SCCS directory shows it to be about 550MB in size.</p> <p>From what I can tell, the script runs on a local machine and operates on both SCCS and SVN locally: SCCS through executing SCCS commands directly; SVN through a python module, but also calls svnadmin to create a local directory.</p> <p>Unfortunately, I need to create the repo on a different server; from what I read in the SVN mailing lists etc, a SVN repo can't simply be copied between servers if the platform is different: an svnadmin dump and restore is required.</p> <p>The only way I think I can see this working is as a two-stage migration: firstly, to install SVN and python on the existing server, run the script there, then secondly dump the repo out and load it into the Windows SVN - which should work, just slightly more time consuming and requiring a little more disk.</p> <p>Is anyone aware of a way I could do this without doing it in two stages? Could the python script be modified to act upon a remote repository if the lines to create the repo are commented out? I'll be doing some reading into the Python SVN module, but Python isn't a scripting language I've played with before.</p>
1
2009-09-21T20:47:23Z
1,456,870
<p>If you use FSFS backend, you can just move the repository to your target platform. FSFS Repositories are truely platform indipendent. They are also standard setup since svn 1.3 so you should not have any problems by creating the repository and then copy it to your final server via any file transfer.</p>
3
2009-09-21T21:07:56Z
[ "python", "svn", "version-control" ]
Convert SCCS repository to SVN
1,456,757
<p>I'm investigating migrating a source code repository currently kept under SCCS on an aging Digital UNIX box to Subversion on a Windows box. My initial searching has led me to a python script, <a href="http://sccs2svn.berlios.de/" rel="nofollow">sccs2svn</a>, which looks like it would do the job - with some restrictions. A <code>du -sk</code> on the SCCS directory shows it to be about 550MB in size.</p> <p>From what I can tell, the script runs on a local machine and operates on both SCCS and SVN locally: SCCS through executing SCCS commands directly; SVN through a python module, but also calls svnadmin to create a local directory.</p> <p>Unfortunately, I need to create the repo on a different server; from what I read in the SVN mailing lists etc, a SVN repo can't simply be copied between servers if the platform is different: an svnadmin dump and restore is required.</p> <p>The only way I think I can see this working is as a two-stage migration: firstly, to install SVN and python on the existing server, run the script there, then secondly dump the repo out and load it into the Windows SVN - which should work, just slightly more time consuming and requiring a little more disk.</p> <p>Is anyone aware of a way I could do this without doing it in two stages? Could the python script be modified to act upon a remote repository if the lines to create the repo are commented out? I'll be doing some reading into the Python SVN module, but Python isn't a scripting language I've played with before.</p>
1
2009-09-21T20:47:23Z
8,649,403
<p>If sccs2svn really must work locally and you want to end up with the SVN repository on a Windows box, then use the Cygwin version of GNU CSSC to run sccs2svn on the Windows box itself. CSSC is an SCCS workalike: see <a href="http://www.gnu.org/software/cssc/" rel="nofollow">http://www.gnu.org/software/cssc/</a></p> <p>Another alternative if you have more flexibility is to use both CSSC and SVN on a GNU/Linux system.</p>
0
2011-12-27T21:19:26Z
[ "python", "svn", "version-control" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result </code></pre> <p>When I run it using <code>python count.py myFile.txt "int(line) == 0"</code>, I get the following error:</p> <pre><code> File "c:/pycode/count.py", line 10, in &lt;module&gt; eval('toAdd = 1 if ' + pred + ' else 0') File "&lt;string&gt;", line 1 toAdd = 1 if int(line) == 0 else 0 </code></pre> <p>This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.</p>
2
2009-09-21T20:47:37Z
1,456,802
<p>Try using exec instead of eval. The difference between the 2 is explained <a href="http://www.ibiblio.org/g2swap/byteofpython/read/exec-statement.html">here</a></p>
11
2009-09-21T20:55:24Z
[ "python", "eval", "syntax-error" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result </code></pre> <p>When I run it using <code>python count.py myFile.txt "int(line) == 0"</code>, I get the following error:</p> <pre><code> File "c:/pycode/count.py", line 10, in &lt;module&gt; eval('toAdd = 1 if ' + pred + ' else 0') File "&lt;string&gt;", line 1 toAdd = 1 if int(line) == 0 else 0 </code></pre> <p>This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.</p>
2
2009-09-21T20:47:37Z
1,456,809
<p>The python eval() function evaluates expressions, not statements. Try replacing the eval() line with:</p> <pre><code>result += eval(pred + " else 0") </code></pre>
2
2009-09-21T20:56:37Z
[ "python", "eval", "syntax-error" ]