title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,158,294
<p>One line solution using sorted:</p> <pre><code>def magic(*args): return sorted(sum(args,[]), key: lambda x: x.points) </code></pre> <p>IMO this solution is very readable.</p> <p>Using heapq module, it could be more efficient, but I have not tested it. You cannot specify cmp/key function in heapq, so you have to implement Obj to be implicitly sorted.</p> <pre><code>import heapq def magic(*args): h = [] for a in args: heapq.heappush(h,a) return [i for i in heapq.heappop(h) </code></pre>
0
2009-07-21T10:01:19Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,159,492
<p>Here you go: a fully functioning merge sort for lists (adapted from my sort <a href="http://github.com/hughdbrown/algorithm/blob/05307be15669de0541cd4e91c03b610d440b4290/mergesort.py" rel="nofollow">here</a>):</p> <pre><code>def merge(*args): import copy def merge_lists(left, right): result = [] while left and right: which_list = (left if left[0] &lt;= right[0] else right) result.append(which_list.pop(0)) return result + left + right lists = list(args) while len(lists) &gt; 1: left, right = copy.copy(lists.pop(0)), copy.copy(lists.pop(0)) result = merge_lists(left, right) lists.append(result) return lists.pop(0) </code></pre> <p>Call it like this:</p> <pre><code>merged_list = merge(a, b, c) for item in merged_list: print item </code></pre> <p>For good measure, I'll throw in a couple of changes to your Obj class:</p> <pre><code>class Obj(object): def __init__(self, p) : self.points = p def __cmp__(self, b) : return cmp(self.points, b.points) def __str__(self): return "%d" % self.points </code></pre> <ul> <li>Derive from object </li> <li>Pass <code>self</code> to <code>__init__()</code></li> <li>Make <code>__cmp__</code> a member function</li> <li>Add a <code>str()</code> member function to present <code>Obj</code> as string</li> </ul>
0
2009-07-21T14:18:02Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,159,612
<p>I like Roberto Liffredo's answer. I didn't know about heapq.merge(). Hmmmph.</p> <p>Here's what the complete solution looks like using Roberto's lead:</p> <pre><code>class Obj(object): def __init__(self, p) : self.points = p def __cmp__(self, b) : return cmp(self.points, b.points) def __str__(self): return "%d" % self.points a = [Obj(1), Obj(3), Obj(8)] b = [Obj(1), Obj(2), Obj(3)] c = [Obj(100), Obj(300), Obj(800)] import heapq sorted = [item for item in heapq.merge(a,b,c)] for item in sorted: print item </code></pre> <p>Or:</p> <pre><code>for item in heapq.merge(a,b,c): print item </code></pre>
1
2009-07-21T14:37:47Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,159,623
<p>I asked a similar question and got some excellent answers:</p> <ul> <li><a href="http://stackoverflow.com/questions/969709/joining-a-set-of-ordered-integer-yielding-python-iterators">Joining a set of ordered-integer yielding Python iterators</a></li> </ul> <p>The best solutions from that question are variants of the merge algorithm, which you can read about here:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Merge%5Falgorithm" rel="nofollow">Wikipedia: Merge Algorithm</a></li> </ul>
0
2009-07-21T14:39:37Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
15,893,551
<p>Below is an example of a function that runs in O(n) comparisons. </p> <p>You could make this faster by making a and b iterators and incrementing them.</p> <p>I have simply called the function twice to merge 3 lists:</p> <pre><code>def zip_sorted(a, b): ''' zips two iterables, assuming they are already sorted ''' i = 0 j = 0 result = [] while i &lt; len(a) and j &lt; len(b): if a[i] &lt; b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 if i &lt; len(a): result.extend(a[i:]) else: result.extend(b[j:]) return result def genSortedList(num,seed): result = [] for i in range(num): result.append(i*seed) return result if __name__ == '__main__': a = genSortedList(10000,2.0) b = genSortedList(6666,3.0) c = genSortedList(5000,4.0) d = zip_sorted(zip_sorted(a,b),c) print d </code></pre> <p>However, <strong>heapq.merge</strong> uses a mix of this method and heaping the current elements of all lists, so should perform much better </p>
0
2013-04-09T04:51:05Z
[ "python", "arrays", "merge", "sorting" ]
django - QuerySet recursive order by method
1,158,267
<p>I may have a classic problem, but I didn't find any snippet allowing me to do it.</p> <p>I want to sort this model by its fullname.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) fullname = property(get_fullname) </code></pre> <ol> <li><p>I tried sorting by "parent", got <em>infinite loop error</em>. "parent__id" did not sort well.</p></li> <li><p>I could not understand how to use <em>annotate()</em> for concatenating string fields.</p></li> <li><p>I added a custom manager with <em>sorted()</em>, but it returns a list object and prevents my <em>forms.ModelChoiceField</em> to work.</p></li> </ol> <p>Here's the sort</p> <pre><code>def all(self): return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname) </code></pre> <p>What else is there in the djangonic jungle ? Thanks for your help.</p>
1
2009-07-21T09:55:50Z
1,158,879
<p>This might work:</p> <pre><code>ProductType.objects.alL().order_by('parent__name', 'name') </code></pre>
0
2009-07-21T12:25:23Z
[ "python", "django", "order" ]
django - QuerySet recursive order by method
1,158,267
<p>I may have a classic problem, but I didn't find any snippet allowing me to do it.</p> <p>I want to sort this model by its fullname.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) fullname = property(get_fullname) </code></pre> <ol> <li><p>I tried sorting by "parent", got <em>infinite loop error</em>. "parent__id" did not sort well.</p></li> <li><p>I could not understand how to use <em>annotate()</em> for concatenating string fields.</p></li> <li><p>I added a custom manager with <em>sorted()</em>, but it returns a list object and prevents my <em>forms.ModelChoiceField</em> to work.</p></li> </ol> <p>Here's the sort</p> <pre><code>def all(self): return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname) </code></pre> <p>What else is there in the djangonic jungle ? Thanks for your help.</p>
1
2009-07-21T09:55:50Z
1,158,972
<p>I would probably create a denomalised field and order on that. Depending on your preferences you might wnat to override .save(), or use a signal to poplate the denormalised field.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) full_name = models.CharField(max_length=128*4) def save(self, *args, **kwargs): if not full_name: self.full_name = self.get_fullname() super(ProductType, self).save(*args, **kwargs) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) </code></pre> <p>Then do a normal order by <code>full_name</code></p>
2
2009-07-21T12:47:10Z
[ "python", "django", "order" ]
django - QuerySet recursive order by method
1,158,267
<p>I may have a classic problem, but I didn't find any snippet allowing me to do it.</p> <p>I want to sort this model by its fullname.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) fullname = property(get_fullname) </code></pre> <ol> <li><p>I tried sorting by "parent", got <em>infinite loop error</em>. "parent__id" did not sort well.</p></li> <li><p>I could not understand how to use <em>annotate()</em> for concatenating string fields.</p></li> <li><p>I added a custom manager with <em>sorted()</em>, but it returns a list object and prevents my <em>forms.ModelChoiceField</em> to work.</p></li> </ol> <p>Here's the sort</p> <pre><code>def all(self): return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname) </code></pre> <p>What else is there in the djangonic jungle ? Thanks for your help.</p>
1
2009-07-21T09:55:50Z
1,159,096
<p>agreed :</p> <p>ProductType.objects.all().order_by('parent__name', 'name')</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields</a></p>
0
2009-07-21T13:14:17Z
[ "python", "django", "order" ]
django - QuerySet recursive order by method
1,158,267
<p>I may have a classic problem, but I didn't find any snippet allowing me to do it.</p> <p>I want to sort this model by its fullname.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) fullname = property(get_fullname) </code></pre> <ol> <li><p>I tried sorting by "parent", got <em>infinite loop error</em>. "parent__id" did not sort well.</p></li> <li><p>I could not understand how to use <em>annotate()</em> for concatenating string fields.</p></li> <li><p>I added a custom manager with <em>sorted()</em>, but it returns a list object and prevents my <em>forms.ModelChoiceField</em> to work.</p></li> </ol> <p>Here's the sort</p> <pre><code>def all(self): return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname) </code></pre> <p>What else is there in the djangonic jungle ? Thanks for your help.</p>
1
2009-07-21T09:55:50Z
1,159,340
<p>I would definitely explore the route you mentioned as 1) above:</p> <pre><code>ProductType.objects.order_by('parent__name', 'name') </code></pre> <p>Why is it erroring with an infinite loop? Is your example data referencing itself? </p>
0
2009-07-21T13:52:45Z
[ "python", "django", "order" ]
django - QuerySet recursive order by method
1,158,267
<p>I may have a classic problem, but I didn't find any snippet allowing me to do it.</p> <p>I want to sort this model by its fullname.</p> <pre><code>class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.parent is None: return self.name return u'%s - %s' % (unicode(self.parent), self.name) fullname = property(get_fullname) </code></pre> <ol> <li><p>I tried sorting by "parent", got <em>infinite loop error</em>. "parent__id" did not sort well.</p></li> <li><p>I could not understand how to use <em>annotate()</em> for concatenating string fields.</p></li> <li><p>I added a custom manager with <em>sorted()</em>, but it returns a list object and prevents my <em>forms.ModelChoiceField</em> to work.</p></li> </ol> <p>Here's the sort</p> <pre><code>def all(self): return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname) </code></pre> <p>What else is there in the djangonic jungle ? Thanks for your help.</p>
1
2009-07-21T09:55:50Z
1,159,406
<p>Or, if what you're trying to do is to generate a tree structure, have a look at <a href="http://code.google.com/p/django-mptt/" rel="nofollow">django-mptt</a>. It also allows for ordering on a manually set order.</p>
1
2009-07-21T14:04:15Z
[ "python", "django", "order" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,418
<p>Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C.</p> <p>If you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapper methods to expose what you want to allow the Lua to modify.</p> <p>Small code base and tight control over the amount of default libraries introduced into your embeded interpreter also means that you can make reasonable assumptions over the security.</p> <p>The only odd part is the 1-based array numbering, however, it was not that big of a deal compared to what I thought, given the existence of the iterators.</p> <p>How to integrate with C: the distribution tarball for Lua has a directory "etc" with a few very good useful examples that should quickly get you started. Specifically - etc/min.c shows how to start up an interpreter, make it interpret the file, and make it call the C function ('print' in that case). From there on you can go by reading the Lua documentation and the source of the standard libraries included with the distribution.</p>
17
2009-07-21T10:39:24Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,423
<p>Lua is designed for exactly this purpose, and fairly easy to work with.</p> <p>Another thing worth looking at would be <a href="http://doc.trolltech.com/4.5/qtscript.html" rel="nofollow">QtScript</a>, which is Javascript based, although this would involve some work to "qt-ify" your app.</p>
3
2009-07-21T10:40:53Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,502
<p>Here's the document from the Python website for embedding Python 2.6...</p> <p><a href="http://docs.python.org/extending/embedding.html">http://docs.python.org/extending/embedding.html</a></p>
7
2009-07-21T10:57:52Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,517
<p>Most scripting language allow embedding in C and usually allow you to expose certain objects or even functions from your C code to the script so it can manipulate the objects and call the functions.</p> <p>As said Lua is designed for this purpose embedding, using the interpreter you can expose objects to the script and call lua functions from C, search for <strong>embedding lua in C</strong> and you should find a lot of information, also don't miss the lua manual section <a href="http://www.lua.org/manual/5.1/manual.html#3" rel="nofollow">"The Application Programming Interface"</a></p> <p>Although Python is more suitable for stand-alone usage, it can also be embedded, it can be useful in case your scripts use the vast amount libraries provided with Python.</p>
1
2009-07-21T11:01:50Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,540
<p>Some useful links:</p> <ul> <li><a href="http://docs.python.org/extending/embedding.html">Embedding Python</a></li> <li>Embedding Lua: <a href="http://www.lua.org/manual/5.1/manual.html#3">http://www.lua.org/manual/5.1/manual.html#3</a>, <a href="http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html">http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html</a></li> <li><a href="http://www.rubycentral.com/pickaxe/ext%5Fruby.html">Embedding Ruby</a></li> <li><a href="http://docs.plt-scheme.org/inside/index.html">Embedding PLT Scheme</a></li> <li><a href="http://www.perl.com/doc/manual/html/pod/perlembed.html">Embedding PERL</a></li> <li><a href="http://wiki.tcl.tk/2074">Embedding TCL</a></li> <li><a href="http://stackoverflow.com/questions/93692/which-javascript-engine-would-you-embed-in-an-application">Embedding JavaScript</a></li> <li><a href="http://my.safaribooksonline.com/067232704X?tocview=true">Embedding PHP</a></li> </ul> <p>I am familiar with Python. Python is a very rich language, and has a huge number of libraries available.</p>
16
2009-07-21T11:06:47Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,158,771
<p>You may also want to take a look at <a href="http://www.swig.org/" rel="nofollow">SWIG</a>, the Simplified Wrapper and Interface Generator. As one would guess, it generates much of the boiler plate code to interface your C/C++ code to the scripting engine (which can be quite cumbersome to do manually).</p> <p>It supports Python and Lua (your preferences) and many other languages. It is quite easy to generate a module that extends the scripting language. Extending <strong>and</strong> embedding, which is what you desire, takes a bit more effort.</p>
3
2009-07-21T12:03:25Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,160,486
<p>You might take a look at <a href="http://rads.stackoverflow.com/amzn/click/1931841578" rel="nofollow">Game Scripting Mastery</a>. As i am interested in the high level aspect of computer games aswell this book has been recommended to me very often. </p> <p>Unfortunately the book seems to be out of print (at least in Europe).</p>
1
2009-07-21T17:10:58Z
[ "python", "c", "scripting", "lua" ]
How to implement a scripting language into a C application?
1,158,396
<p>I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).</p> <p>How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like</p> <pre><code>interpreter-&gt;run("myscript", some_object); </code></pre> <p>How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?</p> <p>Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)</p>
14
2009-07-21T10:32:13Z
1,162,177
<p>Lua is totally optimized for exactly this sort of embedding. A good starting point is Roberto Ierusalimschy's book <em>Programming in Lua</em>; you can get the <a href="http://www.lua.org/pil/">previous edition free online</a>.</p> <p><strong>How does your script know about the properties of your C object?</strong></p> <p>Imagine for a moment your object is defined like this:</p> <pre><code>typedef struct my_object *Object; Object some_object; </code></pre> <p>What does your C code know about the properties of that object? Almost nothing, that's what. All you can do is </p> <ul> <li><p>Pass around pointers to an object, put them in data structures, etc.</p></li> <li><p>Call functions that actually know what's inside a <code>struct my_object</code>.</p></li> </ul> <p>Lua gets access to C objects in exactly the same way: indirectly through functions:</p> <ul> <li><p>You make API calls to put a <em>pointer</em> to the object on Lua's stack, from which it can go into Lua data structures, variables, or anywhere else in the Lua universe.</p></li> <li><p>You define functions that know about the object's internals, and you export those functions to Lua.</p></li> <li><p>There is a lot of stuff in the "auxiliary library" to help you. Don't overlook it!</p></li> </ul> <p>All of this is explained with crystal clarity in the third part of Roberto's book, which includes examples. One fine point is</p> <ul> <li>You have the choice of allocating the memory yourself ("light userdata") or having Lua allocate the memory. It's generally better to have Lua allocate the memory because it can then free the object automatically when it's no longer needed, and you can also associated a Lua <em>metatable</em>, which allows you (among other tricks) to allow the object to participate in standard Lua operations like looking up fields, not just function calls.</li> </ul> <p>A final note: althought it's possible to use SWIG or toLua or other tools to try to generate code to connect C and Lua, I urge you to write the code yourself, by hand. It's actually quite easy to to, and it's the only way to understand what's really going on.</p>
8
2009-07-21T22:54:44Z
[ "python", "c", "scripting", "lua" ]
Changing palette's of 8-bit .png images using python PIL
1,158,736
<p>I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)</p> <p>What I have tried (edited):</p> <pre><code>import Image, ImagePalette output = StringIO.StringIO() palette = (.....) #long palette of 768 items im = Image.open('test_palette.png') #8 bit image im.putpalette(palette) im.save(output, format='PNG') </code></pre> <p>With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster??</p>
2
2009-07-21T11:51:54Z
1,159,577
<p><code>im.palette</code> is not callable -- it's an instance of the <code>ImagePalette</code> class, in mode <code>P</code>, otherwise <code>None</code>. <code>im.putpalette(...)</code> is a method, so callable: the argument must be a sequence of 768 integers giving R, G and B value at each index.</p>
1
2009-07-21T14:32:27Z
[ "python", "image-processing", "python-imaging-library" ]
Changing palette's of 8-bit .png images using python PIL
1,158,736
<p>I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)</p> <p>What I have tried (edited):</p> <pre><code>import Image, ImagePalette output = StringIO.StringIO() palette = (.....) #long palette of 768 items im = Image.open('test_palette.png') #8 bit image im.putpalette(palette) im.save(output, format='PNG') </code></pre> <p>With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster??</p>
2
2009-07-21T11:51:54Z
1,199,832
<p>Changing palette's without decoding and (re)encoding does not seem possible. The method in the question seems best (for now). If performance is important, encoding to GIF seems a lot faster.</p>
0
2009-07-29T12:13:39Z
[ "python", "image-processing", "python-imaging-library" ]
Changing palette's of 8-bit .png images using python PIL
1,158,736
<p>I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so)</p> <p>What I have tried (edited):</p> <pre><code>import Image, ImagePalette output = StringIO.StringIO() palette = (.....) #long palette of 768 items im = Image.open('test_palette.png') #8 bit image im.putpalette(palette) im.save(output, format='PNG') </code></pre> <p>With my testimage the save function takes about 65 millis. My thought: without the decoding and encoding, it can be a lot faster??</p>
2
2009-07-21T11:51:54Z
1,214,765
<p>If you want to change just the palette, then PIL will just get in your way. Luckily, the PNG file format was designed to be easy to deal with when you only are interested in some of the data chunks. The format of the <a href="http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.PLTE" rel="nofollow">PLTE chunk</a> is just an array of RGB triples, with a CRC at the end. To change the palette on a file in-place without reading or writing the whole file:</p> <pre><code>import struct from zlib import crc32 import os # PNG file format signature pngsig = '\x89PNG\r\n\x1a\n' def swap_palette(filename): # open in read+write mode with open(filename, 'r+b') as f: f.seek(0) # verify that we have a PNG file if f.read(len(pngsig)) != pngsig: raise RuntimeError('not a png file!') while True: chunkstr = f.read(8) if len(chunkstr) != 8: # end of file break # decode the chunk header length, chtype = struct.unpack('&gt;L4s', chunkstr) # we only care about palette chunks if chtype == 'PLTE': curpos = f.tell() paldata = f.read(length) # change the 3rd palette entry to cyan paldata = paldata[:6] + '\x00\xff\xde' + paldata[9:] # go back and write the modified palette in-place f.seek(curpos) f.write(paldata) f.write(struct.pack('&gt;L', crc32(chtype+paldata)&amp;0xffffffff)) else: # skip over non-palette chunks f.seek(length+4, os.SEEK_CUR) if __name__ == '__main__': import shutil shutil.copyfile('redghost.png', 'blueghost.png') swap_palette('blueghost.png') </code></pre> <p>This code copies redghost.png over to blueghost.png and modifies the palette of blueghost.png in-place.</p> <p><img src="http://lh3.ggpht.com/%5FfJRu319XW2Q/SnNf5ff-FsI/AAAAAAAAAKs/tWXYVKaEZ3Y/s800/redghost.png" alt="red ghost" /> -> <img src="http://lh4.ggpht.com/%5FfJRu319XW2Q/SnNf5YkbzxI/AAAAAAAAAKw/MKk0Dxbe4O4/s800/blueghost.png" alt="blue ghost" /></p>
4
2009-07-31T20:39:56Z
[ "python", "image-processing", "python-imaging-library" ]
backport function modifiers to python2.1
1,159,023
<p>I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1!</p> <p>function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same functionality is offered by function modifiers but these appeared in python 2.2. cfr: <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">http://www.python.org/dev/peps/pep-0318/</a></p> <p>now some of our customers appear to be still dependent on python 2.1 (ArcGIS 9.1 ships with it and makes it not upgradable), where not even the function modifiers are available...</p> <p>I have been looking for some function modifier definitions in python 2.1, but I did not find any (I mean: working). anybody successfully solved this problem?</p> <p>to be more concrete, I need a way to run this 2.4 code in python 2.1:</p> <pre><code>Python 2.4.6 (#2, Mar 19 2009, 10:00:53) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class sic: ... def f(cls): ... print cls.__name__ ... f = classmethod(f) ... &gt;&gt;&gt; sic().f() sic &gt;&gt;&gt; sic.f() sic &gt;&gt;&gt; </code></pre>
3
2009-07-21T12:57:51Z
1,159,137
<p>If just the @classmethod need to be backported to Python 2.1.<br /> There is a <a href="http://code.activestate.com/recipes/113645/" rel="nofollow">recipe of Classmethod emulation in python2.1</a><br /> Hope this help.</p>
1
2009-07-21T13:22:43Z
[ "python", "syntax", "backport" ]
backport function modifiers to python2.1
1,159,023
<p>I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1!</p> <p>function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same functionality is offered by function modifiers but these appeared in python 2.2. cfr: <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">http://www.python.org/dev/peps/pep-0318/</a></p> <p>now some of our customers appear to be still dependent on python 2.1 (ArcGIS 9.1 ships with it and makes it not upgradable), where not even the function modifiers are available...</p> <p>I have been looking for some function modifier definitions in python 2.1, but I did not find any (I mean: working). anybody successfully solved this problem?</p> <p>to be more concrete, I need a way to run this 2.4 code in python 2.1:</p> <pre><code>Python 2.4.6 (#2, Mar 19 2009, 10:00:53) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class sic: ... def f(cls): ... print cls.__name__ ... f = classmethod(f) ... &gt;&gt;&gt; sic().f() sic &gt;&gt;&gt; sic.f() sic &gt;&gt;&gt; </code></pre>
3
2009-07-21T12:57:51Z
1,159,463
<p>Just like in my old recipe for 2.1 staticmethod:</p> <pre><code>class staticmethod: def __init__(self, thefunc): self.f = thefunc def __call__(self, *a, **k): return self.f(*a, **k) </code></pre> <p>you should be able to do a 2.1 classmethod as:</p> <pre><code>class classmethod: def __init__(self, thefunc): self.f = thefunc def __call__(self, obj, *a, **k): return self.f(obj.__class__, *a, **k) </code></pre> <p>No <code>@</code>-syntax of course, but rather the old way (like in 2.2):</p> <pre><code>class sic: def f(cls): ... f = classmethod(f) </code></pre> <p>If this doesn't work (sorry, been many many years since I had a Python 2.1 around to test), the class will need to be supplied more explicitly -- and since you call classmethod before the class object exists, it will need to be by name -- assuming a global class,</p> <pre><code>class classmethod2: def __init__(self, thefunc, clsnam): self.f = thefunc self.clsnam = clsnam def __call__(self, *a, **k): klass = globals()[self.clsnam] return self.f(klass, *a, **k) class sic2: def f(cls): ... f = classmethod2(f, 'sic2') </code></pre> <p>It's really hard to find elegant ways to get the class object (suppressing the need for self is the easy part, and what suffices for staticmethod: you just need to wrap the function into a non-function callable) since 2.1 had only legacy (old-style classes), no usable metaclasses, and thus no really good way to have sic2.f() magically get that cls.</p> <p>Since the lack of @ syntax in 2.1 inevitably requires editing of code that uses <code>@classmethod</code>, an alternative is to move the functionality (decorating some methods to be "class" ones) to right AFTER the end of the <code>class</code> statement (the advantage is that the class object does exist at that time).</p> <pre><code>class classmethod3: def __init__(self, thefunc, klass): self.f = thefunc self.klass = klass def __call__(self, *a, **k): return self.f(self.klass, *a, **k) def decorate(klass, klassmethodnames): for n in klassmethodnames: thefunc = klass.__dict__[n] setattr(klass, n, classmethod3(thefunc, klass)) class sic2: def f(cls): ... def g(self): ... def h(cls): ... decorate(sic2, ['f', 'h']) </code></pre>
2
2009-07-21T14:12:57Z
[ "python", "syntax", "backport" ]
How to Replace a column in a CSV file in Python?
1,159,524
<p>I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.</p> <p>Here's an example:</p> <p>file1: </p> <pre><code>ID, transect, 90mdist 1, a, 10, 2, b, 20, 3, c, 30, </code></pre> <p>file2: </p> <pre><code>ID, transect, 90mdist 1, a, 50 2, b, 70 3, c, 90 </code></pre> <p>basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.</p> <p>It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?</p> <p>Any help would be greatly appreciated!! </p>
5
2009-07-21T14:23:23Z
1,159,627
<p>The <a href="http://docs.python.org/library/csv.html">CSV Module</a> in the Python Library is what you need here.</p> <p>It allows you to read and write CSV files, treating lines a tuples or lists of items.</p> <p>Just read in the file with the corrected values, store the in a dictionary keyed with the line's ID.</p> <p>Then read in the second file, replacing the relevant column with the data from the dict and write out to a third file.</p> <p>Done.</p>
7
2009-07-21T14:40:21Z
[ "python", "csv" ]
How to Replace a column in a CSV file in Python?
1,159,524
<p>I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.</p> <p>Here's an example:</p> <p>file1: </p> <pre><code>ID, transect, 90mdist 1, a, 10, 2, b, 20, 3, c, 30, </code></pre> <p>file2: </p> <pre><code>ID, transect, 90mdist 1, a, 50 2, b, 70 3, c, 90 </code></pre> <p>basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.</p> <p>It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?</p> <p>Any help would be greatly appreciated!! </p>
5
2009-07-21T14:23:23Z
1,159,672
<p>Once you have your csv lists, one easy way to replace a column in one matrix with another would be to transpose the matrices, replace the row, and then transpose back your edited matrix. Here is an example with your data:</p> <pre><code>csv1 = [['1', 'a', '10'], ['2', 'b', '20'], ['3', 'c', '30']] csv2 = [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']] # transpose in Python is zip(*myData) transposedCSV1, transposedCSV2 = zip(*csv1), zip(*csv2) print transposedCSV1 &gt;&gt;&gt; [['1', '2', '3'], ['a', 'b', 'c'], ['10', '20', '30']] csv1 = transposedCSV1[:2] + [transposedCSV2[2]] print csv1 &gt;&gt;&gt; [['1', '2', '3'], ['a', 'b', 'c'], ['50', '70', '90']] csv1 = zip(*csv1) print csv1 &gt;&gt;&gt; [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']] </code></pre>
0
2009-07-21T14:49:46Z
[ "python", "csv" ]
How to Replace a column in a CSV file in Python?
1,159,524
<p>I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.</p> <p>Here's an example:</p> <p>file1: </p> <pre><code>ID, transect, 90mdist 1, a, 10, 2, b, 20, 3, c, 30, </code></pre> <p>file2: </p> <pre><code>ID, transect, 90mdist 1, a, 50 2, b, 70 3, c, 90 </code></pre> <p>basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.</p> <p>It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?</p> <p>Any help would be greatly appreciated!! </p>
5
2009-07-21T14:23:23Z
1,159,811
<p>If you're only doing this as a one-off, why bother with Python at all? Excel or OpenOffice Calc will open the two CSV files for you, then you can just cut and paste the column from one to the other. </p> <p>If the two lists of IDs are not exactly the same then a simple VB macro would do it for you.</p>
0
2009-07-21T15:09:09Z
[ "python", "csv" ]
How to Replace a column in a CSV file in Python?
1,159,524
<p>I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.</p> <p>Here's an example:</p> <p>file1: </p> <pre><code>ID, transect, 90mdist 1, a, 10, 2, b, 20, 3, c, 30, </code></pre> <p>file2: </p> <pre><code>ID, transect, 90mdist 1, a, 50 2, b, 70 3, c, 90 </code></pre> <p>basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.</p> <p>It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?</p> <p>Any help would be greatly appreciated!! </p>
5
2009-07-21T14:23:23Z
1,160,807
<p>Try this:</p> <pre><code>from __future__ import with_statement import csv def twiddle_csv(file1, file2): def mess_with_record(record): record['90mdist'] = 2 * int(record['90mdist']) + 30 with open(file1, "r") as fin: with open(file2, "w") as fout: fields = ['ID', 'transect', '90mdist'] reader = csv.DictReader(fin, fieldnames=fields) writer = csv.DictWriter(fout, fieldnames=fields) fout.write(",".join(fields) + '\n') reader.next() # Skip the column header for record in reader: mess_with_record(record) writer.writerow(record) if __name__ == '__main__': twiddle_csv('file1', 'file2') </code></pre> <p>A couple of caveats:</p> <ul> <li>DictReader seems to use the first row as data, even if it matches the fields. Call reader.next() to skip.</li> <li>Data rows cannot have trailing commas. They will be interpreted as empty columns.</li> <li>DictWriter does not appear to write out the column headers. DIY.</li> </ul>
2
2009-07-21T18:15:02Z
[ "python", "csv" ]
How to use a custom site-package using pth-files for Python 2.6?
1,159,650
<p>I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\python2.6.</p> <p>Following the instructions <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#administrator-installation" rel="nofollow">here</a>:</p> <p>I've created a pth-file in site-packages directory of the Python installation (C:\Python26\Lib\site-packages). This file contains a single line:</p> <pre><code>import os, site; site.addsitedir(os.path.expanduser('~/lib/python2.6')) </code></pre> <p>Additionally I have a pydistutils.cfg my home directory (C:\Users\wierob) that contains:</p> <pre><code>[install] install_lib = ~/lib/python2.6 install_scripts = ~/bin </code></pre> <p>When I run 'setup.py install' I get the following error message:</p> <pre><code>C:\Users\wierob\Documents\Python\workspace\rsreader&gt;setup.py install running install Checking .pth file support in C:\Users\wierob\lib\python2.6\ C:\Python26\pythonw.exe -E -c pass TEST FAILED: C:\Users\wierob\lib\python2.6\ does NOT support .pth files error: bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: C:\Users\wierob\lib\python2.6\ </code></pre> <p>So it seems that the pth-file does not work. Although, if I enter</p> <pre><code>site.addsitedir(os.path.expanduser('~/lib/python2.6')) </code></pre> <p>in an interactive python session the directory is succesfully added to sys.path.</p> <p>Any ideas? Thanks.</p>
0
2009-07-21T14:45:37Z
1,159,941
<p>According to <a href="http://docs.python.org/library/site.html" rel="nofollow">documentation</a> you should put paths to .pth file so maybe entering:</p> <pre><code>C:\Users\wierob\lib\python2.6 </code></pre> <p>will work</p>
0
2009-07-21T15:27:09Z
[ "python" ]
How to use a custom site-package using pth-files for Python 2.6?
1,159,650
<p>I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\python2.6.</p> <p>Following the instructions <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#administrator-installation" rel="nofollow">here</a>:</p> <p>I've created a pth-file in site-packages directory of the Python installation (C:\Python26\Lib\site-packages). This file contains a single line:</p> <pre><code>import os, site; site.addsitedir(os.path.expanduser('~/lib/python2.6')) </code></pre> <p>Additionally I have a pydistutils.cfg my home directory (C:\Users\wierob) that contains:</p> <pre><code>[install] install_lib = ~/lib/python2.6 install_scripts = ~/bin </code></pre> <p>When I run 'setup.py install' I get the following error message:</p> <pre><code>C:\Users\wierob\Documents\Python\workspace\rsreader&gt;setup.py install running install Checking .pth file support in C:\Users\wierob\lib\python2.6\ C:\Python26\pythonw.exe -E -c pass TEST FAILED: C:\Users\wierob\lib\python2.6\ does NOT support .pth files error: bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: C:\Users\wierob\lib\python2.6\ </code></pre> <p>So it seems that the pth-file does not work. Although, if I enter</p> <pre><code>site.addsitedir(os.path.expanduser('~/lib/python2.6')) </code></pre> <p>in an interactive python session the directory is succesfully added to sys.path.</p> <p>Any ideas? Thanks.</p>
0
2009-07-21T14:45:37Z
1,160,480
<p>The pth-file seems to be ignored if encoded in UTF-8 with BOM.</p> <p>Saving the pth-file in ANSI or UTF-8 without BOM works.</p>
1
2009-07-21T17:09:17Z
[ "python" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,708
<p>I would not do this - in my opinion these questions weaken the security, so as a user I always try to provide another semi-password as an answer - for you it would like mashed. Well, it is mashed, but that is exactly what I want to do.</p> <p>Btw. I am not sure about the fact, that you can query the answers. Since they overcome your password protection they should be handled like passwords = stored as a hash!</p> <p><strong>Edit:</strong><br> When I read <a href="http://www.newsbiscuit.com/2012/06/08/children-warned-name-of-first-pet-should-contain-8-characters-and-a-digit/">this article</a> I instantly remembered this questions ;-)</p>
38
2009-07-21T14:55:51Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,716
<p>There's no way to do this with a regex. Actually, I can't think of a reasonable way to do this at all -- where would you draw the line between suspicious and unsuspicious? I, for once, often answer the security questions with an obfuscated answer. After all, my mother's maiden name isn't the hardest thing to find out.</p>
6
2009-07-21T14:56:27Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,720
<p>You could look for patterns that don't make sense phonetically. Such as:</p> <p>'q' not followed by a 'u'.</p> <p>asdf</p> <p>qwer</p> <p>zxcv</p> <p>asdlasd</p> <p>Basically, try mashing on your own keyboard, see what you get, and plug that in your filter. Also plug in various grammatical rules. However, since it's names you're dealing with, you'll always get 'that guy' with the weird name who will cause a false positive.</p>
0
2009-07-21T14:57:02Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,726
<p>If you can find a list of letter-pair probabilities in English, you could construct an approximate probability for the word not being a "real" English word, using the least possible pairs and pairs that are not in the list. Unfortunately, if you have names or other "non-words" then you can't force them to be English words.</p>
3
2009-07-21T14:57:53Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,738
<p>You could check for a capital letter at the start.... that will get you some false positives for sure.</p> <p>A quick google gave me <a href="http://www.namebase.org/csvdump.html" rel="nofollow">this</a>, you could compare each against a name in that list.</p> <p>Obviously only works for the security question you stated.</p> <p>Have you also seen this:</p> <p><a href="http://www.techcrunch.com/2009/07/19/the-anatomy-of-the-twitter-attack/" rel="nofollow">Anatomy of the twitter attack</a></p> <p>I'm going to think hard next time i implement a security question.</p>
2
2009-07-21T14:59:17Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,741
<p>You're probably better off analyzing n-gram distribution, similar to language detection.</p> <p><a href="http://code.activestate.com/recipes/326576/" rel="nofollow">This code</a> is an example of language detection using trigrams. My guess is the keyboard smashing trigrams are pretty unique and don't appear in normal language.</p>
4
2009-07-21T14:59:57Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,757
<p>If your question is ever something related to a real, human name, this is impossible. Consider Asian names typed with roman characters; they may very well trip whatever filter you come up with, but are still perfectly legitimate.</p>
2
2009-07-21T15:02:24Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,866
<h1>The whole approach of security questions is quite flawed.</h1> <p>I have always found <strong>people put security answers weaker than the passwords they use</strong>.<br /> Security questions are just one more link in a security chain -- the weaker link! </p> <p>IMO, a better way to go would be to <strong>allow the user to request a new-password sent to their registered e-mail id</strong>. This has two advantages.</p> <ol> <li>the brute-force attempt has to locate and break the e-mail service first (and, you will never help them there -- keep the registration e-mail id very protected)</li> <li>the user of your service will always get an indication when someone tries a brute-force (they get a mail saying they tried to regenerate their password)</li> </ol> <p>If you MUST have secret questions, let them trigger a re-generated (never send the user's password, regenerate a temporary, preferably one-time forced) password dispatch to the e-mail id they registered with -- and, do not show that at all.</p> <p>Another trick is to <strong>make the secret question ITSELF their registered e-mail id</strong>.<br /> If they put it right, you send a <strong>re-generated</strong> temporary password to that e-mail id.</p>
11
2009-07-21T15:16:30Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,159,915
<p>Maybe you could check for an abundance of consonants. So for example, in your example <code>lakdsjflkaj</code> there are 2 vowels ( a ) and 9 consonants. Usually the probability of hitting a vowel when randomly pressing keys is much lower than the one of hitting a consonant. </p>
3
2009-07-21T15:22:22Z
[ "python", "regex", "fraud-prevention" ]
Regex for keyboard mashing
1,159,690
<p>When signing up for new accounts, web apps often ask for the answer to a 'security question', i.e. Dog's name, etc.</p> <p>I'd like to go through our database and look for instances where users just mashed the keyboard instead of providing a legitimate answer - this is a high indicator of an abusive/fraudulent account.</p> <p>"Mother's maiden name?" lakdsjflkaj</p> <p>Any suggestions as to how I should go about doing this?</p> <p><strong>Note: I'm not ONLY using regular expressions on these 'security question answers'</strong></p> <p>The 'answers' can be:</p> <ol> <li><p>Selected from a db using a few basic sql regexes</p></li> <li><p>Analyzed as many times as necessary using python regexes</p></li> <li><p>Compared/pruned/scored as needed</p></li> </ol> <p><strong>This is a technical question, not a philosophical one</strong> ;-)</p> <p>Thanks!</p>
5
2009-07-21T14:52:25Z
1,160,107
<p>Instead of regular expressions, why not just compare with a list of known good values? For example, compare Mother's maiden name with census data, or pet name with any of the pet name lists you can find online. For a much simpler version of this, just do a Google search for whatever is entered. Legitimate names should have plenty of results, while keyboard mashing should result in very few if any.</p> <p>As with any other method, you will still need to handle false positives.</p>
0
2009-07-21T15:52:45Z
[ "python", "regex", "fraud-prevention" ]
How do I do cross-project refactorings with ropemacs?
1,160,057
<p>I have a file structure that looks something like this:</p> <pre><code>project1_root/ tests/ ... src/ .ropeproject/ project1/ ... (project1 source code) project2_root/ tests/ ... src/ .ropeproject/ project2/ ... (project2 source) </code></pre> <p>I'm frequently switching back and forth between these two projects, and project2 depends on project1. What is the best way to set up ropemacs to handle this? It would be nice if I could facilitate cross-project refactorings (which I see mentioned in the rope library reference), but I'll be happy if I can at least keep both projects open at once without having to switch back and forth.</p>
3
2009-07-21T15:46:33Z
1,202,929
<p>The documention on ropemacs and ropemode seems to be very sparse (the homepage <a href="http://rope.sourceforge.net/ropemacs.html" rel="nofollow">http://rope.sourceforge.net/ropemacs.html</a> only point to the mercurial repos, which I checked out and read through the code), but it seems you can give a specific .ropeproject to use, and it may be guess it (ropemode/interfaces.py:_guess_project) by searching up in the directory tree for a .ropeproject directory.</p> <p>So it should be fairly easy to hack around the issue by creating a (new) .ropeproject which covers both projects if you create a specific .ropeproject for project1/ and project2/ .</p> <p>Disadvantages that I see might be that you might have to move the orignal .ropeproject dirs out of the way, and it needs some extra scripting to manage ropeproject directories over more than 2 projects.</p>
3
2009-07-29T20:45:32Z
[ "python", "emacs", "elisp", "ropemacs", "rope" ]
Python Math Library Independent of C Math Library and Platform Independent?
1,160,061
<p>Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent?</p>
3
2009-07-21T15:46:56Z
1,160,104
<p>at the bottom of <a href="http://docs.python.org/library/math.html" rel="nofollow">the page it says</a>:</p> <blockquote> <p><strong>Note:</strong> The <code>math</code> module consists mostly of thin wrappers around the platform C <code>math</code> library functions. Behavior in exceptional cases is loosely specified by the C standards, and Python inherits much of its <code>math</code>-function error-reporting behavior from the platform C implementation. As a result, the specific exceptions raised in error cases (and even whether some arguments are considered to be exceptional at all) are not defined in any useful cross-platform or cross-release way. For example, whether <code>math.log(0)</code> returns <code>-Inf</code> or raises <code>ValueError</code> or <code>OverflowError</code> isn’t defined, and in cases where <code>math.log(0)</code> raises <code>OverflowError</code>, <code>math.log(0L)</code> may raise <code>ValueError</code> instead.</p> <p>All functions return a quiet NaN if at least one of the args is <code>NaN</code>. Signaling <code>NaN</code>s raise an exception. The exception type still depends on the platform and libm implementation. It’s usually <code>ValueError</code> for <code>EDOM</code> and <code>OverflowError</code> for <code>errno ERANGE</code>.</p> <p><em>Changed in version 2.6</em>: In earlier versions of Python the outcome of an operation with <code>NaN</code> as input depended on platform and <code>libm</code> implementation.</p> </blockquote>
5
2009-07-21T15:52:11Z
[ "python" ]
Python Math Library Independent of C Math Library and Platform Independent?
1,160,061
<p>Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent?</p>
3
2009-07-21T15:46:56Z
1,162,934
<p>Python uses the C library it is linked against. On Windows, there is no 'platform C library'.. and indeed there are multiple versions of MicrosoftCRunTimeLibrarys (MSCRTs) around on any version.</p>
2
2009-07-22T03:33:02Z
[ "python" ]
redirect browser in SimpleHTTPServer.py?
1,160,329
<p>I am partially through implementing the functionality of <a href="http://hg.python.org/cpython/file/tip/Lib/SimpleHTTPServer.py" rel="nofollow">SimpleHTTPServer.py</a> in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the code". </p> <p>Why is this redirection necessary in such a scenario? </p>
2
2009-07-21T16:39:40Z
1,160,372
<p>It simplifies things to treat the trailing / as irrelevant when the user does a GET on a directory, so that (say) <code>http://www.foo.com/bar</code> and <code>http://www.foo.com/bar/</code> have exactly the same effect. Simplest (though not fastest, see Souders' books;-) is to have the former cause a redirect to the latter.</p>
3
2009-07-21T16:47:06Z
[ "python", "scheme", "racket" ]
redirect browser in SimpleHTTPServer.py?
1,160,329
<p>I am partially through implementing the functionality of <a href="http://hg.python.org/cpython/file/tip/Lib/SimpleHTTPServer.py" rel="nofollow">SimpleHTTPServer.py</a> in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the code". </p> <p>Why is this redirection necessary in such a scenario? </p>
2
2009-07-21T16:39:40Z
1,160,445
<p>Imagine you serve a page</p> <pre><code>http://mydomain.com/bla </code></pre> <p>that contains</p> <pre><code>&lt;a href="more.html"&gt;Read more...&lt;/a&gt; </code></pre> <p>On click, the user's browser would retrieve <code>http://mydomain.com/more.html</code>. Had you instead served</p> <pre><code>http://mydomain.com/bla/ </code></pre> <p>(with the same content), the browser would retrieve <code>http://mydomain.com/bla/more.html</code>. To avoid this ambiguity, the redirection appends a slash if the URL points to a directory.</p>
3
2009-07-21T17:02:28Z
[ "python", "scheme", "racket" ]
Where are Man -pages for the module MySQLdb in Python?
1,160,345
<p>I would like to get <a href="http://docs.python.org/" rel="nofollow">Python's documentation</a> for MySQLdb in Man -format such that I can read them in terminal.</p> <p><strong>Where are Man -pages for MySQLdb in Python?</strong></p>
1
2009-07-21T14:05:54Z
1,160,373
<p>You may have to convert it yourself. MySQLdb doesn't come with man pages (as far as I know) but the documentation can be accessed e.g. from the <a href="http://mysql-python.sourceforge.net/" rel="nofollow">project page</a>. The user guide has a format reasonably similar to a man page so you could probably try to work with that.</p> <p>Note that you can just download the user guide and use an HTML-aware pager like <code>less</code> to read it in the terminal.</p>
1
2009-07-21T16:47:17Z
[ "python", "mysql" ]
Where are Man -pages for the module MySQLdb in Python?
1,160,345
<p>I would like to get <a href="http://docs.python.org/" rel="nofollow">Python's documentation</a> for MySQLdb in Man -format such that I can read them in terminal.</p> <p><strong>Where are Man -pages for MySQLdb in Python?</strong></p>
1
2009-07-21T14:05:54Z
1,160,424
<p>Have you tried using pydoc? Try running the following command.</p> <pre><code>pydoc MySQLdb </code></pre> <p>That should give you something close to what you're looking for.</p>
2
2009-07-21T16:57:06Z
[ "python", "mysql" ]
models.py getting huge, what is the best way to break it up?
1,160,579
<p>Directions from my supervisor: "I want to avoid putting any logic in the <code>models.py</code>. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."</p> <p>I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.</p> <p>So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have <code>models.py</code> include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).</p> <p>So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.</p>
72
2009-07-21T17:27:11Z
1,160,607
<p>Django is designed to let you build many small applications instead of one big application.</p> <p>Inside every large application are many small applications struggling to be free.</p> <p>If your <code>models.py</code> feels big, you're doing too much. Stop. Relax. Decompose.</p> <p>Find smaller, potentially reusable small application components, or pieces. You don't have to <em>actually</em> reuse them. Just think about them as potentially reusable.</p> <p>Consider your upgrade paths and decompose applications that you might want to replace some day. You don't have to <em>actually</em> replace them, but you can consider them as a stand-alone "module" of programming that might get replaced with something cooler in the future.</p> <p>We have about a dozen applications, each <code>model.py</code> is no more than about 400 lines of code. They're all pretty focused on less than about half-dozen discrete class definitions. (These aren't hard limits, they're observations about our code.)</p> <p>We decompose early and often. </p>
49
2009-07-21T17:32:43Z
[ "python", "django", "django-models", "models" ]
models.py getting huge, what is the best way to break it up?
1,160,579
<p>Directions from my supervisor: "I want to avoid putting any logic in the <code>models.py</code>. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."</p> <p>I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.</p> <p>So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have <code>models.py</code> include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).</p> <p>So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.</p>
72
2009-07-21T17:27:11Z
1,160,735
<p>It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method <code>book.get_noun_count()</code>, that's where it belongs--I don't want to have to write "<code>get_noun_count(book)</code>", unless the method actually intrinsically belongs with some other package. (It might--for example, if I have a package for accessing Amazon's API with "<code>get_amazon_product_id(book)</code>".)</p> <p>I cringed when Django's documentation suggested putting models in a single file, and I took a few minutes from the very beginning to figure out how to split it into a proper subpackage.</p> <pre><code>site/models/__init__.py site/models/book.py </code></pre> <p><code>__init__.py</code> looks like:</p> <pre><code>from .book import Book </code></pre> <p>so I can still write "from site.models import Book".</p> <hr> <blockquote> <p>The following is only required for versions prior to Django 1.7, see <a href="https://code.djangoproject.com/ticket/3591">https://code.djangoproject.com/ticket/3591</a></p> </blockquote> <p>The only trick is that you need to explicitly set each model's application, due to a bug in Django: it assumes that the application name is the third-to-last entry in the model path. "site.models.Book" results in "site", which is correct; "site.models.book.Book" makes it think the application name is "models". This is a pretty nasty hack on Django's part; it should probably search the list of installed applications for a prefix match.</p> <pre><code>class Book(models.Model): class Meta: app_label = "site" </code></pre> <p>You could probably use a base class or metaclass to generalize this, but I haven't bothered with that yet.</p>
81
2009-07-21T18:02:38Z
[ "python", "django", "django-models", "models" ]
models.py getting huge, what is the best way to break it up?
1,160,579
<p>Directions from my supervisor: "I want to avoid putting any logic in the <code>models.py</code>. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."</p> <p>I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.</p> <p>So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have <code>models.py</code> include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).</p> <p>So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.</p>
72
2009-07-21T17:27:11Z
1,160,973
<p>I can't quite get which of many possible problems you might have. Here are some possibilities with answers:</p> <ul> <li><p>multiple models in the same file</p> <p>Put them into separate files. If there are dependencies, use import to pull in the additional models.</p></li> <li><p>extraneous logic / utility functions in models.py </p> <p>Put the extra logic into separate files. </p></li> <li><p>static methods for selecting some model instances from database</p> <p>Create a new <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/" rel="nofollow">Manager</a> in a separate file.</p></li> <li><p>methods obviously related to the model</p> <p>save, __unicode__ and get_absolute_url are examples.</p></li> </ul>
4
2009-07-21T18:42:12Z
[ "python", "django", "django-models", "models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
1,160,696
<p>There is no explicit Django support for postgreSQL schemas.</p> <blockquote> <p>When using Django (0.95), we had to add a search_path to the Django database connector for PostgreSQL, because Django didn't support specifying the schema that the tables managed by the ORM used.</p> </blockquote> <p>Taken from: </p> <p><a href="http://nxsy.org/using-postgresql-schemas-with-sqlalchemy-and-elixir" rel="nofollow">http://nxsy.org/using-postgresql-schemas-with-sqlalchemy-and-elixir</a></p> <p>The general response is to use SQLAlchemy to construct the SQL properly.</p> <p>Oh, and here's another link with some suggestions about what you can do with the Django base, extending it to try to support your scheme:</p> <p><a href="http://news.ycombinator.com/item?id=662901" rel="nofollow">http://news.ycombinator.com/item?id=662901</a></p>
2
2009-07-21T17:54:34Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
1,163,591
<p>I've had some success just saying</p> <pre><code>db_table = 'schema\".\"tablename' </code></pre> <p>in the Meta class, but that's really ugly. And I've only used it in limited scenarios - it may well break if you try something complicated. And as said earlier, it's not really supported...</p>
1
2009-07-22T07:21:09Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
1,628,855
<p>I've been using:</p> <pre><code>db_table = '"schema"."tablename"' </code></pre> <p>in the past without realising that only work for read-only operation. When you try to add new record it would fail because the sequence would be something like "schema.tablename"_column_id_seq.</p> <pre><code>db_table = 'schema\".\"tablename' </code></pre> <p>does work so far. Thanks.</p>
18
2009-10-27T05:02:51Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
1,912,906
<p>It's a bit more complicated than tricky escaping. Have a look at Ticket <a href="http://code.djangoproject.com/ticket/6148" rel="nofollow">#6148</a> in Django for perhaps a solution or at least a patch. It makes some minor changes deep in the django.db core but it will hopefully be officially included in django. After that it's just a matter of saying</p> <pre><code>db_schema = 'whatever_schema' </code></pre> <p>in the Meta class or for a global change set</p> <pre><code>DATABASE_SCHEMA = 'default_schema_name' </code></pre> <p>in settings.py</p> <p><strong>UPDATE: 2015-01-08</strong></p> <p>The corresponding issue in django has been open for 7 years and the patch there will not work any more. The correct answer to this should be...</p> <p>At the moment you can't use postgreSQL schemas in django out of the box.</p>
10
2009-12-16T07:18:15Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
15,327,663
<p>I know that this is a rather old question, but a different solution is to alter the SEARCH_PATH.</p> <h2>Example</h2> <p>Lets say you have three tables.</p> <ol> <li><code>schema1.table_name_a</code></li> <li><code>schema2.table_name_b</code></li> <li><code>table_name_c</code></li> </ol> <p>You could run the command:</p> <pre><code>SET SEARCH_PATH to public,schema1,schema2; </code></pre> <p>And refer to the tables by their table names only in django. </p> <p>See <a href="http://www.postgresql.org/docs/9.2/static/ddl-schemas.html" rel="nofollow">5.7.3. The Schema Search Path</a></p>
0
2013-03-10T21:10:36Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
18,391,525
<p>As mentioned in the following ticket: <a href="https://code.djangoproject.com/ticket/6148">https://code.djangoproject.com/ticket/6148</a>, we could set <code>search_path</code> for the django user.</p> <p>One way to achieve this is to set <code>search_path</code> via <code>psql</code> client, like</p> <pre><code>ALTER USER my_user SET SEARCH_PATH TO path; </code></pre> <p>The other way is to modify the django app, so that if we rebuild the database, django won't spit all the tables in <code>public</code> schema.</p> <p>To achieve this, you could override the <code>DatabaseWrapper</code> defined in <a href="https://github.com/django/django/blob/86f4459f9e3c035ec96578617605e93234bf2700/django/db/backends/postgresql_psycopg2/base.py"><code>django.db.backends.postgresql_psycopg2.base</code></a></p> <ol> <li><p>Create the following directory:</p> <pre><code>app/pg/ ├── __init__.py └── base.py </code></pre></li> <li><p>Here's the content of <code>base.py</code></p> <pre><code>from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper class DatabaseWrapper(DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) def _cursor(self): cursor = super(DatabaseWrapper, self)._cursor() cursor.execute('SET search_path = path') return cursor </code></pre></li> <li><p>In <code>settings.py</code>, add the following database configuration:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'app.pg', 'NAME': 'db', 'USER': 'user', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } </code></pre></li> </ol>
7
2013-08-22T21:58:38Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
28,452,103
<p>Maybe this will help.</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=your_schema' }, 'NAME': 'your_name', 'USER': 'your_user', 'PASSWORD': 'your_password', 'HOST': '127.0.0.1', 'PORT': '5432', } } </code></pre> <p>I get the answer from the following link: <a href="http://blog.amvtek.com/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/">http://blog.amvtek.com/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/</a></p>
7
2015-02-11T10:35:48Z
[ "python", "django", "postgresql", "django-models" ]
How to use schemas in Django?
1,160,598
<p>I whould like to use postgreSQL schemas with django, how can I do this?</p>
11
2009-07-21T17:30:53Z
35,471,197
<p>I just developed a package for this problem: <a href="https://github.com/ryannjohnson/django-schemas" rel="nofollow">https://github.com/ryannjohnson/django-schemas</a>.</p> <p>After some configuration, you can simply call <code>set_db()</code> on your models:</p> <pre><code>model_cls = UserModel.set_db(db='db_alias', schema='schema_name') user_on_schema = model_cls.objects.get(pk=1) </code></pre> <p>The package uses techniques described in <a href="http://stackoverflow.com/a/1628855/5307109">http://stackoverflow.com/a/1628855/5307109</a> and <a href="http://stackoverflow.com/a/18391525/5307109">http://stackoverflow.com/a/18391525/5307109</a>, then wraps them for use with Django models.</p>
3
2016-02-18T01:38:51Z
[ "python", "django", "postgresql", "django-models" ]
Django - last insert id
1,161,149
<p>I can't get the last insert id like I usually do and I'm not sure why.</p> <p>In my view:</p> <pre><code>comment = Comments( ...) comment.save() comment.id #returns None </code></pre> <p>In my Model:</p> <pre><code>class Comments(models.Model): id = models.IntegerField(primary_key=True) </code></pre> <p>Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working.</p>
5
2009-07-21T19:12:17Z
1,161,210
<p>Do you want to specifically set a new IntegerField called id as the primary key? Because Django already does that for you for free...</p> <p>That being said, have you tried removing the id field from your comment model?</p>
1
2009-07-21T19:23:48Z
[ "python", "django" ]
Django - last insert id
1,161,149
<p>I can't get the last insert id like I usually do and I'm not sure why.</p> <p>In my view:</p> <pre><code>comment = Comments( ...) comment.save() comment.id #returns None </code></pre> <p>In my Model:</p> <pre><code>class Comments(models.Model): id = models.IntegerField(primary_key=True) </code></pre> <p>Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working.</p>
5
2009-07-21T19:12:17Z
1,161,217
<p>Are you setting the value of the <code>id</code> field in the <code>comment = Comments( ...) </code> line? If not, why are you defining the field instead of just letting Django take care of the primary key with an AutoField?</p> <p>If you specify in IntegerField as a primary key as you're doing in the example Django won't automatically assign it a value.</p>
7
2009-07-21T19:25:00Z
[ "python", "django" ]
Django - last insert id
1,161,149
<p>I can't get the last insert id like I usually do and I'm not sure why.</p> <p>In my view:</p> <pre><code>comment = Comments( ...) comment.save() comment.id #returns None </code></pre> <p>In my Model:</p> <pre><code>class Comments(models.Model): id = models.IntegerField(primary_key=True) </code></pre> <p>Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working.</p>
5
2009-07-21T19:12:17Z
1,161,262
<p>To define an automatically set primary key use AutoField:</p> <pre><code>class Comments(models.Model): id = models.AutoField(primary_key=True) </code></pre>
2
2009-07-21T19:31:16Z
[ "python", "django" ]
Django - last insert id
1,161,149
<p>I can't get the last insert id like I usually do and I'm not sure why.</p> <p>In my view:</p> <pre><code>comment = Comments( ...) comment.save() comment.id #returns None </code></pre> <p>In my Model:</p> <pre><code>class Comments(models.Model): id = models.IntegerField(primary_key=True) </code></pre> <p>Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working.</p>
5
2009-07-21T19:12:17Z
19,051,158
<p>Simply do </p> <pre><code>c = Comment.object.latest() </code></pre> <p>That should return you the last inserted comment</p> <pre><code>c.pk 12 #last comment saved. </code></pre>
2
2013-09-27T12:47:00Z
[ "python", "django" ]
win32api.dll Will Not Install
1,161,178
<p>I am trying to start a Buildbot Buildslave on a Windows XP virtual machine:</p> <pre><code>python buildbot start . ImportError: No module named win32api. </code></pre> <p>Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (<a href="http://www.dll-files.com/unzip.php" rel="nofollow">http://www.dll-files.com/unzip.php</a>). When I try to run regvr32 win32api.dll, it tells me that the specified module could not be found.</p> <p>tl;dr - Where do I put win32api.dll so Windows will install it? Am I trying to use the wrong file? (using python version 2.6)</p>
2
2009-07-21T19:18:02Z
1,162,307
<p>win32api belongs <a href="http://sourceforge.net/projects/pywin32/files/">Python for Windows extensions</a>, Aka Pywn32.<br /> have u installed it?</p>
5
2009-07-21T23:33:03Z
[ "python", "windows", "dll", "twisted", "buildbot" ]
win32api.dll Will Not Install
1,161,178
<p>I am trying to start a Buildbot Buildslave on a Windows XP virtual machine:</p> <pre><code>python buildbot start . ImportError: No module named win32api. </code></pre> <p>Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (<a href="http://www.dll-files.com/unzip.php" rel="nofollow">http://www.dll-files.com/unzip.php</a>). When I try to run regvr32 win32api.dll, it tells me that the specified module could not be found.</p> <p>tl;dr - Where do I put win32api.dll so Windows will install it? Am I trying to use the wrong file? (using python version 2.6)</p>
2
2009-07-21T19:18:02Z
1,162,900
<p>Install ActivePython (<a href="http://www.activestate.com/activepython/" rel="nofollow">http://www.activestate.com/activepython/</a>) - it's a Python distro that comes bundled with the Windows dlls. It's what everyone else does.</p>
0
2009-07-22T03:14:36Z
[ "python", "windows", "dll", "twisted", "buildbot" ]
how do I read everything currently in a subprocess.stdout pipe and then return?
1,161,580
<p>I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.</p> <p>How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.</p>
1
2009-07-21T20:28:25Z
1,161,599
<p>You should loop using read() against a set number of characters. </p>
2
2009-07-21T20:32:09Z
[ "python", "linux" ]
how do I read everything currently in a subprocess.stdout pipe and then return?
1,161,580
<p>I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.</p> <p>How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.</p>
1
2009-07-21T20:28:25Z
1,161,615
<p>Someone else appears to have had the same problem, you can see the related discussion <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python">here</a>. </p> <p>If you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using</p> <pre><code>import fcntl, os fcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK) </code></pre> <p>after which you can loop using read() until you encounter a newline character (if you want to process the output one line at a time).</p>
4
2009-07-21T20:36:52Z
[ "python", "linux" ]
Add data to Django form class using modelformset_factory
1,161,618
<p>I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code...</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=160) class Item(models.Model): category = models.ForeignKey('Category') name = models.CharField(max_length=160) weight = models.IntegerField(default=0) class Meta: ordering = ('category','weight','name') class BudgetValue(models.Model): value = models.IntegerField() plan = models.ForeignKey('Plan') item = models.ForeignKey('Item') </code></pre> <p>I use the modelformset_factory to create a formset of budgetvalue forms for a particular plan. What I'd like is item name and category name for each BudgetValue. When I iterate through the forms each one will be labeled properly. </p> <pre><code>class BudgetValueForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput()) plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput()) category = "" &lt; assign dynamically on form creation &gt; item = "" &lt; assign dynamically on form creation &gt; class Meta: model = BudgetValue fields = ('item','plan','value') </code></pre> <p>What I started out with is just creating a dictionary of budgetvalue.item.category.name, budgetvalue.item.name, and the form for each budget value. This gets passed to the template and I render it as I intended. I'm assuming that the ordering of the forms in the formset and the querset used to genererate the formset keep the budgetvalues in the same order and the dictionary is created correctly. That is the budgetvalue.item.name is associated with the correct form. This scares me and I'm thinking there has to be a better way. Any help would be greatly appreciated.</p>
0
2009-07-21T20:37:45Z
1,161,982
<p>Well, I figured out the answer to my own question. I've overridden the init class on the form and accessed the instance of the model form. Works exactly as I wanted and it was easy.</p> <pre><code>class BudgetValueForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput()) plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): super(BudgetValueForm, self).__init__(*args, **kwargs) self.itemname = self.instance.item.name self.categoryname = self.instance.item.category.name class Meta: model = BudgetValue fields = ('item','plan','value') </code></pre>
3
2009-07-21T21:59:38Z
[ "python", "django", "django-forms" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,161,679
<p>It'll depend on the project and the target audience.</p> <p>If you're building an open source application/plug-in/library, stick with the PEP guidelines.</p> <p>If this is a project for your company, stick with the company conventions, or something similar.</p> <p>If this is your own personal project, then use what ever convention is fluid and easy for you to use.</p> <p>I hope this makes sense.</p>
2
2009-07-21T20:52:16Z
[ "python", "naming-conventions", "notation" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,161,691
<blockquote> <p>(<strong>Almost every Python programmer will say</strong> it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me)</p> </blockquote> <p>FTFY.</p> <p>Seriously though, it will help you but confuse and annoy other Python programmers that try to read your code.</p> <p>This also isn't as necessary because of how Python itself works. For example you would <em>never</em> need your "mVariable" form because it's obvious in Python:</p> <pre><code>class Example(object): def__init__(self): self.my_member_var = "Hello" def sample(self): print self.my_member_var e = Example() e.sample() print e.my_member_var </code></pre> <p>No matter how you access a member variable (using <code>self.foo</code> or <code>myinstance.foo</code>) it's always clear that it's a member.</p> <p>The other cases might not be so painfully obvious, but if your code isn't simple enough that a reader can keep in mind "the 'names' variable is a parameter" while reading a function you're probably doing something wrong.</p>
8
2009-07-21T20:55:07Z
[ "python", "naming-conventions", "notation" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,161,696
<p>I violate PEP8 in my code. I use: </p> <ul> <li>lowercaseCamelCase for methods and functions</li> <li>_prefixedWithUnderscoreLowercaseCamelCase for "private" methods</li> <li>underscore_spaced for variables (any)</li> <li>_prefixed_with_underscore_variables for "private" self variables (attributes)</li> <li>CapitalizedCamelCase for classes and modules (although I am moving to lowercasedmodules)</li> </ul> <p>I never liked hungarian notation. A variable name should be easy and concise, provide sufficient information to be clear where (in which scope) it's used and what is its purpose, easy to read, concerned about the meaning of what it refers to, not its technical mumbo-jumbo (eg. type).</p> <p>The reason behind my violations are due to practical considerations, and previous experience.</p> <ul> <li>in C++ and Java, it's tradition to have CapitalizedCamel for classes and lowercaseCamel for member functions.</li> <li>I worked on a codebase where the underscore prefix was used to indicate private but not that much private. We did not want to mess with the python name mangling (double underscore). This gave us the chance to violate a bit the formalities and peek the internal class state during unit testing.</li> </ul>
4
2009-07-21T20:55:35Z
[ "python", "naming-conventions", "notation" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,162,250
<p>Use PEP-8. It is almost universal in the Python world.</p>
6
2009-07-21T23:16:28Z
[ "python", "naming-conventions", "notation" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,162,282
<p>There exists a handy pep-8 compliance script you can run against your code:</p> <p><a href="http://github.com/cburroughs/pep8.py/tree/master" rel="nofollow">http://github.com/cburroughs/pep8.py/tree/master</a></p>
3
2009-07-21T23:26:15Z
[ "python", "naming-conventions", "notation" ]
Python Notation?
1,161,658
<p>I've just started using Python and I was thinking about which notation I should use. I've read the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).</p> <p>In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)</p> <p>I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet. </p> <p>I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.</p>
2
2009-07-21T20:47:24Z
1,165,299
<p>You should simply be consistent with your naming conventions in your own code. However, if you intend to release your code to other developers you should stick to PEP-8.</p> <p>For example the 4 spaces vs. 1 tab is a big deal when you have a collaborative project. People submitting code to a source repository with tabs requires developers to be constantly arguing over whitespace issues (which in Python is a BIG deal).</p> <p>Python and all languages have preferred conventions. You should learn them.</p> <p>Java likes mixedCaseStuff.</p> <p>C likes szHungarianNotation.</p> <p>Python prefers stuff_with_underscores.</p> <p>You can write Java code with_python_type_function_names.<br /> You can write Python code with javaStyleMixedCaseFunctionNamesThatAreSupposedToBeReallyExplict</p> <p>as long as your consistant :p</p>
1
2009-07-22T13:36:39Z
[ "python", "naming-conventions", "notation" ]
Google Wave Sandbox
1,161,660
<p>Is anyone developing robots and/or gadgets for <a href="http://wave.google.com/" rel="nofollow">Google Wave</a>? </p> <p>I have been a part of the sandbox development for a few days and I was interested in seeing what others have thought about the <a href="http://code.google.com/apis/wave/" rel="nofollow">Google Wave APIs</a>. </p> <p>I was also wondering what everyone has been working on. Please share your opinions and comments!</p>
3
2009-07-21T20:47:59Z
1,161,806
<p>Go to <a href="http://code.google.com/apis/wave/" rel="nofollow">Google Wave developers</a> and read the blogs, forums and all your questions will be answered including a recent post for a gallery of Wave apps. You will also find other developers to play in the sandbox with.</p>
2
2009-07-21T21:16:17Z
[ "java", "python", "google-app-engine", "google-wave" ]
Google Wave Sandbox
1,161,660
<p>Is anyone developing robots and/or gadgets for <a href="http://wave.google.com/" rel="nofollow">Google Wave</a>? </p> <p>I have been a part of the sandbox development for a few days and I was interested in seeing what others have thought about the <a href="http://code.google.com/apis/wave/" rel="nofollow">Google Wave APIs</a>. </p> <p>I was also wondering what everyone has been working on. Please share your opinions and comments!</p>
3
2009-07-21T20:47:59Z
1,174,595
<p>I haven't tried the gadgets, but from the little I've looked at them, they seem pretty straight-forward. They're implemented in a template-ish way and you can easily keep states in them, allowing more complex things such as <a href="http://en.wiktionary.org/wiki/RSVP" rel="nofollow">RSVP</a> lists and even games.</p> <p>Robots are what I'm most interested in, and well, all I can say is that they're really easy to develop! Like barely any effort at all! Heck, I'll code one for you right here:</p> <pre><code>import waveapi.events import waveapi.robot def OnBlipSubmitted(properties, context): # Get the blip that was just submitted. blip = context.GetBlipById(properties['blipId']) # Respond to the blip (i.e. create a child blip) blip.CreateChild().GetDocument().SetText('That\'s so funny!') def OnRobotAdded(properties, context): # Add a message to the end of the wavelet. wavelet = context.GetRootWavelet() wavelet.CreateBlip().GetDocument().SetText('Heeeeey everybody!') if __name__ == '__main__': # Register the robot. bot = waveapi.robot.Robot( 'The Annoying Bot', image_url='http://example.com/annoying-image.gif', version='1.0', profile_url='http://example.com/') bot.RegisterHandler(waveapi.events.BLIP_SUBMITTED, OnBlipSubmitted) bot.RegisterHandler(waveapi.events.WAVELET_SELF_ADDED, OnRobotAdded) bot.Run() </code></pre> <p>Right now I'm working on a Google App Engine project that's going to be a collaborative text adventure game. For this game I made a bot that lets you play it on Wave. It uses Wave's threading of blips to let you branch the game at any point etc. For more info, have a look at <a href="http://code.google.com/p/multifarce" rel="nofollow">the Google Code project page</a> (scroll down a little bit for a screenshot.)</p>
2
2009-07-23T21:27:10Z
[ "java", "python", "google-app-engine", "google-wave" ]
Google Wave Sandbox
1,161,660
<p>Is anyone developing robots and/or gadgets for <a href="http://wave.google.com/" rel="nofollow">Google Wave</a>? </p> <p>I have been a part of the sandbox development for a few days and I was interested in seeing what others have thought about the <a href="http://code.google.com/apis/wave/" rel="nofollow">Google Wave APIs</a>. </p> <p>I was also wondering what everyone has been working on. Please share your opinions and comments!</p>
3
2009-07-21T20:47:59Z
1,175,722
<p>I have been working on Gadgets, using the <a href="http://code.google.com/apis/wave/guide.html" rel="nofollow">Wave API</a>. It's pretty easy to work with. For the most part, you can use javascript inside an XML file. You just need to have the proper tags for the XML file. Below is a sample of what a Gadget would look like, this particular gadget retrieves the top headlines from <a href="http://slashdot.org/" rel="nofollow">Slashdot</a> and displays them at the top of the Wave. You can learn more about Gadgets <a href="http://wave-samples-gallery.appspot.com/about%5Fapp?app%5Fid=18006" rel="nofollow">here</a> and <a href="http://www.m1cr0sux0r.com/2009/07/wave-part-deux.html" rel="nofollow">here</a>. <img src="http://www.m1cr0sux0r.com/xml.jpg" alt="alt text" /></p>
2
2009-07-24T04:11:59Z
[ "java", "python", "google-app-engine", "google-wave" ]
Why can't I import this Zope component in a Python 2.4 virtualenv?
1,161,670
<p>I'm trying to install Plone 3.3rc4 with plone.app.blob and repoze but nothing I've tried has worked so far. For one attempt I've pip-installed repoze.zope2, Plone, and plone.app.blob into a virtualenv. I have <a href="http://svn.zope.org/Zope/trunk/lib/python/DocumentTemplate/?rev=96249" rel="nofollow">this version of DocumentTemplate</a> in the virtualenv's site-packages directory and I'm trying to get it running in RHEL5.</p> <p>For some reason when I try to run <code>paster serve etc/zope2.ini</code> in this environment way Python gives the message <code>ImportError: No module named DT_Util</code>? <code>DT_Util.py</code> exists in the directory, <code>__init__.py</code> is there too, and the C module it depends on is there. I suspect there's some circular dependency or failure when importing the C extension. Of course this module would work in a normal Zope install...</p> <pre><code>&gt;&gt;&gt; import DocumentTemplate Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "DocumentTemplate/__init__.py", line 21, in ? File ".../lib/python2.4/site-packages/DocumentTemplate/DocumentTemplate.py", line 112, in ? from DT_String import String, File File ".../lib/python2.4/site-packages/DocumentTemplate/DT_String.py", line 19, in ? from DocumentTemplate.DT_Util import ParseError, InstanceDict ImportError: No module named DT_Util </code></pre>
-1
2009-07-21T20:50:12Z
1,164,126
<p>I must say I doubt DocumentTemplate from Zope will work standalone. You are welcome to try though. :-)</p> <p>Note that <a href="https://github.com/zopefoundation/DocumentTemplate/blob/master/src/DocumentTemplate/DT_Util.py#L32-L34" rel="nofollow">DT_Util imports C extensions</a>:</p> <pre><code>from DocumentTemplate.cDocumentTemplate import InstanceDict, TemplateDict from DocumentTemplate.cDocumentTemplate import render_blocks, safe_callable from DocumentTemplate.cDocumentTemplate import join_unicode </code></pre> <p>You'll need to make sure those are compiled. My guess is that importing the <code>cDocumentTemplate</code> module fails and thus the import of <code>DT_Util</code> fails.</p>
1
2009-07-22T09:36:17Z
[ "python", "virtualenv", "zope" ]
python docstrings
1,161,810
<p>ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this:</p> <pre><code>Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:--&gt;./apache_logs.py File "./apache_logs.py", line 17 print __doc__ ^ SyntaxError: invalid syntax #!/usr/local/bin/python """ USAGE: apache_logs.py """ import sys import os if __name__ == "__main__": if not len(sys.argv) &gt; 1: print __doc__ sys.exit(1) infile_name = sys.argv[1] </code></pre> <p>I know it must be something really stupid but I've googled and read the documentation without finding anything. The docs all seem to state that what I've coded should work.</p> <p>Many thanks in advance for your help!!</p>
1
2009-07-21T21:17:43Z
1,161,821
<p>What version of Python do you have? In Python 3, <a href="http://docs.python.org/3.1/whatsnew/3.0.html#print-is-a-function"><code>print</code> was changed to work like a function</a> rather than a statement, i.e. <code>print('Hello World')</code> instead of <code>print 'Hello World'</code></p> <p>I can recommend you to keep using Python 2.6 unless you're doing some brand new production development. Python 3 is still pretty new.</p>
5
2009-07-21T21:19:57Z
[ "python", "syntax-error" ]
Retrieving Raw_Input from a system ran script
1,161,959
<p>I'm using the OS.System command to call a python script.</p> <p>example:</p> <pre><code>OS.System("call jython script.py") </code></pre> <p>In the script I'm calling, the following command is present:</p> <pre><code>x = raw_input("Waiting for input") </code></pre> <p>If I run script.py from the command line I can input data no problem, if I run it via the automated approach I get an EOFError. I've read in the past that this happens because the system expects a computer to be running it and therefore could never receive input data in this way.</p> <p>So the question is how can I get python to wait for user input while being run in an automated way?</p>
0
2009-07-21T21:52:35Z
1,162,165
<p>Your question is a bit unclear. What is the process calling your Python script and how is it being run? If the parent process has no standard input, the child won't have it either.</p>
0
2009-07-21T22:52:15Z
[ "python", "jython" ]
Retrieving Raw_Input from a system ran script
1,161,959
<p>I'm using the OS.System command to call a python script.</p> <p>example:</p> <pre><code>OS.System("call jython script.py") </code></pre> <p>In the script I'm calling, the following command is present:</p> <pre><code>x = raw_input("Waiting for input") </code></pre> <p>If I run script.py from the command line I can input data no problem, if I run it via the automated approach I get an EOFError. I've read in the past that this happens because the system expects a computer to be running it and therefore could never receive input data in this way.</p> <p>So the question is how can I get python to wait for user input while being run in an automated way?</p>
0
2009-07-21T21:52:35Z
1,162,243
<p>The problem is the way you run your child script. Since you use os.system() the script's input channel is closed immediately and the raw_input() prompt hits an EOF (end of file). And even if that didn't happen, you wouldn't have a way to actually send some input text to the child as I assume you'd want given that you are using raw_input().</p> <p>You should use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess module</a> instead.</p> <pre><code>import subprocess from subprocess import PIPE p = subprocess.Popen(["jython", "script.py"], stdin=PIPE, stdout=PIPE) print p.communicate("My input") </code></pre>
2
2009-07-21T23:14:22Z
[ "python", "jython" ]
limit output from a sort method
1,162,142
<p>if my views code is:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>what is the argument that will limit the result to 50 tags?</p> <p>I'm assuming this:</p> <pre><code>.... limit=50) </code></pre> <p>is incorrect.</p> <p>more complete code follows:</p> <pre><code>videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') arttags = list(chain(videoarttags, audioarttags, conarttags)) arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>how do incorporate – </p> <pre><code>itertools.islice(sorted(...),50) </code></pre>
0
2009-07-21T22:46:32Z
1,162,159
<p>You'll probably find that a slice works for you:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)[:50] </code></pre>
1
2009-07-21T22:50:21Z
[ "python", "django", "itertools" ]
limit output from a sort method
1,162,142
<p>if my views code is:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>what is the argument that will limit the result to 50 tags?</p> <p>I'm assuming this:</p> <pre><code>.... limit=50) </code></pre> <p>is incorrect.</p> <p>more complete code follows:</p> <pre><code>videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') arttags = list(chain(videoarttags, audioarttags, conarttags)) arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>how do incorporate – </p> <pre><code>itertools.islice(sorted(...),50) </code></pre>
0
2009-07-21T22:46:32Z
1,162,213
<p>The general idea of what you want is a <code>take</code>, I believe. From <a href="http://docs.python.org/library/itertools.html" rel="nofollow">the itertools documentation</a>:</p> <pre><code>def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) </code></pre>
0
2009-07-21T23:08:20Z
[ "python", "django", "itertools" ]
limit output from a sort method
1,162,142
<p>if my views code is:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>what is the argument that will limit the result to 50 tags?</p> <p>I'm assuming this:</p> <pre><code>.... limit=50) </code></pre> <p>is incorrect.</p> <p>more complete code follows:</p> <pre><code>videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') arttags = list(chain(videoarttags, audioarttags, conarttags)) arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>how do incorporate – </p> <pre><code>itertools.islice(sorted(...),50) </code></pre>
0
2009-07-21T22:46:32Z
1,162,595
<p>what about <a href="http://docs.python.org/library/heapq.html#heapq.nlargest" rel="nofollow">heapq.nlargest</a>:<br /> Return a list with the n largest elements from the dataset defined by iterable.key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: <code>key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]</code></p> <pre><code>&gt;&gt;&gt; from heapq import nlargest &gt;&gt;&gt; data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] &gt;&gt;&gt; nlargest(3, data) [9, 8, 7] </code></pre>
2
2009-07-22T01:26:51Z
[ "python", "django", "itertools" ]
limit output from a sort method
1,162,142
<p>if my views code is:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>what is the argument that will limit the result to 50 tags?</p> <p>I'm assuming this:</p> <pre><code>.... limit=50) </code></pre> <p>is incorrect.</p> <p>more complete code follows:</p> <pre><code>videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') arttags = list(chain(videoarttags, audioarttags, conarttags)) arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>how do incorporate – </p> <pre><code>itertools.islice(sorted(...),50) </code></pre>
0
2009-07-21T22:46:32Z
1,181,142
<p>I think I was pretty much barking up the wrong tree. What I was trying to accomplish was actually very simple using a template filter (slice) which I didn't know I could do. The code was as follows:</p> <pre><code>{% for arttag in arttags|slice:":50" %} </code></pre> <p>Yes, I feel pretty stupid, but I'm glad I got it done :-) </p>
0
2009-07-25T03:48:12Z
[ "python", "django", "itertools" ]
limit output from a sort method
1,162,142
<p>if my views code is:</p> <pre><code>arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>what is the argument that will limit the result to 50 tags?</p> <p>I'm assuming this:</p> <pre><code>.... limit=50) </code></pre> <p>is incorrect.</p> <p>more complete code follows:</p> <pre><code>videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art') audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art') conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art') arttags = list(chain(videoarttags, audioarttags, conarttags)) arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True) </code></pre> <p>how do incorporate – </p> <pre><code>itertools.islice(sorted(...),50) </code></pre>
0
2009-07-21T22:46:32Z
1,181,199
<p>You might also want to add [:50] to each of the <code>objects.order_by.filter</code> calls. Doing that will mean you only ever have to sort 150 items in-memory in Python instead of possibly many more.</p>
0
2009-07-25T04:25:50Z
[ "python", "django", "itertools" ]
How can I get DNS records for a domain in python?
1,162,230
<p>How do I get the DNS records for a zone in python? I'm looking for data similar to the output of <code>dig</code>.</p>
7
2009-07-21T23:11:15Z
1,162,308
<p>Try the <code>dnspython</code> library:</p> <ul> <li><a href="http://www.dnspython.org/">http://www.dnspython.org/</a></li> </ul> <p>You can see some examples here:</p> <ul> <li><a href="http://www.dnspython.org/examples.html">http://www.dnspython.org/examples.html</a></li> </ul>
9
2009-07-21T23:33:22Z
[ "python", "dns" ]
How can I get DNS records for a domain in python?
1,162,230
<p>How do I get the DNS records for a zone in python? I'm looking for data similar to the output of <code>dig</code>.</p>
7
2009-07-21T23:11:15Z
1,164,260
<p>Your other option is <a href="http://pydns.sourceforge.net/" rel="nofollow">pydns</a> but the last release is as of 2008 so dnspython is probably a better bet (I only mention this in case dnspython doesn't float your boat).</p>
2
2009-07-22T10:08:20Z
[ "python", "dns" ]
How can I get DNS records for a domain in python?
1,162,230
<p>How do I get the DNS records for a zone in python? I'm looking for data similar to the output of <code>dig</code>.</p>
7
2009-07-21T23:11:15Z
24,532,658
<p>A simple example from <a href="http://c0deman.wordpress.com/2014/06/17/find-nameservers-of-domain-name-python/" rel="nofollow">http://c0deman.wordpress.com/2014/06/17/find-nameservers-of-domain-name-python/</a> :</p> <pre><code>import dns.resolver domain = 'google.com' answers = dns.resolver.query(domain,'NS') for server in answers: print server </code></pre>
0
2014-07-02T13:38:34Z
[ "python", "dns" ]
What is the benefit of private name mangling in Python?
1,162,234
<p>Python provides <a href="http://docs.python.org/reference/expressions.html#atom-identifiers">private name mangling</a> for class methods and attributes.</p> <p>Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?</p> <p><strong>Please describe a use case where Python name mangling should be used, if any?</strong></p> <p>Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.</p>
10
2009-07-21T23:11:31Z
1,162,241
<p>The name mangling is there to prevent accidental external attribute access. Mostly, it's there to make sure that there are no name clashes.</p>
0
2009-07-21T23:14:04Z
[ "python", "private-members", "name-mangling" ]
What is the benefit of private name mangling in Python?
1,162,234
<p>Python provides <a href="http://docs.python.org/reference/expressions.html#atom-identifiers">private name mangling</a> for class methods and attributes.</p> <p>Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?</p> <p><strong>Please describe a use case where Python name mangling should be used, if any?</strong></p> <p>Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.</p>
10
2009-07-21T23:11:31Z
1,162,248
<p>It's partly to prevent accidental <em>internal</em> attribute access. Here's an example:</p> <p>In your code, which is a library:</p> <pre><code>class YourClass: def __init__(self): self.__thing = 1 # Your private member, not part of your API </code></pre> <p>In my code, in which I'm inheriting from your library class:</p> <pre><code>class MyClass(YourClass): def __init__(self): # ... self.__thing = "My thing" # My private member; the name is a coincidence </code></pre> <p>Without private name mangling, my accidental reuse of your name would break your library.</p>
22
2009-07-21T23:16:00Z
[ "python", "private-members", "name-mangling" ]
What is the benefit of private name mangling in Python?
1,162,234
<p>Python provides <a href="http://docs.python.org/reference/expressions.html#atom-identifiers">private name mangling</a> for class methods and attributes.</p> <p>Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?</p> <p><strong>Please describe a use case where Python name mangling should be used, if any?</strong></p> <p>Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.</p>
10
2009-07-21T23:11:31Z
1,162,251
<p>From <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>:</p> <blockquote> <p>If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. <strong>This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.</strong></p> </blockquote> <p>(Emphasis added)</p>
15
2009-07-21T23:16:38Z
[ "python", "private-members", "name-mangling" ]
Easiest way to pop up interactive Python console?
1,162,277
<p>My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python.</p> <p>I've found several similar questions which pointed me to code.InteractiveConsole and IPython. However neither of those seem to do anything when I call them - the call appears to complete okay, but nothing visible happens, presumably because my Python instance isn't outputting anywhere I can see. </p> <p>It was pretty optimistic to think that they'd just magically pop up a new window for me, but it would be nice if I could get that to happen. So, does anybody know if there is an easy way to achieve this (or something similar), or do I have to roll my own dialog and pass the input to Python and display output myself?</p> <p>Thanks :)</p>
2
2009-07-21T23:25:18Z
1,162,325
<p>What have you tried with IPython? Is it the snippets from the documentation:</p> <ul> <li><a href="http://ipython.scipy.org/doc/manual/html/interactive/reference.html#embedding-ipython" rel="nofollow">Embedding IPython</a> (IPython docs)</li> </ul> <p>How about some of the code samples from elsewhere:</p> <ul> <li><a href="http://ipython0.wordpress.com/2008/05/15/embedding-ipython-in-gui-apps-is-trivial/" rel="nofollow">Embedding IPython in GUI apps is trivial</a></li> <li><a href="http://ipython.scipy.org/moin/Cookbook/EmbeddingInGTK" rel="nofollow">Embedding IPython in a PyGTK application</a></li> </ul> <p>I know I fooled around with this a while back and the samples seemed to work, but then I never got a chance to go any further for other reasons.</p>
1
2009-07-21T23:39:11Z
[ "python", "debugging" ]
Easiest way to pop up interactive Python console?
1,162,277
<p>My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python.</p> <p>I've found several similar questions which pointed me to code.InteractiveConsole and IPython. However neither of those seem to do anything when I call them - the call appears to complete okay, but nothing visible happens, presumably because my Python instance isn't outputting anywhere I can see. </p> <p>It was pretty optimistic to think that they'd just magically pop up a new window for me, but it would be nice if I could get that to happen. So, does anybody know if there is an easy way to achieve this (or something similar), or do I have to roll my own dialog and pass the input to Python and display output myself?</p> <p>Thanks :)</p>
2
2009-07-21T23:25:18Z
1,162,883
<p>I know this isn't what you're asking, but when I've wanted to debug compiled Python (using Py2Exe), I've been very pleased to realize that I can add breakpoints to the exe and it will actually stop there when I start the executable from a console window. Simply add:</p> <pre><code>import pdb pdb.set_trace() </code></pre> <p>where you want your code to stop, and you'll have yourself an interactive debugging session with a compiled executable. Python is awesome that way :)</p>
1
2009-07-22T03:08:27Z
[ "python", "debugging" ]
What's the right way to use Unicode metadata in setup.py?
1,162,338
<p>I was writing a setup.py for a Python package using setuptools and wanted to include a non-ASCII character in the long_description field:</p> <pre><code>#!/usr/bin/env python from setuptools import setup setup(... long_description=u"...", # in real code this value is read from a text file ...) </code></pre> <p>Unfortunately, passing a unicode object to setup() breaks either of the following two commands with a UnicodeEncodeError</p> <pre> python setup.py --long-description | rst2html python setup.py upload </pre> <p>If I use a raw UTF-8 string for the long_description field, then the following command breaks with a UnicodeDecodeError:</p> <pre> python setup.py register </pre> <p>I generally release software by running 'python setup.py sdist register upload', which means ugly hacks that look into sys.argv and pass the right object type are right out.</p> <p>In the end I gave up and implemented a different ugly hack:</p> <pre><code>class UltraMagicString(object): # Catch-22: # - if I return Unicode, python setup.py --long-description as well # as python setup.py upload fail with a UnicodeEncodeError # - if I return UTF-8 string, python setup.py sdist register # fails with an UnicodeDecodeError def __init__(self, value): self.value = value def __str__(self): return self.value def __unicode__(self): return self.value.decode('UTF-8') def __add__(self, other): return UltraMagicString(self.value + str(other)) def split(self, *args, **kw): return self.value.split(*args, **kw) ... setup(... long_description=UltraMagicString("..."), ...) </code></pre> <p>Isn't there a better way?</p>
7
2009-07-21T23:43:53Z
1,178,429
<pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name="fudz", description="fudzily", version="0.1", long_description=u"bläh bläh".encode("UTF-8"), # in real code this value is read from a text file py_modules=["fudz"], author="David Fraser", author_email="davidf@sjsoft.com", url="http://en.wikipedia.org/wiki/Fudz", ) </code></pre> <p>I'm testing with the above code - there is no error from --long-description, only from rst2html; upload seems to work OK (although I cancel actually uploading) and register asks me for my username which I don't have. But the traceback in your comment is helpful - it's the automatic conversion to <code>unicode</code> in the <code>register</code> command that causes the problem.</p> <p>See <a href="http://blog.ianbicking.org/illusive-setdefaultencoding.html" rel="nofollow">the illusive setdefaultencoding</a> for more information on this - basically you want the default encoding in Python to be able to convert your encoded string back to unicode, but it's tricky to set this up. In this case I think it's worth the effort:</p> <pre><code>import sys reload(sys).setdefaultencoding("UTF-8") </code></pre> <p>Or even to be correct you can get it from the <code>locale</code> - there's code commented out in <code>/usr/lib/python2.6/site.py</code> that you can find that does this but I'll leave that discussion for now.</p>
3
2009-07-24T15:29:14Z
[ "python", "unicode", "setuptools" ]
What's the right way to use Unicode metadata in setup.py?
1,162,338
<p>I was writing a setup.py for a Python package using setuptools and wanted to include a non-ASCII character in the long_description field:</p> <pre><code>#!/usr/bin/env python from setuptools import setup setup(... long_description=u"...", # in real code this value is read from a text file ...) </code></pre> <p>Unfortunately, passing a unicode object to setup() breaks either of the following two commands with a UnicodeEncodeError</p> <pre> python setup.py --long-description | rst2html python setup.py upload </pre> <p>If I use a raw UTF-8 string for the long_description field, then the following command breaks with a UnicodeDecodeError:</p> <pre> python setup.py register </pre> <p>I generally release software by running 'python setup.py sdist register upload', which means ugly hacks that look into sys.argv and pass the right object type are right out.</p> <p>In the end I gave up and implemented a different ugly hack:</p> <pre><code>class UltraMagicString(object): # Catch-22: # - if I return Unicode, python setup.py --long-description as well # as python setup.py upload fail with a UnicodeEncodeError # - if I return UTF-8 string, python setup.py sdist register # fails with an UnicodeDecodeError def __init__(self, value): self.value = value def __str__(self): return self.value def __unicode__(self): return self.value.decode('UTF-8') def __add__(self, other): return UltraMagicString(self.value + str(other)) def split(self, *args, **kw): return self.value.split(*args, **kw) ... setup(... long_description=UltraMagicString("..."), ...) </code></pre> <p>Isn't there a better way?</p>
7
2009-07-21T23:43:53Z
1,182,262
<p>You need to change your unicode long description <code>u"bläh bläh bläh"</code> to a normal string <code>"bläh bläh bläh"</code> and add an encoding header as the second line of your file:</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 ... ... </code></pre> <p>Obviously, you need to save the file with UTF-8 encoding, too.</p>
1
2009-07-25T15:02:47Z
[ "python", "unicode", "setuptools" ]
What's the right way to use Unicode metadata in setup.py?
1,162,338
<p>I was writing a setup.py for a Python package using setuptools and wanted to include a non-ASCII character in the long_description field:</p> <pre><code>#!/usr/bin/env python from setuptools import setup setup(... long_description=u"...", # in real code this value is read from a text file ...) </code></pre> <p>Unfortunately, passing a unicode object to setup() breaks either of the following two commands with a UnicodeEncodeError</p> <pre> python setup.py --long-description | rst2html python setup.py upload </pre> <p>If I use a raw UTF-8 string for the long_description field, then the following command breaks with a UnicodeDecodeError:</p> <pre> python setup.py register </pre> <p>I generally release software by running 'python setup.py sdist register upload', which means ugly hacks that look into sys.argv and pass the right object type are right out.</p> <p>In the end I gave up and implemented a different ugly hack:</p> <pre><code>class UltraMagicString(object): # Catch-22: # - if I return Unicode, python setup.py --long-description as well # as python setup.py upload fail with a UnicodeEncodeError # - if I return UTF-8 string, python setup.py sdist register # fails with an UnicodeDecodeError def __init__(self, value): self.value = value def __str__(self): return self.value def __unicode__(self): return self.value.decode('UTF-8') def __add__(self, other): return UltraMagicString(self.value + str(other)) def split(self, *args, **kw): return self.value.split(*args, **kw) ... setup(... long_description=UltraMagicString("..."), ...) </code></pre> <p>Isn't there a better way?</p>
7
2009-07-21T23:43:53Z
1,439,009
<p>It is apparently a distutils bug that has been fixed in python 2.6: <a href="http://mail.python.org/pipermail/distutils-sig/2009-September/013275.html" rel="nofollow">http://mail.python.org/pipermail/distutils-sig/2009-September/013275.html</a></p> <p>Tarek suggests to patch post_to_server. The patch should pre-process all values in the "data" argument and turn them into unicode and then call the original method. See <a href="http://mail.python.org/pipermail/distutils-sig/2009-September/013277.html" rel="nofollow">http://mail.python.org/pipermail/distutils-sig/2009-September/013277.html</a></p>
5
2009-09-17T13:51:15Z
[ "python", "unicode", "setuptools" ]
Python Hangs When Importing Swig Generated Wrapper
1,162,461
<p>Python is 'hanging' when I try to import a c++ shared library into the windows version of python 2.5 and I have no clue why.</p> <p>On Linux, everything works fine. We can compile all of our C++ code, generate swig wrapper classes. They compile and can be imported and used in either python 2.5 or 2.6. Now, we are trying to port the code to Windows using Cygwin.</p> <p>We are able to compile each of the C++ libraries to shared dlls using -mno-cygwin, which removes the dependency on cygwin1.dll. Essentially this causes the gcc target to be MinGW instead of Cygwin, enabling the resulting binaries to be run in Windows without any dependency on Cygwin. Moreover, each of these shared libraries can be linked into c++ binaries and run successfully.</p> <p>Once this one done, we used swig to generate wrappers for each of the shared libraries. These wrappers are generated, compiled, and linked without problem.</p> <p>The next step then, was to import the generated python wrapper into python. We are able to import all but two of our libraries. For the two that do not work, when we try to import either the .py or .pyd files into Windows python (the version compiled with Visual C++), python hangs. We cannot kill python with ctrl+c or ctrl+d, the only recourse is to kill it via task manager. If we attach gdb to the python process and print a stack trace, we mostly get garbage, nothing useful.</p> <p>Next, we tried ifdef'ing out blocks of code in the *.i files and recreating the swig wrappers. This process at least allowed me to import the libraries into Windows python, but the problem is we had to comment out too many functions which are necessary for the software to run. In general, there were three types of functions that had to be commented out: static functions, virtual const functions, and regular public functions that were NOT declared as const. This is reproducible too, if we uncomment any one of these functions, then the import hangs again.</p> <p>Next, we tried extracting the functions into a simple hello world program, generate a swig wrapper and import them into python. This worked. We copied functions exactly from the header files. They work in the very small test program, but not in the larger shared library. We are building them the exact same way.</p> <p>So, any ideas about why this is happening or even just better debugging techniques would be very helpful.</p> <p>These work fine on Linux with gcc 3 and 4 and python 2.5 and 2.6. On Windows, this is the software I am using: gcc 3.4.4 swig 1.39 (Windows binaries from swig.org) python 2.5.4 (Windows binaries and includes/libs from python.org)</p> <p>These are the commands I am using for building the simple hello world program (the full library uses the same options, it's just a lot longer because of extra -I, -L, and -l options)</p> <p>swig -c++ -python -o test_wrap.cc test.i</p> <p>gcc -c -mno-cygwin test.cc</p> <p>gcc -c -mno-cygwin test_wrap.cc -I/usr/python25/include</p> <p>dlltool --export-all --output-def _test.def test.o</p> <p>gcc -mno-cygwin -shared -s test_wrap.o test.o -L/usr/python25/libs -lpython25 -lstdc++ -o _TestModule.pyd</p> <p>Thanks, AJ</p>
3
2009-07-22T00:29:21Z
1,196,976
<p>A technique I've used is to insert a "hard" breakpoint (<code>__asm int 3</code>) in the module init function. Then either run it through a debugger or just run it and let the windows debugger pop when the interrupt is called.</p> <p>You can download a nice windows debugger from Microsoft <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow">here</a>.</p>
1
2009-07-28T21:54:50Z
[ "python", "cygwin", "swig" ]
lxml retrieving odd items with cssselector
1,162,580
<p>In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with</p> <pre><code>Selection = html.cssselect(".item") </code></pre> <p>I'd like it to select all the odd items, like this in javascript using JQuery</p> <pre><code>Selection = $(".item:odd"); </code></pre> <p>Trying that verbatim I get the following error </p> <p>lxml.cssselect.ExpressionError: The psuedo-class Symbol(u'odd', 6) is unknown</p> <p>I know this would be trivial to implement on my own, I was wondering if this is supported by lxml natively.</p>
1
2009-07-22T01:20:03Z
1,215,852
<p>The "odd" and "even" features are part of a selector named "nth-child()"; take a look at the CSS selector specification for more details:</p> <pre><code>http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#nth-child-pseudo </code></pre> <p>Therefore, you should be able to get exactly the behavior you want (and it works for me with CSSSelector here) with:</p> <pre><code>".item:nth-child(odd)" </code></pre>
1
2009-08-01T04:43:27Z
[ "python", "css", "html-parsing", "lxml" ]
Iterate over a string 2 (or n) characters at a time in Python
1,162,592
<p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p> <p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p> <pre><code># Might not be exact, but you get the idea, use the step # parameter of range() and slicing to grab 2 chars at a time s = "+c-R+D-e" for op, code in (s[i:i+2] for i in range(0, len(s), 2)): print op, code </code></pre> <p>Are there some better/cleaner ways to do this?</p>
21
2009-07-22T01:24:53Z
1,162,600
<pre><code>&gt;&gt;&gt; s = "+c-R+D-e" &gt;&gt;&gt; s '+c-R+D-e' &gt;&gt;&gt; s[::2] '+-+-' &gt;&gt;&gt; </code></pre>
1
2009-07-22T01:28:28Z
[ "python", "iteration" ]
Iterate over a string 2 (or n) characters at a time in Python
1,162,592
<p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p> <p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p> <pre><code># Might not be exact, but you get the idea, use the step # parameter of range() and slicing to grab 2 chars at a time s = "+c-R+D-e" for op, code in (s[i:i+2] for i in range(0, len(s), 2)): print op, code </code></pre> <p>Are there some better/cleaner ways to do this?</p>
21
2009-07-22T01:24:53Z
1,162,624
<p>Maybe this would be cleaner?</p> <pre><code>s = "+c-R+D-e" for i in xrange(0, len(s), 2): op, code = s[i:i+2] print op, code </code></pre> <p>You could perhaps write a generator to do what you want, maybe that would be more pythonic :)</p>
12
2009-07-22T01:35:35Z
[ "python", "iteration" ]
Iterate over a string 2 (or n) characters at a time in Python
1,162,592
<p>Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like <code>"+c-R+D-E"</code> (there are a few extra letters).</p> <p>I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.</p> <pre><code># Might not be exact, but you get the idea, use the step # parameter of range() and slicing to grab 2 chars at a time s = "+c-R+D-e" for op, code in (s[i:i+2] for i in range(0, len(s), 2)): print op, code </code></pre> <p>Are there some better/cleaner ways to do this?</p>
21
2009-07-22T01:24:53Z
1,162,627
<pre><code>from itertools import izip_longest def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return izip_longest(*args, fillvalue=fillvalue) def main(): s = "+c-R+D-e" for item in grouper(s, 2): print ' '.join(item) if __name__ == "__main__": main() ##output ##+ c ##- R ##+ D ##- e </code></pre> <p><code>izip_longest</code> requires Python 2.6( or higher). If on Python 2.4 or 2.5, use the definition for <code>izip_longest</code> from the <a href="http://docs.python.org/library/itertools.html#itertools.izip%5Flongest" rel="nofollow">document</a> or change the grouper function to:</p> <pre><code>from itertools import izip, chain, repeat def grouper(iterable, n, padvalue=None): return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) </code></pre>
4
2009-07-22T01:36:58Z
[ "python", "iteration" ]