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 |
|---|---|---|---|---|---|---|---|---|---|
Embedded objects in MS Office documents using Python? | 1,559,709 | <p>How could I create embedded objects in an MS office document using Python? </p>
<p>I don't need anything fancy, just what one used to do in the first version of OLE: doing a copy-paste from my application into e.g. MS Word should give me an object embedded in the Word document, which I can then double-click to open a copy of my application and edit the object.</p>
<p>Can this be done from a Python/PyQt application (perhaps using pythoncom?) Are there any simple examples of this that can get me started?</p>
| 1 | 2009-10-13T11:43:31Z | 1,559,740 | <p>OLE compound documents enable users working within a single application to manipulate data written in various formats and derived from multiple sources. A compound document object is essentially a COM object that can be embedded in, or linked to, an existing document. As a COM object, a compound document object exposes the <a href="http://msdn.microsoft.com/en-us/library/ms680509%28VS.85%29.aspx" rel="nofollow"><code>IUnknown</code></a> interface, through which clients can obtain pointers to its other interfaces, including several, such as <a href="http://msdn.microsoft.com/en-us/library/dd542709%28VS.85%29.aspx" rel="nofollow"><code>IOleObject</code></a>, <a href="http://msdn.microsoft.com/en-us/library/ms682297%28VS.85%29.aspx" rel="nofollow"><code>IOleLink</code></a>, and <a href="http://msdn.microsoft.com/en-us/library/ms691318%28VS.85%29.aspx" rel="nofollow"><code>IViewObject2</code></a>, that provide special features unique to compound document objects. </p>
<p>You'll use <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">pywin32 extensions</a>. This <a href="http://www.boddie.org.uk/python/COM.html" rel="nofollow">COM tutorial</a> can get you started (I hope). Most info you need will come from <a href="http://msdn.microsoft.com/en-us/library/ms680573%28VS.85%29.aspx" rel="nofollow">microsoft</a> itself. There's a <a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html" rel="nofollow">book on the subject</a>.</p>
| 1 | 2009-10-13T11:50:40Z | [
"python",
"windows",
"com",
"ms-office",
"ole"
] |
"undefined symbol: TLSv1_method" error when import psycopg2 | 1,560,066 | <p>I installed psycopg2 by "easy_install psycopg2" on CentOS 5.3, no error was reported, but when I tried "import psycopg2", I got :</p>
<pre><code>exceptions.ImportError: /usr/lib/python2.4/site-packages/psycopg2-2.0.9-py2.4-linux-i686.egg/psycopg2/_psycopg.so: undefined symbol: TLSv1_method
</code></pre>
<p>What might cause the problem?</p>
| 0 | 2009-10-13T12:57:20Z | 1,560,204 | <p>You might have to <code>yum install openssl</code>?</p>
| 1 | 2009-10-13T13:19:05Z | [
"python"
] |
Optparse library - callback action while storing arg | 1,560,092 | <p>My code:</p>
<pre><code>def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs")
(options, args) = parser.parse_args()
if x == 0:
print usage, " (-h or --help for help)"
print options.test
</code></pre>
<p>if i had:
<em>script</em> -p hello</p>
<p>i need options.test to print out the argument as type string</p>
| 0 | 2009-10-13T13:00:29Z | 1,560,316 | <p>Ended up passing the argument to the function that is being called.</p>
| 0 | 2009-10-13T13:37:46Z | [
"python",
"ironpython",
"optparse"
] |
Optparse library - callback action while storing arg | 1,560,092 | <p>My code:</p>
<pre><code>def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-p", "--pending", action="callback", callback=pending, type="string", dest="test", help="View Pending Jobs")
(options, args) = parser.parse_args()
if x == 0:
print usage, " (-h or --help for help)"
print options.test
</code></pre>
<p>if i had:
<em>script</em> -p hello</p>
<p>i need options.test to print out the argument as type string</p>
| 0 | 2009-10-13T13:00:29Z | 1,560,544 | <p>The arguments are available through <em>sys.argv</em>.</p>
| 0 | 2009-10-13T14:20:29Z | [
"python",
"ironpython",
"optparse"
] |
What is a good example of an __eq__ method for a collection class? | 1,560,245 | <p>I'm working on a collection class that I want to create an <code>__eq__</code> method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.</p>
<p>What would really help me the most is a good example. Are there any pure Python implementations of an <code>__eq__</code> method either in the standard library or in any third-party libraries?</p>
| 6 | 2009-10-13T13:26:53Z | 1,560,279 | <p>Parts are hard. Parts should be simple delegation.</p>
<pre><code>def __eq__( self, other ):
if len(self) != len(other):
# Can we continue? If so, what rule applies? Pad shorter? Truncate longer?
else:
return all( self[i] == other[i] for i in range(len(self)) )
</code></pre>
| 7 | 2009-10-13T13:31:03Z | [
"python",
"api",
"collections",
"equality"
] |
What is a good example of an __eq__ method for a collection class? | 1,560,245 | <p>I'm working on a collection class that I want to create an <code>__eq__</code> method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.</p>
<p>What would really help me the most is a good example. Are there any pure Python implementations of an <code>__eq__</code> method either in the standard library or in any third-party libraries?</p>
| 6 | 2009-10-13T13:26:53Z | 1,569,134 | <p>Take a look at "collections.py". The latest version (from version control) implements an OrderedDict with an __eq__. There's also an __eq__ in sets.py</p>
| 1 | 2009-10-14T21:33:03Z | [
"python",
"api",
"collections",
"equality"
] |
How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)? | 1,560,424 | <p>Is there an easy way to get the (x,y) values of a contour line that was plotted like this:</p>
<pre><code>import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,2,3,4]
m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]]
cs = plt.contour(x,y,m, [9.5])
plt.show()
</code></pre>
<p>Cheers, Philipp</p>
| 11 | 2009-10-13T13:57:47Z | 1,560,735 | <p>Look at the collections property of the returned ContourSet. In particular the get_paths() method of the first collection returns paired points making up each line segment.</p>
<pre><code>cs.collections[0].get_paths()
</code></pre>
| 8 | 2009-10-13T14:52:11Z | [
"python",
"matplotlib",
"data-analysis"
] |
Equivalent of GetCursorPos() in Mac's Carbon | 1,560,472 | <p><b>Background</b>
We're porting our PythonOgre-based games to Mac, and the publishers demand ability for mouse to leave the window. On Windows, we're going around OIS (Object-oriented Input System) for the purposes of mouse control; that is, we don't let OIS keep the mouse captured inside window borders, and then track the mouse cursor in screen coordinates using <code>GetCursorPos()</code> Win32 API.</p>
<p>We cannot trivially modify the Ogre3d loop -- it would require at least a rebuild of the library, plus a rebuild of the wrapper which can easily take about an entire workday on our build machine. Theoretically we could modify OIS but we're on tight schedule so, for same reasons, we'd rather not unnecessarily play with it either.</p>
<p><b>Question</b>
What is the Carbon API for obtaining screen-space mouse cursor coordinate, equivalent to Windows API <code>GetCursorPos()</code>? </p>
| 1 | 2009-10-13T14:07:08Z | 1,560,610 | <p>I believe that what you are looking for is GetMouse(). You can find an example in Apple's <a href="http://developer.apple.com/mac/library/samplecode/UIElementInspector/listing2.html" rel="nofollow">UIElementInspector sample code</a>. This is in Obj-C not Python, though.</p>
<p>EDIT: HIGetMousePosition() is the preferred method, according to NSD.</p>
| 1 | 2009-10-13T14:31:43Z | [
"python",
"osx",
"mouse",
"carbon"
] |
Histogram in matplotlib gets cropped at top | 1,560,734 | <p>I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where <code>plt</code> is <code>matplotlib.pyplot</code> and <code>fig</code> is <code>matplotlib.figure</code>:</p>
<pre><code>plt.hist(grades, bins=min(20, maxScore), range=(0,maxScore), figure=fig.Figure(figsize=(3,2), dpi=150))
plt.xlabel("Raw Score")
plt.ylabel("Count")
plt.title("Raw Score Histogram")
plt.savefig(histogramFile)
</code></pre>
<p>The problem appears in a situation like the following. I might have 300 elements in <code>grades</code>, 3 of the bins have more than 20 elements in them, and the rest less than 20. The ones with more than 20 will have their tops cut off and the y-axis will only go up to 20. This doesn't always happen though: a different 300 elements in <code>grades</code> with a similar distribution might render correctly, with the y-axis scaling to fit within the <code>figsize</code>. Also note that the x-axis always comes out right.</p>
<p>What can I do to get the y-axis to scale correctly and produce bars that fit within the image?</p>
| 1 | 2009-10-13T14:52:01Z | 1,560,816 | <p>File a bug report to the matplotlib's developers, and ask them to write a test case on it.</p>
<p>You should be able to set the y axis with the ylim function: is it what you are asking for? Can you show a screenshot of your problem?</p>
| 1 | 2009-10-13T15:02:52Z | [
"python",
"matplotlib",
"python-imaging-library"
] |
Python - Overwriting __getattribute__ for an instance? | 1,560,853 | <p>This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:</p>
<pre><code>def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
</code></pre>
<p>which worked very well for me; but now I'm trying to overwrite an instance's <code>__getattribute__()</code> function, which doesn't work for me for the reason the method seems to be</p>
<pre><code><type 'method-wrapper'>
</code></pre>
<p>Is it possible to do anything about that? I couldn't find any decent Python documentation on <code>method-wrapper</code>.</p>
| 3 | 2009-10-13T15:08:50Z | 1,560,948 | <p>There are a couple of methods which you can't overwrite and <code>__getattribute__()</code> is one of them.</p>
| 3 | 2009-10-13T15:24:02Z | [
"python",
"django"
] |
Python - Overwriting __getattribute__ for an instance? | 1,560,853 | <p>This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:</p>
<pre><code>def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
</code></pre>
<p>which worked very well for me; but now I'm trying to overwrite an instance's <code>__getattribute__()</code> function, which doesn't work for me for the reason the method seems to be</p>
<pre><code><type 'method-wrapper'>
</code></pre>
<p>Is it possible to do anything about that? I couldn't find any decent Python documentation on <code>method-wrapper</code>.</p>
| 3 | 2009-10-13T15:08:50Z | 1,560,957 | <p>I believe <em>method-wrapper</em> is a wrapper around a method written in C. </p>
| 1 | 2009-10-13T15:25:34Z | [
"python",
"django"
] |
Python - Overwriting __getattribute__ for an instance? | 1,560,853 | <p>This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:</p>
<pre><code>def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
</code></pre>
<p>which worked very well for me; but now I'm trying to overwrite an instance's <code>__getattribute__()</code> function, which doesn't work for me for the reason the method seems to be</p>
<pre><code><type 'method-wrapper'>
</code></pre>
<p>Is it possible to do anything about that? I couldn't find any decent Python documentation on <code>method-wrapper</code>.</p>
| 3 | 2009-10-13T15:08:50Z | 1,561,244 | <p>You want to override the attribute lookup algorithm on an per instance basis? Without knowing why you are trying to do this, I would hazard a guess that there is a cleaner less convoluted way of doing what you need to do. If you really need to then as Aaron said, you'll need to install a redirecting <code>__getattribute__</code> handler on the class because Python looks up special methods only on the class, ignoring anything defined on the instance.</p>
<p>You also have to be extra careful about not getting into infinite recursion:</p>
<pre><code>class FunkyAttributeLookup(object):
def __getattribute__(self, key):
try:
# Lookup the per instance function via objects attribute lookup
# to avoid infinite recursion.
getter = object.__getattribute__(self, 'instance_getattribute')
return getter(key)
except AttributeError:
return object.__getattribute__(self, key)
f = FunkyAttributeLookup()
f.instance_getattribute = lambda attr: attr.upper()
print(f.foo) # FOO
</code></pre>
<p>Also, if you are overriding methods on your instance, you don't need to instanciate the method object yourself, you can either use the descriptor protocol on functions that generates the methods or just curry the self argument.</p>
<pre><code> #descriptor protocol
self.method_to_overwrite = my_method.__get__(self, type(self))
# or curry
from functools import partial
self.method_to_overwrite = partial(my_method, self)
</code></pre>
| 5 | 2009-10-13T16:09:21Z | [
"python",
"django"
] |
Python - Overwriting __getattribute__ for an instance? | 1,560,853 | <p>This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:</p>
<pre><code>def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
</code></pre>
<p>which worked very well for me; but now I'm trying to overwrite an instance's <code>__getattribute__()</code> function, which doesn't work for me for the reason the method seems to be</p>
<pre><code><type 'method-wrapper'>
</code></pre>
<p>Is it possible to do anything about that? I couldn't find any decent Python documentation on <code>method-wrapper</code>.</p>
| 3 | 2009-10-13T15:08:50Z | 1,562,632 | <p>You can't overwrite special methods at instance level. <a href="http://docs.python.org/reference/datamodel.html#new-style-special-lookup" rel="nofollow">For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an objectâs type, not in the objectâs instance dictionary</a>.</p>
| 3 | 2009-10-13T20:06:17Z | [
"python",
"django"
] |
Playing sounds with python and changing their tone during playback? | 1,561,104 | <p>Is there a way to do this? Also, I need this to work with pygame, since I want audio in my game. I'm asking this because I didn't see any tone change function in pygame.. Anyone knows?</p>
<h3>Update:</h3>
<p>I need to do something like the noise of a car accelerating. I don't really know if it is timbre or tone.</p>
| 1 | 2009-10-13T15:44:54Z | 1,561,314 | <p>Well, it depends on how you're doing your sounds: I'm not sure if this is possible with pygame, but SDL (which pygame is based off of) lets you have a callback to retrieve data for the sound buffer, and it's possible to change the frequency of the sine wave (or whatever) to get different tones in the callback, given that you generate the sound there.</p>
<p>If you're using a pre-rendered tone, or sound file, then you'll probably have to resample it to get it to play at different frequencies, although it'd be difficult to keep the same length. If you're talking about changing the timbre of the sound, then that's a whole different ballpark...</p>
<p>Also, it depends on how fast the sound needs to change: if you can accept a little lag in response, you could probably generate a few short sounds, and play/loop them as necessary. I'm not sure how constant replaying of sounds would impact performance/the overall audio quality, though: you'd have to make sure the ends of all the waveform ends smoothly transition to the beginning of the next one (maybe).</p>
| 1 | 2009-10-13T16:17:23Z | [
"python",
"pygame",
"pitch"
] |
Python Reverse Generator | 1,561,214 | <p>I'm looking for a way to reverse a generator object. I know how to reverse sequences:</p>
<pre><code>foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))
</code></pre>
<p>But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence can be used)?</p>
| 8 | 2009-10-13T16:04:24Z | 1,561,275 | <p><code>reversed(list(input_generator))</code> is probably the easiest way.</p>
<p>There's no way to get a generator's values in "reverse" order without gathering all of them into a sequence first, because generating the second item could very well rely on the first having been generated.</p>
| 6 | 2009-10-13T16:13:18Z | [
"python",
"generator",
"reverse"
] |
Python Reverse Generator | 1,561,214 | <p>I'm looking for a way to reverse a generator object. I know how to reverse sequences:</p>
<pre><code>foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))
</code></pre>
<p>But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence can be used)?</p>
| 8 | 2009-10-13T16:04:24Z | 1,561,276 | <p>You have to walk through the generator anyway to get the first item so you might as well make a list. Try</p>
<pre><code>reversed(list(g))
</code></pre>
<p>where <code>g</code> is a generator.</p>
<pre><code>reversed(tuple(g))
</code></pre>
<p>would work as well (I didn't check to see if there is a significant difference in performance).</p>
| 4 | 2009-10-13T16:13:19Z | [
"python",
"generator",
"reverse"
] |
Python Reverse Generator | 1,561,214 | <p>I'm looking for a way to reverse a generator object. I know how to reverse sequences:</p>
<pre><code>foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))
</code></pre>
<p>But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence can be used)?</p>
| 8 | 2009-10-13T16:04:24Z | 1,561,303 | <p>You cannot reverse a generator in any generic way except by casting it to a sequence and creating an iterator from that. Later terms of a generator cannot necessarily be known until the earlier ones have been calculated. </p>
<p>Even worse, you can't know if your generator will ever hit a StopIteration exception until you hit it, so there's no way to know what there will even be a first term in your sequence.</p>
<p>The best you could do would be to write a reversed_iterator function:</p>
<pre><code>def reversed_iterator(iter):
return reversed(list(iter))
</code></pre>
<p>EDIT: You could also, of course, replace reversed in this with your imap based iterative version, to save one list creation.</p>
| 15 | 2009-10-13T16:15:58Z | [
"python",
"generator",
"reverse"
] |
Structuring a program. Classes and functions in Python | 1,561,282 | <p>I'm writing a program that uses genetic techniques to evolve equations.
I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function.
The function 'mainfunc' calls two or three methods defined in the Utility class.
They instantiate other classes and call various methods.
I think what I want is all of it in one NAMESPACE.
So I've instantiated some (maybe it should be all) of the classes inside the function 'mainfunc'.
I call the Utility method 'generate()'. If we were to follow it's chain of execution
it would involve all of the classes and methods in the code.</p>
<p>Now, the equations are stored in a tree. Each time a tree is generated, mutated or cross
bred, the nodes need to be given a new key so they can be accessed from a dictionary attribute of the tree. The class 'KeySeq' generates these keys.</p>
<p>In Parallel Python, I'm going to send multiple instances of 'mainfunc' to the 'submit' function of PP. Each has to be able to access 'KeySeq'. It would be nice if they all accessed the same instance of KeySeq so that none of the nodes on the returned trees had the same key, but I could get around that if necessary.</p>
<p>So: my question is about stuffing EVERYTHING into mainfunc.
Thanks
(Edit) If I don't include everything in mainfunc, I have to try to tell PP about dependent functions, etc by passing various arguements in various places. I'm trying to avoid that.</p>
<p>(late Edit) if ks.next() is called inside the 'generate() function, it returns the error 'NameError: global name 'ks' is not defined' </p>
<pre><code>class KeySeq:
"Iterator to produce sequential \
integers for keys in dict"
def __init__(self, data = 0):
self.data = data
def __iter__(self):
return self
def next(self):
self.data = self.data + 1
return self.data
class One:
'some code'
class Two:
'some code'
class Three:
'some code'
class Utilities:
def generate(x):
'___________'
def obfiscate(y):
'___________'
def ruminate(z):
'__________'
def mainfunc(z):
ks = KeySeq()
one = One()
two = Two()
three = Three()
utilities = Utilities()
list_of_interest = utilities.generate(5)
return list_of_interest
result = mainfunc(params)
</code></pre>
| 3 | 2009-10-13T16:14:10Z | 1,561,414 | <p>It's fine to structure your program that way. A lot of command line utilities follow the same pattern:</p>
<pre><code>#imports, utilities, other functions
def main(arg):
#...
if __name__ == '__main__':
import sys
main(sys.argv[1])
</code></pre>
<p>That way you can call the <code>main</code> function from another module by importing it, or you can run it from the command line.</p>
| 3 | 2009-10-13T16:34:00Z | [
"python",
"parallel-python"
] |
Structuring a program. Classes and functions in Python | 1,561,282 | <p>I'm writing a program that uses genetic techniques to evolve equations.
I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function.
The function 'mainfunc' calls two or three methods defined in the Utility class.
They instantiate other classes and call various methods.
I think what I want is all of it in one NAMESPACE.
So I've instantiated some (maybe it should be all) of the classes inside the function 'mainfunc'.
I call the Utility method 'generate()'. If we were to follow it's chain of execution
it would involve all of the classes and methods in the code.</p>
<p>Now, the equations are stored in a tree. Each time a tree is generated, mutated or cross
bred, the nodes need to be given a new key so they can be accessed from a dictionary attribute of the tree. The class 'KeySeq' generates these keys.</p>
<p>In Parallel Python, I'm going to send multiple instances of 'mainfunc' to the 'submit' function of PP. Each has to be able to access 'KeySeq'. It would be nice if they all accessed the same instance of KeySeq so that none of the nodes on the returned trees had the same key, but I could get around that if necessary.</p>
<p>So: my question is about stuffing EVERYTHING into mainfunc.
Thanks
(Edit) If I don't include everything in mainfunc, I have to try to tell PP about dependent functions, etc by passing various arguements in various places. I'm trying to avoid that.</p>
<p>(late Edit) if ks.next() is called inside the 'generate() function, it returns the error 'NameError: global name 'ks' is not defined' </p>
<pre><code>class KeySeq:
"Iterator to produce sequential \
integers for keys in dict"
def __init__(self, data = 0):
self.data = data
def __iter__(self):
return self
def next(self):
self.data = self.data + 1
return self.data
class One:
'some code'
class Two:
'some code'
class Three:
'some code'
class Utilities:
def generate(x):
'___________'
def obfiscate(y):
'___________'
def ruminate(z):
'__________'
def mainfunc(z):
ks = KeySeq()
one = One()
two = Two()
three = Three()
utilities = Utilities()
list_of_interest = utilities.generate(5)
return list_of_interest
result = mainfunc(params)
</code></pre>
| 3 | 2009-10-13T16:14:10Z | 1,563,685 | <p>If you want all of the instances of <code>mainfunc</code> to use the same <code>KeySeq</code> object, you can use the default parameter value trick:</p>
<pre><code>def mainfunc(ks=KeySeq()):
key = ks.next()
</code></pre>
<p>As long as you don't actually pass in a value of <code>ks</code>, all calls to <code>mainfunc</code> will use the instance of <code>KeySeq</code> that was created when the function was defined.</p>
<p>Here's why, in case you don't know: A function is an object. It has attributes. One of its attributes is named <code>func_defaults</code>; it's a tuple containing the default values of all of the arguments in its signature that have defaults. When you call a function and don't provide a value for an argument that has a default, the function retrieves the value from <code>func_defaults</code>. So when you call <code>mainfunc</code> without providing a value for <code>ks</code>, it gets the <code>KeySeq()</code> instance out of the <code>func_defaults</code> tuple. Which, for that instance of <code>mainfunc</code>, is always the same <code>KeySeq</code> instance.</p>
<p>Now, you say that you're going to send "multiple instances of <code>mainfunc</code> to the <code>submit</code> function of PP." Do you really mean multiple instances? If so, the mechanism I'm describing won't work.</p>
<p>But it's tricky to create multiple instances of a function (and the code you've posted doesn't). For example, this function does return a new instance of <code>g</code> every time it's called:</p>
<pre><code>>>> def f():
def g(x=[]):
return x
return g
>>> g1 = f()
>>> g2 = f()
>>> g1().append('a')
>>> g2().append('b')
>>> g1()
['a']
>>> g2()
['b']
</code></pre>
<p>If I call <code>g()</code> with no argument, it returns the default value (initially an empty list) from its <code>func_defaults</code> tuple. Since <code>g1</code> and <code>g2</code> are different instances of the <code>g</code> function, their default value for the <code>x</code> argument is <em>also</em> a different instance, which the above demonstrates.</p>
<p>If you'd like to make this more explicit than using a tricky side-effect of default values, here's another way to do it:</p>
<p>def mainfunc():
if not hasattr(mainfunc, "ks"):
setattr(mainfunc, "ks", KeySeq())
key = mainfunc.ks.next()</p>
<p>Finally, a super important point that the code you've posted overlooks: If you're going to be doing parallel processing on shared data, the code that touches that data needs to implement locking. Look at the <code>callback.py</code> example in the Parallel Python documentation and see how locking is used in the <code>Sum</code> class, and why.</p>
| 1 | 2009-10-14T00:26:26Z | [
"python",
"parallel-python"
] |
Structuring a program. Classes and functions in Python | 1,561,282 | <p>I'm writing a program that uses genetic techniques to evolve equations.
I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function.
The function 'mainfunc' calls two or three methods defined in the Utility class.
They instantiate other classes and call various methods.
I think what I want is all of it in one NAMESPACE.
So I've instantiated some (maybe it should be all) of the classes inside the function 'mainfunc'.
I call the Utility method 'generate()'. If we were to follow it's chain of execution
it would involve all of the classes and methods in the code.</p>
<p>Now, the equations are stored in a tree. Each time a tree is generated, mutated or cross
bred, the nodes need to be given a new key so they can be accessed from a dictionary attribute of the tree. The class 'KeySeq' generates these keys.</p>
<p>In Parallel Python, I'm going to send multiple instances of 'mainfunc' to the 'submit' function of PP. Each has to be able to access 'KeySeq'. It would be nice if they all accessed the same instance of KeySeq so that none of the nodes on the returned trees had the same key, but I could get around that if necessary.</p>
<p>So: my question is about stuffing EVERYTHING into mainfunc.
Thanks
(Edit) If I don't include everything in mainfunc, I have to try to tell PP about dependent functions, etc by passing various arguements in various places. I'm trying to avoid that.</p>
<p>(late Edit) if ks.next() is called inside the 'generate() function, it returns the error 'NameError: global name 'ks' is not defined' </p>
<pre><code>class KeySeq:
"Iterator to produce sequential \
integers for keys in dict"
def __init__(self, data = 0):
self.data = data
def __iter__(self):
return self
def next(self):
self.data = self.data + 1
return self.data
class One:
'some code'
class Two:
'some code'
class Three:
'some code'
class Utilities:
def generate(x):
'___________'
def obfiscate(y):
'___________'
def ruminate(z):
'__________'
def mainfunc(z):
ks = KeySeq()
one = One()
two = Two()
three = Three()
utilities = Utilities()
list_of_interest = utilities.generate(5)
return list_of_interest
result = mainfunc(params)
</code></pre>
| 3 | 2009-10-13T16:14:10Z | 1,577,206 | <p>Your concept of classes in Python is not sound I think. Perhaps, it would be a good idea to review the basics. This link will help.</p>
<p><a href="http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm" rel="nofollow">Python Basics - Classes</a></p>
| 0 | 2009-10-16T10:01:41Z | [
"python",
"parallel-python"
] |
handling db connection on daemonize threads | 1,561,427 | <p>I have a problem handling database connections in a daemon I've been working on, I first connect to my postgres database with:</p>
<pre><code>try:
psycopg2.apilevel = '2.0'
psycopg2.threadsafety = 3
cnx = psycopg2.connect( "host='192.168.10.36' dbname='db' user='vas' password='vas'")
except Exception, e:
print "Unable to connect to DB. Error [%s]" % ( e,)
exit( )
</code></pre>
<p>after that I select all rows in the DB that are with status = 0:</p>
<pre><code>try:
cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor)
cursor.execute( "SELECT * FROM table WHERE status = 0")
rows = cursor.fetchall( )
cursor.close( )
except Exception, e:
print "Error on sql query [%s]" % ( e,)
</code></pre>
<p>then if there are rows selected the program forks into:</p>
<pre><code>while 1:
try:
psycopg2.apilevel = '2.0'
psycopg2.threadsafety = 3
cnx = psycopg2.connect( "host='192.168.10.36' dbname='sms' user='vas' password='vas'")
except Exception, e:
print "Unable to connect to DB. Error [%s]" % ( e,)
exit( )
if rows:
daemonize( )
for i in rows:
try:
global q, l
q = Queue.Queue( max_threads)
for i in rows:
cursor = cnx.cursor( cursor_factory = psycopg2.extras.DictCursor)
t = threading.Thread( target=sender, args=(i, cursor))
t.setDaemon( True)
t.start( )
for i in rows:
q.put( i)
q.join( )
except Exception, e:
print "Se ha producido el siguente error [%s]" % ( e,)
exit( )
else:
print "No rows where selected\n"
time.sleep( 5)
</code></pre>
<p>My daemonize function looks like this:</p>
<pre><code>def daemonize( ):
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
os.chdir("/")
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
</code></pre>
<p>threads target to sender function:</p>
<pre><code>def sender( row, db):
while 1:
item = q.get( )
if send_to( row['to'], row['text']):
db.execute( "UPDATE table SET status = 1 WHERE id = %d" % sms['id'])
else:
print "UPDATE table SET status = 2 WHERE id = %d" % sms['id']
db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id'])
db.close( )
q.task_done( )
</code></pre>
<p><code>send_to</code> function just opens a url and return true or false on success</p>
<p>Since yesterday i keep getting these error and cant find my way thru:</p>
<pre><code>UPDATE outbox SET status = 2 WHERE id = 36
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "/usr/lib/python2.6/threading.py", line 477, in run
self.__target(*self.__args, **self.__kwargs)
File "sender.py", line 30, in sender
db.execute( "UPDATE table SET status = 2 WHERE id = %d" % sms['id'])
File "/usr/lib/python2.6/dist-packages/psycopg2/extras.py", line 88, in execute
return _cursor.execute(self, query, vars, async)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 0 | 2009-10-13T16:36:29Z | 1,562,521 | <p>Database handles don't survive across <code>fork()</code>. You'll need to open a new database handle in each subprocess, ie after you call <code>daemonize()</code> call <code>psycopg2.connect</code>.</p>
<p>I've not used postgres but I know this to be definitely true for MySQL.</p>
| 0 | 2009-10-13T19:46:51Z | [
"python",
"multithreading",
"psycopg2",
"daemons"
] |
How do you make a shared network file read-only using Python? | 1,561,482 | <p>Using Python, what's the correct way to set a file to be read-only when the file is located on a network share (being served from a Windows 2003 Server)?</p>
<p>I'm running Python 2.6.2 in OS X (10.6.1).</p>
<p>The following code throws an exception (as expected) when path is local, but <code>os.chmod</code> appears to have no effect when path points to a Windows share.</p>
<pre><code>import os, stat
path = '/Volumes/Temp/test.txt'
# Create a test file.
open(path, 'w').close()
# Make the file read-only.
os.chmod(path, stat.S_IREAD)
# Try writing to it again. This should fail.
open(path, 'w').close()
</code></pre>
| 0 | 2009-10-13T16:46:07Z | 1,561,614 | <p>I am pretty sure you must have the proper settings on your local SAMBA server (/etc/samba/smb.conf) to make this behave the way you intend. There is many ways to go around permission checking if smb.conf isn't set correctly.</p>
| 0 | 2009-10-13T17:07:14Z | [
"python"
] |
Performance difference on insert-sort in C and python | 1,561,596 | <p>I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.</p>
<p>I've profiled both codes and the insert-sort function is the place where the time is most spent.</p>
<p>Here is the C function:</p>
<pre><code>void
insert_sort (vec_t * vec)
{
int j;
for (j = 1 ; j < vec->n ; j++){
int key = vec->v[j];
int i = j - 1;
while (i >= 0 && vec->v[i] > key){
vec->v[i+1] = vec->v[i];
i--;
}
vec->v[i+1] = key;
}
}
</code></pre>
<p>Here is the python function:</p>
<pre><code>def insert_sort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
</code></pre>
<p>The test was made with 10000 integers, each one randomly generated between 0 and 10000.</p>
<p>The results for the time spent in each function was:</p>
<ul>
<li>C time: 0.13 seconds</li>
<li>python time: 8.104 seconds</li>
</ul>
<p>Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.</p>
<p>I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a <em>pythonic</em> way to doing things that I could use in the insert-sort?</p>
| 0 | 2009-10-13T17:04:50Z | 1,561,644 | <p>What's wrong with:</p>
<pre><code>ln.sort()
</code></pre>
| -3 | 2009-10-13T17:12:09Z | [
"python",
"c",
"performance",
"profiling"
] |
Performance difference on insert-sort in C and python | 1,561,596 | <p>I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.</p>
<p>I've profiled both codes and the insert-sort function is the place where the time is most spent.</p>
<p>Here is the C function:</p>
<pre><code>void
insert_sort (vec_t * vec)
{
int j;
for (j = 1 ; j < vec->n ; j++){
int key = vec->v[j];
int i = j - 1;
while (i >= 0 && vec->v[i] > key){
vec->v[i+1] = vec->v[i];
i--;
}
vec->v[i+1] = key;
}
}
</code></pre>
<p>Here is the python function:</p>
<pre><code>def insert_sort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
</code></pre>
<p>The test was made with 10000 integers, each one randomly generated between 0 and 10000.</p>
<p>The results for the time spent in each function was:</p>
<ul>
<li>C time: 0.13 seconds</li>
<li>python time: 8.104 seconds</li>
</ul>
<p>Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.</p>
<p>I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a <em>pythonic</em> way to doing things that I could use in the insert-sort?</p>
| 0 | 2009-10-13T17:04:50Z | 1,561,694 | <p>Python is a dynamic language and the standard implementation uses an interpreter to evaluate code. This means that where the compiled C code can escape with a single machine instruction, for instance assigning to vec->v[i+1], Python's interpreter has to look up the sequence variable from the local scope, look up its class, find the item setting method on the class, call that method. Similarly for the compare, addition. Not to mention that executing almost every bytecode results in an indirect branch mispredict in the CPU that causes a pipeline bubble.</p>
<p>This is the sort of code that would benefit a lot from JIT compilation to native code and runtime type specialization, like unladen-swallow and PyPy are starting to do.</p>
<p>Otherwise the code is pretty much pythonic in the sense that if one needs to implement insertion sort, this is how one would do it in Python. It's also very unpythonic because you should use the very efficient built-in sort.</p>
| 13 | 2009-10-13T17:20:10Z | [
"python",
"c",
"performance",
"profiling"
] |
Performance difference on insert-sort in C and python | 1,561,596 | <p>I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.</p>
<p>I've profiled both codes and the insert-sort function is the place where the time is most spent.</p>
<p>Here is the C function:</p>
<pre><code>void
insert_sort (vec_t * vec)
{
int j;
for (j = 1 ; j < vec->n ; j++){
int key = vec->v[j];
int i = j - 1;
while (i >= 0 && vec->v[i] > key){
vec->v[i+1] = vec->v[i];
i--;
}
vec->v[i+1] = key;
}
}
</code></pre>
<p>Here is the python function:</p>
<pre><code>def insert_sort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
</code></pre>
<p>The test was made with 10000 integers, each one randomly generated between 0 and 10000.</p>
<p>The results for the time spent in each function was:</p>
<ul>
<li>C time: 0.13 seconds</li>
<li>python time: 8.104 seconds</li>
</ul>
<p>Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.</p>
<p>I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a <em>pythonic</em> way to doing things that I could use in the insert-sort?</p>
| 0 | 2009-10-13T17:04:50Z | 1,562,714 | <p>What method did you use to measure the time?<br />
Doing this sort of thing, I find python is at least 30 times slower than C<br />
The C compiler may be able to use some optimisations that Python doesn't even attempt </p>
<p>If might be interesting to try psyco, that type of code is well suited to it.</p>
<p>building on Alex's answer, I tried cython. In his case cython turns the for loop and everything into pure C, so now I can compare C, python and psyco </p>
<p>now i have this insort.py</p>
<pre><code>
import psyco
import random
li = [random.randrange(10000) for _ in xrange(10000)]
def insort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
#psyco.bind(insort)
import pyximport; pyximport.install()
import pyxinsort
def pyx_setup():
pyxinsort.setup(li)
def pyx_insort():
pyxinsort.insort(li)
</code></pre>
and this pyxinsort.pyx
<pre><code>
cdef int ln[10000]
def insort(li):
cdef int i,j,key
for j in range(1, len(li)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
def setup(li):
cdef int i
for i in range(1, len(li)):
ln[i]=li[i]
</code>
</pre>
<p>The code for insort is virtually identical. <code>li</code> is passed in for its length. <code>ln</code> is the array that is sorted and is prepopulated by setup, so I can isolate building the list from the sort</p>
<h2>python</h2>
<pre>
$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'
10000 loops, best of 3: 84.5 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 21.9 sec per loop
</pre>
<h2>psyco</h2>
<pre>
$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'
10000 loops, best of 3: 85.6 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 578 msec per loop
</pre>
<h2>cython ( this is running exactly the same algorithm converted to C and compiled )</h2>
<pre>
$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup()'
10000 loops, best of 3: 141 usec per loop
$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup();inso.pyx_insort()'
10 loops, best of 3: 46.6 msec per loop
</pre>
<p>cython beats psyco by a factor of 16 and Python by a factor of 470!</p>
<p>For completeness, i've included the corresponding piece of C code generated by cython</p>
<pre><code>
for (__pyx_v_j = 1; __pyx_v_j < __pyx_1; __pyx_v_j+=1) {
__pyx_v_key = (__pyx_v_9pyxinsort_ln[__pyx_v_j]);
__pyx_v_i = (__pyx_v_j - 1);
while (1) {
__pyx_2 = (__pyx_v_i >= 0);
if (__pyx_2) {
__pyx_2 = ((__pyx_v_9pyxinsort_ln[__pyx_v_i]) > __pyx_v_key);
}
if (!__pyx_2) break;
(__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = (__pyx_v_9pyxinsort_ln[__pyx_v_i]);
__pyx_v_i -= 1;
}
(__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = __pyx_v_key;
}
</code></pre>
| 2 | 2009-10-13T20:25:19Z | [
"python",
"c",
"performance",
"profiling"
] |
Performance difference on insert-sort in C and python | 1,561,596 | <p>I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.</p>
<p>I've profiled both codes and the insert-sort function is the place where the time is most spent.</p>
<p>Here is the C function:</p>
<pre><code>void
insert_sort (vec_t * vec)
{
int j;
for (j = 1 ; j < vec->n ; j++){
int key = vec->v[j];
int i = j - 1;
while (i >= 0 && vec->v[i] > key){
vec->v[i+1] = vec->v[i];
i--;
}
vec->v[i+1] = key;
}
}
</code></pre>
<p>Here is the python function:</p>
<pre><code>def insert_sort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
</code></pre>
<p>The test was made with 10000 integers, each one randomly generated between 0 and 10000.</p>
<p>The results for the time spent in each function was:</p>
<ul>
<li>C time: 0.13 seconds</li>
<li>python time: 8.104 seconds</li>
</ul>
<p>Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.</p>
<p>I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a <em>pythonic</em> way to doing things that I could use in the insert-sort?</p>
| 0 | 2009-10-13T17:04:50Z | 1,562,819 | <p>So, here are some lessons you should take away from this:</p>
<ul>
<li><p>Interpreted Python is on the slow side. Don't try to write your own FFT, MPEG encoder, etc. in Python.</p></li>
<li><p>Even slow interpreted Python is probably fast enough for small problems. An 8 second run time is not horrible, and it would take you much longer to write and debug the C than the Python, so if you are writing something to run once, Python wins.</p></li>
<li><p>For speed in Python, try to rely on built-in features and C modules. Let someone else's C code do the heavy lifting. I worked on an embedded device where we did our work in Python; despite the slow embedded processor, the performance was decent, because C library modules were doing most of the work.</p></li>
</ul>
<p>For fun and education, please repeat your Python test, this time using the built-in <code>.sort()</code> method on a list; it probably won't be quite as fast as the C, but it will be close. (Although for really large data sets, it will beat the C, because insertion sort sucks. If you rewrote the C to use the C library <code>qsort()</code> function, that would be the speed champ.)</p>
<p>A common Python design "pattern" is: first, write your app in Python. If it is fast enough, stop; you are done. Second, try to rewrite to improve speed; see if there is a C module you can use, for example. If it is still not fast enough, consider writing your own C module; or, write a C program, using the Python prototype code as the basis for your design.</p>
| 4 | 2009-10-13T20:50:26Z | [
"python",
"c",
"performance",
"profiling"
] |
Performance difference on insert-sort in C and python | 1,561,596 | <p>I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.</p>
<p>I've profiled both codes and the insert-sort function is the place where the time is most spent.</p>
<p>Here is the C function:</p>
<pre><code>void
insert_sort (vec_t * vec)
{
int j;
for (j = 1 ; j < vec->n ; j++){
int key = vec->v[j];
int i = j - 1;
while (i >= 0 && vec->v[i] > key){
vec->v[i+1] = vec->v[i];
i--;
}
vec->v[i+1] = key;
}
}
</code></pre>
<p>Here is the python function:</p>
<pre><code>def insert_sort (ln):
for j in range(1, len(ln)):
key = ln[j]
i = j-1
while i >= 0 and ln[i] > key:
ln[i+1] = ln[i]
i-=1
ln[i+1] = key
</code></pre>
<p>The test was made with 10000 integers, each one randomly generated between 0 and 10000.</p>
<p>The results for the time spent in each function was:</p>
<ul>
<li>C time: 0.13 seconds</li>
<li>python time: 8.104 seconds</li>
</ul>
<p>Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster.</p>
<p>I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a <em>pythonic</em> way to doing things that I could use in the insert-sort?</p>
| 0 | 2009-10-13T17:04:50Z | 1,564,061 | <p>My first thought was that the laptop I have at hand right now, a Macbook Pro, must be comparable to but slightly better than your machine -- I don't have enough of your surrounding code to try your C example (what's a vec_t, etc, etc), but running the Python you coded gives me:</p>
<pre><code>$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'
10 loops, best of 3: 7.21 msec per loop
</code></pre>
<p>vs your 8.1 seconds. That's with you code put in <code>insort.py</code>, preceded by:</p>
<pre><code>import random
li = [random.randrange(10000) for _ in xrange(10000)]
</code></pre>
<p><code>array</code> doesn't help -- actually slows things down a bit. Then I installed <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a>, the Python JIT helper (x86-only, 32-bit only), further added:</p>
<pre><code>import psyco
psyco.full()
</code></pre>
<p>and got:</p>
<pre><code>$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'
10 loops, best of 3: 207 usec per loop
</code></pre>
<p>so a speedup of about 7.21 / 0.000207 = 34830 times -- vs the 8.04 / 0.13 = 62 times that surprised you so much;-).</p>
<p>Of course, the problem is that after the first time, the list is already sorted, so insort becomes must faster. You didn't give us enough of the surrounding test harness to know exactly <em>what</em> you measured. A more realisting example (where the actual list isn't touched so it <em>stays</em> disordered, only a <em>copy</em> is sorted...), without psyco:</p>
<pre><code>$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 13.8 sec per loop
</code></pre>
<p>Oops -- so your machine's WAY faster than a Macbook Pro (remembers, core don't count: we're using only one here;-) -- wow... or else, you're mismeasuring. Anyway, WITH psyco:</p>
<pre><code>$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'
10 loops, best of 3: 456 msec per loop
</code></pre>
<p>So psyco's speedup is only 13.8 / 0.456, 30 times -- about half as much as the 60+ times you get with pure-C coding. IOW, you'd expect python + psyco to be twice as slow as pure C. That's a more realistic and typical assessment.</p>
<p>If you we writing reasonably high-level code, psyco's speedup of it would degrade from (say) 30 times down to much less -- but so would C's advantage over Python. For example,</p>
<pre><code>$ python -mtimeit -s'import inso' 'sorted(inso.li)'
100 loops, best of 3: 8.72 msec per loop
</code></pre>
<p>without psyco (in this case, psyco actually -- marginally -- <em>slows down</em> the execution;-), so that's another factor of 52 over psyco, 1582 overall over non-psyco insort.</p>
<p>But, when for some reason or other you <strong>have to</strong> write extremely low-level algorithms in python, rather than using the wealth of support from the builtins and stdlib, psyco can help reduce the pain.</p>
<p>Another point is, when you benchmark, please post ALL code so others can see <em>exactly</em> what you're doing (and possibly spot gotchas) -- your "scaffolding" is as tricky and likely to hide traps, as the code you <strong>think</strong> you're measuring!-)</p>
| 5 | 2009-10-14T03:13:19Z | [
"python",
"c",
"performance",
"profiling"
] |
Google wave robot inline reply | 1,561,655 | <p>I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this!</p>
<p>The API docs have a function <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops.OpBasedDocument-class.html#InsertInlineBlip" rel="nofollow">InsertInlineBlip</a> which sounded promising, however calling that doesn't appear to do anything!</p>
<p>EDIT::
It seems that this is a known bug. However, the question still stands what is the correct way to insert an inline blip? I'm assuming something like this:</p>
<pre><code>inline = blip.GetDocument().InsertInlineBlip(positionInText)
inline.GetDocument().SetText("some text")
</code></pre>
| 5 | 2009-10-13T17:14:10Z | 1,582,481 | <p>It could be a possible <a href="http://code.google.com/p/google-wave-resources/issues/detail?id=212" rel="nofollow">bug</a>.</p>
| 2 | 2009-10-17T15:43:24Z | [
"python",
"google-wave"
] |
Google wave robot inline reply | 1,561,655 | <p>I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this!</p>
<p>The API docs have a function <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops.OpBasedDocument-class.html#InsertInlineBlip" rel="nofollow">InsertInlineBlip</a> which sounded promising, however calling that doesn't appear to do anything!</p>
<p>EDIT::
It seems that this is a known bug. However, the question still stands what is the correct way to insert an inline blip? I'm assuming something like this:</p>
<pre><code>inline = blip.GetDocument().InsertInlineBlip(positionInText)
inline.GetDocument().SetText("some text")
</code></pre>
| 5 | 2009-10-13T17:14:10Z | 1,583,687 | <p>If you look at the <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops-pysrc.html#OpBasedDocument.InsertInlineBlip" rel="nofollow">sourcecode</a> for <code>OpBasedDocument.InsertInlineBlip()</code> you will see the following:</p>
<pre><code> 412 - def InsertInlineBlip(self, position):
413 """Inserts an inline blip into this blip at a specific position.
414
415 Args:
416 position: Position to insert the blip at.
417
418 Returns:
419 The JSON data of the blip that was created.
420 """
421 blip_data = self.__context.builder.DocumentInlineBlipInsert(
422 self._blip.waveId,
423 self._blip.waveletId,
424 self._blip.blipId,
425 position)
426 # TODO(davidbyttow): Add local blip element.
427 return self.__context.AddBlip(blip_data)
</code></pre>
<p>I think the TODO comment suggests this feature is not yet active. The method should be callable and return correctly, however I suspect that the document operation is not applied to the global document.</p>
<p>The syntax you included in your post looks correct. As you can see above, <code>InsertInlineBlip()</code> <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops-pysrc.html#%5FContextImpl.AddBlip" rel="nofollow">returns the value</a> of <code>AddBlip()</code>, which is ...dun, dun, dun... a blip.</p>
<pre><code> 543 - def AddBlip(self, blip_data):
544 """Adds a transient blip based on the data supplied.
545
546 Args:
547 blip_data: JSON data describing this blip.
548
549 Returns:
550 An OpBasedBlip that may have operations applied to it.
551 """
552 blip = OpBasedBlip(blip_data, self)
553 self.blips[blip.GetId()] = blip
554 return blip
</code></pre>
<p>EDIT:
It is interesting to note that the method signature of the Insert method <code>InsertInlineBlip(self, position)</code> is significantly different from the Insert method <code>InsertElement(self, position, element)</code>. <code>InsertInlineBlip()</code> doesn't take an element parameter to insert. It seems the current logic for <code>InsertInlineBlip()</code> is more like <code>Blip.CreateChild()</code>, which returns a new child blip with which to work. From this we can suspect that this API will change as the functionality is added.</p>
| 4 | 2009-10-18T01:16:36Z | [
"python",
"google-wave"
] |
Google wave robot inline reply | 1,561,655 | <p>I've been working on my first robot for google wave recently, a vital part of what it does is to insert inline replies into a blip. I can't for the life of me figure out how to do this!</p>
<p>The API docs have a function <a href="http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/waveapi.ops.OpBasedDocument-class.html#InsertInlineBlip" rel="nofollow">InsertInlineBlip</a> which sounded promising, however calling that doesn't appear to do anything!</p>
<p>EDIT::
It seems that this is a known bug. However, the question still stands what is the correct way to insert an inline blip? I'm assuming something like this:</p>
<pre><code>inline = blip.GetDocument().InsertInlineBlip(positionInText)
inline.GetDocument().SetText("some text")
</code></pre>
| 5 | 2009-10-13T17:14:10Z | 1,649,036 | <p>This appears to have previously been a bug, however, an update today has hopefully fixed it:
<a href="http://code.google.com/p/google-wave-resources/wiki/WaveAPIsChangeLog" rel="nofollow">http://code.google.com/p/google-wave-resources/wiki/WaveAPIsChangeLog</a></p>
| 1 | 2009-10-30T10:32:15Z | [
"python",
"google-wave"
] |
View Windows file metadata in Python | 1,561,831 | <p>I am writing a script to email the owner of a file when a separate process has finished. I have tried:</p>
<pre><code>import os
FileInfo = os.stat("test.txt")
print (FileInfo.st_uid)
</code></pre>
<p>The output of this is the owner ID number. What I need is the Windows user name. </p>
| 0 | 2009-10-13T17:46:06Z | 1,562,035 | <p>I think the only chance you have is to use the <a href="https://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32 extensions</a> and ask windows yourself.</p>
<p>Basically you <a href="http://msdn.microsoft.com/en-us/library/aa446629%28VS.85,loband%29.aspx" rel="nofollow">look on msdn how to do it in c++</a> and use the according pywin32 functions. </p>
<pre><code>from win32security import GetSecurityInfo, LookupAccountSid
from win32security import OWNER_SECURITY_INFORMATION, SE_FILE_OBJECT
from win32file import CreateFile
from win32file import GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL
fh = CreateFile( __file__, GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None )
info = GetSecurityInfo( fh, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION )
name, domain, type_id = LookupAccountSid( None, info.GetSecurityDescriptorOwner() )
print name, domain, type_id
</code></pre>
| 2 | 2009-10-13T18:19:19Z | [
"python"
] |
View Windows file metadata in Python | 1,561,831 | <p>I am writing a script to email the owner of a file when a separate process has finished. I have tried:</p>
<pre><code>import os
FileInfo = os.stat("test.txt")
print (FileInfo.st_uid)
</code></pre>
<p>The output of this is the owner ID number. What I need is the Windows user name. </p>
| 0 | 2009-10-13T17:46:06Z | 1,562,137 | <p>Once I stopped searching for file meta data and started looking for file security I found exactly what I was looking for.</p>
<pre><code>import tempfile
import win32api
import win32con
import win32security
f = tempfile.NamedTemporaryFile ()
FILENAME = f.name
try:
sd = win32security.GetFileSecurity (FILENAME,win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)
print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
print "File owned by %s\\%s" % (domain, name)
finally:
f.close ()
</code></pre>
<p>Mercilessly ganked from <a href="http://timgolden.me.uk/python-on-windows/programming-areas/security/ownership.html" rel="nofollow">http://timgolden.me.uk/python-on-windows/programming-areas/security/ownership.html</a></p>
| 3 | 2009-10-13T18:37:45Z | [
"python"
] |
Retrieving and displaying UTF-8 from a .CSV in Python | 1,561,833 | <p>Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8:</p>
<p>"Nguyá»
n", 0.500
"Trần", 0.250
"Lê", 0.250</p>
<p>Now I am attempting to read it with this code and it displays all funny like this: Trần</p>
<p>Now I have gone through all the Python docs for 2.6 which is the one I use and I can't get the wrapper to work along with all the ideas on the internet which I am assuming are all very correct just not being applied properly by yours truly. On the plus side I have learnt that not all fonts will display those characters correctly anyway something I hadn't even thought of previously and have learned a lot about Unicode etc so it certainly was not wasted time.</p>
<p>If anyone could point out where I went wrong I would be most grateful.</p>
<p>Here is the code updated as per request below that returns this error - </p>
<pre>
Traceback (most recent call last):
File "surname_generator.py", line 39, in
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
File "surname_generator.py", line 27, in unicode_csv_reader
for row in csv_reader:
File "surname_generator.py", line 33, in utf_8_encoder
yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
</pre>
<pre><code>from random import random
import csv
class ChooseFamilyName(object):
def __init__(self, probs):
self._total_prob = 0.
self._familyname_levels = []
for familyname, prob in probs:
self._total_prob += prob
self._familyname_levels.append((self._total_prob, familyname))
return
def pickfamilyname(self):
pickfamilyname = self._total_prob * random()
for level, familyname in self._familyname_levels:
if level >= pickfamilyname:
return familyname
print "pickfamilyname error"
return
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
familynamelist = 'familyname_vietnam.csv'
a = 0
while a < 10:
a = a + 1
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
familynamepicker = ChooseFamilyName(probfamilynames)
print(familynamepicker.pickfamilyname())
</code></pre>
| 0 | 2009-10-13T17:46:41Z | 1,561,871 | <p>There's the unicode_csv_reader demo in the python docs:
<a href="http://docs.python.org/library/csv.html" rel="nofollow">http://docs.python.org/library/csv.html</a></p>
| -2 | 2009-10-13T17:51:41Z | [
"python",
"utf-8",
"csv"
] |
Retrieving and displaying UTF-8 from a .CSV in Python | 1,561,833 | <p>Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8:</p>
<p>"Nguyá»
n", 0.500
"Trần", 0.250
"Lê", 0.250</p>
<p>Now I am attempting to read it with this code and it displays all funny like this: Trần</p>
<p>Now I have gone through all the Python docs for 2.6 which is the one I use and I can't get the wrapper to work along with all the ideas on the internet which I am assuming are all very correct just not being applied properly by yours truly. On the plus side I have learnt that not all fonts will display those characters correctly anyway something I hadn't even thought of previously and have learned a lot about Unicode etc so it certainly was not wasted time.</p>
<p>If anyone could point out where I went wrong I would be most grateful.</p>
<p>Here is the code updated as per request below that returns this error - </p>
<pre>
Traceback (most recent call last):
File "surname_generator.py", line 39, in
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
File "surname_generator.py", line 27, in unicode_csv_reader
for row in csv_reader:
File "surname_generator.py", line 33, in utf_8_encoder
yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
</pre>
<pre><code>from random import random
import csv
class ChooseFamilyName(object):
def __init__(self, probs):
self._total_prob = 0.
self._familyname_levels = []
for familyname, prob in probs:
self._total_prob += prob
self._familyname_levels.append((self._total_prob, familyname))
return
def pickfamilyname(self):
pickfamilyname = self._total_prob * random()
for level, familyname in self._familyname_levels:
if level >= pickfamilyname:
return familyname
print "pickfamilyname error"
return
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
familynamelist = 'familyname_vietnam.csv'
a = 0
while a < 10:
a = a + 1
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
familynamepicker = ChooseFamilyName(probfamilynames)
print(familynamepicker.pickfamilyname())
</code></pre>
| 0 | 2009-10-13T17:46:41Z | 1,563,565 | <p>Your <em>current</em> problem is that you have been given a bum steer with the csv_unicode_reader thingy. As the name suggests, and as the documentation states explicitly: </p>
<p>"""(unicode_csv_reader() below is a generator that wraps csv.reader to handle Unicode CSV data (a list of Unicode strings). """</p>
<p>You don't have unicode strings, you have str strings encoded in UTF-8.</p>
<p>Suggestion: blow away the csv_unicode_reader stuff. Get each row plainly and simply as though it was encoded in ascii. Then convert each row to unicode:</p>
<pre><code>unicode_row = [field.decode('utf8') for field in str_row]
</code></pre>
<p>Getting back to your original problem:</p>
<p>(1) To get help with fonts etc, you need to say what platform you are running on and what software you are using to display the unicode strings.</p>
<p>(2) If you want platform-independent ways of inspecting your data, look at the repr() built-in function, and the name function in the unicodedata module.</p>
| 1 | 2009-10-13T23:48:54Z | [
"python",
"utf-8",
"csv"
] |
Retrieving and displaying UTF-8 from a .CSV in Python | 1,561,833 | <p>Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8:</p>
<p>"Nguyá»
n", 0.500
"Trần", 0.250
"Lê", 0.250</p>
<p>Now I am attempting to read it with this code and it displays all funny like this: Trần</p>
<p>Now I have gone through all the Python docs for 2.6 which is the one I use and I can't get the wrapper to work along with all the ideas on the internet which I am assuming are all very correct just not being applied properly by yours truly. On the plus side I have learnt that not all fonts will display those characters correctly anyway something I hadn't even thought of previously and have learned a lot about Unicode etc so it certainly was not wasted time.</p>
<p>If anyone could point out where I went wrong I would be most grateful.</p>
<p>Here is the code updated as per request below that returns this error - </p>
<pre>
Traceback (most recent call last):
File "surname_generator.py", line 39, in
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
File "surname_generator.py", line 27, in unicode_csv_reader
for row in csv_reader:
File "surname_generator.py", line 33, in utf_8_encoder
yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
</pre>
<pre><code>from random import random
import csv
class ChooseFamilyName(object):
def __init__(self, probs):
self._total_prob = 0.
self._familyname_levels = []
for familyname, prob in probs:
self._total_prob += prob
self._familyname_levels.append((self._total_prob, familyname))
return
def pickfamilyname(self):
pickfamilyname = self._total_prob * random()
for level, familyname in self._familyname_levels:
if level >= pickfamilyname:
return familyname
print "pickfamilyname error"
return
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
familynamelist = 'familyname_vietnam.csv'
a = 0
while a < 10:
a = a + 1
probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))]
familynamepicker = ChooseFamilyName(probfamilynames)
print(familynamepicker.pickfamilyname())
</code></pre>
| 0 | 2009-10-13T17:46:41Z | 1,563,916 | <p><code>unicode_csv_reader(open(familynamelist))</code> is trying to pass non-unicode data (byte strings with utf-8 encoding) to a function you wrote expecting unicode data. You could solve the problem with codecs.open (from standard library module codecs), but that's to roundabout: the codecs would be doing utf8->unicode for you, then your code would be doing unicode->utf8, what's the point?</p>
<p>Instead, define a function more like this one...:</p>
<pre><code>def encoded_csv_reader_to_unicode(encoded_csv_data,
coding='utf-8',
dialect=csv.excel,
**kwargs):
csv_reader = csv.reader(encoded_csv_data,
dialect=dialect,
**kwargs)
for row in csv_reader:
yield [unicode(cell, coding) for cell in row]
</code></pre>
<p>and use <code>encoded_csv_reader_to_unicode(open(familynamelist))</code>.</p>
| 2 | 2009-10-14T02:07:28Z | [
"python",
"utf-8",
"csv"
] |
A good data model for finding a user's favorite stories | 1,562,131 | <h2>Original Design</h2>
<p>Here's how I originally had my <code>Models</code> set up:</p>
<pre><code>class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
</code></pre>
<p>On every page that displayed a story I would query UserData for the current user:</p>
<pre><code>user_data = UserData.all().filter('user =' users.get_current_user()).get()
story_is_favorited = (story in user_data.favorites)
</code></pre>
<h2>New Design</h2>
<p>After watching this talk: <a href="http://www.youtube.com/watch?v=AgaL6NGpkB8" rel="nofollow">Google I/O 2009 - Scalable, Complex Apps on App Engine</a>, I wondered if I could set things up more efficiently. </p>
<pre><code>class FavoriteIndex(db.Model):
favorited_by = db.StringListProperty()
</code></pre>
<p>The <code>Story Model</code> is the same, but I got rid of the <code>UserData Model</code>. Each instance of the new <code>FavoriteIndex Model</code> has a <code>Story</code> instance as a parent. And each <code>FavoriteIndex</code> stores a list of user id's in it's <code>favorited_by</code> property.</p>
<p>If I want to find all of the stories that have been favorited by a certain user:</p>
<pre><code>index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id())
story_keys = [k.parent() for k in index_keys]
stories = db.get(story_keys)
</code></pre>
<p>This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty.</p>
<h2>Efficiency vs Simplicity</h2>
<p>I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it:</p>
<ol>
<li><p>A favorited story is associated with a user, not with her <code>user data</code></p></li>
<li><p>On a page where I display a <code>story</code>, it's pretty easy to ask the <code>story</code> if it's been favorited (without calling up a separate entity filled with user data).</p>
<pre><code>fav_index = FavoriteIndex.all().ancestor(story).get()
fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by
</code></pre></li>
<li><p>It's also easy to get a list of all the users who have favorited a story (using the method in #2)</p></li>
</ol>
<h2>Is there an easier way?</h2>
<p>Please help. How is this kind of thing normally done?</p>
| 4 | 2009-10-13T18:36:46Z | 1,562,372 | <p>I don't want to tackle your actual question, but here's a very small tip: you can replace this code:</p>
<pre><code>if story in user_data.favorites:
story_is_favorited = True
else:
story_is_favorited = False
</code></pre>
<p>with this single line:</p>
<pre><code>story_is_favorited = (story in user_data.favorites)
</code></pre>
<p>You don't even need to put the parentheses around the <code>story in user_data.favorites</code> if you don't want to; I just think that's more readable.</p>
| 1 | 2009-10-13T19:20:41Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
A good data model for finding a user's favorite stories | 1,562,131 | <h2>Original Design</h2>
<p>Here's how I originally had my <code>Models</code> set up:</p>
<pre><code>class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
</code></pre>
<p>On every page that displayed a story I would query UserData for the current user:</p>
<pre><code>user_data = UserData.all().filter('user =' users.get_current_user()).get()
story_is_favorited = (story in user_data.favorites)
</code></pre>
<h2>New Design</h2>
<p>After watching this talk: <a href="http://www.youtube.com/watch?v=AgaL6NGpkB8" rel="nofollow">Google I/O 2009 - Scalable, Complex Apps on App Engine</a>, I wondered if I could set things up more efficiently. </p>
<pre><code>class FavoriteIndex(db.Model):
favorited_by = db.StringListProperty()
</code></pre>
<p>The <code>Story Model</code> is the same, but I got rid of the <code>UserData Model</code>. Each instance of the new <code>FavoriteIndex Model</code> has a <code>Story</code> instance as a parent. And each <code>FavoriteIndex</code> stores a list of user id's in it's <code>favorited_by</code> property.</p>
<p>If I want to find all of the stories that have been favorited by a certain user:</p>
<pre><code>index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id())
story_keys = [k.parent() for k in index_keys]
stories = db.get(story_keys)
</code></pre>
<p>This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty.</p>
<h2>Efficiency vs Simplicity</h2>
<p>I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it:</p>
<ol>
<li><p>A favorited story is associated with a user, not with her <code>user data</code></p></li>
<li><p>On a page where I display a <code>story</code>, it's pretty easy to ask the <code>story</code> if it's been favorited (without calling up a separate entity filled with user data).</p>
<pre><code>fav_index = FavoriteIndex.all().ancestor(story).get()
fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by
</code></pre></li>
<li><p>It's also easy to get a list of all the users who have favorited a story (using the method in #2)</p></li>
</ol>
<h2>Is there an easier way?</h2>
<p>Please help. How is this kind of thing normally done?</p>
| 4 | 2009-10-13T18:36:46Z | 1,562,614 | <p>What you've described is a good solution. You can optimise it further, however: For each favorite, create a 'UserFavorite' entity as a child entity of the relevant Story entry (or equivalently, as a child entity of a UserInfo entry), with the key name set to the user's unique ID. This way, you can determine if a user has favorited a story with a simple get:</p>
<pre><code>UserFavorite.get_by_name(user_id, parent=a_story)
</code></pre>
<p>get operations are 3 to 5 times faster than queries, so this is a substantial improvement.</p>
| 2 | 2009-10-13T20:04:12Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
A good data model for finding a user's favorite stories | 1,562,131 | <h2>Original Design</h2>
<p>Here's how I originally had my <code>Models</code> set up:</p>
<pre><code>class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
</code></pre>
<p>On every page that displayed a story I would query UserData for the current user:</p>
<pre><code>user_data = UserData.all().filter('user =' users.get_current_user()).get()
story_is_favorited = (story in user_data.favorites)
</code></pre>
<h2>New Design</h2>
<p>After watching this talk: <a href="http://www.youtube.com/watch?v=AgaL6NGpkB8" rel="nofollow">Google I/O 2009 - Scalable, Complex Apps on App Engine</a>, I wondered if I could set things up more efficiently. </p>
<pre><code>class FavoriteIndex(db.Model):
favorited_by = db.StringListProperty()
</code></pre>
<p>The <code>Story Model</code> is the same, but I got rid of the <code>UserData Model</code>. Each instance of the new <code>FavoriteIndex Model</code> has a <code>Story</code> instance as a parent. And each <code>FavoriteIndex</code> stores a list of user id's in it's <code>favorited_by</code> property.</p>
<p>If I want to find all of the stories that have been favorited by a certain user:</p>
<pre><code>index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id())
story_keys = [k.parent() for k in index_keys]
stories = db.get(story_keys)
</code></pre>
<p>This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty.</p>
<h2>Efficiency vs Simplicity</h2>
<p>I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it:</p>
<ol>
<li><p>A favorited story is associated with a user, not with her <code>user data</code></p></li>
<li><p>On a page where I display a <code>story</code>, it's pretty easy to ask the <code>story</code> if it's been favorited (without calling up a separate entity filled with user data).</p>
<pre><code>fav_index = FavoriteIndex.all().ancestor(story).get()
fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by
</code></pre></li>
<li><p>It's also easy to get a list of all the users who have favorited a story (using the method in #2)</p></li>
</ol>
<h2>Is there an easier way?</h2>
<p>Please help. How is this kind of thing normally done?</p>
| 4 | 2009-10-13T18:36:46Z | 1,562,643 | <p>You can make the favorite index like a join on the two models</p>
<pre><code>class FavoriteIndex(db.Model):
user = db.UserProperty()
story = db.ReferenceProperty()
</code></pre>
<p>or</p>
<pre><code>class FavoriteIndex(db.Model):
user = db.UserProperty()
story = db.StringListProperty()
</code></pre>
<p>Then your query on by user returns one FavoriteIndex object for each story the user has favorited</p>
<p>You can also query by story to see how many users have Favorited it.</p>
<p>You don't want to be scanning through anything unless you know it is limited to a small size</p>
| 1 | 2009-10-13T20:08:28Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
A good data model for finding a user's favorite stories | 1,562,131 | <h2>Original Design</h2>
<p>Here's how I originally had my <code>Models</code> set up:</p>
<pre><code>class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
</code></pre>
<p>On every page that displayed a story I would query UserData for the current user:</p>
<pre><code>user_data = UserData.all().filter('user =' users.get_current_user()).get()
story_is_favorited = (story in user_data.favorites)
</code></pre>
<h2>New Design</h2>
<p>After watching this talk: <a href="http://www.youtube.com/watch?v=AgaL6NGpkB8" rel="nofollow">Google I/O 2009 - Scalable, Complex Apps on App Engine</a>, I wondered if I could set things up more efficiently. </p>
<pre><code>class FavoriteIndex(db.Model):
favorited_by = db.StringListProperty()
</code></pre>
<p>The <code>Story Model</code> is the same, but I got rid of the <code>UserData Model</code>. Each instance of the new <code>FavoriteIndex Model</code> has a <code>Story</code> instance as a parent. And each <code>FavoriteIndex</code> stores a list of user id's in it's <code>favorited_by</code> property.</p>
<p>If I want to find all of the stories that have been favorited by a certain user:</p>
<pre><code>index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id())
story_keys = [k.parent() for k in index_keys]
stories = db.get(story_keys)
</code></pre>
<p>This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty.</p>
<h2>Efficiency vs Simplicity</h2>
<p>I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it:</p>
<ol>
<li><p>A favorited story is associated with a user, not with her <code>user data</code></p></li>
<li><p>On a page where I display a <code>story</code>, it's pretty easy to ask the <code>story</code> if it's been favorited (without calling up a separate entity filled with user data).</p>
<pre><code>fav_index = FavoriteIndex.all().ancestor(story).get()
fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by
</code></pre></li>
<li><p>It's also easy to get a list of all the users who have favorited a story (using the method in #2)</p></li>
</ol>
<h2>Is there an easier way?</h2>
<p>Please help. How is this kind of thing normally done?</p>
| 4 | 2009-10-13T18:36:46Z | 1,589,364 | <p>With your new Design you can lookup if a user has favorited a certain story with a query.<br />
You don't need the UserFavorite class entities.<br />
It is a keys_only query so not as fast as a get(key) but faster then a normal query.<br />
The FavoriteIndex classes all have the same key_name='favs'.<br />
You can filter based on __key__. </p>
<pre><code>a_story = ......
a_user_id = users.get_current_user().user_id()
favIndexKey = db.Key.from_path('Story', a_story.key.id_or_name(), 'FavoriteIndex', 'favs')
doesFavStory = FavoriteIndex.all(keys_only=True).filter('__key__ =', favIndexKey).filter('favorited_by =', a_user_id).get()
</code></pre>
<p>If you use multiple FavoriteIndex as childs of a Story you can use the ancestor filter</p>
<pre><code>doesFavStory = FavoriteIndex.all(keys_only=True).ancestor(a_story).filter('favorited_by =', a_user_id).get()
</code></pre>
| 1 | 2009-10-19T15:27:48Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Python MySQL installing wrongly on Mac OS X 10.6 i386 | 1,562,314 | <p>When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:</p>
<pre><code>user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo python setup.py build
</code></pre>
<p>I get the following errors:</p>
<pre><code>running build
running build_py
creating build/lib.macosx-10.3-i386-2.6
copying _mysql_exceptions.py -> build/lib.macosx-10.3-i386-2.6
creating build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
creating build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.3-i386-2.6
Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Please check your Xcode installation
</code></pre>
<p>It looks like the setup.py build script is recognizing my OS as Mac OS X 10.3 instead of 10.6 so it tries to locate an older version of XCode which I don't have.</p>
<p>Does anyone know how to get around this problem? Perhaps manually configuring the script to recognize my os as 10.6?</p>
| 2 | 2009-10-13T19:09:36Z | 1,562,361 | <p>Well the error is pretty clear, do you have xcode installed? <a href="http://developer.apple.com/tools/Xcode/" rel="nofollow">http://developer.apple.com/tools/Xcode/</a></p>
<p>You can look at a more detailed solution to this in <a href="http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html" rel="nofollow">http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html</a> which includes downloading the latest xcode. Hope it helps.</p>
| -1 | 2009-10-13T19:19:40Z | [
"python",
"mysql",
"osx"
] |
Python MySQL installing wrongly on Mac OS X 10.6 i386 | 1,562,314 | <p>When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:</p>
<pre><code>user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo python setup.py build
</code></pre>
<p>I get the following errors:</p>
<pre><code>running build
running build_py
creating build/lib.macosx-10.3-i386-2.6
copying _mysql_exceptions.py -> build/lib.macosx-10.3-i386-2.6
creating build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
creating build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.3-i386-2.6
Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Please check your Xcode installation
</code></pre>
<p>It looks like the setup.py build script is recognizing my OS as Mac OS X 10.3 instead of 10.6 so it tries to locate an older version of XCode which I don't have.</p>
<p>Does anyone know how to get around this problem? Perhaps manually configuring the script to recognize my os as 10.6?</p>
| 2 | 2009-10-13T19:09:36Z | 1,562,456 | <p>It appears you have installed and are using a python.org python2.6. Because that installer is designed to work for a range of systems, to build extensions with that python on 10.6, you need to install the optional 10.4 SDK which is part of the Xcode package on the Snow Leopard installation DVD or machine restore DVD; the 10.4 SDK is not installed by default. That's what the message is trying to tell you.</p>
| 9 | 2009-10-13T19:34:22Z | [
"python",
"mysql",
"osx"
] |
Python MySQL installing wrongly on Mac OS X 10.6 i386 | 1,562,314 | <p>When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:</p>
<pre><code>user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo python setup.py build
</code></pre>
<p>I get the following errors:</p>
<pre><code>running build
running build_py
creating build/lib.macosx-10.3-i386-2.6
copying _mysql_exceptions.py -> build/lib.macosx-10.3-i386-2.6
creating build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb
creating build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.3-i386-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.3-i386-2.6
Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Please check your Xcode installation
</code></pre>
<p>It looks like the setup.py build script is recognizing my OS as Mac OS X 10.3 instead of 10.6 so it tries to locate an older version of XCode which I don't have.</p>
<p>Does anyone know how to get around this problem? Perhaps manually configuring the script to recognize my os as 10.6?</p>
| 2 | 2009-10-13T19:09:36Z | 7,658,425 | <p>Installing the latest version of Python from python.org, fixed this problem for me.</p>
| 1 | 2011-10-05T08:11:29Z | [
"python",
"mysql",
"osx"
] |
Could use some help with this soundex coding | 1,562,438 | <p>The US census bureau uses a special encoding called âsoundexâ to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled differently, like SMITH and SMYTH, have the same code and are filed together. The soundex coding system was developed so that you can find a surname even though it may have been recorded under various spellings.</p>
<p>In this lab you will design, code, and document a program that produces the soundex code when input with a surname. A user will be prompted for a surname, and the program should output the corresponding code.</p>
<p>Basic Soundex Coding Rules</p>
<p>Every soundex encoding of a surname consists of a letter and three numbers. The letter used is always the first letter of the surname. The numbers are assigned to the remaining letters of the surname according to the soundex guide shown below. Zeroes are added at the end if necessary to always produce a four-character code. Additional letters are disregarded. </p>
<p>Soundex Coding Guide</p>
<p>Soundex assigns a number for various consonants. Consonants that sound alike are assigned the same number:</p>
<p>Number Consonants</p>
<p>1 B, F, P, V
2 C, G, J, K, Q, S, X, Z
3 D, T
4 L
5 M, N
6 R</p>
<p>Soundex disregards the letters A, E, I, O, U, H, W, and Y.</p>
<p>There are 3 additional Soundex Coding Rules that are followed. A good program design would implement these each as one or more separate functions.</p>
<p>Rule 1. Names With Double Letters</p>
<p>If the surname has any double letters, they should be treated as one letter. For example:</p>
<ul>
<li>Gutierrez is coded G362 (G, 3 for the T, 6 for the first R, second R ignored, 2 for the Z).</li>
</ul>
<p>Rule 2. Names with Letters Side-by-Side that have the Same Soundex Code Number</p>
<p>If the surname has different letters side-by-side that have the same number in the soundex coding guide, they should be treated as one letter. Examples:</p>
<ul>
<li><p>Pfister is coded as P236 (P, F ignored since it is considered same as P, 2 for the S, 3 for the T, 6 for the R).</p></li>
<li><p>Jackson is coded as J250 (J, 2 for the C, K ignored same as C, S ignored same as C, 5 for the N, 0 added).</p></li>
</ul>
<p>Rule 3. Consonant Separators</p>
<p>3.a. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Example:</p>
<ul>
<li>Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.</li>
</ul>
<p>3.b. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right is not coded. Example:</p>
<p>*Ashcraft is coded A261 (A, 2 for the S, C ignored since same as S with H in between, 6 for the R, 1 for the F). It is not coded A226.</p>
<p>So far this is my code:</p>
<pre><code>surname = raw_input("Please enter surname:")
outstring = ""
outstring = outstring + surname[0]
for i in range (1, len(surname)):
nextletter = surname[i]
if nextletter in ['B','F','P','V']:
outstring = outstring + '1'
elif nextletter in ['C','G','J','K','Q','S','X','Z']:
outstring = outstring + '2'
elif nextletter in ['D','T']:
outstring = outstring + '3'
elif nextletter in ['L']:
outstring = outstring + '4'
elif nextletter in ['M','N']:
outstring = outstring + '5'
elif nextletter in ['R']:
outstring = outstring + '6'
print outstring
</code></pre>
<p>The code sufficiently does what it is asked to, I am just not sure how to code the three rules. That is where I need help. So, any help is appreciated.</p>
| 2 | 2009-10-13T19:31:28Z | 1,562,493 | <p>A few hints:</p>
<ul>
<li><p>By using an array where each Soundex code is stored and indexed by the ASCII value (or a value in a shorter numeric range derived thereof) of the letter it corresponds to, you will both make the code for efficient and more readable. This is <strong>a very common technique</strong>: understand, use and reuse ;-)</p></li>
<li><p>As you parse the input string, you need keep track of (or compare with) the letter previously handled to ignore repeating letters, and handle other the rules. (implement each of these these in a separate function as hinted in the write-up). The idea could be to introduce a function in charge of -<em>maybe</em>- adding the soundex code for the current letter of the input being processed. This function would in turn call each of the "rules" functions, possibly quiting early based on the return values of some rules. In other words, replace the systematic...</p></li>
</ul>
<pre>
outstring = outstring + c # btw could be +=
...with
outstring += AppendCodeIfNeeded(c)
</pre>
<ul>
<li>beware that this multi-function structure is overkill for such trivial logic, but it is not a bad idea to do it for practice.</li>
</ul>
| 0 | 2009-10-13T19:41:01Z | [
"python",
"soundex"
] |
Could use some help with this soundex coding | 1,562,438 | <p>The US census bureau uses a special encoding called âsoundexâ to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled differently, like SMITH and SMYTH, have the same code and are filed together. The soundex coding system was developed so that you can find a surname even though it may have been recorded under various spellings.</p>
<p>In this lab you will design, code, and document a program that produces the soundex code when input with a surname. A user will be prompted for a surname, and the program should output the corresponding code.</p>
<p>Basic Soundex Coding Rules</p>
<p>Every soundex encoding of a surname consists of a letter and three numbers. The letter used is always the first letter of the surname. The numbers are assigned to the remaining letters of the surname according to the soundex guide shown below. Zeroes are added at the end if necessary to always produce a four-character code. Additional letters are disregarded. </p>
<p>Soundex Coding Guide</p>
<p>Soundex assigns a number for various consonants. Consonants that sound alike are assigned the same number:</p>
<p>Number Consonants</p>
<p>1 B, F, P, V
2 C, G, J, K, Q, S, X, Z
3 D, T
4 L
5 M, N
6 R</p>
<p>Soundex disregards the letters A, E, I, O, U, H, W, and Y.</p>
<p>There are 3 additional Soundex Coding Rules that are followed. A good program design would implement these each as one or more separate functions.</p>
<p>Rule 1. Names With Double Letters</p>
<p>If the surname has any double letters, they should be treated as one letter. For example:</p>
<ul>
<li>Gutierrez is coded G362 (G, 3 for the T, 6 for the first R, second R ignored, 2 for the Z).</li>
</ul>
<p>Rule 2. Names with Letters Side-by-Side that have the Same Soundex Code Number</p>
<p>If the surname has different letters side-by-side that have the same number in the soundex coding guide, they should be treated as one letter. Examples:</p>
<ul>
<li><p>Pfister is coded as P236 (P, F ignored since it is considered same as P, 2 for the S, 3 for the T, 6 for the R).</p></li>
<li><p>Jackson is coded as J250 (J, 2 for the C, K ignored same as C, S ignored same as C, 5 for the N, 0 added).</p></li>
</ul>
<p>Rule 3. Consonant Separators</p>
<p>3.a. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Example:</p>
<ul>
<li>Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.</li>
</ul>
<p>3.b. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right is not coded. Example:</p>
<p>*Ashcraft is coded A261 (A, 2 for the S, C ignored since same as S with H in between, 6 for the R, 1 for the F). It is not coded A226.</p>
<p>So far this is my code:</p>
<pre><code>surname = raw_input("Please enter surname:")
outstring = ""
outstring = outstring + surname[0]
for i in range (1, len(surname)):
nextletter = surname[i]
if nextletter in ['B','F','P','V']:
outstring = outstring + '1'
elif nextletter in ['C','G','J','K','Q','S','X','Z']:
outstring = outstring + '2'
elif nextletter in ['D','T']:
outstring = outstring + '3'
elif nextletter in ['L']:
outstring = outstring + '4'
elif nextletter in ['M','N']:
outstring = outstring + '5'
elif nextletter in ['R']:
outstring = outstring + '6'
print outstring
</code></pre>
<p>The code sufficiently does what it is asked to, I am just not sure how to code the three rules. That is where I need help. So, any help is appreciated.</p>
| 2 | 2009-10-13T19:31:28Z | 1,562,597 | <p>Here are some small hints on general Python stuff.</p>
<p>0) You can use a for loop to loop over any sequence, and a string counts as a sequence. So you can write:</p>
<pre><code>for nextletter in surname[1:]:
# do stuff
</code></pre>
<p>This is easier to write and easier to understand than computing an index and indexing the surname.</p>
<p>1) You can use the <code>+=</code> operator to append strings. Instead of</p>
<pre><code>x = x + 'a'
</code></pre>
<p>you can write</p>
<pre><code>x += 'a'
</code></pre>
<p>As for help with your specific problem, you will want to keep track of the previous letter. If your assignment had a rule that said "two 'z' characters in a row should be coded as 99" you could add code like this:</p>
<pre><code>def rule_two_z(prevletter, curletter):
if prevletter.lower() == 'z' and curletter.lower() == 'z':
return 99
else:
return -1
prevletter = surname[0]
for curletter in surname[1:]:
code = rule_two_z(prevletter, curletter)
if code < 0:
# do something else here
outstring += str(code)
prevletter = curletter
</code></pre>
<p>Hmmm, you were writing your code to return string integers like <code>'3'</code>, while I wrote my code to return an actual integer and then call <code>str()</code> on it before adding it to the string. Either way is probably fine.</p>
<p>Good luck!</p>
| 0 | 2009-10-13T20:01:38Z | [
"python",
"soundex"
] |
How to encrypt text into a image using python | 1,562,664 | <p>I was wondering how can someone use python to encrypt text into an image.</p>
| 0 | 2009-10-13T20:12:33Z | 1,562,674 | <p>Google search for "python steganography" and you find some stuff.</p>
<p>Here's a Python library module: <a href="http://domnit.org/stepic/doc/" rel="nofollow">stepic</a></p>
| 7 | 2009-10-13T20:15:31Z | [
"python",
"steganography"
] |
How to encrypt text into a image using python | 1,562,664 | <p>I was wondering how can someone use python to encrypt text into an image.</p>
| 0 | 2009-10-13T20:12:33Z | 1,567,877 | <p>This issue has need the type of file . Some image has special has place for description. You can use this with an encripted string. All you need is to write python script to read this places and decrypt it.</p>
| -1 | 2009-10-14T17:44:14Z | [
"python",
"steganography"
] |
Can Python print a function definition? | 1,562,759 | <p>In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? </p>
<p>(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). </p>
| 37 | 2009-10-13T20:33:35Z | 1,562,772 | <p>If you're using <a href="http://ipython.org/" rel="nofollow" title="ipython homepage">iPython</a>, you can use <strong><code>function_name?</code></strong> to get help, and <strong><code>function_name??</code></strong> will print out the source, if it can.</p>
| 32 | 2009-10-13T20:35:55Z | [
"python"
] |
Can Python print a function definition? | 1,562,759 | <p>In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? </p>
<p>(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). </p>
| 37 | 2009-10-13T20:33:35Z | 1,562,795 | <p>If you are importing the function, you can use <a href="http://docs.python.org/library/inspect.html#inspect.getsource"><code>inspect.getsource</code></a>:</p>
<pre><code>>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
</code></pre>
<p>This <em>will</em> work in the interactive prompt, but apparently only on objects that are imported (not objects defined within the interactive prompt). And of course it will only work if Python can find the source code (so not on built-in objects, C libs, .pyc files, etc)</p>
| 53 | 2009-10-13T20:41:18Z | [
"python"
] |
Can Python print a function definition? | 1,562,759 | <p>In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? </p>
<p>(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). </p>
| 37 | 2009-10-13T20:33:35Z | 1,562,798 | <p>You can use the __doc__ keyword:</p>
<pre><code>#print the class description
print string.__doc__
#print function description
print open.__doc__
</code></pre>
| 0 | 2009-10-13T20:41:42Z | [
"python"
] |
Can Python print a function definition? | 1,562,759 | <p>In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? </p>
<p>(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). </p>
| 37 | 2009-10-13T20:33:35Z | 1,564,151 | <p>Take a look at <code>help()</code> function from <code>pydoc</code> module. In interactive mode it should be already imported for you, so just type <code>help(funtion_to_describe)</code>. For more capabilities use <a href="http://ipython.scipy.org/" rel="nofollow">IPython</a>.</p>
| 1 | 2009-10-14T03:53:07Z | [
"python"
] |
Can Python print a function definition? | 1,562,759 | <p>In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python? </p>
<p>(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). </p>
| 37 | 2009-10-13T20:33:35Z | 27,458,391 | <p>While I'd generally agree that <code>inspect</code> is a good answer, I'd disagree that you can't get the source code of objects defined in the interpreter. If you use <code>dill.source.getsource</code> from <a href="https://github.com/uqfoundation/dill" rel="nofollow"><code>dill</code></a>, you can get the source of functions and lambdas, even if they are defined interactively.
It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.</p>
<pre><code>>>> from dill.source import getsource
>>>
>>> def add(x,y):
... return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getsource(add)
def add(x,y):
return x+y
>>> print getsource(squared)
squared = lambda x:x**2
>>>
>>> class Foo(object):
... def bar(self, x):
... return x*x+x
...
>>> f = Foo()
>>>
>>> print getsource(f.bar)
def bar(self, x):
return x*x+x
>>>
</code></pre>
| 4 | 2014-12-13T11:41:58Z | [
"python"
] |
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) | 1,562,999 | <p>After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".</p>
<p>So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.</p>
<p>But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.</p>
<p>Izpack is out of the game because it requires Java for the installer to run on the target system.</p>
<p>Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).</p>
<p>Any other ideas?</p>
<p>Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.</p>
| 2 | 2009-10-13T21:26:51Z | 1,563,032 | <p>You might try looking at <a href="http://www.flexerasoftware.com/products/installanywhere.htm" rel="nofollow">InstallAnywhere</a>, but it may require Java.</p>
| 0 | 2009-10-13T21:34:13Z | [
"python",
"windows",
"linux",
"installer"
] |
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) | 1,562,999 | <p>After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".</p>
<p>So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.</p>
<p>But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.</p>
<p>Izpack is out of the game because it requires Java for the installer to run on the target system.</p>
<p>Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).</p>
<p>Any other ideas?</p>
<p>Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.</p>
| 2 | 2009-10-13T21:26:51Z | 1,564,460 | <p>You may be interested by <a href="http://installbuilder.bitrock.com/index.html" rel="nofollow">BitRock</a></p>
| 2 | 2009-10-14T05:49:10Z | [
"python",
"windows",
"linux",
"installer"
] |
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) | 1,562,999 | <p>After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".</p>
<p>So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.</p>
<p>But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.</p>
<p>Izpack is out of the game because it requires Java for the installer to run on the target system.</p>
<p>Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).</p>
<p>Any other ideas?</p>
<p>Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.</p>
| 2 | 2009-10-13T21:26:51Z | 1,572,176 | <p>Try running <a href="http://www.jrsoftware.org/isinfo.php" rel="nofollow">InnoSetup</a> under <a href="http://www.winehq.org/" rel="nofollow">Wine</a>. It should work unless you have some very specific needs. InnoSetup is open source, BTW.</p>
| 0 | 2009-10-15T12:52:50Z | [
"python",
"windows",
"linux",
"installer"
] |
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) | 1,562,999 | <p>After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".</p>
<p>So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.</p>
<p>But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.</p>
<p>Izpack is out of the game because it requires Java for the installer to run on the target system.</p>
<p>Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).</p>
<p>Any other ideas?</p>
<p>Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.</p>
| 2 | 2009-10-13T21:26:51Z | 3,513,568 | <p>It seems that <a href="http://pyinstaller.python-hosting.com/" rel="nofollow">pyinstaller</a> might do the trick. I'm also looking for something like what you need. I have not tried it yet ...</p>
| 0 | 2010-08-18T15:09:45Z | [
"python",
"windows",
"linux",
"installer"
] |
URLs stored in database for Django site | 1,563,088 | <p>I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.</p>
<p>Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)?</p>
<p>If someone can just point me at the right part of the docs or a site which explains this it would help a lot.</p>
<p>Thanks all.</p>
| 0 | 2009-10-13T21:43:48Z | 1,563,359 | <p>Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches.</p>
<p>We did this on one site where all of the URLs were made "search engine friendly". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed <em>before</em> flatpages in the middleware list).</p>
| 1 | 2009-10-13T22:42:30Z | [
"python",
"database",
"django",
"url",
"content-management-system"
] |
URLs stored in database for Django site | 1,563,088 | <p>I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.</p>
<p>Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)?</p>
<p>If someone can just point me at the right part of the docs or a site which explains this it would help a lot.</p>
<p>Thanks all.</p>
| 0 | 2009-10-13T21:43:48Z | 1,563,592 | <p>You dont have to to it in the flatpage-way</p>
<p>For models, that should be addressable, I do this:</p>
<p>In urls.py I have a url-mapping like</p>
<pre><code> url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name="category-view")
</code></pre>
<p>in this case the regular expression <code>(?P<slug>[a-z1-3_]{1,})</code> will return a variable called slug and send it to my view <code>cms.views.category_view</code>. In that view I query like this:</p>
<pre><code>@render_to('category.html')
def category_view(request, slug):
return {'cat':Category.objects.get(slug=slug)}
</code></pre>
<p>(Note: I am using the <a href="http://bitbucket.org/offline/django-annoying/wiki/Home" rel="nofollow">annoying-decorator</a> <code>render_to</code> â it is the same as <code>render_to_response</code>, just shorter)</p>
<p><strong>Edit</strong> This should be covered by the <a href="http://docs.djangoproject.com/en/dev/intro/" rel="nofollow">tutorial</a>. Here you find the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-urls" rel="nofollow">url-configuration and dispatching</a> in every detail. The djangobook also covers it. And check pythons regex module.</p>
<p>Of course you can use this code. </p>
| 5 | 2009-10-13T23:55:20Z | [
"python",
"database",
"django",
"url",
"content-management-system"
] |
What pure Python library should I use to scrape a website? | 1,563,165 | <p>I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.</p>
<p>Now I'm trying to port this over to Google App Engine, and keep getting stuck.</p>
<p>I've ported Python Mechanize to work with Google App Engine, but it doesn't support DOM inspection with XPATH.</p>
<p>I've tried the built-in ElementTree, but it choked on the first HTML blob I gave it when it ran into '&mdash'.</p>
<p>Do I keep trying to hack ElementTree in there, or do I try to use something else?</p>
<p>thanks,
Mark</p>
| 2 | 2009-10-13T21:58:03Z | 1,563,177 | <p>Beautiful Soup.</p>
| 11 | 2009-10-13T22:01:06Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] |
What pure Python library should I use to scrape a website? | 1,563,165 | <p>I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.</p>
<p>Now I'm trying to port this over to Google App Engine, and keep getting stuck.</p>
<p>I've ported Python Mechanize to work with Google App Engine, but it doesn't support DOM inspection with XPATH.</p>
<p>I've tried the built-in ElementTree, but it choked on the first HTML blob I gave it when it ran into '&mdash'.</p>
<p>Do I keep trying to hack ElementTree in there, or do I try to use something else?</p>
<p>thanks,
Mark</p>
| 2 | 2009-10-13T21:58:03Z | 1,563,301 | <p>lxml -- 100x better than elementtree</p>
| 6 | 2009-10-13T22:28:18Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] |
What pure Python library should I use to scrape a website? | 1,563,165 | <p>I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.</p>
<p>Now I'm trying to port this over to Google App Engine, and keep getting stuck.</p>
<p>I've ported Python Mechanize to work with Google App Engine, but it doesn't support DOM inspection with XPATH.</p>
<p>I've tried the built-in ElementTree, but it choked on the first HTML blob I gave it when it ran into '&mdash'.</p>
<p>Do I keep trying to hack ElementTree in there, or do I try to use something else?</p>
<p>thanks,
Mark</p>
| 2 | 2009-10-13T21:58:03Z | 1,563,302 | <p>There's also <a href="http://scrapy.org/" rel="nofollow">scrapy</a>, might be more up your alley.</p>
| 4 | 2009-10-13T22:29:49Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] |
What pure Python library should I use to scrape a website? | 1,563,165 | <p>I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.</p>
<p>Now I'm trying to port this over to Google App Engine, and keep getting stuck.</p>
<p>I've ported Python Mechanize to work with Google App Engine, but it doesn't support DOM inspection with XPATH.</p>
<p>I've tried the built-in ElementTree, but it choked on the first HTML blob I gave it when it ran into '&mdash'.</p>
<p>Do I keep trying to hack ElementTree in there, or do I try to use something else?</p>
<p>thanks,
Mark</p>
| 2 | 2009-10-13T21:58:03Z | 1,563,437 | <p>There are a number of examples of web page scrapers written using <a href="http://pyparsing.wikispaces.com" rel="nofollow">pyparsing</a>, such as <a href="http://pyparsing.wikispaces.com/file/view/urlExtractorNew.py" rel="nofollow">this one</a> (extracts all URL links from yahoo.com) and <a href="http://pyparsing.wikispaces.com/file/view/getNTPserversNew.py" rel="nofollow">this one</a> (for extracting the NIST NTP server addresses). Be sure to use the pyparsing helper method makeHTMLTags, instead of just hand coding <code>"<" + Literal(tagname) + ">"</code> - makeHTMLTags creates a very robust parser, with accommodation for extra spaces, upper/lower case inconsistencies, unexpected attributes, attribute values with various quoting styles, and so on. Pyparsing will also give you more control over special syntax issues, such as custom entities. Also it is pure Python, liberally licensed, and small footprint (a single source module), so it is easy to drop into your GAE app right in with your other application code.</p>
| 0 | 2009-10-13T23:01:53Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] |
What pure Python library should I use to scrape a website? | 1,563,165 | <p>I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.</p>
<p>Now I'm trying to port this over to Google App Engine, and keep getting stuck.</p>
<p>I've ported Python Mechanize to work with Google App Engine, but it doesn't support DOM inspection with XPATH.</p>
<p>I've tried the built-in ElementTree, but it choked on the first HTML blob I gave it when it ran into '&mdash'.</p>
<p>Do I keep trying to hack ElementTree in there, or do I try to use something else?</p>
<p>thanks,
Mark</p>
| 2 | 2009-10-13T21:58:03Z | 1,793,897 | <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> is good, but its API is awkward. Try <a href="http://effbot.org/zone/element-soup.htm" rel="nofollow">ElementSoup</a>, which provides an ElementTree interface to BeautifulSoup. </p>
| 0 | 2009-11-25T00:18:51Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] |
How does the Jinja2 "recursive" tag actually work? | 1,563,276 | <p>I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the way that Jinja's recursion works that I don't understand. The code is shown below:</p>
<pre><code>from jinja2 import Template
class Category(object):
def __init__(self, name):
self.name = name
self.items = {}
self.children = True
def __iter__(self):
return iter(self.items)
def add(self, key, item):
self.items[key] = item
return item
def __getitem__(self, item):
return self.items[item]
def __getattr__(self, attr):
try:
return self.items[attr]
except KeyError:
raise AttributeError(attr)
def __str__(self):
return "<Category '%s'>" % self.name
template = '''
<saved_data>
{% for key in category recursive %}
{% set item = category[key] %}
{% if item.children %}
<category name="{{key}}">
{{ loop(item) }}
</category>
{% else %}
<item name="{{ key }}" value="{{ item }}" />
{% endif %}
{% endfor %}
</saved_data>
'''
b = Category('root')
c = b.add("numbers", Category('numbers'))
c.add("one", 1)
c.add("two", 2)
c.add("three", 3)
d = b.add("letters", Category('letters'))
d.add('ay','a')
d.add('bee','b')
d.add('cee','c')
e = d.add("bools", Category('bools'))
e.add('tru', True)
e.add('fals', False)
def walk(c, depth=0):
for key in c:
item = c[key]
print (' '*depth) + str(item)
if hasattr(item, 'children'):
walk(item, depth+3)
print "Python walking the tree:"
walk(b)
print ""
print "Jinja2 Walking the tree:"
t = Template(template)
print t.render(category = b)
</code></pre>
<p>The template is raising an exception as if the recursion didn't actually take place. The inner call is made, but somehow the reference to 'category' still refers to the parent. What gives here? There must be something very fundamental I'm missing about how these recursive templates are supposed to work. (Or something very fundamentally silly that I'm doing that I just can't see.</p>
| 8 | 2009-10-13T22:21:37Z | 1,565,090 | <p>As I see from your code you understand recursive correctly, except one thing: it does replace iterable in the for statement, but doesn't update variable (<code>category</code> in your code) originally used in it. Thus, you nested loop iterates through children, but <code>set</code> tag lookups in original <code>category</code>, not one passed to the <code>loop()</code>. </p>
<p>I suggest changing <code>__iter__()</code> method to return <code>self.items.iteritems()</code> and template to:</p>
<pre><code><saved_data>
{% for key, item in category recursive %}
{% if item.children %}
<category name="{{key}}">
{{ loop(item) }}
</category>
{% else %}
<item name="{{ key }}" value="{{ item }}" />
{% endif %}
{% endfor %}
</saved_data>
</code></pre>
| 7 | 2009-10-14T08:56:56Z | [
"python",
"recursion",
"templates",
"jinja2"
] |
What is an "app" in Django? | 1,563,457 | <p>According to <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3">the documentation</a>:</p>
<blockquote>
<p>An app is a Web application that does
something -- e.g., a weblog system, a
database of public records or a simple
poll app. A project is a collection of
configuration and apps for a
particular Web site. A project can
contain multiple apps. An app can be
in multiple projects.</p>
</blockquote>
<p>However, what are other examples of what makes an "app"?</p>
| 11 | 2009-10-13T23:09:56Z | 1,563,466 | <p>User management could very well be an app, if you are not going to use Django's built in user framework.</p>
<p>It has user interfaces and defined models for stored data, and it is really separate from the Blog or the Wiki application (although the information will be shared).</p>
<p>As long as both applications are in the same 'project' they should use the same settings for the DB. You should be able to by just making sure the proper models are imported where you are trying to use them.</p>
<p>See <a href="http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/" rel="nofollow">this link</a> for a little more information.</p>
| 2 | 2009-10-13T23:14:34Z | [
"python",
"django"
] |
What is an "app" in Django? | 1,563,457 | <p>According to <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3">the documentation</a>:</p>
<blockquote>
<p>An app is a Web application that does
something -- e.g., a weblog system, a
database of public records or a simple
poll app. A project is a collection of
configuration and apps for a
particular Web site. A project can
contain multiple apps. An app can be
in multiple projects.</p>
</blockquote>
<p>However, what are other examples of what makes an "app"?</p>
| 11 | 2009-10-13T23:09:56Z | 1,563,500 | <p>What makes an app (for us) is one thing:</p>
<p><strong>An App Is The Unit Of Reuse</strong></p>
<p>If we might want to split it off to use somewhere else, it's an app. </p>
<p>If it has a reusable data model, it's an app. User Profiles: App. Customers: App. Customer Statistical History (this is hard to explain without providing too many details): App. Reporting: App. Actuarial Analysis: App. Vendor API's for data gathering: App.</p>
<p>If it is unique and will never be reused (i.e., customer specific) it's an app that depends on other apps. Data Loads are customer specific. Each is an app that builds on an existing pair of apps (Batch Uploads, and Statistical History)</p>
| 12 | 2009-10-13T23:24:30Z | [
"python",
"django"
] |
What is an "app" in Django? | 1,563,457 | <p>According to <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3">the documentation</a>:</p>
<blockquote>
<p>An app is a Web application that does
something -- e.g., a weblog system, a
database of public records or a simple
poll app. A project is a collection of
configuration and apps for a
particular Web site. A project can
contain multiple apps. An app can be
in multiple projects.</p>
</blockquote>
<p>However, what are other examples of what makes an "app"?</p>
| 11 | 2009-10-13T23:09:56Z | 1,566,404 | <p>Django apps are bundles of reusable functionality. When starting off it's easy to just use one custom app for your project, but the "Django way" is to break it up into separate apps that each only do one thing. You can take a look at django.contrib for examples of really well made reusable apps.</p>
<p>A recent example of mine: a client needed a way to import CSV data into the Django models. The easiest way would be to just add a model with a FileField and write a quick parser for the specific format of what they are uploading. That would work fine until the format changed and I had to go make the parser match. But this is a commonly repeated task (importing data) and unrelated to the existing app (managing that data) so I broke it out on its own. This pluggable app can import data for any active model. Now the next time a client needs import functionality I just add this code to installed_apps and run syncdb.</p>
<p>It's a judgement call when to break out an app onto its own, but the rule of thumb for me is if I'm likely to do something again I'll take the extra time to make it a generic app. That means I've created some tiny apps (some just contain a template tag), but it's little overhead for the future gains.</p>
| 4 | 2009-10-14T13:58:59Z | [
"python",
"django"
] |
Python library/framework to write an application that sends emails periodically | 1,563,468 | <p>I am considering to write an application that would covert the comments in reddit threads (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/" rel="nofollow">example</a>) to emails. The idea is to parse the reddit json data (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/.json" rel="nofollow">example</a>) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for writing this tool is to read reddit comments in our favorite EMail client (with filters and what not) without having to refresh the reddit thread.</p>
<p>Which library/framework is best suited for this task? To get it done faster? With minimal code?</p>
| 0 | 2009-10-13T23:14:46Z | 1,563,508 | <p>I've used <a href="http://flexget.com/" rel="nofollow">Flexget</a> to parse RSS feeds and email them.
You can get ideas from there.</p>
| 0 | 2009-10-13T23:28:52Z | [
"python",
"email",
"frameworks",
"reddit"
] |
Python library/framework to write an application that sends emails periodically | 1,563,468 | <p>I am considering to write an application that would covert the comments in reddit threads (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/" rel="nofollow">example</a>) to emails. The idea is to parse the reddit json data (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/.json" rel="nofollow">example</a>) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for writing this tool is to read reddit comments in our favorite EMail client (with filters and what not) without having to refresh the reddit thread.</p>
<p>Which library/framework is best suited for this task? To get it done faster? With minimal code?</p>
| 0 | 2009-10-13T23:14:46Z | 1,563,561 | <p>I would go with AppEngine to tackle this: integrated cron + email support.</p>
| 1 | 2009-10-13T23:46:25Z | [
"python",
"email",
"frameworks",
"reddit"
] |
Python library/framework to write an application that sends emails periodically | 1,563,468 | <p>I am considering to write an application that would covert the comments in reddit threads (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/" rel="nofollow">example</a>) to emails. The idea is to parse the reddit json data (<a href="http://www.reddit.com/r/Python/comments/9tebz/pje%5Fis%5Fabout%5Fto%5Fmake%5Fa%5Fnew%5Frelease%5Fof%5Fsetuptools/.json" rel="nofollow">example</a>) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for writing this tool is to read reddit comments in our favorite EMail client (with filters and what not) without having to refresh the reddit thread.</p>
<p>Which library/framework is best suited for this task? To get it done faster? With minimal code?</p>
| 0 | 2009-10-13T23:14:46Z | 1,563,629 | <p><a href="http://lamsonproject.org/" rel="nofollow">Lamson</a> aims to be an 'email app framework' (taking after the recent developments in web app frameworks). It seems like it would be a good fit for the problem you describe.</p>
| 0 | 2009-10-14T00:07:27Z | [
"python",
"email",
"frameworks",
"reddit"
] |
Sending a file with OBEX push in Python | 1,563,488 | <p>How to send a file using OBEX push to a device, which has an open OBEX port in Python? In my case it is a Bluetooth device.</p>
| 3 | 2009-10-13T23:21:04Z | 1,563,545 | <p>There is an "<a href="http://packages.debian.org/lenny/obex-data-server" rel="nofollow">OBEX data server</a>" DEBIAN package with DBus interface which could help you. Accessing DBus through Python is fairly easy.</p>
| 0 | 2009-10-13T23:41:21Z | [
"python",
"bluetooth",
"obex"
] |
Sending a file with OBEX push in Python | 1,563,488 | <p>How to send a file using OBEX push to a device, which has an open OBEX port in Python? In my case it is a Bluetooth device.</p>
| 3 | 2009-10-13T23:21:04Z | 1,595,353 | <p>Try <a href="http://lightblue.sourceforge.net/" rel="nofollow">http://lightblue.sourceforge.net/</a></p>
<p>The documentation for the OBEX client is here: <a href="http://lightblue.sourceforge.net/doc/lightblue.obex-OBEXClient.html" rel="nofollow">http://lightblue.sourceforge.net/doc/lightblue.obex-OBEXClient.html</a></p>
| 0 | 2009-10-20T15:13:10Z | [
"python",
"bluetooth",
"obex"
] |
Naming convention for actually choosing the words in Python, PEP8 compliant | 1,563,673 | <p>Iâm looking for a better way to name everything in Python. Yes, Iâve read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">Spolskyâs wonderful rant</a>, and various other articles. But Iâm looking for more guidance in choosing the actual words.</p>
<p>And yes I know</p>
<blockquote>
<p>A Foolish Consistency is the Hobgoblin
of Little Minds.</p>
</blockquote>
<p>But, you can keep consistent with PEP8 etc, and still not have consistent variable/method/class names which are easy to remember. By consistent, I mean that if you were presented with the same decision twice, you would produce the same name. </p>
<p>As an example, there are multiple PEP8 compliant ways to name the items below:</p>
<ul>
<li>number of columns in the table</li>
<li>current column number</li>
<li>column object</li>
<li>sum of column</li>
</ul>
<p>Yeah, sure, it is easy to make a decision to use something like <code>num_col</code> and <code>count_col</code> rather than <code>col_num</code> and <code>col_count</code> (or v.v.). But, I would like to see an example that has seen some testing/refining over time. I often start with a given convention, and then it starts to break down as I venture into a new area. </p>
<p>I guess what I am looking for is not only what the prefix/root/tag/suffix should do (which was partly covered for Apps Hungarian in the Spolsky article), but (many) examples for each, or a rule for generating each.</p>
| 3 | 2009-10-14T00:21:52Z | 1,563,890 | <p>The universe is multi-dimensional.</p>
<p>You have at least two dimensions to each variable name.</p>
<p>"Total", "Count", "Of Columns", "In a Table"</p>
<p>"Current", "Index", "", "Of a Column"</p>
<p>"Current", "Column", "", ""</p>
<p>"Sum", "Of Something", "", "In a Column"</p>
<p>Rats. It's irregular. </p>
<p>Worse, we can pick anything as the "Primary" dimension and pick any sequence of other features as "secondary" dimensions.</p>
<p>Even worse, we could have a truly complex thing. "Total", "Count", "of Non-Underscore", "Columns", "In Tables", "With Even-Length Names", "From a Dictionary", "Keyed by", "Mother's Maiden Name".</p>
<p>Frankly, there's no possible schema for variable names that encompasses "all" knowledge in a systematic, repeatable form.</p>
<p>Keep trying though. It's always fun and games until someone finds a counter-example.</p>
<p>You can keep trying or you can simply use simple, clear names. If your scope of names is small (a small method function, for example), there's nothing to "remember". It's all perfectly visible in the 20 lines of code that make up the method function. </p>
| 1 | 2009-10-14T01:57:34Z | [
"python",
"naming-conventions"
] |
Naming convention for actually choosing the words in Python, PEP8 compliant | 1,563,673 | <p>Iâm looking for a better way to name everything in Python. Yes, Iâve read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">Spolskyâs wonderful rant</a>, and various other articles. But Iâm looking for more guidance in choosing the actual words.</p>
<p>And yes I know</p>
<blockquote>
<p>A Foolish Consistency is the Hobgoblin
of Little Minds.</p>
</blockquote>
<p>But, you can keep consistent with PEP8 etc, and still not have consistent variable/method/class names which are easy to remember. By consistent, I mean that if you were presented with the same decision twice, you would produce the same name. </p>
<p>As an example, there are multiple PEP8 compliant ways to name the items below:</p>
<ul>
<li>number of columns in the table</li>
<li>current column number</li>
<li>column object</li>
<li>sum of column</li>
</ul>
<p>Yeah, sure, it is easy to make a decision to use something like <code>num_col</code> and <code>count_col</code> rather than <code>col_num</code> and <code>col_count</code> (or v.v.). But, I would like to see an example that has seen some testing/refining over time. I often start with a given convention, and then it starts to break down as I venture into a new area. </p>
<p>I guess what I am looking for is not only what the prefix/root/tag/suffix should do (which was partly covered for Apps Hungarian in the Spolsky article), but (many) examples for each, or a rule for generating each.</p>
| 3 | 2009-10-14T00:21:52Z | 1,563,901 | <p>I believe that the need for complex variable naming conventions goes away with good object-oriented design. In the Spolsky article, much focus is on how variable naming helps preventing errors. I believe that those errors will more often occur when you have many variables in the same scope; this can be avoided by grouping data into objects - then, a single naming context will have only few variables, which don't need combined names.</p>
<p>The other purpose of a naming convention is to better remember the names. Again, object-orientation helps (by hiding much data from users that look from the outside); what you then need is a convention for naming methods, not data. In addition, tools can help which provide you with a list of names available in a certain scope (again, those tools rely on object-orientation to do their job).</p>
<p>In your specific example, if column is an object, I would expect that <code>len(table)</code> gives me the number of columns in a table, <code>sum(column)</code> or <code>column.sum()</code> gives me its sum; and the current column is just the variable in the for loop (often <code>c</code> or <code>column</code>).</p>
| 4 | 2009-10-14T02:01:33Z | [
"python",
"naming-conventions"
] |
Naming convention for actually choosing the words in Python, PEP8 compliant | 1,563,673 | <p>Iâm looking for a better way to name everything in Python. Yes, Iâve read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">Spolskyâs wonderful rant</a>, and various other articles. But Iâm looking for more guidance in choosing the actual words.</p>
<p>And yes I know</p>
<blockquote>
<p>A Foolish Consistency is the Hobgoblin
of Little Minds.</p>
</blockquote>
<p>But, you can keep consistent with PEP8 etc, and still not have consistent variable/method/class names which are easy to remember. By consistent, I mean that if you were presented with the same decision twice, you would produce the same name. </p>
<p>As an example, there are multiple PEP8 compliant ways to name the items below:</p>
<ul>
<li>number of columns in the table</li>
<li>current column number</li>
<li>column object</li>
<li>sum of column</li>
</ul>
<p>Yeah, sure, it is easy to make a decision to use something like <code>num_col</code> and <code>count_col</code> rather than <code>col_num</code> and <code>col_count</code> (or v.v.). But, I would like to see an example that has seen some testing/refining over time. I often start with a given convention, and then it starts to break down as I venture into a new area. </p>
<p>I guess what I am looking for is not only what the prefix/root/tag/suffix should do (which was partly covered for Apps Hungarian in the Spolsky article), but (many) examples for each, or a rule for generating each.</p>
| 3 | 2009-10-14T00:21:52Z | 1,583,072 | <p>Remember that in English, when two ambiguous words are next to each other, the first one becomes an adjective which describes the second one. Try to stick to this rule and always name things with two components where the first component decribes the second.</p>
<p>For instance col_num is a number. What kind of number? A column number.</p>
<p>Next rule is the word of. It is a nice short word so please do not leave it out. Same goes with pluralization. And past tense ending in -ed or -d. Maybe even -ing.</p>
<p>For instance, num_col is a column. What kind? A number column. If you really wanted to refer to the number of columns, you should write num_of_cols. Received date is recd_date or rcvd_date, not rec_date or rcv_date.</p>
<p>English speaking readers are very sensitive to -s and -d at the end of words, as well as of in the middle of a phrase, so don't assume that such short bits of text would be missed. That is very unlikely because we are programmed from a very young age to notice a handful of word endings. </p>
<p>Try for consistency, and keep a glossary or data dictionary of any words, or word fragments that you use. Don't use the same fragment for two different things. If you are using recd to mean received, and you need a variable name for recorded, then either write it out in full or come up with a new abbreviation and put it in the glossary. If you use a relational database, try to be consistent with the naming convention used there. Let the dba know what you are doing and tell them where to find your glossary.</p>
| 2 | 2009-10-17T19:59:39Z | [
"python",
"naming-conventions"
] |
Bundle additional executables with py2exe | 1,563,948 | <p>I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs?</p>
<p><hr /></p>
<p>Full explanation: My script is made to execute over a network share (S:\share\my_script.exe) and it makes hundreds of calls to sigcheck and accesscheck. If sigcheck and accesschk also reside on the server, they seem to get transferred to the host, called once, transferred the the host again, called a second time, on and on until the almost 400-500 calls are complete.</p>
<p>I can probably fall back to copying these two executables to the host (C:) and then deleting them when I'm done... how would you solve this problem?</p>
| 3 | 2009-10-14T02:21:30Z | 1,563,963 | <p>I could be wrong about this, but I don't believe this is what py2exe was intended for. It's more about <em>what</em> you're distributing than about <em>how</em> you're distributing. I think what you may be looking for is the option to create a <a href="http://docs.python.org/distutils/builtdist.html#creating-windows-installers" rel="nofollow">windows installer</a>. You could probably add the executables as data files or scripts using distutils.</p>
<blockquote>
<p>arggg Why can't my data_files just get bundled into the zipfile?</p>
</blockquote>
<p>I've started using <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a> for this kind of thing. It makes it really easy to override commands or create new commands that will allow you to put some new files into the sdist.</p>
| 2 | 2009-10-14T02:29:37Z | [
"python",
"executable",
"bundle",
"py2exe"
] |
List of tuples to Numpy recarray | 1,564,000 | <p>Given a list of tuples, where each tuple represents a row in a table, e.g.</p>
<pre><code>tab = [('a',1),('b',2)]
</code></pre>
<p>Is there an easy way to convert this to a record array? I tried</p>
<pre><code>np.recarray(tab,dtype=[('name',str),('value',int)])
</code></pre>
<p>which doesn't seem to work.</p>
| 2 | 2009-10-14T02:45:16Z | 1,564,041 | <p>try</p>
<pre><code>np.rec.fromrecords(tab)
rec.array([('a', 1), ('b', 2)],
dtype=[('f0', '|S1'), ('f1', '<i4')])
</code></pre>
| 4 | 2009-10-14T03:01:48Z | [
"python",
"numpy"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,564,427 | <pre><code>s = 'ABCDEFGHIJKLM'
print s[3:7]
print s[8:11]
</code></pre>
| 2 | 2009-10-14T05:35:15Z | [
"python"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,564,428 | <pre><code>>>> 'ABCDEFGHIJKLM'[3:7]
'DEFG'
>>> 'ABCDEFGHIJKLM'[8:11]
'IJK'
</code></pre>
<p>You might want to read a <a href="http://docs.python.org/tutorial/" rel="nofollow">tutorial</a> or beginners book.</p>
| 2 | 2009-10-14T05:35:34Z | [
"python"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,564,429 | <p>Look into Python's concept called sequence slicing!</p>
| 3 | 2009-10-14T05:35:49Z | [
"python"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,564,431 | <p>Here you go</p>
<pre><code>myString = 'ABCDEFGHIJKLM'
first = myString[3:7] # => DEFG
second = myString[8:11] # => IJK
</code></pre>
<p>In the slicing syntax, the first number is inclusive and the second is excluded.</p>
<p>You can read more about String slicing from <a href="http://docs.python.org/tutorial/introduction.html#strings" rel="nofollow">python docs</a></p>
| 8 | 2009-10-14T05:36:16Z | [
"python"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,564,433 | <pre><code>a = "ABCDEFGHIJKLM"
print a[3:7], a[8:11]
</code></pre>
<p>--> DEFG IJK</p>
| 3 | 2009-10-14T05:36:59Z | [
"python"
] |
Extracting substrings at specified positions | 1,564,414 | <p>How to extract substrings from a string at specified positions
For e.g.: âABCDEFGHIJKLMâ. I have To extract the substring from 3 to 6 and 8 to 10.</p>
<p>Required output: DEFG, IJK</p>
<p>Thanks in advance.</p>
| 0 | 2009-10-14T05:30:26Z | 1,565,208 | <p>In alternative you can use operator.itemgetter:</p>
<pre><code>>>> import operator
>>> s = 'ABCDEFGHIJKLM'
>>> f = operator.itemgetter(3,4,5,6,7,8,9,10,11)
>>> f(s)
('D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')
</code></pre>
| 0 | 2009-10-14T09:30:20Z | [
"python"
] |
Add timeout argument to python's Queue.join() | 1,564,501 | <p>I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet.
What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass?</p>
| 9 | 2009-10-14T06:02:49Z | 1,564,777 | <p>At first, you should ensure that all your working threads in the queue exit with <code>task_done()</code></p>
<p>To implement a timeout functionality with <code>Queue</code>, you can wrap the Queue's code in a Thread and add a timeout for this Thread using <code>Thread.join([timeout])</code></p>
<p><strong>untested example to outline what I suggest</strong></p>
<pre><code>def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
def queuefunc():
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.setDaemon(True)
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
t = Thread(target=queuefunc)
t.start()
t.join(100) # timeout applies here
</code></pre>
| 0 | 2009-10-14T07:30:41Z | [
"python",
"join",
"timeout",
"queue"
] |
Add timeout argument to python's Queue.join() | 1,564,501 | <p>I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet.
What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass?</p>
| 9 | 2009-10-14T06:02:49Z | 1,564,786 | <p>Subclassing <code>Queue</code> is probably the best way. Something like this should work (untested):</p>
<pre><code>def join_with_timeout(self, timeout):
self.all_tasks_done.acquire()
try:
endtime = time() + timeout
while self.unfinished_tasks:
remaining = endtime - time()
if remaining <= 0.0:
raise NotFinished
self.all_tasks_done.wait(remaining)
finally:
self.all_tasks_done.release()
</code></pre>
| 14 | 2009-10-14T07:33:14Z | [
"python",
"join",
"timeout",
"queue"
] |
Add timeout argument to python's Queue.join() | 1,564,501 | <p>I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet.
What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass?</p>
| 9 | 2009-10-14T06:02:49Z | 3,516,318 | <p>The <em>join()</em> method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count:</p>
<pre><code>stop = time() + timeout
while q.unfinished_tasks and time() < stop:
sleep(1)
</code></pre>
<p>This loop will exist either when the tasks are done or when the timeout period has elapsed.</p>
<p>Raymond</p>
| 8 | 2010-08-18T20:20:30Z | [
"python",
"join",
"timeout",
"queue"
] |
CMake output name for dynamic-loaded library? | 1,564,696 | <p>I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called <code>foo.so</code>.
But by default, cmake uses standard rules for library naming, so if I write</p>
<pre><code>add_library(foo foo.cpp)
</code></pre>
<p>I will get <code>libfoo.so</code> on output.
Even <code>set_target_properties(foo PROPERTIES OUTPUT_NAME "foobar")</code>
will create <code>libfoobar.so</code>.</p>
<p>How to change this behavior?</p>
| 32 | 2009-10-14T07:08:01Z | 1,564,798 | <p>The prefix "lib" is a convention for unix/linux and is exploited widely by compilers (e.g. when you link you write -lfoo). </p>
<p>I don't know if you can force cmake to create foo.so instead of libfoo.so, but maybe you can use "libfoo" for python module. Another option is to create install target in cmake ,which will renmae libfoo.so to foo.so</p>
| 1 | 2009-10-14T07:37:17Z | [
"python",
"cmake",
"shared-libraries",
"boost-python"
] |
CMake output name for dynamic-loaded library? | 1,564,696 | <p>I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called <code>foo.so</code>.
But by default, cmake uses standard rules for library naming, so if I write</p>
<pre><code>add_library(foo foo.cpp)
</code></pre>
<p>I will get <code>libfoo.so</code> on output.
Even <code>set_target_properties(foo PROPERTIES OUTPUT_NAME "foobar")</code>
will create <code>libfoobar.so</code>.</p>
<p>How to change this behavior?</p>
| 32 | 2009-10-14T07:08:01Z | 1,566,114 | <p>You can unset the prefix with this line:</p>
<pre><code>set_target_properties(foo PROPERTIES PREFIX "")
</code></pre>
| 53 | 2009-10-14T13:07:17Z | [
"python",
"cmake",
"shared-libraries",
"boost-python"
] |
Pylons/Formencode With Multiple Checkboxes | 1,565,035 | <p>I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:</p>
<pre><code><input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" name="Project" value="2">Project 2</input>
<input type="checkbox" name="Project" value="3">Project 3</input>
<input type="checkbox" name="Project" value="4">Project 4</input>
<input type="checkbox" name="Project" value="5">Project 5</input>
</code></pre>
<p>In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me):</p>
<pre><code>Project = formencode.foreach.ForEach(formencode.validators.Int())
</code></pre>
<p>I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails. </p>
<p>Anyone have any ideas?</p>
| 0 | 2009-10-14T08:38:45Z | 1,566,740 | <p>maybe using <a href="http://formencode.org/modules/validators.html#formencode.validators.Set" rel="nofollow"><code>formencode.validators.Set</code></a>:</p>
<pre><code>>>> Set.to_python(None)
[]
>>> Set.to_python('this')
['this']
>>> Set.to_python(('this', 'that'))
['this', 'that']
>>> s = Set(use_set=True)
>>> s.to_python(None)
set([])
>>> s.to_python('this')
set(['this'])
>>> s.to_python(('this',))
set(['this'])
</code></pre>
| 2 | 2009-10-14T14:41:28Z | [
"python",
"validation",
"pylons",
"formencode"
] |
Pylons/Formencode With Multiple Checkboxes | 1,565,035 | <p>I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:</p>
<pre><code><input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" name="Project" value="2">Project 2</input>
<input type="checkbox" name="Project" value="3">Project 3</input>
<input type="checkbox" name="Project" value="4">Project 4</input>
<input type="checkbox" name="Project" value="5">Project 5</input>
</code></pre>
<p>In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me):</p>
<pre><code>Project = formencode.foreach.ForEach(formencode.validators.Int())
</code></pre>
<p>I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails. </p>
<p>Anyone have any ideas?</p>
| 0 | 2009-10-14T08:38:45Z | 1,570,833 | <p>redrockettt,</p>
<p>Have you looked at the docstring to variabledecode? It suggests you use something like:</p>
<pre><code><input type="checkbox" name="Project-1" value="1">Project 1</input>
<input type="checkbox" name="Project-2" value="2">Project 2</input>
<input type="checkbox" name="Project-3" value="3">Project 3</input>
</code></pre>
<p>Check out the text in variabledecode.py, or pasted <a href="http://paste.turbogears.org/paste/122974/plain" rel="nofollow" title="here">here</a>.</p>
| 0 | 2009-10-15T07:38:07Z | [
"python",
"validation",
"pylons",
"formencode"
] |
python expression for this: max_value = max(firstArray) that is not in secondArray | 1,565,095 | <p>I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :)</p>
<p>I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the value can not be in the second array.</p>
<p>Is there any "fancy" way in python to put this down to one expression?<br>
<em>max_value = max(firstArray) that is not in secondArray</em></p>
| 1 | 2009-10-14T08:59:46Z | 1,565,103 | <p>Here's one way:</p>
<pre><code>max_value = [x for x in sorted(first) if x not in second][0]
</code></pre>
<p>It's less efficient than sorting then using a for loop to test if elements are in the second array, but it fits on one line nicely!</p>
| 1 | 2009-10-14T09:03:57Z | [
"python",
"expression"
] |
python expression for this: max_value = max(firstArray) that is not in secondArray | 1,565,095 | <p>I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :)</p>
<p>I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the value can not be in the second array.</p>
<p>Is there any "fancy" way in python to put this down to one expression?<br>
<em>max_value = max(firstArray) that is not in secondArray</em></p>
| 1 | 2009-10-14T08:59:46Z | 1,565,105 | <p>Use sets to get the values in firstArray that are not in secondArray:</p>
<pre><code>max_value = max(set(firstArray) - set(secondArray))
</code></pre>
| 12 | 2009-10-14T09:04:11Z | [
"python",
"expression"
] |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | <p>The <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> recommends that modules be imported at the beginning of programs.</p>
<p>Now, I feel that importing some of them at the beginning of the <em>main</em> program (i.e., after <code>if __name__ == '__main__'</code>) makes sense. For instance, if the main program reads arguments from the command line, I tend to do <code>import sys</code> at the beginning of the <em>main</em> program: this way, <code>sys</code> does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.</p>
<p>How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?</p>
| 5 | 2009-10-14T09:20:19Z | 1,565,181 | <p>I can't really tell you how bad this is to do.</p>
<p>However, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage.</p>
<p>BTW, the following is also from PEP 8:</p>
<blockquote>
<p>But most importantly: know when to be
inconsistent -- sometimes the style
guide just doesn't apply. When in
doubt, use your best judgment. Look
at other examples and decide what
looks best. And don't hesitate to
ask!</p>
</blockquote>
| 8 | 2009-10-14T09:23:03Z | [
"python",
"import",
"main",
"pep8",
"pep"
] |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | <p>The <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> recommends that modules be imported at the beginning of programs.</p>
<p>Now, I feel that importing some of them at the beginning of the <em>main</em> program (i.e., after <code>if __name__ == '__main__'</code>) makes sense. For instance, if the main program reads arguments from the command line, I tend to do <code>import sys</code> at the beginning of the <em>main</em> program: this way, <code>sys</code> does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.</p>
<p>How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?</p>
| 5 | 2009-10-14T09:20:19Z | 1,565,185 | <p>I would recommend you to do what you feel is most appropriate when there is nothing in PEP about your concern.</p>
| 2 | 2009-10-14T09:23:54Z | [
"python",
"import",
"main",
"pep8",
"pep"
] |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | <p>The <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> recommends that modules be imported at the beginning of programs.</p>
<p>Now, I feel that importing some of them at the beginning of the <em>main</em> program (i.e., after <code>if __name__ == '__main__'</code>) makes sense. For instance, if the main program reads arguments from the command line, I tend to do <code>import sys</code> at the beginning of the <em>main</em> program: this way, <code>sys</code> does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.</p>
<p>How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?</p>
| 5 | 2009-10-14T09:20:19Z | 1,565,258 | <p>Importing sys doesn't really take that long that I would worry about it. Some modules do take longer however.
I don't think sys really clogs up the namespace very much. I wouldn't use a variable or class called sys regardless.</p>
<p>If you think it's doing more harm than good to have it at the top, by all means do it however you like. PEP 8 is just a guide line and lots of code you see does not conform to it.</p>
| 2 | 2009-10-14T09:43:17Z | [
"python",
"import",
"main",
"pep8",
"pep"
] |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | <p>The <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> recommends that modules be imported at the beginning of programs.</p>
<p>Now, I feel that importing some of them at the beginning of the <em>main</em> program (i.e., after <code>if __name__ == '__main__'</code>) makes sense. For instance, if the main program reads arguments from the command line, I tend to do <code>import sys</code> at the beginning of the <em>main</em> program: this way, <code>sys</code> does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.</p>
<p>How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?</p>
| 5 | 2009-10-14T09:20:19Z | 1,565,266 | <p>In general I don't think there's much harm in late importing for modules that may not be needed.</p>
<p>However <code>sys</code> I would definitely import early, at the top. It's such a common module that it's quite likely you might use sys elsewhere in your script and not notice that it's not always imported. <code>sys</code> is also one of the modules that always gets loaded by Python itself, so you are not saving any module startup time by avoiding the import (not that there's much startup for sys anyway).</p>
| 6 | 2009-10-14T09:45:14Z | [
"python",
"import",
"main",
"pep8",
"pep"
] |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | <p>The <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> recommends that modules be imported at the beginning of programs.</p>
<p>Now, I feel that importing some of them at the beginning of the <em>main</em> program (i.e., after <code>if __name__ == '__main__'</code>) makes sense. For instance, if the main program reads arguments from the command line, I tend to do <code>import sys</code> at the beginning of the <em>main</em> program: this way, <code>sys</code> does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.</p>
<p>How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?</p>
| 5 | 2009-10-14T09:20:19Z | 1,565,853 | <p>The issue isn't performance.</p>
<p>The issue is clarity.</p>
<p>Your "main" program is only a main program today. Tomorrow, it may be a library included in some higher-level main program. Later, it will be just one module in a bigger package. </p>
<p>Since your "main" program's life may change, you have two responses.</p>
<ol>
<li><p>Isolate the "main" things inside <code>if __name__ == "__main__"</code>. This is not a grotesque violation of PEP-8. This is a reasonable way to package things.</p></li>
<li><p>Try to limit the number of features in your "main" program scripts. Try to keep them down to <code>import</code>s and the <code>if __name__ == "__main__"</code> stuff. If your main script is small, then your import question goes away.</p></li>
</ol>
| 2 | 2009-10-14T12:07:10Z | [
"python",
"import",
"main",
"pep8",
"pep"
] |
Subclassing Python tuple with multiple __init__ arguments | 1,565,374 | <p>The following code works:</p>
<pre><code>class Foo(tuple):
def __init__(self, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo([3, 4])
$ python play.py
play.py:4: DeprecationWarning: object.__init__() takes no parameters
super(Foo, self).__init__(tuple(b))
(3, 4)
</code></pre>
<p>But not the following:</p>
<pre><code>class Foo(tuple):
def __init__(self, a, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo(None, [3, 4])
$ python play.py
Traceback (most recent call last):
File "play.py", line 7, in <module>
print Foo(None, [3, 4])
TypeError: tuple() takes at most 1 argument (2 given)
</code></pre>
<p>Why?</p>
| 33 | 2009-10-14T10:10:41Z | 1,565,448 | <p>Because tuples are immutable, you have to override <code>__new__</code> instead:</p>
<p><a href="http://docs.python.org/reference/datamodel.html#object.__new__" rel="nofollow">python docs</a></p>
<blockquote>
<p><code>object.__new__(cls[, ...])</code></p>
<p>Called to create a new instance of
class <code>cls</code>. <code>__new__()</code> is a static
method (special-cased so you need not
declare it as such) that takes the
class of which an instance was
requested as its first argument. The
remaining arguments are those passed
to the object constructor expression
(the call to the class). The return
value of <code>__new__()</code> should be the new
object instance (usually an instance
of <code>cls</code>).</p>
<p>Typical implementations create a new
instance of the class by invoking the
superclassâs <code>__new__()</code> method using
<code>super(currentclass, cls).__new__(cls[, ...])</code> with appropriate arguments and
then modifying the newly-created
instance as necessary before returning
it.</p>
<p>If <code>__new__()</code> returns an instance of
<code>cls</code>, then the new instanceâs
<code>__init__()</code> method will be invoked like <code>__init__(self[, ...])</code>, where self is the new instance and the remaining
arguments are the same as were passed
to <code>__new__()</code>.</p>
<p>If <code>__new__()</code> does not return an
instance of <code>cls</code>, then the new
instanceâs <code>__init__()</code> method will not
be invoked.</p>
<p><code>__new__()</code> is intended mainly to allow subclasses of immutable types (like
<code>int</code>, <code>str</code>, or <code>tuple</code>) to customize
instance creation. It is also commonly
overridden in custom metaclasses in
order to customize class creation.</p>
</blockquote>
| 43 | 2009-10-14T10:24:33Z | [
"python",
"inheritance",
"subclass",
"tuples"
] |
Subclassing Python tuple with multiple __init__ arguments | 1,565,374 | <p>The following code works:</p>
<pre><code>class Foo(tuple):
def __init__(self, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo([3, 4])
$ python play.py
play.py:4: DeprecationWarning: object.__init__() takes no parameters
super(Foo, self).__init__(tuple(b))
(3, 4)
</code></pre>
<p>But not the following:</p>
<pre><code>class Foo(tuple):
def __init__(self, a, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo(None, [3, 4])
$ python play.py
Traceback (most recent call last):
File "play.py", line 7, in <module>
print Foo(None, [3, 4])
TypeError: tuple() takes at most 1 argument (2 given)
</code></pre>
<p>Why?</p>
| 33 | 2009-10-14T10:10:41Z | 13,094,796 | <p>To assign the tuple value you need to override the <code>__new__</code> method:</p>
<pre><code>class Foo(tuple):
def __new__ (cls, a, b):
return super(Foo, cls).__new__(cls, tuple(b))
</code></pre>
<p>The arguments seem to be ignored by the <code>__init__</code> implementation of the tuple class, but if you need to do some init stuff you can do it as follows:</p>
<pre><code>class Foo(tuple):
def __new__ (cls, a, b):
return super(Foo, cls).__new__(cls, tuple(b))
def __init__(self, a, b):
self.a=a
self.b=b
if __name__ == '__main__':
foo = Foo(None, [3, 4])
print foo
print foo.a
print foo.b
</code></pre>
| 26 | 2012-10-26T21:38:33Z | [
"python",
"inheritance",
"subclass",
"tuples"
] |
Plot GeoIP data on a World Map | 1,565,555 | <p>I need a library (preferably written in Python) which is able to take a series of IP addresses (or geographic coordinates) and plots them on a World Map. </p>
<p>I already found <a href="http://gsl-nagoya-u.net/appendix/software/worldmap/">this one</a>, but it outputs data as a .svg file and it's simply unable to cope with large data sets. </p>
<p>Please note that I need something which can be downloaded and run locally, so no data uploading to 3rd party web services.</p>
<p>Thanks!</p>
| 6 | 2009-10-14T10:49:21Z | 1,565,791 | <p>The google maps API can support all of the above if you would be willing to set up a local web environment for testing. There is a wrapper around the API for Python called <a href="http://code.google.com/p/pymaps/" rel="nofollow">pymaps</a>.</p>
<p>The API documentation has an example on how to use Google's geocoder to plot points on a map given a particular input address:</p>
<p><a href="http://www.google.com/url?sa=t&source=web&ct=res&cd=5&ved=0CB0QFjAE&url=http%3A%2F%2Fgmaps-samples.googlecode.com%2Fsvn%2Ftrunk%2Fgeocoder%2Fsinglegeocode.html&rct=j&q=google+maps+geocoder+example&ei=cbvVSq16lKQwtdC0lQM&usg=AFQjCNHzLhF0T07OOBamhHY-cPo%5Fpuj2eg" rel="nofollow">Google Maps API Example: Simple Geocoding</a></p>
| 2 | 2009-10-14T11:53:14Z | [
"python",
"geolocation",
"maps",
"plot"
] |
Plot GeoIP data on a World Map | 1,565,555 | <p>I need a library (preferably written in Python) which is able to take a series of IP addresses (or geographic coordinates) and plots them on a World Map. </p>
<p>I already found <a href="http://gsl-nagoya-u.net/appendix/software/worldmap/">this one</a>, but it outputs data as a .svg file and it's simply unable to cope with large data sets. </p>
<p>Please note that I need something which can be downloaded and run locally, so no data uploading to 3rd party web services.</p>
<p>Thanks!</p>
| 6 | 2009-10-14T10:49:21Z | 1,566,197 | <p>Perhaps <a href="http://matplotlib.org/basemap/" rel="nofollow">Basemap</a> in <a href="http://matplotlib.sourceforge.net/" rel="nofollow">Matplotlib</a> for the plotting. </p>
<p>It can do all sorts of <a href="http://matplotlib.org/basemap/users/mapsetup.html" rel="nofollow">projections</a> (don't mind the ugly default colours). And you have good control over what/how you plot. You can even use <a href="http://matplotlib.org/basemap/users/geography.html" rel="nofollow">NASA Blue Marble imagery</a>. And of course, you can plot markers, lines, etc on the map <a href="http://matplotlib.org/basemap/api/basemap_api.html" rel="nofollow">using the plot command</a>.</p>
<p>I haven't put huge datasets through it, but being that it is a part of Matplotlib I suspect it will do well.</p>
<p>If I remember right, despite being part of the library, by default it doesn't ship with Matplotlib.</p>
| 7 | 2009-10-14T13:23:08Z | [
"python",
"geolocation",
"maps",
"plot"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.