title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Model and Validation Confusion - Looking for advice
606,782
<p>I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.</p> <p>I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.</p> <p>Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I <em>would</em> like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?</p> <p>I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?</p> <p>Anything to help my confusion would be appreciated.</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>Here's my model so far, for those who are asking, "nzb" is the XML file field.<br /> <a href="http://dpaste.com/hold/6101/" rel="nofollow">http://dpaste.com/hold/6101/</a></p> <blockquote> <p>The admin interface will use the Form you associate with your model; your own views can also use the form.</p> </blockquote> <p>This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?</p> <p>I've read over the link you gave me and it seams to be what I've done in the past, with no luck.</p> <blockquote> <p>Getting attributes from the file, should probably be a method.</p> </blockquote> <p>Sorry, could you please elaborate on this? A method where?</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>It seams I've been compleatly missing this step to link a form to the administration view. <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p> <p>This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?</p>
0
2009-03-03T15:15:16Z
607,034
<p>I guess the best way would be to implement a special field class that extends <code>FileField</code> with custom validation of the uploaded file. </p> <p>The validation is implemented in the field's <code>clean</code> method. It should check the XML file and raise <code>ValidationError</code>s if it encounters errors. The admin system should then treat your custom errors like any other field errors. </p> <p>The ImageField class is a good example of special validation like this — I recommend <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L475" rel="nofollow">just reading through the source</a>.</p>
1
2009-03-03T16:14:08Z
[ "python", "django", "validation" ]
Model and Validation Confusion - Looking for advice
606,782
<p>I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.</p> <p>I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.</p> <p>Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I <em>would</em> like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?</p> <p>I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?</p> <p>Anything to help my confusion would be appreciated.</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>Here's my model so far, for those who are asking, "nzb" is the XML file field.<br /> <a href="http://dpaste.com/hold/6101/" rel="nofollow">http://dpaste.com/hold/6101/</a></p> <blockquote> <p>The admin interface will use the Form you associate with your model; your own views can also use the form.</p> </blockquote> <p>This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?</p> <p>I've read over the link you gave me and it seams to be what I've done in the past, with no luck.</p> <blockquote> <p>Getting attributes from the file, should probably be a method.</p> </blockquote> <p>Sorry, could you please elaborate on this? A method where?</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>It seams I've been compleatly missing this step to link a form to the administration view. <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p> <p>This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?</p>
0
2009-03-03T15:15:16Z
607,586
<p>You can provide a form that will be used by the admin site. You can then perform validations in the form code that will be displayed in the admin area.</p> <p>See the docs on the admin site, and in particular <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form" rel="nofollow">the form attribute of ModelAdmin</a>.</p>
1
2009-03-03T18:34:30Z
[ "python", "django", "validation" ]
Model and Validation Confusion - Looking for advice
606,782
<p>I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.</p> <p>I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.</p> <p>Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I <em>would</em> like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?</p> <p>I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?</p> <p>Anything to help my confusion would be appreciated.</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>Here's my model so far, for those who are asking, "nzb" is the XML file field.<br /> <a href="http://dpaste.com/hold/6101/" rel="nofollow">http://dpaste.com/hold/6101/</a></p> <blockquote> <p>The admin interface will use the Form you associate with your model; your own views can also use the form.</p> </blockquote> <p>This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?</p> <p>I've read over the link you gave me and it seams to be what I've done in the past, with no luck.</p> <blockquote> <p>Getting attributes from the file, should probably be a method.</p> </blockquote> <p>Sorry, could you please elaborate on this? A method where?</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>It seams I've been compleatly missing this step to link a form to the administration view. <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p> <p>This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?</p>
0
2009-03-03T15:15:16Z
608,100
<p>"I'm throwing an custom "Exception" error " - Where exactly are you throwing the exception ? In your model or in your view ?</p> <p>I am confused with your question, so I am assuming that you should be asking 'Where should I catch input errors if any ? ' to yourself.</p> <p>The Model and View as I see are like pieces in a small assembly line. View/ Form validation is the first action which should be performed. If there is any issue with the input data through the forms. It should be prevented at the form level using form.is_valid() etc.</p> <p>The models functionality should be to provide meta information about the entity itself apart from performing CRUD. Ideally it should not be bothered about the data it is getting for the CRUD operations.</p>
0
2009-03-03T20:45:21Z
[ "python", "django", "validation" ]
Django Override form
606,946
<p>Another question on some forms</p> <p>Here is my model</p> <pre><code>class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() </code></pre> <p>Here is my modelform</p> <pre><code>class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts') </code></pre> <p>Here is my method to save it</p> <pre><code>def addJournal(request, id=0): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # # checking if they own the tank # from django.contrib.auth.models import User user = User.objects.get(pk=request.session['id']) if request.method == 'POST': form = JournalForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # # setting the user and ts # from time import time obj.ts = int(time()) obj.user = user obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank']) # # saving the test # obj.save() else: print form.errors else: form = JournalForm(initial={'tank': id}) </code></pre> <p>When it saves.. it complains the tank is not a TankProfile but a Integer.. how can I override the form object to make tank a TankProfile</p> <p>thanks</p>
2
2009-03-03T15:55:21Z
607,022
<p>Why are you overriding the definition of tank?</p> <pre><code>class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) </code></pre> <p>If you omit this override, Django handles the foreign key reference for you.</p> <p>"how can I override the form object to make tank a TankProfile?"</p> <p>I don't understand this question, since it looks like you specifically overrode the form to prevent the foreign key from working.</p>
2
2009-03-03T16:11:01Z
[ "python", "django", "forms" ]
Django Override form
606,946
<p>Another question on some forms</p> <p>Here is my model</p> <pre><code>class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() </code></pre> <p>Here is my modelform</p> <pre><code>class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts') </code></pre> <p>Here is my method to save it</p> <pre><code>def addJournal(request, id=0): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # # checking if they own the tank # from django.contrib.auth.models import User user = User.objects.get(pk=request.session['id']) if request.method == 'POST': form = JournalForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # # setting the user and ts # from time import time obj.ts = int(time()) obj.user = user obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank']) # # saving the test # obj.save() else: print form.errors else: form = JournalForm(initial={'tank': id}) </code></pre> <p>When it saves.. it complains the tank is not a TankProfile but a Integer.. how can I override the form object to make tank a TankProfile</p> <p>thanks</p>
2
2009-03-03T15:55:21Z
607,051
<p>I think you want this:</p> <pre><code>class JournalForm(ModelForm): tank = forms.ModelChoiceField(label="", queryset=TankProfile.objects.all(), widget=forms.HiddenInput) </code></pre>
5
2009-03-03T16:17:01Z
[ "python", "django", "forms" ]
How does Python's "super" do the right thing?
607,186
<p>I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's <a href="http://www.python.org/download/releases/2.3/mro/">MRO</a>; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:</p> <pre><code>#!/usr/bin/python class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() class C(A): def __init__(self): print "C init" super(C, self).__init__() class D(B, C): def __init__(self): print "D init" super(D, self).__init__() x = D() </code></pre> <p>The code does the intuitive thing, it prints:</p> <pre><code>D init B init C init A init </code></pre> <p>However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?</p> <p>Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling <code>dir(B)</code>. It has no <code>super</code> or <code>__super__</code> attributes.</p>
43
2009-03-03T16:45:37Z
607,287
<p>just guessing:</p> <p><code>self</code> in all the four methods refer to the same object, that is, of class <code>D</code>. so, in <code>B.__init__()</code>, the call to to <code>super(B,self)</code> knows the whole diamond ancestry of <code>self</code> and it has to fetch the method from 'after' <code>B</code>. in this case, it's the <code>C</code> class.</p>
6
2009-03-03T17:14:45Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
How does Python's "super" do the right thing?
607,186
<p>I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's <a href="http://www.python.org/download/releases/2.3/mro/">MRO</a>; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:</p> <pre><code>#!/usr/bin/python class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() class C(A): def __init__(self): print "C init" super(C, self).__init__() class D(B, C): def __init__(self): print "D init" super(D, self).__init__() x = D() </code></pre> <p>The code does the intuitive thing, it prints:</p> <pre><code>D init B init C init A init </code></pre> <p>However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?</p> <p>Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling <code>dir(B)</code>. It has no <code>super</code> or <code>__super__</code> attributes.</p>
43
2009-03-03T16:45:37Z
607,298
<p>Change your code to this and I think it'll explain things (presumably <code>super</code> is looking at where, say, <code>B</code> is in the <code>__mro__</code>?):</p> <pre><code>class A(object): def __init__(self): print "A init" print self.__class__.__mro__ class B(A): def __init__(self): print "B init" print self.__class__.__mro__ super(B, self).__init__() class C(A): def __init__(self): print "C init" print self.__class__.__mro__ super(C, self).__init__() class D(B, C): def __init__(self): print "D init" print self.__class__.__mro__ super(D, self).__init__() x = D() </code></pre> <p>If you run it you'll see:</p> <pre><code>D init (&lt;class '__main__.D'&gt;, &lt;class '__main__.B'&gt;, &lt;class '__main__.C'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) B init (&lt;class '__main__.D'&gt;, &lt;class '__main__.B'&gt;, &lt;class '__main__.C'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) C init (&lt;class '__main__.D'&gt;, &lt;class '__main__.B'&gt;, &lt;class '__main__.C'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) A init (&lt;class '__main__.D'&gt;, &lt;class '__main__.B'&gt;, &lt;class '__main__.C'&gt;, &lt;class '__main__.A'&gt;, &lt;type 'object'&gt;) </code></pre> <p>Also it's worth checking out <a href="http://fuhm.net/super-harmful/">Python's Super is nifty, but you can't use it</a>.</p>
33
2009-03-03T17:17:53Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
How does Python's "super" do the right thing?
607,186
<p>I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's <a href="http://www.python.org/download/releases/2.3/mro/">MRO</a>; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:</p> <pre><code>#!/usr/bin/python class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() class C(A): def __init__(self): print "C init" super(C, self).__init__() class D(B, C): def __init__(self): print "D init" super(D, self).__init__() x = D() </code></pre> <p>The code does the intuitive thing, it prints:</p> <pre><code>D init B init C init A init </code></pre> <p>However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?</p> <p>Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling <code>dir(B)</code>. It has no <code>super</code> or <code>__super__</code> attributes.</p>
43
2009-03-03T16:45:37Z
607,448
<p>I have provided a bunch of links below, that answer your question in more detail and more precisely than I can ever hope to. I will however give an answer to your question in my own words as well, to save you some time. I'll put it in points -</p> <ol> <li>super is a builtin function, not an attribute.</li> <li>Every <em>type</em> (class) in Python has an <code>__mro__</code> attribute, that stores the method resolution order of that particular instance.</li> <li>Each call to super is of the form super(type[, object-or-type]). Let us assume that the second attribute is an object for the moment.</li> <li>At the starting point of super calls, the object is of the type of the Derived class (<strong>say DC</strong>).</li> <li>super looks for methods that match (in your case <code>__init__</code>) in the classes in the MRO, after the class specified as the first argument (in this case classes after DC). </li> <li>When the matching method is found (say in class <strong>BC1</strong>), it is called.<br /> (This method should use super, so I am assuming it does - See Python's super is nifty but can't be used - link below) That method then causes a search in the object's class' MRO for the next method, to the right of <strong>BC1</strong>. </li> <li>Rinse wash repeat till all methods are found and called.</li> </ol> <p><strong>Explanation for your example</strong></p> <pre><code> MRO: D,B,C,A,object </code></pre> <ol> <li><code>super(D, self).__init__()</code> is called. isinstance(self, D) => True </li> <li><p>Search for <strong>next method</strong> in the MRO in classes to the right of D. </p> <p><code>B.__init__</code> found and called</p></li> <li><p><code>B.__init__</code> calls <code>super(B, self).__init__()</code>. </p> <p>isinstance(self, B) => False<br /> isinstance(self, D) => True</p></li> <li><p>Thus, the MRO is the same, but the search continues to the right of B i.e. C,A,object are searched one by one. The next <code>__init__</code> found is called.</p></li> <li><p>And so on and so forth.</p></li> </ol> <p><strong>An explanation of super</strong><br /> <a href="http://www.python.org/download/releases/2.2.3/descrintro/#cooperation">http://www.python.org/download/releases/2.2.3/descrintro/#cooperation</a><br /> <strong>Things to watch for when using super</strong><br /> <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a><br /> <strong>Pythons MRO Algorithm:</strong><br /> <a href="http://www.python.org/download/releases/2.3/mro/">http://www.python.org/download/releases/2.3/mro/</a><br /> <strong>super's docs:</strong><br /> <a href="http://docs.python.org/library/functions.html">http://docs.python.org/library/functions.html</a><br /> <strong>The bottom of this page has a nice section on super:</strong><br /> <a href="http://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-5-sect-2.html">http://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-5-sect-2.html</a> </p> <p>I hope this helps clear it up.</p>
14
2009-03-03T17:58:41Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
How does Python's "super" do the right thing?
607,186
<p>I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's <a href="http://www.python.org/download/releases/2.3/mro/">MRO</a>; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:</p> <pre><code>#!/usr/bin/python class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() class C(A): def __init__(self): print "C init" super(C, self).__init__() class D(B, C): def __init__(self): print "D init" super(D, self).__init__() x = D() </code></pre> <p>The code does the intuitive thing, it prints:</p> <pre><code>D init B init C init A init </code></pre> <p>However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?</p> <p>Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling <code>dir(B)</code>. It has no <code>super</code> or <code>__super__</code> attributes.</p>
43
2009-03-03T16:45:37Z
13,941,387
<p><code>super()</code> knows the <strong>full</strong> class hierarchy. This is what happens inside B's init:</p> <pre><code>&gt;&gt;&gt; super(B, self) &lt;super: &lt;class 'B'&gt;, &lt;D object&gt;&gt; </code></pre> <p>This resolves the central question,</p> <blockquote> <p>how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition?</p> </blockquote> <p>Namely, in B's init definition, <code>self</code> is an instance of <code>D</code>, and thus communicates the existence of <code>C</code>. For example <code>C</code> can be found in <code>type(self).__mro__</code>.</p>
3
2012-12-18T20:57:49Z
[ "python", "constructor", "multiple-inheritance", "super", "python-2.5" ]
Preserving last new line when reading a file
607,375
<p>I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:</p> <pre><code>def fread(): record = False for line in open('somefile.txt'): if line.startswith('Record'): record = True d = SomeObject() # do some processing with line d.process(line) if not line.strip() and record: yield d record = False for record in fread(): print(record) </code></pre> <p>In this data sample, everything works as expected ('---' is an empty line):</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n<br /> \n</p> </blockquote> <p>But in this, the last record isn´t returned:</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n </p> </blockquote> <p>How can I preserve the last new line from the file to get the last record?</p> <p>PS.: I´m using the term "preserve" as I couldn´t find a better name.</p> <p>Thanks.</p> <p><strong>Edit</strong> The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.</p> <p>A little more explanation: The object <code>SomeObject</code> is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).</p> <p>The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.</p>
2
2009-03-03T17:38:44Z
607,432
<p>line.strip() will result in an empty string on an empty line. An empty string is False, so you swallow the empty line</p> <pre><code>&gt;&gt;&gt; bool("\n".strip()) False &gt;&gt;&gt; bool("\n") True </code></pre>
0
2009-03-03T17:56:02Z
[ "python", "file" ]
Preserving last new line when reading a file
607,375
<p>I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:</p> <pre><code>def fread(): record = False for line in open('somefile.txt'): if line.startswith('Record'): record = True d = SomeObject() # do some processing with line d.process(line) if not line.strip() and record: yield d record = False for record in fread(): print(record) </code></pre> <p>In this data sample, everything works as expected ('---' is an empty line):</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n<br /> \n</p> </blockquote> <p>But in this, the last record isn´t returned:</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n </p> </blockquote> <p>How can I preserve the last new line from the file to get the last record?</p> <p>PS.: I´m using the term "preserve" as I couldn´t find a better name.</p> <p>Thanks.</p> <p><strong>Edit</strong> The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.</p> <p>A little more explanation: The object <code>SomeObject</code> is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).</p> <p>The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.</p>
2
2009-03-03T17:38:44Z
607,444
<p>If you call <code>readline</code> repeatedly (in a loop) on your file object (instead of using <code>in</code>) it should work as you expect. Compare these:</p> <pre><code>&gt;&gt;&gt; x = open('/tmp/xyz') &gt;&gt;&gt; x.readline() 'x\n' &gt;&gt;&gt; x.readline() '\n' &gt;&gt;&gt; x.readline() 'y\n' &gt;&gt;&gt; x.readline() '' &gt;&gt;&gt; open('/tmp/xyz').readlines() ['x\n', '\n', 'y\n'] </code></pre>
0
2009-03-03T17:58:16Z
[ "python", "file" ]
Preserving last new line when reading a file
607,375
<p>I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:</p> <pre><code>def fread(): record = False for line in open('somefile.txt'): if line.startswith('Record'): record = True d = SomeObject() # do some processing with line d.process(line) if not line.strip() and record: yield d record = False for record in fread(): print(record) </code></pre> <p>In this data sample, everything works as expected ('---' is an empty line):</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n<br /> \n</p> </blockquote> <p>But in this, the last record isn´t returned:</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n </p> </blockquote> <p>How can I preserve the last new line from the file to get the last record?</p> <p>PS.: I´m using the term "preserve" as I couldn´t find a better name.</p> <p>Thanks.</p> <p><strong>Edit</strong> The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.</p> <p>A little more explanation: The object <code>SomeObject</code> is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).</p> <p>The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.</p>
2
2009-03-03T17:38:44Z
607,508
<p>You might find a slight twist in a more classically pythonic direction improves the predicability of the code:</p> <pre><code>def fread(): for line in open('text.txt'): if line.strip(): d = SomeObject() yield d raise StopIteration for record in fread(): print record </code></pre> <p>The preferred way to end a generator in Python, though often not strictly necessary, is with the StopIteration exception. Using <code>if line.strip()</code> simply means that you'll do the yield if there's anything remaining in line after stripping whitespace. The construction of SomeObject() can be anywhere... I just happened to move it in case construction of SomeObject was expensive, or had side-effects that shouldn't happen if the line is empty.</p> <p>EDIT: I'll leave my answer here for posterity's sake, but DNS below got the original intent right, where several lines contribute to the same SomeObject() record (which I totally glossed over).</p>
5
2009-03-03T18:14:17Z
[ "python", "file" ]
Preserving last new line when reading a file
607,375
<p>I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:</p> <pre><code>def fread(): record = False for line in open('somefile.txt'): if line.startswith('Record'): record = True d = SomeObject() # do some processing with line d.process(line) if not line.strip() and record: yield d record = False for record in fread(): print(record) </code></pre> <p>In this data sample, everything works as expected ('---' is an empty line):</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n<br /> \n</p> </blockquote> <p>But in this, the last record isn´t returned:</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n </p> </blockquote> <p>How can I preserve the last new line from the file to get the last record?</p> <p>PS.: I´m using the term "preserve" as I couldn´t find a better name.</p> <p>Thanks.</p> <p><strong>Edit</strong> The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.</p> <p>A little more explanation: The object <code>SomeObject</code> is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).</p> <p>The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.</p>
2
2009-03-03T17:38:44Z
607,515
<p>The way it's written now probably doesn't work anyway; with <code>d = SomeObject()</code> inside your loop, a new SomeObject is being created for every line. Yet, if I understand correctly, what you want is for all of the lines in between empty lines to contribute to that one object. You could do something like this instead:</p> <pre><code>def fread(): d = None for line in open('somefile.txt'): if d is None: d = SomeObject() if line.strip(): # do some processing else: yield d d = None if d: yield d </code></pre> <p>This isn't great code, but it does work; that last object that misses its empty line is yielded when the loop is done.</p>
6
2009-03-03T18:16:43Z
[ "python", "file" ]
Preserving last new line when reading a file
607,375
<p>I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:</p> <pre><code>def fread(): record = False for line in open('somefile.txt'): if line.startswith('Record'): record = True d = SomeObject() # do some processing with line d.process(line) if not line.strip() and record: yield d record = False for record in fread(): print(record) </code></pre> <p>In this data sample, everything works as expected ('---' is an empty line):</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n<br /> \n</p> </blockquote> <p>But in this, the last record isn´t returned:</p> <blockquote> <p>Record 1<br /> data a<br /> data b<br /> data c<br /> \n<br /> Record 2<br /> data a<br /> data b<br /> data c<br /> \n </p> </blockquote> <p>How can I preserve the last new line from the file to get the last record?</p> <p>PS.: I´m using the term "preserve" as I couldn´t find a better name.</p> <p>Thanks.</p> <p><strong>Edit</strong> The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.</p> <p>A little more explanation: The object <code>SomeObject</code> is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).</p> <p>The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.</p>
2
2009-03-03T17:38:44Z
607,565
<p>replace <code>open('somefile.txt'):</code> with <code>open('somefile.txt').read().split('\n'):</code> and your code will work. <br><br> But Jarret Hardie's answer is better.</p>
0
2009-03-03T18:28:41Z
[ "python", "file" ]
Integrate postfix mail into my (python)webapp
607,548
<p>I have a postfix server listening and receiving all emails received at mywebsite.com Now I want to show these postfix emails in a customized interface and that too for each user</p> <p>To be clear, all the users of mywebsite.com will be given mail addresses like someguy@mywebsite.com who receives email on my production machine but he sees them in his own console built into his dashboard at mywebsite.com. </p> <p>So to make the user see the mail he received, I need to create an email replica of the postfix mail so that mywebsite(which runs on django-python) will be reflecting them readily. How do I achieve this. To be precise this is my question, how do I convert a postfix mail to a python mail object(so that my system/website)understands it? </p> <p>Just to be clear I have written psuedo code to achieve what I want:</p> <pre><code>email_as_python_object = postfix_email_convertor(postfix_email) attachments_list = email_as_python_object.attachments body = email_as_python_object.body # be it html or whatever </code></pre> <p>And by the way I have tried default email module which comes with python but thats not handy for all the cases. And even I need to deal with mail attachments manually(which I hate). I just need a simple way to deal with cases like these(I was wondering how postfix understands a email received. ie.. how it automatically figures out different headers,attachments etc..). Please help me.</p>
4
2009-03-03T18:23:31Z
607,588
<p>I'm not sure that I understand the question.</p> <p>If you want your remote web application to be able to view users' mailbox, you could install a pop or imap server and use a mail client (you should be able to find one off the shelf) to read the emails. Alternatively, you could write something to interrogate the pop/imap server using the relevant libraries that come with Python itself.</p> <p>If you want to replicate the mail to another machine, you could use procmail and set up actions to do this. Postfix can be set up to invoke procmail in this wayy.</p>
0
2009-03-03T18:35:07Z
[ "python", "email", "message", "postfix-mta" ]
Integrate postfix mail into my (python)webapp
607,548
<p>I have a postfix server listening and receiving all emails received at mywebsite.com Now I want to show these postfix emails in a customized interface and that too for each user</p> <p>To be clear, all the users of mywebsite.com will be given mail addresses like someguy@mywebsite.com who receives email on my production machine but he sees them in his own console built into his dashboard at mywebsite.com. </p> <p>So to make the user see the mail he received, I need to create an email replica of the postfix mail so that mywebsite(which runs on django-python) will be reflecting them readily. How do I achieve this. To be precise this is my question, how do I convert a postfix mail to a python mail object(so that my system/website)understands it? </p> <p>Just to be clear I have written psuedo code to achieve what I want:</p> <pre><code>email_as_python_object = postfix_email_convertor(postfix_email) attachments_list = email_as_python_object.attachments body = email_as_python_object.body # be it html or whatever </code></pre> <p>And by the way I have tried default email module which comes with python but thats not handy for all the cases. And even I need to deal with mail attachments manually(which I hate). I just need a simple way to deal with cases like these(I was wondering how postfix understands a email received. ie.. how it automatically figures out different headers,attachments etc..). Please help me.</p>
4
2009-03-03T18:23:31Z
607,622
<p>You want to have postfix deliver to a local mailbox, and then use a webmail system for people to access that stored mail.</p> <p>Don't get hung up on postfix - it just a transfer agent - it takes messages from one place, and puts them somewhere else, it doesn't store messages. So postfix will take the messages over SMTP, and put them in local mail files.</p> <p>Then IMAP or some webmail system will display those messages to your users.</p> <p>If you want the mail integrated in your webapp, then you should probably run an IMAP server, and use python IMAP libraries to get the messages.</p>
9
2009-03-03T18:50:21Z
[ "python", "email", "message", "postfix-mta" ]
Integrate postfix mail into my (python)webapp
607,548
<p>I have a postfix server listening and receiving all emails received at mywebsite.com Now I want to show these postfix emails in a customized interface and that too for each user</p> <p>To be clear, all the users of mywebsite.com will be given mail addresses like someguy@mywebsite.com who receives email on my production machine but he sees them in his own console built into his dashboard at mywebsite.com. </p> <p>So to make the user see the mail he received, I need to create an email replica of the postfix mail so that mywebsite(which runs on django-python) will be reflecting them readily. How do I achieve this. To be precise this is my question, how do I convert a postfix mail to a python mail object(so that my system/website)understands it? </p> <p>Just to be clear I have written psuedo code to achieve what I want:</p> <pre><code>email_as_python_object = postfix_email_convertor(postfix_email) attachments_list = email_as_python_object.attachments body = email_as_python_object.body # be it html or whatever </code></pre> <p>And by the way I have tried default email module which comes with python but thats not handy for all the cases. And even I need to deal with mail attachments manually(which I hate). I just need a simple way to deal with cases like these(I was wondering how postfix understands a email received. ie.. how it automatically figures out different headers,attachments etc..). Please help me.</p>
4
2009-03-03T18:23:31Z
607,741
<p>First of all, Postfix mail routing rules can be very complex and your presumably preferred solution involves a lot of trickery in the wrong places. You do not want to accidentally show some user anothers mails, do you? Second, although Postfix can do almost anything, it shouldn't as it only is a MDA (mail delivery agent).</p> <p>Your solution is best solved by using a POP3 or IMAP server (Cyrus IMAPd, Courier, etc). IMAP servers can have "superuser accounts" who can read mails of all users. Your web application can then connect to the users mailbox and retreive the headers and bodys.</p> <p>If you only want to show the subject-line you can fetch those with a special IMAP command and very low overhead. The Python IMAP library has not the easiest to understand API though. I'll give it a shot (not checked!) with an example taken from the standard library:</p> <pre><code>import imaplib sess = imaplib.IMAP4() sess.login('superuser', 'password') # Honor the mailbox syntax of your server! sess.select('INBOX/Luke') # Or something similar. typ, data = sess.search(None, 'ALL') # All Messages. subjectlines = [] for num in data[0].split(): typ, msgdata = sess.fetch(num, '(RFC822.SIZE BODY[HEADER.FIELDS (SUBJECT)])') subject = msgdata[0][1].lstrip('Subject: ').strip() subjectlines.append(subject) </code></pre> <p>This logs into the IMAP server, selects the users mailbox, fetches all the message-ids then fetches (hopefully) only the subjectlines and appends the resulting data onto the <em>subjectlines</em> list.</p> <p>To fetch other parts of the mail vary the line with <em>sess.fetch</em>. For the specific syntax of <em>fetch</em> have a look at <a href="http://www.faqs.org/rfcs/rfc2060.html">RFC 2060</a> (Section 6.4.5).</p> <p><strong>Good luck!</strong></p>
7
2009-03-03T19:17:57Z
[ "python", "email", "message", "postfix-mta" ]
Python parsing
607,760
<p>I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing <code>)</code>] with the code below:</p> <blockquote> <pre><code>feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") for item in feed: print repr(item.title[0:-1]) </code></pre> </blockquote> <p>I include that because, as you can see, the item.title is a repr() data type, which I don't know much about.</p> <p>A particular <code>repr(item.title[0:-1])</code> <code>print</code>ed in the interactive window looks like this:</p> <blockquote> <pre><code>'randy travis (Billy Bobs 3/21' 'Michael Schenker Group (House of Blues Dallas 3/26' </code></pre> </blockquote> <p>The user selects a band and I hope to, after parsing each <code>item.title</code> into 3 variables (one each for band, venue, and date... or possibly an array or I don't know...) select only those related to the band selected. Then they are sent to Google for geocoding, but that's another story.</p> <p>I've seen some examples of <code>regex</code> and I'm reading about them, but it seems very complicated. Is it? I thought maybe someone here would have some insight as to exactly how to do this in an intelligent way. Should I use the <code>re</code> module? Does it matter that the output is currently is <code>repr()</code>s? Is there a better way? I was thinking I'd use a loop like (and this is my pseudoPython, just kind of notes I'm writing):</p> <pre> list = bandRaw,venue,date,latLong for item in feed: parse item.title for bandRaw, venue, date if bandRaw == str(band) send venue name + ", Dallas, TX" to google for geocoding return lat,long list = list + return character + bandRaw + "," + venue + "," + date + "," + lat + "," + long else </pre> <p>In the end, I need to have the chosen entries in a .csv (comma-delimited) file looking like this:</p> <blockquote> <pre><code>band,venue,date,lat,long randy travis,Billy Bobs,3/21,1234.5678,1234.5678 Michael Schenker Group,House of Blues Dallas,3/26,4321.8765,4321.8765 </code></pre> </blockquote> <p>I hope this isn't too much to ask. I'll be looking into it on my own, just thought I should post here to make sure it got answered. </p> <p>So, the question is, how do I best parse each <code>repr(item.title[0:-1])</code> in the <code>feed</code> into the 3 separate values that I can then concatenate into a .csv file?</p>
4
2009-03-03T19:25:17Z
607,803
<p>Don't let regex scare you off... it's well worth learning.</p> <p>Given the examples above, you might try putting the trailing parenthesis back in, and then using this pattern:</p> <pre><code>import re pat = re.compile('([\w\s]+)\(([\w\s]+)(\d+/\d+)\)') info = pat.match(s) print info.groups() ('Michael Schenker Group ', 'House of Blues Dallas ', '3/26') </code></pre> <p>To get at each group individual, just call them on the <code>info</code> object:</p> <pre><code>print info.group(1) # or info.groups()[0] print '"%s","%s","%s"' % (info.group(1), info.group(2), info.group(3)) "Michael Schenker Group","House of Blues Dallas","3/26" </code></pre> <p>The hard thing about regex in this case is making sure you know all the known possible characters in the title. If there are non-alpha chars in the 'Michael Schenker Group' part, you'll have to adjust the regex for that part to allow them.</p> <p>The pattern above breaks down as follows, which is parsed left to right:</p> <p><code>([\w\s]+)</code> : Match any word or space characters (the plus symbol indicates that there should be one or more such characters). The parentheses mean that the match will be captured as a group. This is the "Michael Schenker Group " part. If there can be numbers and dashes here, you'll want to modify the pieces between the square brackets, which are the possible characters for the set.</p> <p><code>\(</code> : A literal parenthesis. The backslash escapes the parenthesis, since otherwise it counts as a regex command. This is the "(" part of the string.</p> <p><code>([\w\s]+)</code> : Same as the one above, but this time matches the "House of Blues Dallas " part. In parentheses so they will be captured as the second group.</p> <p><code>(\d+/\d+)</code> : Matches the digits 3 and 26 with a slash in the middle. In parentheses so they will be captured as the third group.</p> <p><code>\)</code> : Closing parenthesis for the above.</p> <p>The python intro to regex is quite good, and you might want to spend an evening going over it <a href="http://docs.python.org/library/re.html#module-re" rel="nofollow">http://docs.python.org/library/re.html#module-re</a>. Also, check Dive Into Python, which has a friendly introduction: <a href="http://diveintopython3.ep.io/regular-expressions.html" rel="nofollow">http://diveintopython3.ep.io/regular-expressions.html</a>.</p> <p>EDIT: See zacherates below, who has some nice edits. Two heads are better than one!</p>
16
2009-03-03T19:35:41Z
[ "python", "regex", "parsing", "text-parsing" ]
Python parsing
607,760
<p>I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing <code>)</code>] with the code below:</p> <blockquote> <pre><code>feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") for item in feed: print repr(item.title[0:-1]) </code></pre> </blockquote> <p>I include that because, as you can see, the item.title is a repr() data type, which I don't know much about.</p> <p>A particular <code>repr(item.title[0:-1])</code> <code>print</code>ed in the interactive window looks like this:</p> <blockquote> <pre><code>'randy travis (Billy Bobs 3/21' 'Michael Schenker Group (House of Blues Dallas 3/26' </code></pre> </blockquote> <p>The user selects a band and I hope to, after parsing each <code>item.title</code> into 3 variables (one each for band, venue, and date... or possibly an array or I don't know...) select only those related to the band selected. Then they are sent to Google for geocoding, but that's another story.</p> <p>I've seen some examples of <code>regex</code> and I'm reading about them, but it seems very complicated. Is it? I thought maybe someone here would have some insight as to exactly how to do this in an intelligent way. Should I use the <code>re</code> module? Does it matter that the output is currently is <code>repr()</code>s? Is there a better way? I was thinking I'd use a loop like (and this is my pseudoPython, just kind of notes I'm writing):</p> <pre> list = bandRaw,venue,date,latLong for item in feed: parse item.title for bandRaw, venue, date if bandRaw == str(band) send venue name + ", Dallas, TX" to google for geocoding return lat,long list = list + return character + bandRaw + "," + venue + "," + date + "," + lat + "," + long else </pre> <p>In the end, I need to have the chosen entries in a .csv (comma-delimited) file looking like this:</p> <blockquote> <pre><code>band,venue,date,lat,long randy travis,Billy Bobs,3/21,1234.5678,1234.5678 Michael Schenker Group,House of Blues Dallas,3/26,4321.8765,4321.8765 </code></pre> </blockquote> <p>I hope this isn't too much to ask. I'll be looking into it on my own, just thought I should post here to make sure it got answered. </p> <p>So, the question is, how do I best parse each <code>repr(item.title[0:-1])</code> in the <code>feed</code> into the 3 separate values that I can then concatenate into a .csv file?</p>
4
2009-03-03T19:25:17Z
607,804
<p>Regular expressions are a great solution to this problem:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = 'Michael Schenker Group (House of Blues Dallas 3/26' &gt;&gt;&gt; re.match(r'(.*) \((.*) (\d+/\d+)', s).groups() ('Michael Schenker Group', 'House of Blues Dallas', '3/26') </code></pre> <p>As a side note, you might want to look at the <a href="http://feedparser.org/" rel="nofollow">Universal Feed Parser</a> for handling the RSS parsing as feeds have a bad habit of being malformed.</p> <p><strong>Edit</strong></p> <p>In regards to your comment... The strings occasionally being wrapped in "s rather than 's has to do with the fact that you're using repr. The repr of a string is usually delimited with 's, unless that string contains one or more 's, where instead it uses "s so that the 's don't have to be escaped:</p> <pre><code>&gt;&gt;&gt; "Hello there" 'Hello there' &gt;&gt;&gt; "it's not its" "it's not its" </code></pre> <p>Notice the different quote styles.</p>
7
2009-03-03T19:35:51Z
[ "python", "regex", "parsing", "text-parsing" ]
Python parsing
607,760
<p>I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing <code>)</code>] with the code below:</p> <blockquote> <pre><code>feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") for item in feed: print repr(item.title[0:-1]) </code></pre> </blockquote> <p>I include that because, as you can see, the item.title is a repr() data type, which I don't know much about.</p> <p>A particular <code>repr(item.title[0:-1])</code> <code>print</code>ed in the interactive window looks like this:</p> <blockquote> <pre><code>'randy travis (Billy Bobs 3/21' 'Michael Schenker Group (House of Blues Dallas 3/26' </code></pre> </blockquote> <p>The user selects a band and I hope to, after parsing each <code>item.title</code> into 3 variables (one each for band, venue, and date... or possibly an array or I don't know...) select only those related to the band selected. Then they are sent to Google for geocoding, but that's another story.</p> <p>I've seen some examples of <code>regex</code> and I'm reading about them, but it seems very complicated. Is it? I thought maybe someone here would have some insight as to exactly how to do this in an intelligent way. Should I use the <code>re</code> module? Does it matter that the output is currently is <code>repr()</code>s? Is there a better way? I was thinking I'd use a loop like (and this is my pseudoPython, just kind of notes I'm writing):</p> <pre> list = bandRaw,venue,date,latLong for item in feed: parse item.title for bandRaw, venue, date if bandRaw == str(band) send venue name + ", Dallas, TX" to google for geocoding return lat,long list = list + return character + bandRaw + "," + venue + "," + date + "," + lat + "," + long else </pre> <p>In the end, I need to have the chosen entries in a .csv (comma-delimited) file looking like this:</p> <blockquote> <pre><code>band,venue,date,lat,long randy travis,Billy Bobs,3/21,1234.5678,1234.5678 Michael Schenker Group,House of Blues Dallas,3/26,4321.8765,4321.8765 </code></pre> </blockquote> <p>I hope this isn't too much to ask. I'll be looking into it on my own, just thought I should post here to make sure it got answered. </p> <p>So, the question is, how do I best parse each <code>repr(item.title[0:-1])</code> in the <code>feed</code> into the 3 separate values that I can then concatenate into a .csv file?</p>
4
2009-03-03T19:25:17Z
607,997
<p>Regarding the <code>repr(item.title[0:-1])</code> part, not sure where you got that from but I'm pretty sure you can simply use <code>item.title</code>. All you're doing is removing the last char from the string and then calling <code>repr()</code> on it, which does nothing.</p> <p>Your code should look something like this:</p> <pre><code>import geocoders # from GeoPy us = geocoders.GeocoderDotUS() import feedparser # from www.feedparser.org feedurl = "http://www.tourfilter.com/dallas/rss/by_concert_date" feed = feedparser.parse(feedurl) lines = [] for entry in feed.entries: m = re.search(r'(.*) \((.*) (\d+/\d+)\)', entry.title) if m: bandRaw, venue, date = m.groups() if band == bandRaw: place, (lat, lng) = us.geocode(venue + ", Dallas, TX") lines.append(",".join([band, venue, date, lat, lng])) result = "\n".join(lines) </code></pre> <p><strong>EDIT</strong>: replaced <code>list</code> with <code>lines</code> as the var name. <code>list</code> is a builtin and should not be used as a variable name. Sorry.</p>
0
2009-03-03T20:22:36Z
[ "python", "regex", "parsing", "text-parsing" ]
Django email
607,819
<p>I am using the Gmail SMTP server to send out emails from users of my website.</p> <p>These are the default settings in my settings.py</p> <pre><code>EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'example@example.com' EMAIL_HOST_PASSWORD = 'pwd' EMAIL_PORT = 587 EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER </code></pre> <p>If I want a user to send an email, I am overriding these settings and sending the email using Django's email sending methods. When an exception occurs in the system, I receive an email from the example@example.com. Sometimes I receive an email from some logged in user. Which could also possibly mean that when a user receives an email sent from my website it has a sent address different from the actual user. </p> <p>What should be done to avoid this situation?</p>
11
2009-03-03T19:40:23Z
608,218
<p>Django only uses <strong>settings.DEFAULT_FROM_EMAIL</strong> when any of the mail sending functions pass <code>None</code> or empty string as the <em>sender address</em>. This can be verified in <code>django/core/mail.py</code>.</p> <p>When there is an unhandled exception Django calls the <code>mail_admins()</code> function in <code>django/core/mail.py</code> which always uses <strong>settings.SERVER_EMAIL</strong> and is <strong>only</strong> sent to addresses listed in <strong>settings.ADMINS</strong>. This can also be verified in <code>django/core/mail.py</code>.</p> <p>The only other place Django itself sends e-mails is if <strong>settings.SEND_BROKEN_LINK_EMAILS</strong> is True, then CommonMiddleware will send mail to all addresses listed in <strong>settings.MANAGERS</strong> and the e-mail sender is <strong>settings.SERVER_EMAIL</strong>.</p> <p>Therefore, the only time a regular user will receive e-mail from your site is when you call <code>send_mail()</code>. So, always pass a real address as the <code>from_mail</code> argument and you will avoid users receiving email from <strong>settings.SERVER_EMAIL</strong> or <strong>settings.DEFAULT_FROM_EMAIL</strong>.</p> <p>Side note: django-registration is at least one example of a Django pluggable that will send mail from <strong>settings.DEFAULT_FROM_EMAIL</strong> so in cases like this you need to make sure it is a proper e-mail address such as support@yoursite.com or webmaster@yoursite.com.</p>
21
2009-03-03T21:15:14Z
[ "python", "django", "email", "django-email" ]
What will I lose or gain from switching database APIs? (from pywin32 and pysqlite to QSql)
608,098
<p>I am writing a Python (2.5) GUI Application that does the following:</p> <ul> <li>Imports from Access to an Sqlite database </li> <li>Saves ui form settings to an Sqlite database</li> </ul> <p>Currently I am using pywin32 to read Access, and pysqlite2/dbapi2 to read/write Sqlite.</p> <p>However, certain Qt objects don't automatically cast to Python or Sqlite equivalents when updating the Sqlite database. For example, a QDate, QDateTime, QString and others raise an error. Currently I am maintaining conversion functions.</p> <p>I investigated using QSql, which appears to overcome the casting problem. In addition, it is able to connect to both Access and Sqlite. These two benefits would <em>appear</em> to allow me to refactor my code to use less modules and not maintain my own conversion functions.</p> <p><strong>What I am looking for is a list of important side-effects, performance gains/losses, functionality gains/losses that any of the SO community has experienced as a result from the switch to QSql.</strong></p> <p>One functionality loss I have experienced thus far is the inability to use Access functions using the QODBC driver (e.g., 'SELECT LCASE(fieldname) from tablename' fails, as does 'SELECT FORMAT(fieldname, "General Number") from tablename')</p>
1
2009-03-03T20:45:14Z
608,262
<p>When dealing with databases and PyQt UIs, I'll use something similar to model-view-controller model to help organize and simplify the code. </p> <p><strong>View module</strong></p> <ul> <li>uses/holds any QObjects that are necessary for the UI </li> <li>contain simple functions/methods for updating your QTGui Object, as well as extracting input from GUI objects</li> </ul> <p><strong>Controller module</strong></p> <ul> <li>will perform all DB interactions</li> <li>the more complex code lives here</li> </ul> <p>By using a MVC, you will not need to rely on the QT Library as much, and you will run into less problems linking QT with Python.</p> <p>So I guess <strong>my suggestion is to continue using pysqlite</strong> (since that's what you are used to), but refactor your design a little so the only thing dealing with the QT libraries is the UI. From the description of your GUI, it should be fairly straightforward.</p>
1
2009-03-03T21:22:54Z
[ "python", "qt", "sqlite", "pyqt4", "pywin32" ]
is there COMMIT analog in python for writing into a file?
608,316
<p>I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true?</p> <p>What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?</p>
5
2009-03-03T21:33:02Z
608,322
<p>You should be able to use <code>file.flush()</code> to do this.</p>
15
2009-03-03T21:34:57Z
[ "python", "file-io", "commit", "buffering" ]
is there COMMIT analog in python for writing into a file?
608,316
<p>I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true?</p> <p>What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?</p>
5
2009-03-03T21:33:02Z
608,373
<p>If you don't want to kill the current process to add <code>f.flush()</code> (it sounds like it's been running for days already?), you should be OK. If you see the file you are writing to getting bigger, you will not lose that data...</p> <p>From Python docs:</p> <blockquote> <p><strong>write(str)</strong> Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.</p> </blockquote> <p>It sounds like Python's buffering system will automatically flush file objects, but it is not guaranteed when that happens. </p>
3
2009-03-03T21:51:08Z
[ "python", "file-io", "commit", "buffering" ]
is there COMMIT analog in python for writing into a file?
608,316
<p>I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true?</p> <p>What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?</p>
5
2009-03-03T21:33:02Z
608,518
<p>To make sure that you're data is written to disk, use <code>file.flush()</code> followed by <code>os.fsync(file.fileno())</code>.</p>
1
2009-03-03T22:34:33Z
[ "python", "file-io", "commit", "buffering" ]
is there COMMIT analog in python for writing into a file?
608,316
<p>I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true?</p> <p>What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?</p>
5
2009-03-03T21:33:02Z
609,465
<p>As has already been stated use the .flush() method to force the write out of the buffer, but avoid using a lot of calls to flush as this can actually slow your writing down (if the application relies on fast writes) as you'll be forcing your filesystem to write changes that are smaller than it's buffer size which can bring you to your knees. :)</p>
2
2009-03-04T06:41:06Z
[ "python", "file-io", "commit", "buffering" ]
Python port binding
608,558
<p>I've recently been learning python and I just started playing with networking using python's <code>socket</code> library. Everything has been going well until recently when my script terminated without closing the connection. The next time I ran the script, I got:</p> <pre><code>File "./alert_server.py", line 9, in &lt;module&gt; s.bind((HOST, PORT)) File "&lt;string&gt;", line 1, in bind socket.error: (98, 'Address already in use') </code></pre> <p>So it seems that something is still binded to the port, even though the python script isn't running (and I've verified this using <code>$px aux</code>. What's weird is that after a minute or so, I can run the script again on the same port and it will be fine. Is there any way to prevent/unbind a port for when this happens in the future?</p>
5
2009-03-03T22:46:08Z
608,589
<p>What you want to do is just before the <code>bind</code>, do:</p> <pre><code>s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) </code></pre> <p>The reason you are seeing the behaviour you are is that the OS is reserving that particular port for some time after the last connection terminated. This is so that it can properly discard any stray further packets that might come in after the application has terminated.</p> <p>By setting the <code>SO_REUSEADDR</code> socket option, you are telling the OS that you know what you're doing and you still want to bind to the same port.</p>
13
2009-03-03T22:55:10Z
[ "python" ]
Monitoring user idle time
608,710
<p>Developing a mac app, how can I tell whether the user is currently at their computer or not? Or how long ago they last pressed a key or moved the mouse?</p>
3
2009-03-03T23:41:47Z
608,833
<p>You can use Quartz event taps and an NSTimer. Any time one of your event taps lights up, postpone the timer by setting its fire date. When the timer fires, the user is idle.</p> <p>I'm not sure whether Quartz event taps are exposed to Python, though. The drawing APIs are, but I'm not sure about event taps.</p>
0
2009-03-04T00:36:22Z
[ "python", "cocoa", "osx", "idle-processing" ]
Monitoring user idle time
608,710
<p>Developing a mac app, how can I tell whether the user is currently at their computer or not? Or how long ago they last pressed a key or moved the mouse?</p>
3
2009-03-03T23:41:47Z
608,955
<p>it turns out the answer was here</p> <p><a href="http://osdir.com/ml/python.pyobjc.devel/2006-09/msg00013.html" rel="nofollow">http://osdir.com/ml/python.pyobjc.devel/2006-09/msg00013.html</a></p>
1
2009-03-04T01:40:48Z
[ "python", "cocoa", "osx", "idle-processing" ]
django- run a script from admin
608,789
<p>I would like to write a script that is not activated by a certain URL, but by clicking on a link from the admin interface. How do I do this? Thanks!</p>
4
2009-03-04T00:17:13Z
608,823
<p>But a link has to go to a URL, so I think what you mean is you want to have a view function that is only visible in the admin interface, and that view function runs a script?</p> <p>If so, override <code>admin/base_site.html</code> template with something this simple:</p> <pre><code>{% extends "admin/base.html" %} {% block nav-global %} &lt;p&gt;&lt;a href="{% url your-named-url %}"&gt;Do Something&lt;/a&gt;&lt;/p&gt; {% endblock %} </code></pre> <p>This (should) put the link at the top of the admin interface.</p> <p>Add your url with named pattern to your urls.py</p> <p>Then just make a normal django view and at the top of the view check to make sure the user is superuser like this:</p> <pre><code>if not request.user.is_staff: return Http404 </code></pre> <p>That will prevent unauthorized people from accessing this view.</p> <p>Next, in your view after the above code, just run the script.</p> <p>Do that with Python's subprocess module, for example:</p> <pre><code>from subprocess import call retcode = call(["/full/path/myscript.py", "arg1"]) </code></pre>
10
2009-03-04T00:31:24Z
[ "python", "django" ]
Getting the name of the active window
608,809
<p>I want to write a python script on Windows that saves the title of the program that the user uses at a given time like the <a href="http://www.rescuetime.com">http://www.rescuetime.com</a> . I don't want to use rescuetime because of privacy consideration but instead write a script that does something similar myself to capture data about how much I use my computer.</p> <p>Is there some easy command that I can use to read that information?</p>
5
2009-03-04T00:24:57Z
608,814
<p><a href="http://www.daniweb.com/forums/thread134111.html">From daniweb</a></p> <pre><code> import win32gui w=win32gui w.GetWindowText (w.GetForegroundWindow()) </code></pre>
7
2009-03-04T00:27:40Z
[ "python", "windows" ]
python PIL install on shared hosting
608,854
<p>I'm going to deploy a django app on a shared hosting provider. I installed my own python in my home, it works fine. My promblem comes with the installation of PIL, i have no support for JPEG after the compile process.</p> <p>I know that the compiler dont find "libjpeg", so i tried to install it at my home, i download the tar.gz and compile it with </p> <pre><code>./configure -prefix=$HOME/lib make make install </code></pre> <p>after i put the path in my.bashrc file. </p> <p>After all i re-compile PIL and still no have the jpeg support.</p> <p>It is possible to have the libs installed in a shared hosted enviroment? How would I do this?</p>
2
2009-03-04T00:50:22Z
608,988
<p>Does the machine actually have libjpeg available on it?</p> <p>Look for /usr/lib/libjpeg.so, and /usr/include/jpeglib.h; they may possibly be in a different lib and include directory. If you can't find them you'll have to also download and compile libjpeg into your home (typically prefix ~/.local).</p> <p>Then you'll need to add the ‘lib’ path to the ‘library_dirs’ variable and the ‘include’ to ‘include_dirs’ in PIL's setup.py (eg. just under “# add standard directories”), to get it to notice the availability of libjpeg.</p>
2
2009-03-04T01:56:50Z
[ "python", "compilation", "python-imaging-library" ]
python PIL install on shared hosting
608,854
<p>I'm going to deploy a django app on a shared hosting provider. I installed my own python in my home, it works fine. My promblem comes with the installation of PIL, i have no support for JPEG after the compile process.</p> <p>I know that the compiler dont find "libjpeg", so i tried to install it at my home, i download the tar.gz and compile it with </p> <pre><code>./configure -prefix=$HOME/lib make make install </code></pre> <p>after i put the path in my.bashrc file. </p> <p>After all i re-compile PIL and still no have the jpeg support.</p> <p>It is possible to have the libs installed in a shared hosted enviroment? How would I do this?</p>
2
2009-03-04T00:50:22Z
614,073
<p>I'm not sure where your problem comes from,</p> <p>you can use PIL without compiling anything! just drop the folder in a place that's in PYTHONPATH, and you're all set. </p>
-1
2009-03-05T09:21:23Z
[ "python", "compilation", "python-imaging-library" ]
Excluding a top-level directory from a setuptools package
608,855
<p>I'm trying to put a Python project into a tarball using setuptools. The problem is that setuptools doesn't appear to like the way that the source tree was originally setup (not by me, I must add). Everything that I actually want to distribute is in the top-level directory, rather than in a subdirectory like the setuptools docs talk about.</p> <p>The tree has a directory, <code>tests</code>, that I don't want to have in the released package. However, using <code>exclude_package_data</code> doesn't seem to actually do any excluding, and I'd like to work out what I've done wrong.</p> <p>My <code>setup.py</code> looks like this, in relevant part:</p> <pre><code>setup( name="project", packages=[''], include_package_data=True, exclude_package_data={'': ['tests']}, test_suite='nose.collector', ) </code></pre>
7
2009-03-04T00:50:23Z
609,067
<p>Ug, setuptools makes this really tricky :(</p> <p>I don't know if this is what you want, but one project I work on uses a combination of two things:</p> <pre><code>from setuptools import setup, find_packages ... packages = find_packages(exclude=['tests']), data_files = os.walk(path_to_files), </code></pre>
3
2009-03-04T02:41:14Z
[ "python", "setuptools" ]
Excluding a top-level directory from a setuptools package
608,855
<p>I'm trying to put a Python project into a tarball using setuptools. The problem is that setuptools doesn't appear to like the way that the source tree was originally setup (not by me, I must add). Everything that I actually want to distribute is in the top-level directory, rather than in a subdirectory like the setuptools docs talk about.</p> <p>The tree has a directory, <code>tests</code>, that I don't want to have in the released package. However, using <code>exclude_package_data</code> doesn't seem to actually do any excluding, and I'd like to work out what I've done wrong.</p> <p>My <code>setup.py</code> looks like this, in relevant part:</p> <pre><code>setup( name="project", packages=[''], include_package_data=True, exclude_package_data={'': ['tests']}, test_suite='nose.collector', ) </code></pre>
7
2009-03-04T00:50:23Z
1,000,702
<p>For similar purpose, my collegue wrote setuptools-dummy package: <a href="http://github.com/ella/setuptools-dummy/tree/master" rel="nofollow">http://github.com/ella/setuptools-dummy/tree/master</a></p> <p>Take a look at setuptools_dummy, modify excludes to your needs and it should work. If not, open an issue ;)</p>
0
2009-06-16T10:33:39Z
[ "python", "setuptools" ]
Excluding a top-level directory from a setuptools package
608,855
<p>I'm trying to put a Python project into a tarball using setuptools. The problem is that setuptools doesn't appear to like the way that the source tree was originally setup (not by me, I must add). Everything that I actually want to distribute is in the top-level directory, rather than in a subdirectory like the setuptools docs talk about.</p> <p>The tree has a directory, <code>tests</code>, that I don't want to have in the released package. However, using <code>exclude_package_data</code> doesn't seem to actually do any excluding, and I'd like to work out what I've done wrong.</p> <p>My <code>setup.py</code> looks like this, in relevant part:</p> <pre><code>setup( name="project", packages=[''], include_package_data=True, exclude_package_data={'': ['tests']}, test_suite='nose.collector', ) </code></pre>
7
2009-03-04T00:50:23Z
9,769,754
<p>We use the following convention to exclude 'tests' from packages.</p> <pre><code>setup( name="project", packages=find_packages(exclude=("tests",)), include_package_data=True, test_suite='nose.collector', ) </code></pre> <p>We also use MANIFEST.in to better control what 'include_package_data=True' does.</p> <p>Regards, Martin.</p>
5
2012-03-19T11:59:20Z
[ "python", "setuptools" ]
Excluding a top-level directory from a setuptools package
608,855
<p>I'm trying to put a Python project into a tarball using setuptools. The problem is that setuptools doesn't appear to like the way that the source tree was originally setup (not by me, I must add). Everything that I actually want to distribute is in the top-level directory, rather than in a subdirectory like the setuptools docs talk about.</p> <p>The tree has a directory, <code>tests</code>, that I don't want to have in the released package. However, using <code>exclude_package_data</code> doesn't seem to actually do any excluding, and I'd like to work out what I've done wrong.</p> <p>My <code>setup.py</code> looks like this, in relevant part:</p> <pre><code>setup( name="project", packages=[''], include_package_data=True, exclude_package_data={'': ['tests']}, test_suite='nose.collector', ) </code></pre>
7
2009-03-04T00:50:23Z
28,267,311
<p>I have the following in my <code>setup.py</code>...</p> <pre><code>setup(name='pyfoo', version="1.0.2", description='Example for stack overflow', url='http://stackoverflow.com/', author='David Michael Pennington', author_email='mike /|at|\ pennington.net', license='GPL', platforms='any', keywords='Stack Overflow Example', entry_points = "", long_description=read('README.rst'), include_package_data=True, # Checks MANIFEST.in for explicit rules # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ packages=find_packages(), use_2to3=True, zip_safe=False, setup_requires=["setuptools_hg"], </code></pre> <p>I had a <code>doc/</code> directory that was getting massive due to the number of images I had in it; this meant that the size of my <code>sdist</code> was growing over 500kB. Originally I had this in my <code>MANIFEST.in</code>...</p> <pre><code>include LICENSE CHANGES README.rst requirements.txt recursive-exclude * __pycache__ recursive-exclude * *.pyc recursive-exclude * *.pyo recursive-exclude * *.orig </code></pre> <p>The only thing I had to do to exclude my doc directory was this line at the bottom of <code>MANIFEST.in</code>...</p> <pre><code>prune doc* </code></pre> <p>Using <code>prune doc*</code> suddenly removed all my <code>doc/</code> directory from the <code>sdist</code> tarball. So, it looks like you just need to use this in a <code>MANIFEST.in</code> file...</p> <pre><code>prune tests* </code></pre>
0
2015-02-01T20:11:07Z
[ "python", "setuptools" ]
Excluding a top-level directory from a setuptools package
608,855
<p>I'm trying to put a Python project into a tarball using setuptools. The problem is that setuptools doesn't appear to like the way that the source tree was originally setup (not by me, I must add). Everything that I actually want to distribute is in the top-level directory, rather than in a subdirectory like the setuptools docs talk about.</p> <p>The tree has a directory, <code>tests</code>, that I don't want to have in the released package. However, using <code>exclude_package_data</code> doesn't seem to actually do any excluding, and I'd like to work out what I've done wrong.</p> <p>My <code>setup.py</code> looks like this, in relevant part:</p> <pre><code>setup( name="project", packages=[''], include_package_data=True, exclude_package_data={'': ['tests']}, test_suite='nose.collector', ) </code></pre>
7
2009-03-04T00:50:23Z
32,726,439
<p>This is what I found in <a href="https://pythonhosted.org/setuptools/setuptools.html#using-find-packages" rel="nofollow">setuptools manual</a>:</p> <pre><code>from setuptools import setup, find_packages ... packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), </code></pre> <p>In my case the following was enough to exclude top-level tests directory:</p> <pre><code>packages = find_packages(exclude=["tests.*", "tests"]), </code></pre>
1
2015-09-22T20:38:46Z
[ "python", "setuptools" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
608,965
<p>I know it's not exactly what you were looking for, but a more elegant way to express your example in ruby is:</p> <pre><code>result = Array.new(100) {|x| x*x} </code></pre>
1
2009-03-04T01:46:43Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
608,966
<pre><code>def squares(x) (0..x).map { |i| i * i } end </code></pre> <p>Anything involving a range of values is best handled with, well, a range, rather than <code>times</code> and array generation.</p>
1
2009-03-04T01:47:00Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
609,059
<p>So, for your new example, try this:</p> <pre><code>def foo(x) (0..x).select { |i| bar(i) } end </code></pre> <p>Basically, unless you're writing an iterator of your own, you don't need <code>yield</code> very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax.</p>
10
2009-03-04T02:34:45Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
609,077
<p>For the Python version I would use a generator expression like:</p> <pre><code>(i for i in range(x) if bar(i)) </code></pre> <p>Or for this specific case of filtering values, even more simply</p> <pre><code>itertools.ifilter(bar,range(x)) </code></pre>
7
2009-03-04T02:53:40Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
610,782
<p>For the Python list comprehension version posted by stbuton use <a href="http://docs.python.org/library/functions.html#xrange" rel="nofollow">xrange</a> instead of range if you want a generator. range will create the entire list in memory.</p>
1
2009-03-04T14:21:07Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
610,840
<p><code>yield</code> means different things ruby and python. In ruby, you have to specify a callback block if I remember correctly, whereas generators in python can be passed around and yield to whoever holds them.</p>
1
2009-03-04T14:34:17Z
[ "python", "ruby", "list", "yield" ]
Creating lists using yield in Ruby and Python
608,951
<p>I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.</p> <p>In Python:</p> <pre><code>def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) </code></pre> <p>In Ruby:</p> <pre><code>def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result &lt;&lt; x} </code></pre> <p>Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's <code>yield</code> results in simple iteration, which is great. Ruby's <code>yield</code> invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.</p> <p>Is there a more elegant Ruby way?</p> <p><strong>UPDATE</strong> Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.</p>
3
2009-03-04T01:39:33Z
3,781,210
<p>The exact equivalent of your Python code (using Ruby Generators) would be:</p> <pre><code>def foo(x) Enumerator.new do |yielder| (0..x).each { |v| yielder.yield(v) if bar(v) } end end result = Array(foo(100)) </code></pre> <p>In the above, the list is lazily generated (just as in the Python example); see:</p> <pre><code>def bar(v); v % 2 == 0; end f = foo(100) f.next #=&gt; 0 f.next #=&gt; 2 </code></pre>
5
2010-09-23T17:58:46Z
[ "python", "ruby", "list", "yield" ]
Is there anything that cannot appear inside parentheses?
609,169
<p>I was intrigued by <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim/543881#543881">this answer</a> to my question about <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim">getting vim to highlight unmatched brackets</a> in python code. Specifically, I'm talking about the second part of his answer where he mentions that the C syntax highlighting is actually flagging as an error any instance of curly braces inside parens. It is an unobtrusive cue that you have unclosed parens when all of your downstream curly braces light up in red.</p> <p>That trick works because C syntax doesn't allow curly braces inside parentheses. To satisfy my (morbid?) curiosity, can I do something similar with python code? Is there anything in python syntax that isn't legal inside parentheses?</p> <p>Note: I'm not trolling for a better answer to my other question (there are plenty of good answers there already). I'm merely curious if this trick is even possible with python code.</p>
1
2009-03-04T03:58:35Z
609,176
<p>I'm not sure what are you trying to do, but how about "def" or "class"?</p> <p>this snippet is valid when it's not inside parenthesis</p> <pre><code>class dummy: pass </code></pre>
0
2009-03-04T04:03:26Z
[ "python", "vim", "syntax", "syntax-highlighting" ]
Is there anything that cannot appear inside parentheses?
609,169
<p>I was intrigued by <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim/543881#543881">this answer</a> to my question about <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim">getting vim to highlight unmatched brackets</a> in python code. Specifically, I'm talking about the second part of his answer where he mentions that the C syntax highlighting is actually flagging as an error any instance of curly braces inside parens. It is an unobtrusive cue that you have unclosed parens when all of your downstream curly braces light up in red.</p> <p>That trick works because C syntax doesn't allow curly braces inside parentheses. To satisfy my (morbid?) curiosity, can I do something similar with python code? Is there anything in python syntax that isn't legal inside parentheses?</p> <p>Note: I'm not trolling for a better answer to my other question (there are plenty of good answers there already). I'm merely curious if this trick is even possible with python code.</p>
1
2009-03-04T03:58:35Z
609,675
<p>Any Python statement (import, if, for, while, def, class etc.) cannot be in the parentheses:</p> <pre><code>In [1]: (import sys) ------------------------------------------------------------ File "&lt;ipython console&gt;", line 1 (import sys) ^ &lt;type 'exceptions.SyntaxError'&gt;: invalid syntax </code></pre>
5
2009-03-04T08:17:45Z
[ "python", "vim", "syntax", "syntax-highlighting" ]
Is there anything that cannot appear inside parentheses?
609,169
<p>I was intrigued by <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim/543881#543881">this answer</a> to my question about <a href="http://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim">getting vim to highlight unmatched brackets</a> in python code. Specifically, I'm talking about the second part of his answer where he mentions that the C syntax highlighting is actually flagging as an error any instance of curly braces inside parens. It is an unobtrusive cue that you have unclosed parens when all of your downstream curly braces light up in red.</p> <p>That trick works because C syntax doesn't allow curly braces inside parentheses. To satisfy my (morbid?) curiosity, can I do something similar with python code? Is there anything in python syntax that isn't legal inside parentheses?</p> <p>Note: I'm not trolling for a better answer to my other question (there are plenty of good answers there already). I'm merely curious if this trick is even possible with python code.</p>
1
2009-03-04T03:58:35Z
609,731
<p>Here's an exact answer:</p> <ul> <li><a href="http://docs.python.org/reference/expressions.html#grammar-token-expression%5Flist" rel="nofollow">http://docs.python.org/reference/expressions.html#grammar-token-expression_list</a></li> <li><a href="http://docs.python.org/reference/compound%5Fstmts.html#function" rel="nofollow">http://docs.python.org/reference/compound_stmts.html#function</a></li> </ul>
4
2009-03-04T08:42:09Z
[ "python", "vim", "syntax", "syntax-highlighting" ]
How can I stop IDLE from printing giant lists?
609,190
<p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.</p>
1
2009-03-04T04:10:12Z
609,670
<p>Use <a href="http://ipython.scipy.org/moin/FrontPage" rel="nofollow">IPython</a> as shell instead. </p>
0
2009-03-04T08:14:28Z
[ "python", "ide", "editor", "python-idle" ]
How can I stop IDLE from printing giant lists?
609,190
<p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.</p>
1
2009-03-04T04:10:12Z
612,104
<p>You could use custom print function.</p>
0
2009-03-04T19:37:20Z
[ "python", "ide", "editor", "python-idle" ]
How can I stop IDLE from printing giant lists?
609,190
<p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.</p>
1
2009-03-04T04:10:12Z
636,913
<p>As above, try a custom print function like:</p> <pre><code>def my_print(obj): if hasattr(obj, '__len__') and len(obj) &gt; 100: print '... omitted object of %s with length %d ...' % (type(obj), len(obj)) else: print obj </code></pre>
2
2009-03-12T00:21:44Z
[ "python", "ide", "editor", "python-idle" ]
How can I stop IDLE from printing giant lists?
609,190
<p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.</p>
1
2009-03-04T04:10:12Z
991,877
<p>In Python 3, since print is a function, you should be able to "override" it. (I don't have it installed so I can't try it out to make sure.) Probably not recommended for real applications but if you're just trying things out, it would be okay I suppose.</p> <p>It would go something like:</p> <pre><code>def myprint(*args): # write the function as described by other people print = myprint </code></pre>
0
2009-06-14T00:56:35Z
[ "python", "ide", "editor", "python-idle" ]
How can I stop IDLE from printing giant lists?
609,190
<p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.</p>
1
2009-03-04T04:10:12Z
8,237,338
<p>The <a href="http://pypi.python.org/pypi/Squeezer/1.0" rel="nofollow">Squeezer</a> extension for IDLE was written to do just this. From the description on Pypi:</p> <blockquote> <p>IDLE can hang if very long output is printed. To avoid this, the Squeezer extensions catches any output longer than 80 lines of text (configurable) and displays a rectangular box instead:</p> </blockquote> <p>Squeezer, and many other IDLE extensions are included in <a href="http://idlex.sourceforge.net" rel="nofollow">IdleX</a>.</p>
0
2011-11-23T04:27:36Z
[ "python", "ide", "editor", "python-idle" ]
PY: Url Encode without variable name
609,212
<p>Is there a way in python to url encode list without variables names? for example <BR> q=['with space1', 'with space2'] <BR> into qescaped=['with%20space1', 'with%20space2']</p>
3
2009-03-04T04:23:36Z
609,228
<p>You can use <a href="http://docs.python.org/library/urllib.html#urllib.quote" rel="nofollow">urllib.quote</a> together with <a href="http://docs.python.org/library/functions.html#map" rel="nofollow">map</a>:</p> <pre><code>import urllib q = ['with space1', 'with space2'] qescaped = map(urllib.quote, q) </code></pre>
7
2009-03-04T04:31:00Z
[ "python" ]
PY: Url Encode without variable name
609,212
<p>Is there a way in python to url encode list without variables names? for example <BR> q=['with space1', 'with space2'] <BR> into qescaped=['with%20space1', 'with%20space2']</p>
3
2009-03-04T04:23:36Z
13,743,452
<p>Nowadays list comprehensions are the Pythonic way to do this:</p> <pre><code>q = [ 'with space1', 'with space2' ] qescaped = [ urllib.quote(u) for u in q ] </code></pre> <p>Often you do not even have to build that list but can use the generator itself instead:</p> <pre><code>qescapedGenerator = (urllib.quote(u) for u in q) </code></pre> <p>(This saves memory and, in case you do not need all elements, also computation time.)</p> <p>A lot of receivers can process on generators as well:</p> <pre><code>urlsInLines = '\n'.join(urllib.quote(u) for u in q) </code></pre> <p> </p> <pre><code>for escapedUrl in (urllib.quote(u) for u in q): print escapedUrl </code></pre> <p>And if any receive needs a list after all, just putting <code>list()</code> around the generator creates the list anyway.</p>
0
2012-12-06T12:15:43Z
[ "python" ]
pysqlite user types in select statement
609,516
<p>Using pysqlite how can a user-defined-type be used as a value in a comparison, e. g: “... WHERE columnName > userType”?</p> <p>For example, I've defined a bool type with the requisite registration, converter, etc. Pysqlite/Sqlite responds as expected for INSERT and SELECT operations (bool 'True' stored as an integer 1 and returned as True).</p> <p>But it fails when the bool is used in either “SELECT * from tasks WHERE display = True” or “... WHERE display = 'True.' “ In the first case Sqlite reports an error that there is not a column named True. And in the second case no records are returned. The select works if a 1 is used in place of True. I seem to have the same problem when using pysqlite's own date and timestamp adaptors.</p> <p>I can work around this behavior for this and other user-types but that's not as fun. I'd like to know if using a user-defined type in a query is or is not possible so that I don't keep banging my head on this particular wall.</p> <p>Thank you.</p>
0
2009-03-04T07:08:06Z
610,761
<p>You probably have to cast it to the correct type. Try "SELECT * FROM tasks WHERE (display = CAST ('True' AS bool))".</p>
0
2009-03-04T14:17:11Z
[ "python", "sqlite", "pysqlite" ]
pysqlite user types in select statement
609,516
<p>Using pysqlite how can a user-defined-type be used as a value in a comparison, e. g: “... WHERE columnName > userType”?</p> <p>For example, I've defined a bool type with the requisite registration, converter, etc. Pysqlite/Sqlite responds as expected for INSERT and SELECT operations (bool 'True' stored as an integer 1 and returned as True).</p> <p>But it fails when the bool is used in either “SELECT * from tasks WHERE display = True” or “... WHERE display = 'True.' “ In the first case Sqlite reports an error that there is not a column named True. And in the second case no records are returned. The select works if a 1 is used in place of True. I seem to have the same problem when using pysqlite's own date and timestamp adaptors.</p> <p>I can work around this behavior for this and other user-types but that's not as fun. I'd like to know if using a user-defined type in a query is or is not possible so that I don't keep banging my head on this particular wall.</p> <p>Thank you.</p>
0
2009-03-04T07:08:06Z
611,619
<p>Use the correct way of passing variables to queries: <strong>Don't build the query, use question marks and pass the parameters as a tuple to <code>execute()</code>.</strong></p> <pre><code>myvar = True cur.execute('SELECT * FROM tasks WHERE display = ?', (myvar,)) </code></pre> <p>That way the sqlite driver will use the value directly. No escapeing, quoting, conversion is needed anymore.</p> <p>Use this technique for every parameter, even string, integer, etc. That way you avoid SQL injection automatically.</p>
1
2009-03-04T17:27:33Z
[ "python", "sqlite", "pysqlite" ]
<class> has no foreign key to <class> in Django when trying to inline models
609,556
<p>I need to be able to create a quiz type application with 20 some odd multiple choice questions. </p> <p>I have 3 models: <code>Quizzes</code>, <code>Questions</code>, and <code>Answers</code>. </p> <p>I want in the admin interface to create a quiz, and inline the quiz and answer elements.</p> <p>The goal is to click "Add Quiz", and be transferred to a page with 20 question fields, with 4 answer fields per each in place. </p> <p>Here's what I have currently:</p> <pre><code>class Quiz(models.Model): label = models.CharField(blank=true, max_length=50) class Question(models.Model): label = models.CharField(blank=true, max_length=50) quiz = models.ForeignKey(Quiz) class Answer(models.Model): label = models.CharField(blank=true, max_length=50) question = models.ForeignKey(Question) class QuestionInline(admin.TabularInline): model = Question extra = 20 class QuestionAdmin(admin.ModelAdmin): inlines = [QuestionInline] class AnswerInline(admin.TabularInline): model = Answer extra = 4 class AnswerAdmin(admin.ModelAdmin): inlines = [AnswerInline] class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline, AnswerInline] admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) admin.site.register(Quiz, QuizAdmin) </code></pre> <p>I get the following error when I try to add a quiz:</p> <pre><code>class 'quizzer.quiz.models.Answer'&gt; has no ForeignKey to &lt;class 'quizzer.quiz.models.Quiz'&gt; </code></pre> <p>Is this doable, or am I trying to pull too much out of the Django Admin app? </p>
6
2009-03-04T07:22:27Z
609,591
<p>Correct: trying to pull too much out of admin app :) Inline models need a foreign key to the parent model.</p>
2
2009-03-04T07:41:15Z
[ "python", "django", "django-admin" ]
<class> has no foreign key to <class> in Django when trying to inline models
609,556
<p>I need to be able to create a quiz type application with 20 some odd multiple choice questions. </p> <p>I have 3 models: <code>Quizzes</code>, <code>Questions</code>, and <code>Answers</code>. </p> <p>I want in the admin interface to create a quiz, and inline the quiz and answer elements.</p> <p>The goal is to click "Add Quiz", and be transferred to a page with 20 question fields, with 4 answer fields per each in place. </p> <p>Here's what I have currently:</p> <pre><code>class Quiz(models.Model): label = models.CharField(blank=true, max_length=50) class Question(models.Model): label = models.CharField(blank=true, max_length=50) quiz = models.ForeignKey(Quiz) class Answer(models.Model): label = models.CharField(blank=true, max_length=50) question = models.ForeignKey(Question) class QuestionInline(admin.TabularInline): model = Question extra = 20 class QuestionAdmin(admin.ModelAdmin): inlines = [QuestionInline] class AnswerInline(admin.TabularInline): model = Answer extra = 4 class AnswerAdmin(admin.ModelAdmin): inlines = [AnswerInline] class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline, AnswerInline] admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) admin.site.register(Quiz, QuizAdmin) </code></pre> <p>I get the following error when I try to add a quiz:</p> <pre><code>class 'quizzer.quiz.models.Answer'&gt; has no ForeignKey to &lt;class 'quizzer.quiz.models.Quiz'&gt; </code></pre> <p>Is this doable, or am I trying to pull too much out of the Django Admin app? </p>
6
2009-03-04T07:22:27Z
610,083
<p>Let's follow through step by step.</p> <p>The error: "Answer has no FK to Quiz".</p> <p>That's correct. The Answer model has no FK to Quiz. It has an FK to Question, but not Quiz.</p> <p>Why does Answer need an FK to quiz? </p> <p>The QuizAdmin has an AnswerInline and a QuestionInline. For an admin to have inlines, it means the inlined models (Answer and Question) must have FK's to the parent admin.</p> <p>Let's check. Question has an FK to Quiz.</p> <p>And. Answer has no FK to Quiz. So your Quiz admin demands an FK that your model lacks. That's the error. </p>
3
2009-03-04T10:51:57Z
[ "python", "django", "django-admin" ]
<class> has no foreign key to <class> in Django when trying to inline models
609,556
<p>I need to be able to create a quiz type application with 20 some odd multiple choice questions. </p> <p>I have 3 models: <code>Quizzes</code>, <code>Questions</code>, and <code>Answers</code>. </p> <p>I want in the admin interface to create a quiz, and inline the quiz and answer elements.</p> <p>The goal is to click "Add Quiz", and be transferred to a page with 20 question fields, with 4 answer fields per each in place. </p> <p>Here's what I have currently:</p> <pre><code>class Quiz(models.Model): label = models.CharField(blank=true, max_length=50) class Question(models.Model): label = models.CharField(blank=true, max_length=50) quiz = models.ForeignKey(Quiz) class Answer(models.Model): label = models.CharField(blank=true, max_length=50) question = models.ForeignKey(Question) class QuestionInline(admin.TabularInline): model = Question extra = 20 class QuestionAdmin(admin.ModelAdmin): inlines = [QuestionInline] class AnswerInline(admin.TabularInline): model = Answer extra = 4 class AnswerAdmin(admin.ModelAdmin): inlines = [AnswerInline] class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline, AnswerInline] admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) admin.site.register(Quiz, QuizAdmin) </code></pre> <p>I get the following error when I try to add a quiz:</p> <pre><code>class 'quizzer.quiz.models.Answer'&gt; has no ForeignKey to &lt;class 'quizzer.quiz.models.Quiz'&gt; </code></pre> <p>Is this doable, or am I trying to pull too much out of the Django Admin app? </p>
6
2009-03-04T07:22:27Z
611,145
<p>You can't do <a href="http://code.djangoproject.com/ticket/9025">"nested" inlines</a> in the Django admin (i.e. you can't have a Quiz with inline Questions, with each inline Question having inline Answers). So you'll need to lower your sights to just having inline Questions (then if you navigate to view a single Question, it could have inline Answers).</p> <p>So your models are fine, but your admin code should look like this:</p> <pre><code>class QuestionInline(admin.TabularInline): model = Question extra = 20 class AnswerInline(admin.TabularInline): model = Answer extra = 4 class QuestionAdmin(admin.ModelAdmin): inlines = [AnswerInline] class AnswerAdmin(admin.ModelAdmin): pass class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline] </code></pre> <p>It doesn't make sense for AnswerAdmin to have an AnswerInline, or QuestionAdmin to have a QuestionInline (unless these were models with a self-referential foreign key). And QuizAdmin can't have an AnswerInline, because Answer has no foreign key to Quiz.</p> <p>If Django did support nested inlines, the logical syntax would be for QuestionInline to accept an "inlines" attribute, which you'd set to [AnswerInline]. But it doesn't.</p> <p>Also note that "extra = 20" means you'll have 20 blank Question forms at the bottom of every Quiz, every time you load it up (even if it already has 20 actual Questions). Maybe that's what you want - makes for a long page, but makes it easy to add lots of questions at once.</p>
14
2009-03-04T15:46:04Z
[ "python", "django", "django-admin" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
609,854
<p>Strings are immutable. They can't be changed. You must create a new string with the changed content. If you want to make every 'j' uppercase:</p> <pre><code>def make_uppercase_j(char): if char == 'j': return 'J' else: return char name = "markus johansson" ''.join(make_uppercase_j(c) for c in name) </code></pre>
5
2009-03-04T09:31:16Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
609,857
<p>I guess that what you're trying to achieve is:</p> <pre><code>from string import capwords capwords(name) </code></pre> <p>Which yields:</p> <pre><code>'Markus Johansson' </code></pre> <p>EDIT: OK, I see you want to tear down a open door. Here's low level implementation.</p> <pre><code>''.join([char.upper() if prev==' ' else char for char,prev in zip(name,' '+name)]) </code></pre>
8
2009-03-04T09:31:19Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
609,873
<p>If I understand your original algorithm correctly, this is what you want to do:</p> <pre><code>namn = list("markus johansson") if namn[0] == 'm': namn[0] = "M" count = 0 for i in range(1, len(namn)): if namn[i] == " ": count = i + 1 if count and namn[count] == 'j': namn[count] = 'J' print ''.join(namn) </code></pre> <p>Of course, there's a million better ways ("wannabe" ways) to do what you're trying to do, like as shown in vartec's answer. :)</p> <p>As it stands, your code only works for names that start with a J and an M for the first and last names, respectively.</p>
1
2009-03-04T09:37:03Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
610,095
<pre><code>&gt;&gt;&gt; "markus johansson".title() 'Markus Johansson' </code></pre> <p>Built in string methods are the way to go.</p> <p>EDIT: I see you want to re-invent the wheel. Any particular reason ? You can choose from any number of convoluted methods like:</p> <pre><code>' '.join(j[0].upper()+j[1:] for j in "markus johansson".split()) </code></pre> <p>Standard Libraries are still the way to go.</p>
9
2009-03-04T10:55:15Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
610,120
<p>"real programming"?</p> <p>I would use .title(), and I'm a real programmer.</p> <p>Or I would use regular expressions</p> <pre><code>re.sub(r"(^|\s)[a-z]", lambda m: m.group(0).upper(), "this is a set of words") </code></pre> <p>This says "If the start of the text or a whitespace character is followed by a lower-case letter" (in English - other languages are likely not supported), then for each match convert the match text to upper-case. Since the match text is the space and the lower-case letter, this works just fine.</p> <p>If you want it as low-level code then the following works. Here I only allow space as the separator (but you may want to support newline and other characters). On the other hand, "string.lowercase" is internationalized, so if you're in another locale then it will, for the most part, still work. If you don't want that then use string.ascii_lowercase.</p> <pre><code>import string def title(s): # Capitalize the first character if s[:1] in string.lowercase: s = s[0].upper() + s[1:] # Find spaces offset = 0 while 1: offset = s.find(" ", offset) # Reached the end of the string or the # last character is a space if offset == -1 or offset == len(s)-1: break if s[offset+1:offset+2] in string.lowercase: # Is it followed by a lower-case letter? s = s[:offset+1] + s[offset+1].upper() + s[offset+2:] # Skip the space and the letter offset += 2 else: # Nope, so start searching for the next space offset += 1 return s </code></pre> <p>To elaborate on my comment to this answer, this question can only be an exercise for curiosity's sake. Real names have special capitalization rules: the "van der" in "Johannes Diderik van der Waals" is never capitalized, "Farrah Fawcett-Majors" has the "M", and "Cathal Ó hEochaidh" uses the non-ASCII Ó and h, which modify "Eochaidh" to mean "grandson of Eochaidh".</p>
0
2009-03-04T11:07:10Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
610,204
<p>Plenty of good suggestions, so I'll be in good company adding my own 2 cents :-)</p> <p>I'm assuming you want something a little more generic that can handle more than just names starting with 'm' and 'j'. You'll probably also want to consider hyphenated names (like Markus Johnson-Smith) which have caps after the hyphen too.</p> <pre><code>from string import lowercase, uppercase name = 'markus johnson-smith' state = 0 title_name = [] for c in name: if c in lowercase and not state: c = uppercase[lowercase.index(c)] state = 1 elif c in [' ', '-']: state = 0 else: state = 1 # might already be uppercase title_name.append(c) print ''.join(title_name) </code></pre> <p>Last caveat is the potential for non-ascii characters. Using the <code>uppercase</code> and <code>lowercase</code> properties of the <code>string</code> module is good in this case becase their contents change depending on the user's locale (ie: system-dependent, or when locale.setlocale() is called). I know you want to avoid using <code>upper()</code> for this exercise, and that's quite neat... as an FYI, <code>upper()</code> uses the <code>locale</code> controlled by <code>setlocale()</code> too, so the practice of use <code>uppercase</code> and <code>lowercase</code> is a good use of the API without getting too high-level. That said, if you need to handle, say, French names on a system running an English locale, you'll need a more robust implementation.</p>
1
2009-03-04T11:42:23Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
610,281
<h3><code>string.capwords()</code> (defined in <a href="http://svn.python.org/view/python/trunk/Lib/string.py?view=markup" rel="nofollow"><code>string.py</code></a>)</h3> <pre><code># Capitalize the words in a string, e.g. " aBc dEf " -&gt; "Abc Def". def capwords(s, sep=None): """capwords(s, [sep]) -&gt; string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space. """ return (sep or ' ').join(x.capitalize() for x in s.split(sep)) </code></pre> <h3><code>str.title()</code> (defined in <a href="http://svn.python.org/view/python/trunk/Objects/stringobject.c?view=markup" rel="nofollow"><code>stringobject.c</code></a>)</h3> <pre><code>PyDoc_STRVAR(title__doc__, "S.title() -&gt; string\n\ \n\ Return a titlecased version of S, i.e. words start with uppercase\n\ characters, all remaining cased characters have lowercase."); static PyObject* string_title(PyStringObject *self) { char *s = PyString_AS_STRING(self), *s_new; Py_ssize_t i, n = PyString_GET_SIZE(self); int previous_is_cased = 0; PyObject *newobj = PyString_FromStringAndSize(NULL, n); if (newobj == NULL) return NULL; s_new = PyString_AsString(newobj); for (i = 0; i &lt; n; i++) { int c = Py_CHARMASK(*s++); if (islower(c)) { if (!previous_is_cased) c = toupper(c); previous_is_cased = 1; } else if (isupper(c)) { if (previous_is_cased) c = tolower(c); previous_is_cased = 1; } else previous_is_cased = 0; *s_new++ = c; } return newobj; } </code></pre> <h3><code>str.title()</code> in pure Python</h3> <pre><code>class String(str): def title(self): s = [] previous_is_cased = False for c in self: if c.islower(): if not previous_is_cased: c = c.upper() previous_is_cased = True elif c.isupper(): if previous_is_cased: c = c.lower() previous_is_cased = True else: previous_is_cased = False s.append(c) return ''.join(s) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; s = ' aBc dEf ' &gt;&gt;&gt; import string &gt;&gt;&gt; string.capwords(s) 'Abc Def' &gt;&gt;&gt; s.title() ' Abc Def ' &gt;&gt;&gt; s ' aBc dEf ' &gt;&gt;&gt; String(s).title() ' Abc Def ' &gt;&gt;&gt; String(s).title() == s.title() True </code></pre>
5
2009-03-04T12:08:36Z
[ "python" ]
Problems title-casing a string in Python
609,830
<p>I have a name as a string, in this example "markus johansson".</p> <p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p> <pre><code>name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J' </code></pre> <p>I'm pretty sure this should work, but it gives me this error:</p> <pre><code>File "main.py", line 5 in &lt;module&gt; name[0] = "M" TypeError: 'str' object does support item assignment </code></pre> <p>I know there is a library function called .title(), but I want to do "real programming".</p> <p>How do I fix this?</p>
2
2009-03-04T09:24:35Z
610,572
<p>If you're looking into more generic solution for names, you should also look at following examples:</p> <ul> <li>John Adams-Smith</li> <li>Joanne d'Arc</li> <li>Jean-Luc de'Breu</li> <li>Donatien Alphonse François de Sade</li> </ul> <p>Also some parts of the names shouldn't start with capital letters, like:</p> <ul> <li>Herbert von Locke</li> <li>Sander van Dorn</li> <li>Edwin van der Sad</li> </ul> <p>so, if you're looking into creating a more generic solution, keep all those little things in mind.</p> <p><em>(This would be a perfect place to run a test-driven development, with all those conditions your method/function must follow)</em>.</p>
1
2009-03-04T13:35:03Z
[ "python" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
610,019
<p>Another choice is <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/" rel="nofollow">CairoPlot</a>.</p> <p>We picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed.</p> <p>Performance generating PNG's was fine for us but... it was a highly specialized app with less than 10 logins a day.</p>
7
2009-03-04T10:29:38Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
610,272
<p>Open Flash Chart 2</p> <p><a href="http://teethgrinder.co.uk/open-flash-chart-2/" rel="nofollow">http://teethgrinder.co.uk/open-flash-chart-2/</a></p> <p>python library <a href="http://btbytes.github.com/pyofc2/" rel="nofollow">http://btbytes.github.com/pyofc2/</a></p> <p>kybi</p>
3
2009-03-04T12:06:15Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
611,528
<p>Well, I'm involved in an open source project, <a href="http://djime.github.com/" rel="nofollow">Djime</a>, that uses <a href="http://teethgrinder.co.uk/open-flash-chart-2/" rel="nofollow">OpenFlashChart 2</a>.</p> <p>As you can see from <a href="http://github.com/mikl/djime/blob/e6832c6e8d2aa8a3801b16121a0499f3b6d63503/djime/statistics/flashcharts.py" rel="nofollow">our code</a>, generating the JSON-data that OFC uses is a bit complex, but the output is very nice and user friendly, since you can add tooltips, etc. to the different elements.</p>
5
2009-03-04T17:04:50Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
1,385,804
<p>I have used <a href="http://www.fusioncharts.com/free/" rel="nofollow">FusionCharts Free</a> with Django.</p> <p>Its flash based, open source, multi-licensed and it's well documented. It's ActionScript 1, but AS version wasn't really a criteria for me, though it could be for others.</p>
0
2009-09-06T14:37:36Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
1,386,926
<p>One package I've wanted to try is <a href="http://graphite.wikidot.com/" rel="nofollow">graphite</a>. It's a graphing server / platform built with Django. It's specialized for "numeric time-series data" though, like stock prices or bandwidth utilization. If that fits your need I would check it out. Here are some screenshots:</p> <p><a href="http://graphite.wikidot.com/screen-shots" rel="nofollow">http://graphite.wikidot.com/screen-shots</a></p>
3
2009-09-06T22:44:31Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
3,997,250
<p>I like client side charts because you can get full page plotting. </p> <p>A good options seems to be Jquery Flot : <a href="http://code.google.com/p/flot/" rel="nofollow">http://code.google.com/p/flot/</a> which can load JSON data. However, you won't get pdf support.</p>
1
2010-10-22T13:29:06Z
[ "python", "django", "charts" ]
Charts in django Web Applications
609,944
<p>I want to Embed a chart in a Web Application developed using django.</p> <p>I have come across <a href="http://code.google.com/p/google-chartwrapper/">Google charts API</a>, <a href="http://code.djangoproject.com/wiki/Charts">ReportLab</a>, <a href="http://home.gna.org/pychart/">PyChart</a>, <a href="http://matplotlib.sourceforge.net/">MatPlotLib</a> and <a href="http://www.advsofteng.com/?gid=misc&amp;gclid=CJLaibjeiJkCFQMwpAodXkETng">ChartDirector</a></p> <p>I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.</p> <p>Which is the best option to use, and what are the relative merits and demerits of one over the other.</p>
20
2009-03-04T10:08:21Z
5,781,231
<p>Perhaps you might want to have a look here: <a href="http://www.rotareeclub.de/?p=312" rel="nofollow">Django Plotting app</a>. The HowTo describes how to embed matplotlib plots into the admin interface and create a PDF view.</p>
1
2011-04-25T17:43:37Z
[ "python", "django", "charts" ]
Yahoo Pipes, simplejson and slashes
610,205
<p>Im trying to use <a href="http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/" rel="nofollow">http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/</a> as inspiration, but I'm having some troubles with the output.</p> <p>Its obvious when testing with the console and the App Engine "django util simplejson":</p> <pre><code>/cygdrive/c/Program Files/Google/google_appengine/lib/django $ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from django.utils import simplejson as json &gt;&gt;&gt; json.dumps('/') '"\\/"' &gt;&gt;&gt; json.dumps('http://stackoverflow.com') '"http:\\/\\/stackoverflow.com" </code></pre> <p><a href="http://microformats.org/wiki/json" rel="nofollow">As far as I can read</a> this is ok behavior:</p> <blockquote> <p>In JSON only the backslash, double quote and ASCII control characters need to be escaped. Forward slashes may be escaped as in the URL example below, but do not have to be.</p> </blockquote> <p>But when inputting back to yahoopipes, they don't "unescape" the output and all my urls and html doesnt work.</p> <p>should I really do a </p> <pre><code>self.response.out.write(json.dumps(obj).replace('\\/','/')) </code></pre> <p>?</p> <p>==== Edit ===</p> <p>To my great suprise I see that newest simplejson downloaded from simplejson site doesnt do the "slash" stuff :( So the real issue is with app engines django.util.simplejson version?</p> <p>=== Edit again ===</p> <p>And now Ive created an issue in the tracker for it: <a href="http://code.google.com/p/googleappengine/issues/detail?id=1128" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=1128</a></p>
0
2009-03-04T11:42:25Z
677,751
<p>Nothing here to see. The ticket is there, but thats it, as far as I can see</p>
0
2009-03-24T14:53:50Z
[ "python", "yahoo-pipes", "simplejson" ]
Catching Python exceptions using 'expect' method?
610,403
<pre><code>import sys try: file = open("words.txt") expect(IOError): if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>this gives me an a error - </p> <pre><code>File "main.py", line 4 expect(IOError): SyntaxError: invaild syntax </code></pre> <p>What im going wrong/ how do you fix this</p>
1
2009-03-04T12:52:33Z
610,412
<p>Actually, it is except as in exception:</p> <p>For instance:</p> <pre><code>except IOError: print "Error opening file!" </code></pre>
12
2009-03-04T12:54:46Z
[ "python" ]
Catching Python exceptions using 'expect' method?
610,403
<pre><code>import sys try: file = open("words.txt") expect(IOError): if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>this gives me an a error - </p> <pre><code>File "main.py", line 4 expect(IOError): SyntaxError: invaild syntax </code></pre> <p>What im going wrong/ how do you fix this</p>
1
2009-03-04T12:52:33Z
610,417
<p>It's <code>except</code>. Read <a href="http://docs.python.org/tutorial/index.html" rel="nofollow">this</a>.</p>
1
2009-03-04T12:55:52Z
[ "python" ]
Catching Python exceptions using 'expect' method?
610,403
<pre><code>import sys try: file = open("words.txt") expect(IOError): if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>this gives me an a error - </p> <pre><code>File "main.py", line 4 expect(IOError): SyntaxError: invaild syntax </code></pre> <p>What im going wrong/ how do you fix this</p>
1
2009-03-04T12:52:33Z
610,426
<p>I think you're looking for <a href="http://docs.python.org/reference/compound%5Fstmts.html#except" rel="nofollow">except</a>. The <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">error handling</a> part of the python tutorial explains it well.</p> <p>-John</p>
1
2009-03-04T12:57:38Z
[ "python" ]
Catching Python exceptions using 'expect' method?
610,403
<pre><code>import sys try: file = open("words.txt") expect(IOError): if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>this gives me an a error - </p> <pre><code>File "main.py", line 4 expect(IOError): SyntaxError: invaild syntax </code></pre> <p>What im going wrong/ how do you fix this</p>
1
2009-03-04T12:52:33Z
610,431
<p>I assume you are trying to handle exceptions. In that case, use <strong>except</strong>, not <strong>expect</strong>. In any case except is <strong>not a function</strong>, rather it precedes a block of error handling code. When using files, you may want to look at the <strong>with statement</strong> and <strong>try-except-finally</strong>. The correction to your code is-</p> <pre><code>import sys try: file = open("words.txt") except IOError: #Handle error pass if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>I hope this helps.</p>
4
2009-03-04T12:58:38Z
[ "python" ]
Catching Python exceptions using 'expect' method?
610,403
<pre><code>import sys try: file = open("words.txt") expect(IOError): if file: print "%s" % file else: print "Cant the %s file" % "words.txt" </code></pre> <p>this gives me an a error - </p> <pre><code>File "main.py", line 4 expect(IOError): SyntaxError: invaild syntax </code></pre> <p>What im going wrong/ how do you fix this</p>
1
2009-03-04T12:52:33Z
610,457
<pre> <code> >>> try: ... f = open('words.txt') ... except IOError: ... print "Cant the %s file" % "words.txt" ... else: ... print "%s" % f </code> </pre>
1
2009-03-04T13:05:25Z
[ "python" ]
Is there something like CherryPy or Cerise in the Java world?
610,516
<p><a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> and <a href="http://cerise.rubyforge.org/" rel="nofollow">Cerise</a> are two small frameworks that implement nothing but the barebones of a web-framework and I love their simplicity: in fact I reckon that if Classic ASP was implemented that way (and didn't pretty much <em>require</em> VBScript) I could have settled for it and lived happily ever after.</p> <p>But now I'm living at the borders of the Java world and would like to know if there's something similar to these 2 frameworks and that doesn't try to take control away from you. My requrements would be that they have an:</p> <ul> <li><p>a dispatcher that maps urls to methods (like CherryPy, Django, Cerise, Rails, etc...)</p></li> <li><p>bonus points if it has a simple, yet powerful templating language (a la JSP/ASP) that is not too religious in separation of concerns</p></li> <li><p>bonus points if it has some sort of library that helps in validating forms</p></li> </ul> <p>Thanks</p> <p>--</p>
2
2009-03-04T13:21:36Z
610,538
<p><a href="http://www.stripesframework.org/display/stripes/Home" rel="nofollow">Stripes</a></p> <p>URLs to methods, check, form validation, check. Powerful but stays out of your way unless you need it.</p>
2
2009-03-04T13:27:23Z
[ "java", "python" ]
Is there something like CherryPy or Cerise in the Java world?
610,516
<p><a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> and <a href="http://cerise.rubyforge.org/" rel="nofollow">Cerise</a> are two small frameworks that implement nothing but the barebones of a web-framework and I love their simplicity: in fact I reckon that if Classic ASP was implemented that way (and didn't pretty much <em>require</em> VBScript) I could have settled for it and lived happily ever after.</p> <p>But now I'm living at the borders of the Java world and would like to know if there's something similar to these 2 frameworks and that doesn't try to take control away from you. My requrements would be that they have an:</p> <ul> <li><p>a dispatcher that maps urls to methods (like CherryPy, Django, Cerise, Rails, etc...)</p></li> <li><p>bonus points if it has a simple, yet powerful templating language (a la JSP/ASP) that is not too religious in separation of concerns</p></li> <li><p>bonus points if it has some sort of library that helps in validating forms</p></li> </ul> <p>Thanks</p> <p>--</p>
2
2009-03-04T13:21:36Z
610,544
<p>Groovy and <a href="http://www.grails.org" rel="nofollow">Grails</a>. If you like MVC or even have a existing library written in Java/JVM, that are the tools you're looking for! </p> <blockquote> <p>Grails aims to bring the "coding by convention" paradigm to Groovy. It's an open-source web application framework that leverages the Groovy language and complements Java Web development. You can use Grails as a standalone development environment that hides all configuration details or integrate your Java business logic. Grails aims to make development as simple as possible and hence should appeal to a wide range of developers not just those from the Java community.</p> </blockquote>
0
2009-03-04T13:29:01Z
[ "java", "python" ]
Is there something like CherryPy or Cerise in the Java world?
610,516
<p><a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> and <a href="http://cerise.rubyforge.org/" rel="nofollow">Cerise</a> are two small frameworks that implement nothing but the barebones of a web-framework and I love their simplicity: in fact I reckon that if Classic ASP was implemented that way (and didn't pretty much <em>require</em> VBScript) I could have settled for it and lived happily ever after.</p> <p>But now I'm living at the borders of the Java world and would like to know if there's something similar to these 2 frameworks and that doesn't try to take control away from you. My requrements would be that they have an:</p> <ul> <li><p>a dispatcher that maps urls to methods (like CherryPy, Django, Cerise, Rails, etc...)</p></li> <li><p>bonus points if it has a simple, yet powerful templating language (a la JSP/ASP) that is not too religious in separation of concerns</p></li> <li><p>bonus points if it has some sort of library that helps in validating forms</p></li> </ul> <p>Thanks</p> <p>--</p>
2
2009-03-04T13:21:36Z
612,435
<p><a href="http://ooweb.sourceforge.net/tutorial.html" rel="nofollow">OOWeb</a>, essentially a port of CherryPy.</p>
2
2009-03-04T21:10:29Z
[ "java", "python" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
610,893
<p>Try hasattr():</p> <pre><code>if hasattr(a, 'property'): a.property </code></pre> <p>EDIT: See <a href="http://stackoverflow.com/a/610923/117030">zweiterlinde's answer</a> below, who offers good advice about asking forgiveness! A very pythonic approach! </p> <p>The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than <code>hasattr</code>. If the property is likely to not be there most of the time, or you're not sure, using <code>hasattr</code> will probably be faster than repeatedly falling into an exception block.</p>
1,006
2009-03-04T14:48:43Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
610,907
<p>I think what you are looking for is <strong>hasattr</strong>. However, I'd recommend something like this if you want to detect <strong>python properties</strong>-</p> <pre><code>try: getattr(someObject, 'someProperty') except AttributeError: print "Doesn't exist" else print "Exists" </code></pre> <p>The disadvantage here is that attribute errors in the properties <code>__get__</code> code are also caught.</p> <p>Otherwise, do-</p> <pre><code>if hasattr(someObject, 'someProp'): #Access someProp/ set someProp pass </code></pre> <p>Docs:<a href="http://docs.python.org/library/functions.html">http://docs.python.org/library/functions.html</a><br /> <strong>Warning:</strong><br /> The reason for my recommendation is that hasattr doesn't detect properties.<br /> Link:<a href="http://mail.python.org/pipermail/python-dev/2005-December/058498.html">http://mail.python.org/pipermail/python-dev/2005-December/058498.html</a></p>
23
2009-03-04T14:52:26Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
610,922
<p>According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.</p> <pre><code>a = SomeClass() try: return a.fake_prop except AttributeError: return default_value </code></pre>
15
2009-03-04T14:56:26Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
610,923
<p>As <a href="http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610893#610893">Jarret Hardie</a> answered, <code>hasattr</code> will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:</p> <p><a href="http://web.archive.org/web/20070929122422/http://mail.python.org/pipermail/python-list/2003-May/205182.html">EAFP vs LBYL (was Re: A little disappointed so far)</a><br> <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl">EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python</a></p> <p>ie:</p> <pre><code>try: doStuff(a.property) except AttributeError: otherStuff() </code></pre> <p>... is preferred to:</p> <pre><code>if hasattr(a, 'property'): doStuff(a.property) else: otherStuff() </code></pre>
322
2009-03-04T14:56:28Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
611,122
<p>Depending on the situation you can check with <code>isinstance</code> what kind of object you have, and then use the corresponding attributes. With the introduction of <a href="http://www.python.org/dev/peps/pep-3119/">abstract base classes</a> in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).</p> <p>One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only <code>hasattr</code> might then lead to strange errors.</p> <p>One nice example is the distinction between iterators and iterables (see <a href="http://stackoverflow.com/questions/709084/how-to-tell-the-difference-between-an-iterator-and-an-iterable">this</a> question). The <code>__iter__</code> methods in an iterator and an iterable have the same name but are semantically quite different! So <code>hasattr</code> is useless, but <code>isinstance</code> together with ABC's provides a clean solution.</p> <p>However, I agree that in most situations the <code>hasattr</code> approach (described in other answers) is the most appropriate solution.</p>
8
2009-03-04T15:41:04Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
611,708
<p>You can use <code>hasattr()</code> or catch <code>AttributeError</code>, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use <code>getattr()</code>:</p> <pre><code>getattr(a, 'property', 'default value') </code></pre>
251
2009-03-04T17:54:29Z
[ "python", "attributes" ]
How to know if an object has an attribute in Python
610,883
<p>Is there a way in Python to determine if an object has some attribute? For example:</p> <pre><code>&gt;&gt;&gt; a = SomeClass() &gt;&gt;&gt; a.someProperty = value &gt;&gt;&gt; a.property Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: SomeClass instance has no attribute 'property' </code></pre> <p>How can you tell if <code>a</code> has the attribute <code>property</code> before using it?</p>
737
2009-03-04T14:45:59Z
39,167,034
<p>I would like to suggest avoid this:</p> <pre><code>try: doStuff(a.property) except AttributeError: otherStuff() </code></pre> <p>The user @jpalecek mentioned it: If an <code>AttributeError</code> occurs inside <code>doStuff()</code>, you are lost.</p> <p>Maybe this approach is better:</p> <pre><code>try: val = a.property except AttributeError: otherStuff() else: doStuff(val) </code></pre>
2
2016-08-26T13:04:30Z
[ "python", "attributes" ]
What is a good strategy for constructing a directed graph for a game map (in Python)?
610,892
<p>I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is <em>not</em> necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) </p> <p>To the world generation algorithm, rooms of different sorts will be distinguished by each room's "tags" attribute (a set of strings). Once they have been instantiated, rooms can be queried and selected by tags (single-tag, tag intersection, tag union, best-candidate).</p> <p>I'll be creating specific sorts of rooms using a glorified system of template objects and factory methods--I don't think the details are important here, as the current implementation will probably change to match the chosen strategy. (For instance, it would be possible to add tags and tag-queries to the room template system.)</p> <p>For an example, I will have rooms of these sorts: <pre><code>side_street</code>, <code>main_street</code>, plaza, bar, hotel, restaurant, shop, office</pre></p> <p>Finally, the question: what is a good strategy for instantiating and arranging these rooms to create a graph that might correspond to given rules? </p> <p>Some rules might include: one plaza per 10,000 population; <code>main_street</code> connects to <code>plaza</code>; <code>side_street</code> connects to <code>main_street</code> or <code>side_street</code>; <code>hotel</code> favors <code>main_street</code> or <code>plaza</code> connections, and receives further tags accordingly; etc.</p> <p>Bonus points if a suggested strategy would enable a data-driven implementation.</p>
9
2009-03-04T14:48:19Z
611,124
<p>First, you need some sense of Location. Your various objects occupy some amount of coordinate space.</p> <p>You have to decide how regular these various things are. In the trivial case, you can drop them into your coordinate space as simple rectangles (or rectangular solids) to make locations simpler to plan out.</p> <p>If the things are irregular -- and densely packed -- life is somewhat more complex.</p> <p>Define a Map to contain locations. Each location has a span of coordinates; if you work with simple rectangles, then each location can have a (left, top, right, bottom) tuple. </p> <p>Your Map will need methods to determine who is residing in a given space, and what's adjacent to the space, etc.</p> <p>You can then unit test this with a fixed set of locations you've worked out that can all be dropped into the map and pass some basic sanity checks for non-conflicting, adjacent, and the like.</p> <p><hr /></p> <p>Second, you need a kind of "maze generator". A simply-connected maze is easily generated as a tree structure that's folded up into the given space.</p> <p>The maze/tree has a "root" node that will be the center of the maze. Not necessarily the physical center of your space, but the root node will be the middle of the maze structure. </p> <p>Ideally, one branch from this node contains one "entrance" to the entire space.</p> <p>The other branch from this node contains one "exit" from the entire space. </p> <p>Someone can wander from entrance to exit, visiting a lot of "dead-end" locations along the way.</p> <p>Pick a kind of space for the root node. Drop it into your Map space.</p> <p>This will have 1 - <em>n</em> entrances, each of which is a sub-tree with a root node and 1 - <em>n</em> entrances. It's this multiple-entrance business that makes a tree a natural fit for this structure. Also a proper tree is always well-connected in that you never have isolated sections that can't be reached.</p> <p>You'll -- recursively -- fan out from the root node, picking locations and dropping them into the available space. </p> <p>Unit test this to be sure it fills space reasonably well.</p> <p><hr /></p> <p>The rest of your requirements are fine-tuning on the way the maze generator picks locations. </p> <p>The easiest is to have a table of weights and random choices. Choose a random number, compare it with the weights to see which kind of location gets identified.</p> <p><hr /></p> <p>Your definition of space can be 2D or 3D -- both are pretty rational. For bonus credit, consider how you'd implement a 2D-space tiled with hexagons instead of squares.</p> <p>This "geometry" can be a <strong>Strategy</strong> plug-in to the various algorithms. If you can replace square 2D with hexagonal 2D, you've done a good job of OO Design.</p>
7
2009-03-04T15:41:51Z
[ "python", "graph", "procedural-generation" ]
What is a good strategy for constructing a directed graph for a game map (in Python)?
610,892
<p>I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is <em>not</em> necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) </p> <p>To the world generation algorithm, rooms of different sorts will be distinguished by each room's "tags" attribute (a set of strings). Once they have been instantiated, rooms can be queried and selected by tags (single-tag, tag intersection, tag union, best-candidate).</p> <p>I'll be creating specific sorts of rooms using a glorified system of template objects and factory methods--I don't think the details are important here, as the current implementation will probably change to match the chosen strategy. (For instance, it would be possible to add tags and tag-queries to the room template system.)</p> <p>For an example, I will have rooms of these sorts: <pre><code>side_street</code>, <code>main_street</code>, plaza, bar, hotel, restaurant, shop, office</pre></p> <p>Finally, the question: what is a good strategy for instantiating and arranging these rooms to create a graph that might correspond to given rules? </p> <p>Some rules might include: one plaza per 10,000 population; <code>main_street</code> connects to <code>plaza</code>; <code>side_street</code> connects to <code>main_street</code> or <code>side_street</code>; <code>hotel</code> favors <code>main_street</code> or <code>plaza</code> connections, and receives further tags accordingly; etc.</p> <p>Bonus points if a suggested strategy would enable a data-driven implementation.</p>
9
2009-03-04T14:48:19Z
612,730
<p>Check out the discussions on <a href="http://www.mudconnector.com" rel="nofollow">The MUD Connector</a> - there are some great discussions about world layout and generation, and different types of coordinate / navigation systems in the "Advanced Coding and Design" (or similar) forum.</p>
2
2009-03-04T22:20:48Z
[ "python", "graph", "procedural-generation" ]
Django Model Inheritance. Hiding or removing fields
611,691
<p>I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first place?</p> <p>Additionally - what can I do if one of the unwanted fields is required? My first thought is to override the save method and just put in a default value.</p>
10
2009-03-04T17:49:26Z
611,725
<p>If you are inheriting the model then it is probably not wise to attempt to hide or disable any existing fields. The best thing you could probably do is exactly what you suggested: override <code>save()</code> and handle your logic in there. </p>
4
2009-03-04T17:57:34Z
[ "python", "django", "django-models", "django-admin" ]
Django Model Inheritance. Hiding or removing fields
611,691
<p>I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first place?</p> <p>Additionally - what can I do if one of the unwanted fields is required? My first thought is to override the save method and just put in a default value.</p>
10
2009-03-04T17:49:26Z
611,813
<p>Rather than inherit, consider using customized Forms.</p> <ol> <li><p>You can eliminate fields from display that are still in the model.</p></li> <li><p>You can validate and provide default values in the form's <code>clean()</code> method.</p></li> </ol> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p>
4
2009-03-04T18:20:55Z
[ "python", "django", "django-models", "django-admin" ]
Django Model Inheritance. Hiding or removing fields
611,691
<p>I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first place?</p> <p>Additionally - what can I do if one of the unwanted fields is required? My first thought is to override the save method and just put in a default value.</p>
10
2009-03-04T17:49:26Z
611,972
<p>You can control the fields that are editable in admin.</p> <p>From the Django docs:</p> <p>"If you want a form for the Author model that includes only the name and title fields, you would specify fields or exclude like this:</p> <pre><code>class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title') class AuthorAdmin(admin.ModelAdmin): exclude = ('birth_date',)" </code></pre> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/</a></p>
4
2009-03-04T19:02:41Z
[ "python", "django", "django-models", "django-admin" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
612,955
<p>No, but you can copy admin template and define app name there.</p>
6
2009-03-04T23:22:05Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
615,760
<p>Give them a verbose_name property.</p> <p>Don't get your hopes up. You will also need to copy the index view from django.contrib.admin.sites into your own ProjectAdminSite view and include it in your own custom admin instance:</p> <pre><code>class ProjectAdminSite(AdminSite): def index(self, request, extra_context=None): copied stuff here... admin.site = ProjectAdminSite() </code></pre> <p>then tweak the copied view so that it uses your verbose_name property as the label for the app.</p> <p>I did it by adding something a bit like this to the copied view:</p> <pre><code> try: app_name = model_admin.verbose_name except AttributeError: app_name = app_label </code></pre> <p>While you are tweaking the index view why not add an 'order' property too.</p>
11
2009-03-05T17:29:30Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
3,164,163
<p><strong>Prior to Django 1.7</strong></p> <p>You can give your application a custom name by defining app_label in your model definition. But as django builds the admin page it will hash models by their app_label, so if you want them to appear in one application, you have to define this name in all models of your application.</p> <pre><code>class MyModel(models.Model): pass class Meta: app_label = 'My APP name' </code></pre> <p><strong>Django 1.7+</strong></p> <p>As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7</p> <p>Taken from the <a href="https://docs.djangoproject.com/en/1.7/ref/applications/#for-application-authors">docs</a>:</p> <pre class="lang-py prettyprint-override"><code># in yourapp/apps.py from django.apps import AppConfig class YourAppConfig(AppConfig): name = 'yourapp' verbose_name = 'Fancy Title' </code></pre> <p>then set the <code>default_app_config</code> variable to <code>YourAppConfig</code></p> <pre class="lang-py prettyprint-override"><code># in yourapp/__init__.py default_app_config = 'yourapp.apps.YourAppConfig' </code></pre>
85
2010-07-02T08:20:34Z
[ "python", "django" ]
Can you give a Django app a verbose name for use throughout the admin?
612,372
<p>In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?</p>
95
2009-03-04T20:51:03Z
3,628,988
<p>Well I started an app called <strong>todo</strong> and have now decided I want it to be named <strong>Tasks</strong>. The problem is that I already have data within my table so my work around was as follows. Placed into the models.py:</p> <pre><code> class Meta: app_label = 'Tasks' db_table = 'mytodo_todo' </code></pre> <p>Hope it helps.</p>
10
2010-09-02T16:08:22Z
[ "python", "django" ]