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
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,841
<p>The best way to achieve is by defining <code>__slots__</code>. That way your instances can't have new attributes.</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): __slots__ = [] def __init__(self, ks, vs): self.update(zip(ks, vs)) def __getattr__(self, key): return self[key] if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>That prints <code>12</code></p> <pre><code> c.ab = 33 </code></pre> <p>That gives: <code>AttributeError: 'C' object has no attribute 'ab'</code></p>
2
2009-08-25T03:01:35Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,328,686
<blockquote> <p>The goal is to create a mock class which behaves like a db resultset.</p> </blockquote> <p>So what you want is a dictionary where you can spell a['b'] as a.b?</p> <p>That's easy:</p> <pre><code>class atdict(dict): __getattr__= dict.__getitem__ __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ </code></pre>
34
2009-08-25T14:33:07Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,333,275
<p>This seems to work(but see below):</p> <pre><code>class data(dict,object): def __init__(self,*args,**argd): dict.__init__(self,*args,**argd) self.__dict__.update(self) def __setattr__(self,name,value): raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__) def __delattr__(self,name): raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__) </code></pre> <p>If you need more complex behavior, feel free to edit your answer.</p> <h2>edit</h2> <p>The following would probably be more memory-efficient for large datasets:</p> <pre><code>class data(dict,object): def __init__(self,*args,**argd): dict.__init__(self,*args,**argd) def __getattr__(self,name): return self[name] def __setattr__(self,name,value): raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__) def __delattr__(self,name): raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__) </code></pre>
0
2009-08-26T08:50:30Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,333,397
<p>I asked a similary question <a href="http://stackoverflow.com/questions/1264833/python-class-factory-to-produce-simple-struct-like-classes">on this Stack Overflow post</a> to create a class factory which created simple types. The outcome was <a href="http://stackoverflow.com/questions/1264833/python-class-factory-to-produce-simple-struct-like-classes/1275088#1275088">this answer</a> which had a working version of the class factory. Here is a snippet of the answer:</p> <pre><code>def Struct(*args, **kwargs): def init(self, *iargs, **ikwargs): for k,v in kwargs.items(): setattr(self, k, v) for i in range(len(iargs)): setattr(self, args[i], iargs[i]) for k,v in ikwargs.items(): setattr(self, k, v) name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()}) &gt;&gt;&gt; Person = Struct('fname', 'age') &gt;&gt;&gt; person1 = Person('Kevin', 25) &gt;&gt;&gt; person2 = Person(age=42, fname='Terry') &gt;&gt;&gt; person1.age += 10 &gt;&gt;&gt; person2.age -= 10 &gt;&gt;&gt; person1.fname, person1.age, person2.fname, person2.age ('Kevin', 35, 'Terry', 32) &gt;&gt;&gt; </code></pre> <p>You could use some variation of this to create default values which is your goal (there is also an answer in that question which deals with this).</p>
4
2009-08-26T09:15:12Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,355,444
<p>I suppose I should expand this answer, now that I'm older and wiser and know what's going on. Better late than never.</p> <p>You <em>can</em> add a property to a class dynamically. But that's the catch: you have to add it to the <em>class</em>.</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... pass ... &gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; foo.a = 3 &gt;&gt;&gt; Foo.b = property(lambda self: self.a + 1) &gt;&gt;&gt; foo.b 4 </code></pre> <p>A <code>property</code> is actually a simple implementation of a thing called a <a href="http://docs.python.org/2/reference/datamodel.html#implementing-descriptors">descriptor</a>. It's an object that provides custom handling for a given attribute, <em>on a given class</em>. Kinda like a way to factor a huge <code>if</code> tree out of <code>__getattribute__</code>.</p> <p>When I ask for <code>foo.b</code> in the example above, Python sees that the <code>b</code> defined on the class implements the <em>descriptor protocol</em>—which just means it's an object with a <code>__get__</code>, <code>__set__</code>, or <code>__delete__</code> method. The descriptor claims responsibility for handling that attribute, so Python calls <code>Foo.b.__get__(foo, Foo)</code>, and the return value is passed back to you as the value of the attribute. In the case of <code>property</code>, each of these methods just calls the <code>fget</code>, <code>fset</code>, or <code>fdel</code> you passed to the <code>property</code> constructor.</p> <p>Descriptors are really Python's way of exposing the plumbing of its entire OO implementation. In fact, there's another type of descriptor even more common than <code>property</code>.</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def bar(self): ... pass ... &gt;&gt;&gt; Foo().bar &lt;bound method Foo.bar of &lt;__main__.Foo object at 0x7f2a439d5dd0&gt;&gt; &gt;&gt;&gt; Foo().bar.__get__ &lt;method-wrapper '__get__' of instancemethod object at 0x7f2a43a8a5a0&gt; </code></pre> <p>The humble method is just another kind of descriptor. Its <code>__get__</code> tacks on the calling instance as the first argument; in effect, it does this:</p> <pre><code>def __get__(self, instance, owner): return functools.partial(self.function, instance) </code></pre> <p>Anyway, I suspect this is why descriptors only work on classes: they're a formalization of the stuff that powers classes in the first place. They're even the exception to the rule: you can obviously assign descriptors to a class, and classes are themselves instances of <code>type</code>! In fact, trying to read <code>Foo.b</code> still calls <code>property.__get__</code>; it's just idiomatic for descriptors to return themselves when accessed as class attributes.</p> <p>I think it's pretty cool that virtually all of Python's OO system can be expressed in Python. :)</p> <p>Oh, and I wrote a <a href="http://me.veekun.com/blog/2012/05/23/python-faq-descriptors/">wordy blog post about descriptors</a> a while back if you're interested.</p>
170
2009-08-31T01:30:05Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
23,371,846
<p>I recently ran into a similar problem, the solution that I came up with uses <code>__getattr__</code> and <code>__setattr__</code> for the properties that I want it to handle, everything else gets passed on to the originals.</p> <pre><code>class C(object): def __init__(self, properties): self.existing = "Still Here" self.properties = properties def __getattr__(self, name): if "properties" in self.__dict__ and name in self.properties: return self.properties[name] # Or call a function, etc return self.__dict__[name] def __setattr__(self, name, value): if "properties" in self.__dict__ and name in self.properties: self.properties[name] = value else: self.__dict__[name] = value if __name__ == "__main__": my_properties = {'a':1, 'b':2, 'c':3} c = C(my_properties) assert c.a == 1 assert c.existing == "Still Here" c.b = 10 assert c.properties['b'] == 10 </code></pre>
-1
2014-04-29T17:52:55Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
23,574,412
<p>Just another example how to achieve desired effect</p> <pre><code>class Foo(object): _bar = None @property def bar(self): return self._bar @bar.setter def bar(self, value): self._bar = value def __init__(self, dyn_property_name): setattr(Foo, dyn_property_name, Foo.bar) </code></pre> <p>So now we can do stuff like:</p> <pre><code>&gt;&gt;&gt; foo = Foo('baz') &gt;&gt;&gt; foo.baz = 5 &gt;&gt;&gt; foo.bar 5 &gt;&gt;&gt; foo.baz 5 </code></pre>
2
2014-05-09T21:41:06Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
28,355,849
<blockquote> <h1>How to add property to a python class dynamically?</h1> </blockquote> <p>Say you have an object that you want to add a property to. Typically, I want to use properties when I need to begin managing access to an attribute in code that has downstream usage, so that I can maintain a consistent API. Now I will typically add them to the source code where the object is defined, but let's assume you don't have that access, or you need to truly dynamically choose your functions programmatically.</p> <h2>Create a class</h2> <p>Using an example based on the <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow">documentation for <code>property</code></a>, let's create a class of object with a "hidden" attribute and create an instance of it:</p> <pre><code>class C(object): '''basic class''' _x = None o = C() </code></pre> <p>In Python, we expect there to be one obvious way of doing things. However, in this case, I'm going to show two ways: with decorator notation, and without. First, without decorator notation. This may be more useful for the dynamic assignment of getters, setters, or deleters.</p> <h2>Dynamic (a.k.a. Monkey Patching)</h2> <p>Let's create some for our class:</p> <pre><code>def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x </code></pre> <p>And now we assign these to the property. Note that we could choose our functions programmatically here, answering the dynamic question:</p> <pre><code>C.x = property(getx, setx, delx, "I'm the 'x' property.") </code></pre> <p>And usage:</p> <pre><code>&gt;&gt;&gt; o.x = 'foo' &gt;&gt;&gt; o.x 'foo' &gt;&gt;&gt; del o.x &gt;&gt;&gt; print(o.x) None &gt;&gt;&gt; help(C.x) Help on property: I'm the 'x' property. </code></pre> <h2>Decorators</h2> <p>We could do the same as we did above with decorator notation, but in this case, we <em>must</em> name the methods all the same name (and I'd recommend keeping it the same as the attribute), so programmatic assignment is not so trivial as it is using the above method:</p> <pre><code>@property def x(self): '''I'm the 'x' property.''' return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x </code></pre> <p>And assign the property object with its provisioned setters and deleters to the class:</p> <pre><code>C.x = x </code></pre> <p>And usage:</p> <pre><code>&gt;&gt;&gt; help(C.x) Help on property: I'm the 'x' property. &gt;&gt;&gt; o.x &gt;&gt;&gt; o.x = 'foo' &gt;&gt;&gt; o.x 'foo' &gt;&gt;&gt; del o.x &gt;&gt;&gt; print(o.x) None </code></pre>
1
2015-02-05T23:12:19Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
28,357,426
<p>To answer the main thrust of your question, you want a read-only attribute from a dict as an immutable datasource:</p> <blockquote> <p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, <code>{'ab':100, 'cd':200}</code>, then I would to see</p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> </blockquote> <p>I'll demonstrate how to use a <code>namedtuple</code> from the <code>collections</code> module to accomplish just this:</p> <pre><code>import collections data = {'ab':100, 'cd':200} def maketuple(d): '''given a dict, return a namedtuple''' Tup = collections.namedtuple('TupName', d.keys()) # iterkeys in Python2 return Tup(**d) dummy = maketuple(data) dummy.ab </code></pre> <p>returns <code>100</code></p>
0
2015-02-06T02:04:54Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
38,874,138
<p>For those coming from search engines, here are the two things I was looking for when talking about <em>dynamic</em> properties:</p> <pre><code>class Foo: def __init__(self): # we can dynamically access to the properties dict using __dict__ self.__dict__['foo'] = 'bar' assert Foo().foo == 'bar' # or we can use __getattr__ and __setattr__ to execute code on set/get class Bar: def __init__(self): self._data = {} def __getattr__(self, key): return self._data[key] def __setattr__(self, key, value): self._data[key] = value bar = Bar() bar.foo = 'bar' assert bar.foo == 'bar' </code></pre> <p><code>__dict__</code> is good if you want to put dynamically create properties. <code>__getattr__</code> is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).</p> <p>If you only want one dynamic property, have a look at the <a href="https://docs.python.org/3/library/functions.html#property" rel="nofollow">property()</a> built-in function.</p>
0
2016-08-10T12:58:15Z
[ "python", "properties", "runtime", "monkeypatching" ]
Inserting Line at Specified Position of a Text File
1,325,905
<p>I have a text file which looks like this:</p> <pre><code>blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah </code></pre> <p>Now I want to insert <code>'foo bar'</code> between <code>'foo1 bar3'</code> and <code>'foo2 bar4'</code>.</p> <p>This is how I did it:</p> <pre><code>import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infile: flag = 0 for line in infile: if not line.startswith('foo1') and flag == 0: outfile.write(line) continue if line.startswith('foo1') and flag == 0: flag = 1 outfile.write(line) continue if line.startswith('foo1') and flag == 1: outfile.write(line) continue if not line.startswith('foo1') and flag == 1: outfile.write('foo bar\n') outfile.write(line) flag = 2 continue if not line.startswith('foo1') and flag == 2: outfile.write(line) continue shutil.move(tmptxt, txt) </code></pre> <p>This works for me, but looks rather ugly.</p>
26
2009-08-25T03:27:23Z
1,325,927
<p>The best way to make "pseudo-inplace" changes to a file in Python is with the <code>fileinput</code> module from the standard library:</p> <pre><code>import fileinput processing_foo1s = False for line in fileinput.input('1.txt', inplace=1): if line.startswith('foo1'): processing_foo1s = True else: if processing_foo1s: print 'foo bar' processing_foo1s = False print line, </code></pre> <p>You can also specify a backup extension if you want to keep the old version around, but this works in the same vein as your code -- uses <code>.bak</code> as the backup extension but also removes it once the change has successfully completed.</p> <p>Besides using the right standard library module, this code uses simpler logic: to insert a <code>"foo bar"</code> line after every run of lines starting with <code>foo1</code>, a boolean is all you need (am I inside such a run or not?) and the bool in question can be set unconditionally just based on whether the current line starts that way or not. If the precise logic you desire is slightly different from this one (which is what I deduced from your code), it shouldn't be hard to tweak this code accordingly.</p>
50
2009-08-25T03:34:13Z
[ "python", "text", "insert" ]
Inserting Line at Specified Position of a Text File
1,325,905
<p>I have a text file which looks like this:</p> <pre><code>blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah </code></pre> <p>Now I want to insert <code>'foo bar'</code> between <code>'foo1 bar3'</code> and <code>'foo2 bar4'</code>.</p> <p>This is how I did it:</p> <pre><code>import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infile: flag = 0 for line in infile: if not line.startswith('foo1') and flag == 0: outfile.write(line) continue if line.startswith('foo1') and flag == 0: flag = 1 outfile.write(line) continue if line.startswith('foo1') and flag == 1: outfile.write(line) continue if not line.startswith('foo1') and flag == 1: outfile.write('foo bar\n') outfile.write(line) flag = 2 continue if not line.startswith('foo1') and flag == 2: outfile.write(line) continue shutil.move(tmptxt, txt) </code></pre> <p>This works for me, but looks rather ugly.</p>
26
2009-08-25T03:27:23Z
1,327,523
<p>Recall that an iterator is a first-class object. It can be used in multiple <strong>for</strong> statements.</p> <p>Here's a way to handle this without a lot of complex-looking if-statements and flags.</p> <pre><code>with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infile: rowIter= iter(infile) for row in rowIter: if row.startswith('foo2'): # Start of next section break print row.rstrip(), repr(row) print "foo bar" print row for row in rowIter: print row.rstrip() </code></pre>
8
2009-08-25T11:02:47Z
[ "python", "text", "insert" ]
Inserting Line at Specified Position of a Text File
1,325,905
<p>I have a text file which looks like this:</p> <pre><code>blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah </code></pre> <p>Now I want to insert <code>'foo bar'</code> between <code>'foo1 bar3'</code> and <code>'foo2 bar4'</code>.</p> <p>This is how I did it:</p> <pre><code>import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infile: flag = 0 for line in infile: if not line.startswith('foo1') and flag == 0: outfile.write(line) continue if line.startswith('foo1') and flag == 0: flag = 1 outfile.write(line) continue if line.startswith('foo1') and flag == 1: outfile.write(line) continue if not line.startswith('foo1') and flag == 1: outfile.write('foo bar\n') outfile.write(line) flag = 2 continue if not line.startswith('foo1') and flag == 2: outfile.write(line) continue shutil.move(tmptxt, txt) </code></pre> <p>This works for me, but looks rather ugly.</p>
26
2009-08-25T03:27:23Z
6,281,147
<p>Adapting Alex Martelli's example:</p> <pre><code>import fileinput for line in fileinput.input('1.txt', inplace=1): print line, if line.startswith('foo1 bar3'): print 'foo bar' </code></pre>
11
2011-06-08T15:15:22Z
[ "python", "text", "insert" ]
Executing Python Scripts in Android
1,326,169
<p>This <a href="http://perlbuzz.com/2009/08/perl-coming-to-android-phones.html" rel="nofollow">link</a> says that Android support Python, Lua and BeanShell Scripts, subsequently for Perl too. If it is so, is it possible for developers to write python scripts and call them in their standard Java based android applications?</p>
0
2009-08-25T05:10:49Z
1,326,235
<p>I remember reading about this awhile back as well. It's not on the android <a href="http://developer.android.com/index.html" rel="nofollow">dev site</a>.</p> <p>It's a separate project, <a href="http://code.google.com/p/android-scripting/" rel="nofollow">android-scripting</a>.</p> <p>Python API:</p> <p><a href="http://code.google.com/p/android-scripting/wiki/ApiReference" rel="nofollow">API Reference</a></p> <p><a href="http://www.mithril.com.au/android/doc/" rel="nofollow">SL4A API Help</a></p>
5
2009-08-25T05:32:53Z
[ "python", "android", "scripting" ]
Executing Python Scripts in Android
1,326,169
<p>This <a href="http://perlbuzz.com/2009/08/perl-coming-to-android-phones.html" rel="nofollow">link</a> says that Android support Python, Lua and BeanShell Scripts, subsequently for Perl too. If it is so, is it possible for developers to write python scripts and call them in their standard Java based android applications?</p>
0
2009-08-25T05:10:49Z
1,338,137
<p>I think I have read somewhere that ASE with Python was a huge library ( several Mo), and so was completely unpractical for a public application. But you can still use it for development...</p>
0
2009-08-26T23:32:31Z
[ "python", "android", "scripting" ]
How to organize a Data Base Access layer?
1,326,243
<p>I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API.</p> <p>But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so I can use mock objects during test instead of access database directly.</p> <p>I think there are 2 choices to do that :</p> <ol> <li><p>use a single class which contains a DB connection and many methods like addUser/delUser/updateUser, addBook/delBook/updateBook. But this means this <em>class</em> will be very large.</p></li> <li><p>Another approach is create different manager classes like "UserManager", "BookManager". But that means I have to pass a list of managers to Business layer, which seems a little Cumbersome.</p></li> </ol> <p>How will you organize a database layer?</p>
6
2009-08-25T05:35:09Z
1,326,335
<p>I would set up a database connection during testing that connects to a in memory database instead. Like so:</p> <pre><code>sqlite_memory_db = create_engine('sqlite://') </code></pre> <p>That will be pretty much as fast as you can get, you are also not connecting to a real database, but just a temporary one in memory, so you don't have to worry about the changes done by your tests remaining after the test, etc. And you don't have to mock anything.</p>
2
2009-08-25T06:09:03Z
[ "python", "database", "testing", "orm", "mocking" ]
How to organize a Data Base Access layer?
1,326,243
<p>I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API.</p> <p>But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so I can use mock objects during test instead of access database directly.</p> <p>I think there are 2 choices to do that :</p> <ol> <li><p>use a single class which contains a DB connection and many methods like addUser/delUser/updateUser, addBook/delBook/updateBook. But this means this <em>class</em> will be very large.</p></li> <li><p>Another approach is create different manager classes like "UserManager", "BookManager". But that means I have to pass a list of managers to Business layer, which seems a little Cumbersome.</p></li> </ol> <p>How will you organize a database layer?</p>
6
2009-08-25T05:35:09Z
1,326,708
<p>SQLAlchemy has some facilities for <a href="http://svn.sqlalchemy.org/sqlalchemy/trunk/lib/sqlalchemy/engine/strategies.py" rel="nofollow">making mocking easier</a> -- maybe that would be easier than trying to rewrite whole sections of your project? </p>
0
2009-08-25T07:58:33Z
[ "python", "database", "testing", "orm", "mocking" ]
How to organize a Data Base Access layer?
1,326,243
<p>I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API.</p> <p>But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so I can use mock objects during test instead of access database directly.</p> <p>I think there are 2 choices to do that :</p> <ol> <li><p>use a single class which contains a DB connection and many methods like addUser/delUser/updateUser, addBook/delBook/updateBook. But this means this <em>class</em> will be very large.</p></li> <li><p>Another approach is create different manager classes like "UserManager", "BookManager". But that means I have to pass a list of managers to Business layer, which seems a little Cumbersome.</p></li> </ol> <p>How will you organize a database layer?</p>
6
2009-08-25T05:35:09Z
1,326,734
<p>That's a good question!<br /> The problem is not trivial, and may require several approaches to tackle it. For instance:</p> <ol> <li>Organize the code, so that you can test most of the application logic without accessing the database. This means that each class will have methods for accessing data, and methods for processing it, and the second ones may be tested easily.</li> <li>When you need to test database access, you may use a proxy (so, like solution #1); you can think of it as an engine for SqlAlchemy or as a drop-in replacement for the SA. In both cases, you may want to think to a <a href="http://martinfowler.com/bliki/SelfInitializingFake.html" rel="nofollow">self initializing fake</a>.</li> <li>If the code does not involve stored procedures, think about using in-memory databases, like Lennart says (even if in this case, calling it "unit test" may sound a bit strange!).</li> </ol> <p>However, from my experience, everything is quite easy on word, and then falls abruptly when you go on the field. For instance, what to do when most of the logic is in the SQL statements? What if accessing data is strictly interleaved with its processing? Sometimes you may be able to refactor, sometimes (especially with large and legacy applications) not.</p> <p>In the end, I think it is mostly a matter of <strong>mindset</strong>.<br /> If you think you need to have unit tests, and you need to have them running fast, then you design your application in a certain way, that allow for easier unit testing.<br /> Unfortunately, this is not always true (many people see unit tests as something that can run overnight, so time is not an issue), and you get something that will not be really unit-testable.</p>
4
2009-08-25T08:05:45Z
[ "python", "database", "testing", "orm", "mocking" ]
How to organize a Data Base Access layer?
1,326,243
<p>I am using SqlAlchemy, a python ORM library. And I used to access database directly from business layer directly by calling SqlAlchemy API.</p> <p>But then I found that would cause too much time to run all my test cases and now I think maybe I should create a DB access layer, so I can use mock objects during test instead of access database directly.</p> <p>I think there are 2 choices to do that :</p> <ol> <li><p>use a single class which contains a DB connection and many methods like addUser/delUser/updateUser, addBook/delBook/updateBook. But this means this <em>class</em> will be very large.</p></li> <li><p>Another approach is create different manager classes like "UserManager", "BookManager". But that means I have to pass a list of managers to Business layer, which seems a little Cumbersome.</p></li> </ol> <p>How will you organize a database layer?</p>
6
2009-08-25T05:35:09Z
1,326,937
<p>One way to capture modifications to the database, is to use the SQLAlchemy session extension mechanism and intercept flushes to the database using something like this:</p> <pre><code>from sqlalchemy.orm.attributes import instance_state from sqlalchemy.orm import SessionExtension class MockExtension(SessionExtension): def __init__(self): self.clear() def clear(self): self.updates = set() self.inserts = set() self.deletes = set() def before_flush(self, session, flush_context, instances): for obj in session.dirty: self.updates.add(obj) state = instance_state(obj) state.commit_all({}) session.identity_map._mutable_attrs.discard(state) session.identity_map._modified.discard(state) for obj in session.deleted: self.deletes.add(obj) session.expunge(obj) self.inserts.update(session.new) session._new = {} </code></pre> <p>Then for tests you can configure your session with that mock and see if it matches your expectations.</p> <pre><code>mock = MockExtension() Session = sessionmaker(extension=[mock], expire_on_commit=False) def do_something(attr): session = Session() obj = session.query(Cls).first() obj.attr = attr session.commit() def test_something(): mock.clear() do_something('foobar') assert len(mock.updates) == 1 updated_obj = mock.updates.pop() assert updated_obj.attr == 'foobar' </code></pre> <p>But you'll want to do at least some tests with a database anyway because you'll atleast want to know if your queries work as expected. And keep in mind that you can also have modifications to the database via <code>session.update()</code>, <code>.delete()</code> and <code>.execute()</code>.</p>
2
2009-08-25T08:51:23Z
[ "python", "database", "testing", "orm", "mocking" ]
how to take file like object in a file in python
1,326,271
<pre><code>filename = fileobject.read() </code></pre> <p>i want to transfer/assign the whole data of a object within a file.</p>
0
2009-08-25T05:45:04Z
1,326,289
<p>You are almost doing it correctly already; the code should read</p> <pre><code>filecontent = fileobject.read() </code></pre> <p>read() with no arguments will read the whole data, i.e. the whole file content. The file name has nothing to do with that.</p>
4
2009-08-25T05:48:54Z
[ "python", "file-io" ]
Problem with shelve module?
1,326,459
<p>Using the shelve module has given me some surprising behavior. keys(), iter(), and iteritems() don't return all the entries in the shelf! Here's the code:</p> <pre><code>cache = shelve.open('my.cache') # ... cache[url] = (datetime.datetime.today(), value) </code></pre> <p>later:</p> <pre><code>cache = shelve.open('my.cache') urls = ['accounts_with_transactions.xml', 'targets.xml', 'profile.xml'] try: print list(cache.keys()) # doesn't return all the keys! print [url for url in urls if cache.has_key(url)] print list(cache.keys()) finally: cache.close() </code></pre> <p>and here's the output:</p> <pre><code>['targets.xml'] ['accounts_with_transactions.xml', 'targets.xml'] ['targets.xml', 'accounts_with_transactions.xml'] </code></pre> <p>Has anyone run into this before, and is there a workaround without knowing all possible cache keys <em>a priori</em>?</p>
1
2009-08-25T06:56:48Z
1,326,652
<p>Seeing your examples, my first thought is that <code>cache.has_key()</code> has side effects, i.e. this call will add keys to the cache. What do you get for</p> <pre><code>print cache.has_key('xxx') print list(cache.keys()) </code></pre>
0
2009-08-25T07:48:15Z
[ "python", "shelve" ]
Problem with shelve module?
1,326,459
<p>Using the shelve module has given me some surprising behavior. keys(), iter(), and iteritems() don't return all the entries in the shelf! Here's the code:</p> <pre><code>cache = shelve.open('my.cache') # ... cache[url] = (datetime.datetime.today(), value) </code></pre> <p>later:</p> <pre><code>cache = shelve.open('my.cache') urls = ['accounts_with_transactions.xml', 'targets.xml', 'profile.xml'] try: print list(cache.keys()) # doesn't return all the keys! print [url for url in urls if cache.has_key(url)] print list(cache.keys()) finally: cache.close() </code></pre> <p>and here's the output:</p> <pre><code>['targets.xml'] ['accounts_with_transactions.xml', 'targets.xml'] ['targets.xml', 'accounts_with_transactions.xml'] </code></pre> <p>Has anyone run into this before, and is there a workaround without knowing all possible cache keys <em>a priori</em>?</p>
1
2009-08-25T06:56:48Z
1,326,860
<p>According to the <a href="http://docs.python.org/library/shelve.html#restrictions" rel="nofollow">python library reference</a>:</p> <blockquote> <p>...The database is also (unfortunately) subject to the limitations of dbm, if it is used — this means that (the pickled representation of) the objects stored in the database should be fairly small...</p> </blockquote> <p>This correctly reproduces the 'bug':</p> <pre><code>import shelve a = 'trxns.xml' b = 'foobar.xml' c = 'profile.xml' urls = [a, b, c] cache = shelve.open('my.cache', 'c') try: cache[a] = a*1000 cache[b] = b*10000 finally: cache.close() cache = shelve.open('my.cache', 'c') try: print cache.keys() print [url for url in urls if cache.has_key(url)] print cache.keys() finally: cache.close() </code></pre> <p>with the output:</p> <pre><code>[] ['trxns.xml', 'foobar.xml'] ['foobar.xml', 'trxns.xml'] </code></pre> <p>The answer, therefore, is don't store anything big—like raw xml—but rather results of calculations in a shelf.</p>
3
2009-08-25T08:34:06Z
[ "python", "shelve" ]
Django_tagging (v0.3/pre): Configuration issue
1,326,512
<p>I am trying to use the django-tagging in one of my project and run into some errors.</p> <p>I can play with tags in the shell but couldn't assign them from admin interface.</p> <p>What I want to do is add "tag" functionality to a model and add/remove tags from Admin interface.</p> <p>Why is it the "tags" are seen by shell and not by "admin" interface? What is going on?</p> <p>Model.py:</p> <pre><code>import tagging class Department(models.Model): tags = TagField() </code></pre> <p>Admin.py:</p> <pre><code>class DepartmentAdmin(admin.ModelAdmin): list_display = ('name', 'tags') --&gt; works .... fields = ['name', 'tags'] --&gt; throws error </code></pre> <p>Error</p> <pre><code> OperationalError at /admin/department/1/ (1054, "Unknown column 'schools_department.tags' in 'field list'") </code></pre> <p>I looked at the docs and couldn't find further information <a href="http://code.google.com/p/django-tagging/wiki/UsefulTips" rel="nofollow">Useful Tips</a> <a href="http://code.google.com/p/django-tagging/source/browse/trunk/docs/overview.txt" rel="nofollow">Overview Txt</a></p>
1
2009-08-25T07:12:42Z
1,330,194
<p>The TagField requires an actual database column on your model; it uses this to cache the tags as entered. If you add a TagField to a model that already has a database table, you will need to add the column to the database table, just as with adding any other type of field. Either use a schema migration tool (like South or django-evolution) or run the appropriate SQL ALTER TABLE command manually.</p>
4
2009-08-25T18:43:05Z
[ "python", "django", "django-admin", "tagging" ]
Using sphinx to auto-document a python class, module
1,326,796
<p>I have installed <a href="http://sphinx.pocoo.org/">Sphinx</a> in order to document some python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a python code.</p> <p>Basically, I have the following python module:</p> <pre><code>SegLib.py </code></pre> <p>And A class called <code>Seg</code> in it. I would like to display the docstrings of the class and module within the generated sphinx document, and add further formatted text to it.</p> <p>My <code>index.rst</code> looks like this:</p> <pre><code>Contents: .. toctree:: :maxdepth: 2 chapter1.rst </code></pre> <p>and <code>chapter1.rst</code>:</p> <pre><code>This is a header ================ Some text, *italic text*, **bold text** * bulleted list. There needs to be a space right after the "*" * item 2 .. note:: This is a note. See :class:`Seg` </code></pre> <p>But <code>Seg</code> is just printed in bold, and not linked to an autogenerated documentation of the class.</p> <p>Trying: See :class:<code>Seg</code> Module :mod:'SegLib' Module :mod:'SegLib.py'</p> <p>Didn't help, too. Any ideas or good tutorial links?</p> <p><strong>Edit: changed SegLib to segments (thanks, iElectric!), and changed chapter1.rst to:</strong> The :mod:<code>segments</code> Module --------------------------</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg </code></pre> <p>Still, can't get sphinx to directly document functions within a class, or better - to automatically add all the functions within a class to the document. Tried </p> <pre><code>.. autofunction:: segments.segments.Seg.sid </code></pre> <p>and got:</p> <pre><code>autodoc can't import/find function 'segments.segments.Seg.sid', it reported error: "No module named Seg" </code></pre> <p>Any ideas how to autodocument the functions and classes with a short command?</p> <p>Udi</p>
20
2009-08-25T08:23:25Z
1,326,893
<p>Add to the begining of the file:</p> <pre><code>.. module:: SegLib </code></pre> <p>Try using <strong>:autoclass:</strong> directive for class doc.</p> <p>BTW: module names should be lower_case.</p> <p><strong>EDIT:</strong> <a href="http://almir.readthedocs.org/en/latest/_sources/api.txt" rel="nofollow">I learned a lot from reading other source files</a>.</p>
12
2009-08-25T08:41:23Z
[ "python", "documentation-generation", "python-sphinx" ]
How can I overload the assignment of a class member?
1,326,978
<p>I am writing a Player model class in Python with Django, and I've ran into a small problem with the password member. I'd like the password to be automatically hashed upon assignment, but I can't find anything about overloading the assignment operator or anything. Is there any way I can overload the assignment of <code>password</code> so as to automatically do <code>hashlib.md5(password).hexdigest()</code> on it?</p> <pre><code>from django.db import models class Player(models.Model): name = models.CharField(max_length=30,unique=True) password = models.CharField(max_length=32) email = models.EmailField() </code></pre>
1
2009-08-25T08:58:32Z
1,327,025
<p>Can't you use properties and override setter for the field?</p> <p>Citing from <a href="http://www.djangoproject.com/documentation/models/properties/" rel="nofollow">django documentation</a>:</p> <pre><code>from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def _get_full_name(self): return "%s %s" % (self.first_name, self.last_name) def _set_full_name(self, combined_name): self.first_name, self.last_name = combined_name.split(' ', 1) full_name = property(_get_full_name) full_name_2 = property(_get_full_name, _set_full_name) </code></pre>
6
2009-08-25T09:06:33Z
[ "python", "django", "class", "variable-assignment" ]
How can I overload the assignment of a class member?
1,326,978
<p>I am writing a Player model class in Python with Django, and I've ran into a small problem with the password member. I'd like the password to be automatically hashed upon assignment, but I can't find anything about overloading the assignment operator or anything. Is there any way I can overload the assignment of <code>password</code> so as to automatically do <code>hashlib.md5(password).hexdigest()</code> on it?</p> <pre><code>from django.db import models class Player(models.Model): name = models.CharField(max_length=30,unique=True) password = models.CharField(max_length=32) email = models.EmailField() </code></pre>
1
2009-08-25T08:58:32Z
1,327,026
<p>You can use the <a href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/HashProperty" rel="nofollow">HashedProperty</a> class that I created for SQLAlchemy. You can use with Django like this:</p> <pre><code>class Player(models.Model): name = models.CharField(max_length=30,unique=True) password_hash = models.CharField(max_length=32) password_salt = models.CharField(max_length=32) password = HashedProperty('password_hash', 'password_salt', hashfunc=salted_hexdigest(hashlib.md5), saltfunc=random_string(32)) email = models.EmailField() </code></pre>
0
2009-08-25T09:06:37Z
[ "python", "django", "class", "variable-assignment" ]
Append a tuple to a list
1,327,204
<p>Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is:</p> <pre><code>def fn(*args): l = ['foo', 'bar'] l.extend(args) fn2(l) </code></pre> <p>Which, given Pythons usual terseness when it comes to this sort of thing, seems like it takes 2 more lines than it should. Is there a more pythonic way?</p>
2
2009-08-25T09:50:43Z
1,327,227
<p>You can convert the tuple to a list, which will allow you to concatenate it to the other list. ie:</p> <pre><code>def fn(*args): fn2(['foo', 'bar'] + list(args)) </code></pre>
9
2009-08-25T09:55:59Z
[ "python" ]
Append a tuple to a list
1,327,204
<p>Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is:</p> <pre><code>def fn(*args): l = ['foo', 'bar'] l.extend(args) fn2(l) </code></pre> <p>Which, given Pythons usual terseness when it comes to this sort of thing, seems like it takes 2 more lines than it should. Is there a more pythonic way?</p>
2
2009-08-25T09:50:43Z
1,327,317
<p>If your fn2 took varargs also, you wouldn't need to build the combined list:</p> <pre><code>def fn2(*l): print l def fn(*args): fn2(1, 2, *args) fn(10, 9, 8) </code></pre> <p>produces</p> <pre><code>(1, 2, 10, 9, 8) </code></pre>
1
2009-08-25T10:15:39Z
[ "python" ]
file accessing in load_pub_key
1,327,211
<p>Consider the code:</p> <pre><code>fileHandle = open ( 'test8.pem','w' ) fileHandle.write (data) pub_key = M2Crypto.RSA.load_pub_key(open('test8.pem')) </code></pre> <p>Error coming like :</p> <pre><code> File "/usr/lib/python2.4/site-packages/M2Crypto/RSA.py", line 343, in load_pub_key bio = BIO.openfile(file) File "/usr/lib/python2.4/site-packages/M2Crypto/BIO.py", line 186, in openfile return File(open(filename, mode)) IOError: [Errno 2] No such file or directory: '' </code></pre> <p>what wrong in the way i use ? My query is how do I pass the file into <code>load_pub_key</code> method so it can be accessible by simply passing the file name ?</p>
0
2009-08-25T09:51:55Z
1,327,264
<p>If you pass test8.pem without quotes, Python interprets it as the name of a variable, which is not defined, hence the error.</p> <p>I don't know the specific library you are using but I would guess that you need to pass fileHandle instead.</p>
0
2009-08-25T10:04:18Z
[ "python", "m2crypto" ]
file accessing in load_pub_key
1,327,211
<p>Consider the code:</p> <pre><code>fileHandle = open ( 'test8.pem','w' ) fileHandle.write (data) pub_key = M2Crypto.RSA.load_pub_key(open('test8.pem')) </code></pre> <p>Error coming like :</p> <pre><code> File "/usr/lib/python2.4/site-packages/M2Crypto/RSA.py", line 343, in load_pub_key bio = BIO.openfile(file) File "/usr/lib/python2.4/site-packages/M2Crypto/BIO.py", line 186, in openfile return File(open(filename, mode)) IOError: [Errno 2] No such file or directory: '' </code></pre> <p>what wrong in the way i use ? My query is how do I pass the file into <code>load_pub_key</code> method so it can be accessible by simply passing the file name ?</p>
0
2009-08-25T09:51:55Z
1,327,456
<p>this should work for you:</p> <pre><code>fname = 'test8.pem' fileHandle = open(fname, 'w') fileHandle.write(data) fileHandle.close() pub_key = M2Crypto.RSA.load_pub_key(fname) </code></pre>
0
2009-08-25T10:44:31Z
[ "python", "m2crypto" ]
file accessing in load_pub_key
1,327,211
<p>Consider the code:</p> <pre><code>fileHandle = open ( 'test8.pem','w' ) fileHandle.write (data) pub_key = M2Crypto.RSA.load_pub_key(open('test8.pem')) </code></pre> <p>Error coming like :</p> <pre><code> File "/usr/lib/python2.4/site-packages/M2Crypto/RSA.py", line 343, in load_pub_key bio = BIO.openfile(file) File "/usr/lib/python2.4/site-packages/M2Crypto/BIO.py", line 186, in openfile return File(open(filename, mode)) IOError: [Errno 2] No such file or directory: '' </code></pre> <p>what wrong in the way i use ? My query is how do I pass the file into <code>load_pub_key</code> method so it can be accessible by simply passing the file name ?</p>
0
2009-08-25T09:51:55Z
17,672,187
<p>I also have the same issue. I tried loading a file handler instead of path but it didn't help. </p> <p>The thing that workout was using X509 module from M2Crypto. You can try use this functions to obtain a public key instance:</p> <pre><code>certificate = M2Crypto.X509.load_cert(cert_path) pubkey = certificate.get_pubkey() </code></pre> <p>More details in the following answer: <a href="http://stackoverflow.com/q/8743213/2586315">RSACryptoServiceProvider message signature verification with m2crypto</a></p>
0
2013-07-16T08:58:05Z
[ "python", "m2crypto" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,417
<p>How about:</p> <pre><code>def call_one(func, param1, param2): if param2: code_chunk_1 func(param1) if param2: code_chunk_2 def _fooA(param1): fooA_code #uses only param1 def _fooB(param1): fooB_code #uses only param1 def fooA(param1, param2): call_one(_fooA, param1, param2) def fooB(param1, param2): call_one(_fooB, param1, param2) </code></pre>
6
2009-08-25T10:35:37Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,429
<p>Since you try to enable some wrapper functionality iff the passed option is True, consider using keyword arguments. Here is a real-world example that will wrap your code in a (database-) transaction if requested:</p> <pre><code>def wrap_transaction(func): def wrapper(*args, **kwargs): # If the option "use_transaction" is given, wrap the function in # a transaction. Note that pop() will remove the parameter so # that it won't get passed to the wrapped function, that does not need # to know about its existance. use_transaction = kwargs.pop('use_transaction', False) if use_transaction: get_connection().begin_transaction() try: result = func(*args, **kwargs) except: if use_transaction: get_connection().rollback() raise if use_transaction: get_connection().commit() return result return wrapper @wrap_transaction def my_func(param): # Note that this function knows nothing about the 'use_transaction' parameter get_connection().exec("...") # Usage: Explicitely enabling the transaction. my_func(param, use_transaction=True) </code></pre>
5
2009-08-25T10:38:51Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,464
<p>I would do a straightforward extract method refactoring:</p> <pre><code>def _code_chunk_1(param): if param == True: code_chunk_1 def _code_chunk_2(param): if param == True: code_chunk_2 def fooA(param1, param2): _code_chunk_1(param2) fooA_code #uses only param1 _code_chunk_2(param2) def fooB(param1, param2): _code_chunk_1(param2) fooB_code #uses only param1 _code_chunk_2(param2) </code></pre> <p>The decorator looks inappropriate to me in this context. Ned's answer above also looks nice.</p>
1
2009-08-25T10:45:30Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,494
<p>I'm wondering if you're adding debugging code. Since param2 is not used in the function proper, maybe you want to move it into the decorator:</p> <pre><code>class debugging: def __init__(self, show): self.show = show def __call__(self, f): def wrapper(*args): if self.show: print "inside", f rv = f(*args) if self.show: print "outside", f return rv return wrapper @debugging(True) def test(n): print n test(10) </code></pre> <p>will print</p> <pre><code>inside &lt;function test at 0x7fb28ff102a8&gt; 10 outside &lt;function test at 0x7fb28ff102a8&gt; </code></pre>
0
2009-08-25T10:54:25Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,564
<p>What you are describing is a situation where you have some boilerplate, some behaviour, followed by some boiler plate. Essentially a situation where you could use a <a href="http://en.wikipedia.org/wiki/Higher-order%5Ffunction" rel="nofollow">Higher Order Function</a> (like map, reduce or filter).</p> <p>You could do what Ned suggests (though, I'd use <a href="http://docs.python.org/library/functools.html#functools.partial" rel="nofollow">functools.partial</a> rather than defining fooA/fooB longhand):</p> <pre><code>import functools ... fooA = functools.partial(call_one, _fooA) fooB = functools.partial(call_one, _fooB) </code></pre> <p>... but that effectively gets you back to the same place as with your decorator, introducing some clutter into the namespace along the way.</p> <p>You could rewrite your decorator to allow functions that only take one parameter, but return functions that take two:</p> <pre><code>def refactorMe(func): def wrapper(parm1, parm2): if parm1: code_chunk_1 func(parm1) if parm2[-1]: code_chunk_2 return wrapper </code></pre> <p>Getting rid of the star magic is an improvement as this decorator is not general to all functions so we should be explicit about it. I like the fact that we change the number of parameters less as anyone looking at the code could easily be confused by the fact that when we call the function we are adding an extra parameter. Furthermore it just feels like decorators that change the signature of the function they decorate <em>should</em> be bad form.</p> <p>In summary:</p> <p>Decorators are higher order functions, and templating behaviour is <em>precisely</em> what they're for.</p> <p>I would embrace the fact that this code is specific to your fooXXX functions, by making the decorator internal and having it take precisely the number of arguments needed (because foo(*args, **kwargs) signatures makes introspection a pain).</p> <pre><code>def _refactorMe(func): @functools.wraps(func) #the wraps decorator propagates name/docsting def wrapper(parm1, parm2): if parm1: code_chunk_1 func(parm1, parm2) if parm2: code_chunk_2 return wrapper </code></pre> <p>I'd leave the calls taking two parameters, even though one is unused just so that the decorator doesn't change the signature. This isn't strictly necessary as if you document the functions as they look after decoration and you are restricting the use of the decorator to this small set of functions then the fact that the signature changes shouldn't be that big a deal.</p> <pre><code>@_refactorMe def fooB(param1, param2): fooB_code #uses only param1 @_refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre>
3
2009-08-25T11:09:06Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
1,327,749
<p>I like Ferdinand Beyer's answer and I think we need examples like that to understand what we are talking about. I'm just goin to give two further inspirational suggestions.</p> <p>Why not explicitly use transaction code?</p> <pre><code>def fooA(param1, use_transaction=param2): enter_transaction(param2) fooA_code #uses only param1 exit_transaction(param2) def fooB(param1, use_transaction=param2): enter_transaction(param2) fooB_code #uses only param1 exit_transaction(param2) </code></pre> <p>Now with that written we understand that we should probably write this:</p> <pre><code>def fooA(param1, use_transaction=param2): with transaction(param2): fooA_code #uses only param1 def fooB(param1, use_transaction=param2): with transaction(param2): fooB_code #uses only param1 </code></pre> <p>Using some context manager.</p> <p>But wait! We can put that outside!</p> <p>if you want this use:</p> <pre><code>with transactional(): fooA(param1) </code></pre> <p>for the <code>not param2</code> case, simply call <code>fooA(param1)</code></p> <p>Last syntax suggestion, when param2 == true:</p> <pre><code>do_transaction(fooA, param1) </code></pre> <p>here we define</p> <pre><code>def do_transaction(func, *args): code_1 func(*args) code_2 </code></pre> <p>Ok that was my stream of thoughts. Can you use a context manager? It is also hard to document, but somehow this wrapping process must be integral to your application, or if it's not, you could remove it.</p>
1
2009-08-25T11:43:41Z
[ "python", "refactoring", "decorator" ]
Code refactoring with python decorators?
1,327,362
<p>I'm actually struggling with some piece of code. I do know that it can be refactored, but I can't find the nice-smart-elegant solution.</p> <p>Here are two functions (much more functions of that kind are in my code):</p> <pre><code>def fooA(param1, param2): if param2 == True: code_chunk_1 fooA_code #uses only param1 if param2 == True: code_chunk_2 def fooB(param1, param2): if param2 == True: code_chunk_1 fooB_code #uses only param1 if param2 == True: code_chunk_2 </code></pre> <p>My first idea was to use this decorator:</p> <pre><code>def refactorMe(func): def wrapper(*args): if args[-1]: code_chunk_1 func(*args) if args[-1]: code_chunk_2 return wrapper </code></pre> <p>And finally:</p> <pre><code>@refactorMe def fooA(param1, param2): fooA_code #uses only param1 @refactorMe def fooB(param1, param2): fooB_code #uses only param1 </code></pre> <p>Unfortunately, I'm not happy with this solution:</p> <ul> <li>This decorator is "intrusive" and specific to the fooA &amp; fooB functions</li> <li>param2 is not used anymore in the fooA &amp; fooB body, but we must keep it in the function signature</li> </ul> <p>Perhaps I'm not using the decorator for its initial purpose?</p> <p>Is there any other way to refactor the code?</p> <p>Thanks a lot!</p>
4
2009-08-25T10:24:23Z
8,772,255
<p>Having a similar problem, I came up with a more generic solution that allows to:</p> <ul> <li>wrap a function with one implementing more parameters</li> <li>preserving the wrapped function documentation, including the wrapper documentation</li> </ul> <p>Hoping to help I wanted to share it and found this "old" question, which seems appropriate.</p> <p>Example:</p> <pre><code>@decorator_more_args_prepend def add_params_a_b(f, a, b, *args, **kw): """ Wrapper whose description we don't want in the generated function Line that we want in the generated function :param a: description of a :param b: description of b No idea about the rest of the arguments """ print("Doing something with %s and %s, calling %s with args %s" % (a, b, f.__name__, args)) return f(*args, **kw) @add_params_a_b def test_func(c, d): """ Test function that we want augmented :param c: description of c :param d: description of d """ print("Called with c=%(c)s and d=%(d)s" % locals()) </code></pre> <p>Help:</p> <pre><code>Help on function test_func in module __main__: test_func(a, b, c, d) Test function that we want augmented Line that we want in the generated function :param a: description of a :param b: description of b No idea about the rest of the arguments :param c: description of c :param d: description of d </code></pre> <p>Call:</p> <pre><code>&gt;&gt;&gt; test_func(1, 2, 3, 4) Doing something with 1 and 2, calling test_func with args (3, 4) Called with c=3 and d=4 </code></pre> <p>So the implementation of <code>decorator_more_args_prepend</code> uses <code>decorator</code>:</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 # A few decorators __author__ = "Jérôme Carretero &lt;cJ-py@zougloub.eu&gt;" __contact__ = "http://gitorious.org/py_decorators" __license__ = "Python" __credits__ = ["Michele Simionato"] __version__ = "1.0.0" from decorator import FunctionMaker, partial, inspect, decorator # def decorator_more_args_prepend(caller, func=None): """ Decorator that construcs a function which calls the caller on func, adding the arguments of caller as first arguments of the function. Directly inspired by the decorator module code, but: - we build a generated signature instead of passing the callee function - we generate a docstring consisting of a merging of info from wrapper and wrapped ones Based on decorator.decorator, Copyright (c) 2005-2011, Michele Simionato """ if func is not None: # returns a decorated function evaldict = func.__globals__.copy() evaldict.update({'_call_': caller, '_func_': func}) caller_spec = inspect.getargspec(caller) callee_spec = inspect.getargspec(func) def cleaned_docstring(o): import pydoc return pydoc.getdoc(o).split("\n") caller_doc = cleaned_docstring(caller) callee_doc = cleaned_docstring(func) newdoc = "\n".join(callee_doc[:1] + caller_doc[1:] + callee_doc[1:]) return FunctionMaker.create( "%s(%s)" % (func.__name__, ", ".join(caller_spec.args[1:]+callee_spec.args)), "return _call_(_func_, %(shortsignature)s)", evaldict, undecorated=func, __wrapped__=func, doc=newdoc, ) else: if isinstance(caller, partial): return partial(decorator, caller) # otherwise assume caller is a function first = inspect.getargspec(caller)[0][0] evaldict = caller.__globals__.copy() evaldict['_call_'] = caller evaldict['decorator'] = decorator return FunctionMaker.create( '%s(%s)' % (caller.__name__, first), 'return %s(_call_, %s)' % (inspect.stack()[0][3], first), evaldict, undecorated=caller, __wrapped__=caller, doc=caller.__doc__, module=caller.__module__) </code></pre> <p>Edit: I put the code on <a href="https://gitorious.org/py_decorators" rel="nofollow">gitorious</a> and won't maintain it here.</p>
0
2012-01-07T19:07:18Z
[ "python", "refactoring", "decorator" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,384
<p>Try:</p> <pre><code>title = re.search('&lt;title&gt;(.*)&lt;/title&gt;', html, re.IGNORECASE).group(1) </code></pre>
2
2009-08-25T10:28:45Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,385
<p><code>re.search('&lt;title&gt;(.*)&lt;/title&gt;', s, re.IGNORECASE).group(1)</code></p>
2
2009-08-25T10:28:53Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,389
<p>Use <code>(</code> <code>)</code> in regexp and <code>group(1)</code> in python to retrieve the captured string (<code>re.search</code> will return <code>None</code> if it doesn't find the result, so <em>don't use group() directly</em>):</p> <pre><code>title_search = re.search('&lt;title&gt;(.*)&lt;/title&gt;', html, re.IGNORECASE) if title_search: title = title_search.group(1) </code></pre>
45
2009-08-25T10:29:31Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,394
<p>Try using capturing groups:</p> <pre><code>title = re.search('&lt;title&gt;(.*)&lt;/title&gt;', html, re.IGNORECASE).group(1) </code></pre>
4
2009-08-25T10:30:02Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,398
<p><strong>Please, do NOT use regex to parse markup languages. Use lxml or beautifulsoup.</strong></p>
18
2009-08-25T10:31:31Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,415
<p><strong>Using regular expressions to parse the HTML is generally not a good idea.</strong> You can use any HTML parser like Beautiful Soup for that. Check out <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/documentation.html</a></p> <p>Also remember that <strong>some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.</strong></p>
3
2009-08-25T10:35:08Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
1,327,416
<p>Don't use regular expressions for HTML parsing in Python. Use an HTML parser! (Unless you're going to write a full parser, which would be a of extra work when various HTML, SGML and XML parsers are already in the standard libraries.</p> <p>If your handling "real world" <strong>tag soup</strong> HTML (which is frequently non-conforming to any SGML/XML validator) then use the BeautifulSoup package (which isn't in the standard libraries (yet) but is wide recommended for this purpose.</p>
0
2009-08-25T10:35:29Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
15,165,269
<p>May I recommend you to Beautiful Soup. Soup is a very good lib to parse all of your html document.</p> <pre><code>soup = BeatifulSoup(html_doc) titleName = soup.title.name </code></pre>
1
2013-03-01T19:22:25Z
[ "python", "html", "regex", "html-content-extraction" ]
extract contents of regex
1,327,369
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p> <pre><code>title = re.search('&lt;title&gt;.*&lt;/title&gt;', html, re.IGNORECASE).group() if title: title = title.replace('&lt;title&gt;', '').replace('&lt;/title&gt;', '') </code></pre> <p>Is there a regular expression to extract just the contents of so I don't have to remove the tags?</p> <p>thanks!</p>
29
2009-08-25T10:24:58Z
19,618,950
<p>The provided pieces of code do not cope with <code>Exceptions</code> May I suggest</p> <pre><code>getattr(re.search(r"&lt;title&gt;(.*)&lt;/title&gt;", s, re.IGNORECASE), 'groups', lambda:[u""])()[0] </code></pre> <p>This returns an empty string by default if the pattern has not been found, or the first match.</p>
0
2013-10-27T14:07:28Z
[ "python", "html", "regex", "html-content-extraction" ]
python - problems with regular expression and unicode
1,327,731
<p>Hi I have a problem in python. I try to explain my problem with an example.</p> <p>I have this string:</p> <pre><code>&gt;&gt;&gt; string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' &gt;&gt;&gt; print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà </code></pre> <p>and i want, for example, replace charachters different from Ñ,Ã,ï with ""</p> <p>i have tried:</p> <pre><code>&gt;&gt;&gt; rePat = re.compile('[^ÑÃï]',re.UNICODE) &gt;&gt;&gt; print rePat.sub("",string) �Ñ�����������������������������ï�������������������à </code></pre> <p>I obtained this �. I think that it's happen because this type of characters in python are represented by two position in the vector: for example \xc3\x91 = Ñ. For this, when i make the regolar expression, all the \xc3 are not substitued. How I can do this type of sub?????</p> <p>Thanks Franco</p>
4
2009-08-25T11:40:25Z
1,327,764
<p>You need to make sure that your strings are unicode strings, not plain strings (plain strings are like byte arrays).</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' &gt;&gt;&gt; type(string) &lt;type 'str'&gt; # do this instead: # (note the u in front of the ', this marks the character sequence as a unicode literal) &gt;&gt;&gt; string = u'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\xc0\xc1\xc2\xc3' # or: &gt;&gt;&gt; string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'.decode('utf-8') # ... but be aware that the latter will only work if the terminal (or source file) has utf-8 encoding # ... it is a best practice to use the \xNN form in unicode literals, as in the first example &gt;&gt;&gt; type(string) &lt;type 'unicode'&gt; &gt;&gt;&gt; print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà &gt;&gt;&gt; rePat = re.compile(u'[^\xc3\x91\xc3\x83\xc3\xaf]',re.UNICODE) &gt;&gt;&gt; print rePat.sub("", string) à </code></pre> <p><hr /></p> <p>When reading from a file, <code>string = open('filename.txt').read()</code> reads a byte sequence.</p> <p>To get the unicode content, do: <code>string = unicode(open('filename.txt').read(), 'encoding')</code>. Or: <code>string = open('filename.txt').read().decode('encoding')</code>.</p> <p>The <a href="http://docs.python.org/library/codecs.html">codecs</a> module can decode unicode streams (such as files) on-the-fly.</p> <p>Do a google search for <a href="http://www.google.com/search?q=python+unicode">python unicode</a>. Python unicode handling can be a bit hard to grasp at first, it pays to read up on it.</p> <p>I live by this rule: "Software should only work with Unicode strings internally, converting to a particular encoding on output." (from <a href="http://www.amk.ca/python/howto/unicode">http://www.amk.ca/python/howto/unicode</a>)</p> <p>I also recommend: <a href="http://www.joelonsoftware.com/articles/Unicode.html">http://www.joelonsoftware.com/articles/Unicode.html</a></p>
14
2009-08-25T11:47:03Z
[ "python", "regex", "unicode" ]
Having instance-like behaviour in databases
1,327,848
<p>Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following:</p> <p>I have a generic item that represents a group, lets call it <strong>Car</strong>. Now this <strong>Car</strong> has attributes, that range within certain limits, lets say for example speed is between 0 and 180 for a usual <strong>Car</strong>. Imagine some more attributes with ranges here, for example Color is between 0 and 255 whatever that value might stand for.</p> <p>So in my table <strong>GenericItems</strong> I have:</p> <pre><code>ID Name 1 Car </code></pre> <p>And in my <strong>Attributes</strong> I have:</p> <pre><code>ID Name Min_Value Max Value 1 Speed 0 180 2 Color 0 255 </code></pre> <p>The relation between Car and Attributes is thus 1:n.</p> <p>Now I start having very specific instances of my <strong>Car</strong> for example a FordMustang, A FerrariF40, and a DodgeViper. These are specific instances and now I want to give them specific values for their attributes.</p> <p>So in my table <strong>SpecificItem</strong> I have:</p> <pre><code>ID Name GenericItem_ID 1 FordMustang 1 2 DodgeViper 1 3 FerrariF40 1 </code></pre> <p>Now I need a third table <strong>SpecificAttributes2SpecificItems</strong>, to match attributes to <strong>SpecificItems</strong>:</p> <pre><code>ID SpecificItem_ID Attribute_ID Value 1 1 1 120 ;Ford Mustang goes 120 only 2 1 2 123 ;Ford Mustang is red 3 2 1 150 ;Dodge Viper goes 150 4 2 2 255 ;Dodge Viper is white 5 3 1 180 ;FerrariF40 goes 180 6 3 2 0 ;FerrariF40 is black </code></pre> <p>The problem with this design is, as you can see, that I am basically always copying over all rows of attributes, and I feel like this is bad design, inconsistent etc. How can I achieve this logic in a correct, normalized way?</p> <p>I want to be able to have multiple generic items, with multiple attributes with min/max values as interval, that can be "instantiated" with specific values</p>
0
2009-08-25T12:02:33Z
1,327,897
<p>The easiest way to use inheritance in database models is to use an ORM tool. For Python there is SQLAlchemy, Django and others.</p> <p>Now you should wonder whether e.g. a Ford Mustang is a kind of Car, or an instance of Car. In the former case, you should create a ford_mustang table defining the ford_mustang attributes. The ford_mustang table should then also have a foreign key to the car table, where the generic attributes of each FordMustang are specified. In the latter case, each kind of car is just a row in the Car table. Either way, each attribute should be represented in a single column.</p> <p>Validation of the attributes is typically done in the business logic of the application.</p>
1
2009-08-25T12:13:44Z
[ "python", "mysql", "database", "database-design" ]
Having instance-like behaviour in databases
1,327,848
<p>Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following:</p> <p>I have a generic item that represents a group, lets call it <strong>Car</strong>. Now this <strong>Car</strong> has attributes, that range within certain limits, lets say for example speed is between 0 and 180 for a usual <strong>Car</strong>. Imagine some more attributes with ranges here, for example Color is between 0 and 255 whatever that value might stand for.</p> <p>So in my table <strong>GenericItems</strong> I have:</p> <pre><code>ID Name 1 Car </code></pre> <p>And in my <strong>Attributes</strong> I have:</p> <pre><code>ID Name Min_Value Max Value 1 Speed 0 180 2 Color 0 255 </code></pre> <p>The relation between Car and Attributes is thus 1:n.</p> <p>Now I start having very specific instances of my <strong>Car</strong> for example a FordMustang, A FerrariF40, and a DodgeViper. These are specific instances and now I want to give them specific values for their attributes.</p> <p>So in my table <strong>SpecificItem</strong> I have:</p> <pre><code>ID Name GenericItem_ID 1 FordMustang 1 2 DodgeViper 1 3 FerrariF40 1 </code></pre> <p>Now I need a third table <strong>SpecificAttributes2SpecificItems</strong>, to match attributes to <strong>SpecificItems</strong>:</p> <pre><code>ID SpecificItem_ID Attribute_ID Value 1 1 1 120 ;Ford Mustang goes 120 only 2 1 2 123 ;Ford Mustang is red 3 2 1 150 ;Dodge Viper goes 150 4 2 2 255 ;Dodge Viper is white 5 3 1 180 ;FerrariF40 goes 180 6 3 2 0 ;FerrariF40 is black </code></pre> <p>The problem with this design is, as you can see, that I am basically always copying over all rows of attributes, and I feel like this is bad design, inconsistent etc. How can I achieve this logic in a correct, normalized way?</p> <p>I want to be able to have multiple generic items, with multiple attributes with min/max values as interval, that can be "instantiated" with specific values</p>
0
2009-08-25T12:02:33Z
1,327,948
<p>It looks like you're trying to replicate Entity Atribute Value as a design, which leads to a lot of ugly tables (well, usually it is one single table for everything). </p> <p><a href="http://en.wikipedia.org/wiki/Entity-attribute-value%5Fmodel" rel="nofollow">http://en.wikipedia.org/wiki/Entity-attribute-value%5Fmodel</a> <a href="http://ycmi.med.yale.edu/nadkarni/Introduction%20to%20EAV%20systems.htm" rel="nofollow">http://ycmi.med.yale.edu/nadkarni/Introduction%20to%20EAV%20systems.htm</a> </p> <p>Discussing EAV tends to lead to "religious wars" as there are very few good places to use it (many folks say there are zero good places) and there are other folks who think that since it is so very flexible, it should be used everywhere. If I can find the reference I'm looking for, I'll add it to this.</p>
1
2009-08-25T12:25:04Z
[ "python", "mysql", "database", "database-design" ]
Having instance-like behaviour in databases
1,327,848
<p>Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following:</p> <p>I have a generic item that represents a group, lets call it <strong>Car</strong>. Now this <strong>Car</strong> has attributes, that range within certain limits, lets say for example speed is between 0 and 180 for a usual <strong>Car</strong>. Imagine some more attributes with ranges here, for example Color is between 0 and 255 whatever that value might stand for.</p> <p>So in my table <strong>GenericItems</strong> I have:</p> <pre><code>ID Name 1 Car </code></pre> <p>And in my <strong>Attributes</strong> I have:</p> <pre><code>ID Name Min_Value Max Value 1 Speed 0 180 2 Color 0 255 </code></pre> <p>The relation between Car and Attributes is thus 1:n.</p> <p>Now I start having very specific instances of my <strong>Car</strong> for example a FordMustang, A FerrariF40, and a DodgeViper. These are specific instances and now I want to give them specific values for their attributes.</p> <p>So in my table <strong>SpecificItem</strong> I have:</p> <pre><code>ID Name GenericItem_ID 1 FordMustang 1 2 DodgeViper 1 3 FerrariF40 1 </code></pre> <p>Now I need a third table <strong>SpecificAttributes2SpecificItems</strong>, to match attributes to <strong>SpecificItems</strong>:</p> <pre><code>ID SpecificItem_ID Attribute_ID Value 1 1 1 120 ;Ford Mustang goes 120 only 2 1 2 123 ;Ford Mustang is red 3 2 1 150 ;Dodge Viper goes 150 4 2 2 255 ;Dodge Viper is white 5 3 1 180 ;FerrariF40 goes 180 6 3 2 0 ;FerrariF40 is black </code></pre> <p>The problem with this design is, as you can see, that I am basically always copying over all rows of attributes, and I feel like this is bad design, inconsistent etc. How can I achieve this logic in a correct, normalized way?</p> <p>I want to be able to have multiple generic items, with multiple attributes with min/max values as interval, that can be "instantiated" with specific values</p>
0
2009-08-25T12:02:33Z
1,327,984
<p>There is a school of thought which holds that any attempt to build an EAV model in an RDBMS constitutes "bad design" but we won't go there. Ooops, looks like somebody else already has done.</p> <p>I'm not certain what worries you. <strong>SpecificAttributes2SpecificItems</strong> is an intersection table (the clue is in the name). Necessarily it includes links to the <strong>Attributes</strong> and the <strong>SpecificItems</strong>. How could it not? </p> <p>You probably need to have a MinVal and a MaxVal on <strong>SpecificAttributes2SpecificItems</strong>, as certain items will have a more limited range than that permitted by the <strong>GenericItems</strong>. For instance, everybody knows that Ferraris should only be available in red. </p>
1
2009-08-25T12:31:19Z
[ "python", "mysql", "database", "database-design" ]
Having instance-like behaviour in databases
1,327,848
<p>Sorry for the bad title, but I have no idea how to put this in short. The Problem is the following:</p> <p>I have a generic item that represents a group, lets call it <strong>Car</strong>. Now this <strong>Car</strong> has attributes, that range within certain limits, lets say for example speed is between 0 and 180 for a usual <strong>Car</strong>. Imagine some more attributes with ranges here, for example Color is between 0 and 255 whatever that value might stand for.</p> <p>So in my table <strong>GenericItems</strong> I have:</p> <pre><code>ID Name 1 Car </code></pre> <p>And in my <strong>Attributes</strong> I have:</p> <pre><code>ID Name Min_Value Max Value 1 Speed 0 180 2 Color 0 255 </code></pre> <p>The relation between Car and Attributes is thus 1:n.</p> <p>Now I start having very specific instances of my <strong>Car</strong> for example a FordMustang, A FerrariF40, and a DodgeViper. These are specific instances and now I want to give them specific values for their attributes.</p> <p>So in my table <strong>SpecificItem</strong> I have:</p> <pre><code>ID Name GenericItem_ID 1 FordMustang 1 2 DodgeViper 1 3 FerrariF40 1 </code></pre> <p>Now I need a third table <strong>SpecificAttributes2SpecificItems</strong>, to match attributes to <strong>SpecificItems</strong>:</p> <pre><code>ID SpecificItem_ID Attribute_ID Value 1 1 1 120 ;Ford Mustang goes 120 only 2 1 2 123 ;Ford Mustang is red 3 2 1 150 ;Dodge Viper goes 150 4 2 2 255 ;Dodge Viper is white 5 3 1 180 ;FerrariF40 goes 180 6 3 2 0 ;FerrariF40 is black </code></pre> <p>The problem with this design is, as you can see, that I am basically always copying over all rows of attributes, and I feel like this is bad design, inconsistent etc. How can I achieve this logic in a correct, normalized way?</p> <p>I want to be able to have multiple generic items, with multiple attributes with min/max values as interval, that can be "instantiated" with specific values</p>
0
2009-08-25T12:02:33Z
1,328,003
<p>Couple of ideas:</p> <p>First, you should consider making your "genericgroups" table an "attribute" rather than something hovering above the rest of the data.</p> <p>Second, you may have an easier time having each attribute table actually holding the attributes of the items, not simply the idea of the attributes. If you want to have a range, consider either an enum type (for item names) or simply an integer with a set maximum (so the value of the color_value column can't be above 255). This way you would end up with something more like:</p> <pre><code> Item Table ID Name 1 FordMustang 2 DodgeViper 3 FerrariF40 ItemType Table: ItemID Type 1 Car 2 Car 3 Car ItemColor Table: ItemID ColorID 1 123 2 255 3 0 MaxSpeed Table ItemID MaxSpeedID 1 120 2 150 3 180 </code></pre>
1
2009-08-25T12:35:56Z
[ "python", "mysql", "database", "database-design" ]
Search function with PyGTKsourceview
1,327,906
<p>I'm writing a small html editor in python mostly for personal use and have integrated a gtksourceview2 object into my Python code. All the mayor functions seem to work more or less, but I'm having trouble getting a search function to work. Obvioiusly the GUI work is already done, but I can't figure out how to somehow buildin methods of the GTKsourceview.Buffer object (<a href="http://www.gnome.org/~gianmt/pygtksourceview2/class-gtksourcebuffer2.html" rel="nofollow">http://www.gnome.org/~gianmt/pygtksourceview2/class-gtksourcebuffer2.html</a>) to actually search through the text in it. </p> <p>Does anybody have a suggestion? I find the documentation not very verbose and can't really find a working example on the web. </p> <p>Thanks in advance. </p>
0
2009-08-25T12:18:04Z
1,328,004
<p>The <a href="http://library.gnome.org/devel/gtksourceview/stable/" rel="nofollow">reference for the C API</a> can probably be helpful, including this chapter that I found <a href="http://library.gnome.org/devel/gtksourceview/stable/gtksourceview-2.0-Searching-in-a-GtkSourceBuffer.html" rel="nofollow">"Searching in a GtkSourceBuffer"</a>.</p> <p>As is the reference for the superclass <a href="http://www.pygtk.org/docs/pygtk/class-gtktextbuffer.html" rel="nofollow">gtk.TextBuffer</a></p>
1
2009-08-25T12:36:07Z
[ "python", "pygtk" ]
Search function with PyGTKsourceview
1,327,906
<p>I'm writing a small html editor in python mostly for personal use and have integrated a gtksourceview2 object into my Python code. All the mayor functions seem to work more or less, but I'm having trouble getting a search function to work. Obvioiusly the GUI work is already done, but I can't figure out how to somehow buildin methods of the GTKsourceview.Buffer object (<a href="http://www.gnome.org/~gianmt/pygtksourceview2/class-gtksourcebuffer2.html" rel="nofollow">http://www.gnome.org/~gianmt/pygtksourceview2/class-gtksourcebuffer2.html</a>) to actually search through the text in it. </p> <p>Does anybody have a suggestion? I find the documentation not very verbose and can't really find a working example on the web. </p> <p>Thanks in advance. </p>
0
2009-08-25T12:18:04Z
1,329,252
<p>Here is the python doc, I couldn't find any up-to-date documentation so I stuffed it in my dropbox. Here is the <a href="http://dl.getdropbox.com/u/961121/class-gtksourcebuffer2.html" rel="nofollow">link</a>. What you want to look at is at is the <code>gtk.iter_forward_search</code> and <code>gtk.iter_backward_search</code> functions.</p>
1
2009-08-25T16:02:46Z
[ "python", "pygtk" ]
Rescale intensities of a PIL Image
1,327,954
<p>What is the simplest/cleanest way to rescale the intensities of a PIL Image?</p> <p>Suppose that I have a 16-bit image from a 12-bit camera, so only the values 0–4095 are in use. I would like to rescale the intensities so that the entire range 0–65535 is used. What is the simplest/cleanest way to do this when the image is represented as PIL's Image type?</p> <p>The best solution I have come up with so far is:</p> <pre><code>pixels = img.getdata() img.putdata(pixels, 16) </code></pre> <p>That works, but always leaves the four least significant bits blank. Ideally, I would like to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits. I don't know how to do that fast.</p>
2
2009-08-25T12:25:51Z
1,327,987
<p>What you need to do is <a href="http://en.wikipedia.org/wiki/Histogram%5Fequalization" rel="nofollow">Histogram Equalization</a>. For how to do it with python and pil:</p> <ul> <li><a href="http://effbot.org/zone/pil-histogram-equalization.htm" rel="nofollow">LINK1</a></li> <li><a href="http://jesolem.blogspot.com/2009/06/histogram-equalization-with-python-and.html" rel="nofollow">LINK2</a></li> </ul> <p>EDIT: Code to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits...</p> <pre><code>def f(n): return n&lt;&lt;4 + int(bin(n)[2:6],2) print(f(0)) print(f(2**12)) # output &gt;&gt;&gt; 0 65664 # Oops &gt; 2^16 </code></pre>
1
2009-08-25T12:31:36Z
[ "python", "image-processing", "python-imaging-library" ]
Rescale intensities of a PIL Image
1,327,954
<p>What is the simplest/cleanest way to rescale the intensities of a PIL Image?</p> <p>Suppose that I have a 16-bit image from a 12-bit camera, so only the values 0–4095 are in use. I would like to rescale the intensities so that the entire range 0–65535 is used. What is the simplest/cleanest way to do this when the image is represented as PIL's Image type?</p> <p>The best solution I have come up with so far is:</p> <pre><code>pixels = img.getdata() img.putdata(pixels, 16) </code></pre> <p>That works, but always leaves the four least significant bits blank. Ideally, I would like to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits. I don't know how to do that fast.</p>
2
2009-08-25T12:25:51Z
1,328,394
<p>Why would you want to copy the 4 msb back into the 4 lsb? You only have 12 significant bits of information per pixel. Nothing you do will improve that. If you are OK with only having 4K of intensities, which is fine for most applications, then your solution is correct and probably optimal. If you need more levels of shading, then as David posted, recompute using a histogram. But, this will be significantly slower. </p> <p>But, copying the 4 msb into the 4 lsb is NOT the way to go :)</p>
2
2009-08-25T13:49:39Z
[ "python", "image-processing", "python-imaging-library" ]
Rescale intensities of a PIL Image
1,327,954
<p>What is the simplest/cleanest way to rescale the intensities of a PIL Image?</p> <p>Suppose that I have a 16-bit image from a 12-bit camera, so only the values 0–4095 are in use. I would like to rescale the intensities so that the entire range 0–65535 is used. What is the simplest/cleanest way to do this when the image is represented as PIL's Image type?</p> <p>The best solution I have come up with so far is:</p> <pre><code>pixels = img.getdata() img.putdata(pixels, 16) </code></pre> <p>That works, but always leaves the four least significant bits blank. Ideally, I would like to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits. I don't know how to do that fast.</p>
2
2009-08-25T12:25:51Z
1,334,419
<p>You need to do a histogram <em>stretch</em> (<a href="http://stackoverflow.com/questions/1295057/i-need-to-do-a-histogram-stretch/1299079#1299079">link to a similar question I answered</a>) not histogram <em>equalization</em>: <img src="http://cct.rncan.gc.ca/resource/tutor/fundam/images/linstre.gif" alt="histogram stretch" /></p> <p><a href="http://cct.rncan.gc.ca/resource/tutor/fundam/chapter4/05%5Fe.php" rel="nofollow">Image source</a></p> <p>In your case you one need to <strong>multiply</strong> all the pixel values by <strong>16</strong>, which is the factor between the two dynamic ranges (65536/4096).</p>
2
2009-08-26T12:45:18Z
[ "python", "image-processing", "python-imaging-library" ]
Rescale intensities of a PIL Image
1,327,954
<p>What is the simplest/cleanest way to rescale the intensities of a PIL Image?</p> <p>Suppose that I have a 16-bit image from a 12-bit camera, so only the values 0–4095 are in use. I would like to rescale the intensities so that the entire range 0–65535 is used. What is the simplest/cleanest way to do this when the image is represented as PIL's Image type?</p> <p>The best solution I have come up with so far is:</p> <pre><code>pixels = img.getdata() img.putdata(pixels, 16) </code></pre> <p>That works, but always leaves the four least significant bits blank. Ideally, I would like to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits. I don't know how to do that fast.</p>
2
2009-08-25T12:25:51Z
1,410,979
<p>Maybe you should pass 16. (a float) instead of 16 (an int). I was trying to test it, but for some reason putdata does not multiply at all... So I hope it just works for you.</p>
0
2009-09-11T13:48:17Z
[ "python", "image-processing", "python-imaging-library" ]
Rescale intensities of a PIL Image
1,327,954
<p>What is the simplest/cleanest way to rescale the intensities of a PIL Image?</p> <p>Suppose that I have a 16-bit image from a 12-bit camera, so only the values 0–4095 are in use. I would like to rescale the intensities so that the entire range 0–65535 is used. What is the simplest/cleanest way to do this when the image is represented as PIL's Image type?</p> <p>The best solution I have come up with so far is:</p> <pre><code>pixels = img.getdata() img.putdata(pixels, 16) </code></pre> <p>That works, but always leaves the four least significant bits blank. Ideally, I would like to shift each value four bits to the left, then copy the four most significant bits to the four least significant bits. I don't know how to do that fast.</p>
2
2009-08-25T12:25:51Z
1,430,673
<p>Since you know that the pixel values are 0-4095, I can't find a faster way than this:</p> <pre><code>new_image= image.point(lambda value: value&lt;&lt;4 | value&gt;&gt;8) </code></pre> <p>According to the <a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">documentation</a>, the lambda function will be called at most 4096 times, whatever the size of your image.</p> <p>EDIT: Since the function given to point <em>must</em> be of the form <code>argument * scale + offset</code> for in <code>I</code> image, then this is the best possible using the <code>point</code> function:</p> <pre><code>new_image= image.point(lambda argument: argument*16) </code></pre> <p>The maximum output pixel value will be 65520.</p> <h3>A second take:</h3> <p>A modified version of your own solution, using <code>itertools</code> for improved efficiency:</p> <pre><code>import itertools as it # for brevity import operator def scale_12to16(image): new_image= image.copy() new_image.putdata( it.imap(operator.or_, it.imap(operator.lshift, image.getdata(), it.repeat(4)), it.imap(operator.rshift, image.getdata(), it.repeat(8)) ) ) return new_image </code></pre> <p>This avoids the limitation of the <code>point</code> function argument.</p>
2
2009-09-16T02:42:59Z
[ "python", "image-processing", "python-imaging-library" ]
Autodocumenting Python using Sphinx
1,328,041
<p>This is a generalized version of a <a href="http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module">previous question regarding Sphinx</a>.</p> <p>Is there a way to recursively autodocument modules or packages which contain classes and functions within them?</p> <p>I think it is silly to add the <code>autofunction</code> or <code>automodule</code> directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> <p><strong>Clarification:</strong> Instead of :</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. automethod:: Seg.method_1 .. automethod:: Seg.method_2 .. automethod:: Seg.method_3 ....... .. automethod:: Seg.method_n </code></pre> <p>Which requires me to manually cut-and-paste all method names and update the documentation correspondingly, I want to have a command like:</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. MAGIC COMMAND: Automatically print the docstrings and signatures of all Seg() methods. </code></pre>
15
2009-08-25T12:42:38Z
1,328,075
<p>You want it more simpler than just specifing automodule? Even for a large library, it's 5min amount of work to type all the module names.</p> <p>The reason of doing so is because Sphinx hardly guesses what needs to be documented.</p> <p>You could also write autopackage, that would search for modules and use automodule directive (if automodule does not do that already).</p>
-8
2009-08-25T12:47:54Z
[ "python", "documentation-generation", "python-sphinx" ]
Autodocumenting Python using Sphinx
1,328,041
<p>This is a generalized version of a <a href="http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module">previous question regarding Sphinx</a>.</p> <p>Is there a way to recursively autodocument modules or packages which contain classes and functions within them?</p> <p>I think it is silly to add the <code>autofunction</code> or <code>automodule</code> directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> <p><strong>Clarification:</strong> Instead of :</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. automethod:: Seg.method_1 .. automethod:: Seg.method_2 .. automethod:: Seg.method_3 ....... .. automethod:: Seg.method_n </code></pre> <p>Which requires me to manually cut-and-paste all method names and update the documentation correspondingly, I want to have a command like:</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. MAGIC COMMAND: Automatically print the docstrings and signatures of all Seg() methods. </code></pre>
15
2009-08-25T12:42:38Z
1,328,264
<p>We use </p> <pre><code>.. automodule:: module :members: </code></pre>
35
2009-08-25T13:26:39Z
[ "python", "documentation-generation", "python-sphinx" ]
Autodocumenting Python using Sphinx
1,328,041
<p>This is a generalized version of a <a href="http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module">previous question regarding Sphinx</a>.</p> <p>Is there a way to recursively autodocument modules or packages which contain classes and functions within them?</p> <p>I think it is silly to add the <code>autofunction</code> or <code>automodule</code> directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> <p><strong>Clarification:</strong> Instead of :</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. automethod:: Seg.method_1 .. automethod:: Seg.method_2 .. automethod:: Seg.method_3 ....... .. automethod:: Seg.method_n </code></pre> <p>Which requires me to manually cut-and-paste all method names and update the documentation correspondingly, I want to have a command like:</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. MAGIC COMMAND: Automatically print the docstrings and signatures of all Seg() methods. </code></pre>
15
2009-08-25T12:42:38Z
1,328,297
<blockquote> <p>I think it is silly to add the autofunction or automodule directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> </blockquote> <p>I would suggest <a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a>, which is specialized at generating documentation from docstrings.</p>
0
2009-08-25T13:32:26Z
[ "python", "documentation-generation", "python-sphinx" ]
Autodocumenting Python using Sphinx
1,328,041
<p>This is a generalized version of a <a href="http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module">previous question regarding Sphinx</a>.</p> <p>Is there a way to recursively autodocument modules or packages which contain classes and functions within them?</p> <p>I think it is silly to add the <code>autofunction</code> or <code>automodule</code> directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> <p><strong>Clarification:</strong> Instead of :</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. automethod:: Seg.method_1 .. automethod:: Seg.method_2 .. automethod:: Seg.method_3 ....... .. automethod:: Seg.method_n </code></pre> <p>Which requires me to manually cut-and-paste all method names and update the documentation correspondingly, I want to have a command like:</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. MAGIC COMMAND: Automatically print the docstrings and signatures of all Seg() methods. </code></pre>
15
2009-08-25T12:42:38Z
1,328,722
<p>To make things easier you can use this script (look at the bottom of the page for the last version): <a href="http://bitbucket.org/birkenfeld/sphinx/issue/98/add-the-autogenerate-script-to-sphinx">http://bitbucket.org/birkenfeld/sphinx/issue/98/add-the-autogenerate-script-to-sphinx</a></p> <p>This script will parse your packages/modules and generate all the rest files necessary to build the doc from docstrings.</p> <p>I'm the original author of this script.</p> <p><strong>UPDATE</strong></p> <p>This script is now part of Sphinx 1.1 as <em><a href="http://sphinx.pocoo.org/man/sphinx-apidoc.html?highlight=apidoc">apidoc</a></em>.</p>
21
2009-08-25T14:37:36Z
[ "python", "documentation-generation", "python-sphinx" ]
Autodocumenting Python using Sphinx
1,328,041
<p>This is a generalized version of a <a href="http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module">previous question regarding Sphinx</a>.</p> <p>Is there a way to recursively autodocument modules or packages which contain classes and functions within them?</p> <p>I think it is silly to add the <code>autofunction</code> or <code>automodule</code> directive for each function; There must be a way to automate the process, otherwise I don't see the point of using Sphinx at all.</p> <p><strong>Clarification:</strong> Instead of :</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. automethod:: Seg.method_1 .. automethod:: Seg.method_2 .. automethod:: Seg.method_3 ....... .. automethod:: Seg.method_n </code></pre> <p>Which requires me to manually cut-and-paste all method names and update the documentation correspondingly, I want to have a command like:</p> <pre><code>.. automodule:: segments.segments .. autoclass:: segments.segments.Seg .. MAGIC COMMAND: Automatically print the docstrings and signatures of all Seg() methods. </code></pre>
15
2009-08-25T12:42:38Z
5,141,321
<p>Etienne's script, mentioned in his answer, has now been integrated into Sphinx as sphinx-apidoc. It does exactly what the OP wants. It is slated for release in Sphinx 1.1, or is available from the Hg repo:</p> <p><a href="https://bitbucket.org/birkenfeld/sphinx">https://bitbucket.org/birkenfeld/sphinx</a></p> <p>It works beautifully for me. The docs read thus:</p> <pre><code>&gt; sphinx-apidoc --help Usage: sphinx-apidoc-script.py [options] -o &lt;output_path&gt; &lt;module_path&gt; [exclude_paths, ...] Look recursively in &lt;module_path&gt; for Python modules and packages and create a reST file with automodule directives per package in the &lt;output_path&gt;. </code></pre>
15
2011-02-28T11:22:50Z
[ "python", "documentation-generation", "python-sphinx" ]
SHA256 hash in Python 2.4
1,328,155
<p>Is there a way I can calculate a SHA256 hash in Python 2.4 ? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in <a href="http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-a-string-secret-key-in-python">this</a> question, but using Python 2.4. Any help will be greatly appreciated.</p> <p>EDIT: Sorry, I mean SHA 256. I was too in a hurry. Sorry again.</p>
7
2009-08-25T13:04:25Z
1,328,162
<p>Yes you can. With Python 2.4, there was SHA-1 module which does exactly this. See <a href="http://www.python.org/doc/2.4/lib/module-sha.html" rel="nofollow">the documentation</a>.</p> <p>However, bear in mind that code importing from this module will cause DeprecationWarnings when run with newer Python.</p> <p>Ok, as the requirement was tightened to be SHA-256, using the SHA-1 module in standard library isn't enough. I'd suggest checking out <a href="http://pycrypto.org" rel="nofollow">pycrypto</a>, it has a SHA-256 implementation. There are also windows binary releases to match older Pythons, follow the links from Andrew Kuchlings <a href="http://www.amk.ca/python/code/crypto.html" rel="nofollow">old PyCrypto page</a>.</p>
10
2009-08-25T13:06:42Z
[ "python", "sha256", "python-2.4" ]
SHA256 hash in Python 2.4
1,328,155
<p>Is there a way I can calculate a SHA256 hash in Python 2.4 ? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in <a href="http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-a-string-secret-key-in-python">this</a> question, but using Python 2.4. Any help will be greatly appreciated.</p> <p>EDIT: Sorry, I mean SHA 256. I was too in a hurry. Sorry again.</p>
7
2009-08-25T13:04:25Z
1,328,203
<p>You can use the <code>sha</code> module, if you want to stay compatible, you can import it like this:</p> <pre><code>try: from hashlib import sha1 except ImportError: from sha import sha as sha1 </code></pre>
8
2009-08-25T13:13:16Z
[ "python", "sha256", "python-2.4" ]
SHA256 hash in Python 2.4
1,328,155
<p>Is there a way I can calculate a SHA256 hash in Python 2.4 ? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in <a href="http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-a-string-secret-key-in-python">this</a> question, but using Python 2.4. Any help will be greatly appreciated.</p> <p>EDIT: Sorry, I mean SHA 256. I was too in a hurry. Sorry again.</p>
7
2009-08-25T13:04:25Z
3,896,047
<p>There is a backported version of hashlib at <a href="http://pypi.python.org/pypi/hashlib" rel="nofollow">http://pypi.python.org/pypi/hashlib</a> and I just backported the newer hmac version and put it up at <a href="http://pypi.python.org/pypi/hmac" rel="nofollow">http://pypi.python.org/pypi/hmac</a></p>
4
2010-10-09T14:58:37Z
[ "python", "sha256", "python-2.4" ]
Should I forward arguments as *args & **kwargs?
1,328,248
<p>I have a class that handles command line arguments in my program using python's <code>optparse</code> module. It is also inherited by several classes to create subsets of parameters. To encapsulate the option parsing mechanism I want to reveal only a function <code>add_option</code> to inheriting classes. What this function does is then call <code>optparse.make_option</code>.</p> <p>Is it a good practice to simply have my <code>add_option</code> method say that it accepts the same arguments as <code>optparse.make_option</code> in the documentation, and forward the arguments as <code>*args</code> and <code>**kwargs</code>?</p> <p>Should I do some parameter checking beforehand? In a way I want to avoid this to decouple that piece of code as much from a specific version of <code>optparse</code>.</p>
2
2009-08-25T13:23:06Z
1,328,298
<p>Are you sure that subclassing is what you want to do? Your overriding behavior could just be implemented in a function.</p>
0
2009-08-25T13:32:30Z
[ "python", "optparse" ]
Should I forward arguments as *args & **kwargs?
1,328,248
<p>I have a class that handles command line arguments in my program using python's <code>optparse</code> module. It is also inherited by several classes to create subsets of parameters. To encapsulate the option parsing mechanism I want to reveal only a function <code>add_option</code> to inheriting classes. What this function does is then call <code>optparse.make_option</code>.</p> <p>Is it a good practice to simply have my <code>add_option</code> method say that it accepts the same arguments as <code>optparse.make_option</code> in the documentation, and forward the arguments as <code>*args</code> and <code>**kwargs</code>?</p> <p>Should I do some parameter checking beforehand? In a way I want to avoid this to decouple that piece of code as much from a specific version of <code>optparse</code>.</p>
2
2009-08-25T13:23:06Z
1,328,511
<p>It seems that you want your subclasses to have awareness of the command line stuff, which is often not a good idea.</p> <p>You want to encapsulate the whole config input portion of your program so that you can drive it with a command line, config file, other python program, whatever.</p> <p>So, I would remove any call to add_option from your subclasses. </p> <p>If you want to discover what your config requirements look like at runtime, I would simply add that data to your subclasses; let each one have a member or method that can be used to figure out what kind of inputs it needs.</p> <p>Then, you can have an input organizer class walk over them, pull this data out, and use it to drive a command line, config file, or what have you.</p> <p>But honestly, I've never needed to do this at run time. I usually pull all that config stuff out to it's own separate thing which answers the question "What does the user need to tell the tool?", and then the subclasses go looking in the config data structure for what they need.</p>
1
2009-08-25T14:07:35Z
[ "python", "optparse" ]
Guitar Tablature and Music sheet oriented plugins for wordpress or Drupal
1,328,533
<p>I'm familiar with wordpress and cakePHP; however, I'm building a small community website (hobby) that allows users to post music sheet (pdf/image) or guitar tabs ( text files). These music sheets should be organized by artists and songs. I've already built my own cms, but I'm not looking forward to maintain it as i'm scared I won't have the time.</p> <p>An example of this would be <a href="http://ultimate-guitar.com" rel="nofollow">ultimate-guitar.com</a> . Not the whole site, just the way they display tabs and stuff</p> <p><a href="http://arabtabs.com/tab.php?id=15" rel="nofollow">I posted a 1 month old build for you guys to see what i've done here</a>. the site for the most part works, but as i said, I'm scared that i won't be able to maintain it. This is not the latest build, i haven't gotten around to uploading it. It fixes most of the issues</p> <p>Are there any music publishing plugins for drupal and wordpress (I haven't seen any personally)? I'm open to other suggestions and comments as well so please feel free to mention them</p>
4
2009-08-25T14:10:07Z
1,328,990
<p>It doesn’t sound like you have any music specific needs, you just need to be able to attach text, pdf or images to an item (node in Drupal) and assign tags to it. </p> <p>You can use taxonomy in Drupal to assign artists to the nodes. I should think what you want is pretty simple to do. I would suggest that you try installing it and seeing what it can do.</p>
3
2009-08-25T15:21:29Z
[ "php", "python", "wordpress", "drupal", "music" ]
Guitar Tablature and Music sheet oriented plugins for wordpress or Drupal
1,328,533
<p>I'm familiar with wordpress and cakePHP; however, I'm building a small community website (hobby) that allows users to post music sheet (pdf/image) or guitar tabs ( text files). These music sheets should be organized by artists and songs. I've already built my own cms, but I'm not looking forward to maintain it as i'm scared I won't have the time.</p> <p>An example of this would be <a href="http://ultimate-guitar.com" rel="nofollow">ultimate-guitar.com</a> . Not the whole site, just the way they display tabs and stuff</p> <p><a href="http://arabtabs.com/tab.php?id=15" rel="nofollow">I posted a 1 month old build for you guys to see what i've done here</a>. the site for the most part works, but as i said, I'm scared that i won't be able to maintain it. This is not the latest build, i haven't gotten around to uploading it. It fixes most of the issues</p> <p>Are there any music publishing plugins for drupal and wordpress (I haven't seen any personally)? I'm open to other suggestions and comments as well so please feel free to mention them</p>
4
2009-08-25T14:10:07Z
1,333,285
<p>You might want to take a look at the <a href="http://drupal.org/project/guitar" rel="nofollow">Guitar module</a>, which will allow you to easily add chord fingerings to your tabs.</p>
1
2009-08-26T08:53:23Z
[ "php", "python", "wordpress", "drupal", "music" ]
Stable python serialization (e.g. no pickle module relocation issues)
1,328,581
<p>I am considering the use of <a href="http://packages.python.org/quantities/user/tutorial.html" rel="nofollow">Quantities</a> to define a number together with its unit. This value most likely will have to be stored on the disk. As you are probably aware, pickling has one major issue: if you relocate the module around, unpickling will not be able to resolve the class, and you will not be able to unpickle the information. There are workarounds for this behavior, but they are, indeed, workarounds. </p> <p>A solution I fantasized for this issue would be to create a string encoding uniquely a given unit. Once you obtain this encoding from the disk, you pass it to a factory method in the Quantities module, which decodes it to a proper unit instance. The advantage is that even if you relocate the module around, everything will still work, as long as you pass the magic string token to the factory method. </p> <p>Is this a known concept?</p>
0
2009-08-25T14:17:31Z
1,328,899
<p>Looks like an application of Wheeler's First Principle, "all problems in computer science can be solved by another level of indirection" (the Second Principle adds "but that will usually create another problem";-). Essentially what you need to do is an indirection to identify the <em>type</em> -- entity-within-type will be fine with pickling-like approaches (you can study the sources of <code>pickle.py</code> and <code>copy_reg.py</code> for all the fine details of the latter).</p> <p>Specifically, I believe that what you want to do is subclass <code>pickle.Pickler</code> and override the <code>save_inst</code> method. Where the current version says:</p> <pre><code> if self.bin: save(cls) for arg in args: save(arg) write(OBJ) else: for arg in args: save(arg) write(INST + cls.__module__ + '\n' + cls.__name__ + '\n') </code></pre> <p>you want to write something different than just the class's module and name -- some kind of unique identifier (made up of two string) for the class, probably held in your own registry or registries; and similarly for the <code>save_global</code> method.</p> <p>It's even easier for your subclass of <code>Unpickler</code>, because the <code>_instantiate</code> part is already factored out in its own method: you only need to override <code>find_class</code>, which is:</p> <pre><code>def find_class(self, module, name): # Subclasses may override this __import__(module) mod = sys.modules[module] klass = getattr(mod, name) return klass </code></pre> <p>it must take two strings and return a class object; you can do that through your registries, again.</p> <p>Like always when registries are involved, you need to think about how to ensure you register all objects (classes) of interest, etc, etc. One popular strategy here is to leave pickling alone, but ensure that all moves of classes, renames of modules, etc, are recorded somewhere permanent; this way, just the subclassed unpickler can do all the work, and it can most conveniently do it all in the overridden <code>find_class</code> -- bypassing all issues of registration. I gather you consider this a "workaround" but to me it seems just an extremely simple, powerful and convenient implementation of the "one more level of indirection" concept, which avoids the "one more problem" issue;-).</p>
1
2009-08-25T15:08:48Z
[ "python", "serialization", "pickle" ]
Python/PySerial and CPU usage
1,328,606
<p>I've created a script to monitor the output of a serial port that receives 3-4 lines of data every half hour - the script runs fine and grabs everything that comes off the port which at the end of the day is what matters...</p> <p>What bugs me, however, is that the cpu usage seems rather high for a program that's just monitoring a single serial port, 1 core will always be at 100% usage while this script is running.</p> <p>I'm basically running a modified version of the code in this question: <a href="http://stackoverflow.com/questions/1093598/pyserial-how-to-read-last-line-sent-from-serial-device">pyserial - How to Read Last Line Sent from Serial Device</a></p> <p>I've tried polling the inWaiting() function at regular intervals and having it sleep when inWaiting() is 0 - I've tried intervals from 1 second down to 0.001 seconds (basically, as often as I can without driving up the cpu usage) - this will succeed in grabbing the first line but seems to miss the rest of the data.</p> <p>Adjusting the timeout of the serial port doesn't seem to have any effect on cpu usage, nor does putting the listening function into it's own thread (not that I really expected a difference but it was worth trying).</p> <ul> <li>Should python/pyserial be using this much cpu? (this seems like overkill)</li> <li>Am I wasting my time on this quest / Should I just bite the bullet and schedule the script to sleep for the periods that I know no data will be coming?</li> </ul>
9
2009-08-25T14:20:37Z
1,328,634
<p>Would a system style solution be better? Create the python script and have it executed via Cron/Scheduled Task?</p> <p>pySerial shouldn't be using that much CPU but if its just sitting there polling for an hour I can see how it may happen. Sleeping may be a better option in conjunction with periodic wakeup and polls.</p>
0
2009-08-25T14:25:48Z
[ "python", "cpu-usage", "pyserial" ]
Python/PySerial and CPU usage
1,328,606
<p>I've created a script to monitor the output of a serial port that receives 3-4 lines of data every half hour - the script runs fine and grabs everything that comes off the port which at the end of the day is what matters...</p> <p>What bugs me, however, is that the cpu usage seems rather high for a program that's just monitoring a single serial port, 1 core will always be at 100% usage while this script is running.</p> <p>I'm basically running a modified version of the code in this question: <a href="http://stackoverflow.com/questions/1093598/pyserial-how-to-read-last-line-sent-from-serial-device">pyserial - How to Read Last Line Sent from Serial Device</a></p> <p>I've tried polling the inWaiting() function at regular intervals and having it sleep when inWaiting() is 0 - I've tried intervals from 1 second down to 0.001 seconds (basically, as often as I can without driving up the cpu usage) - this will succeed in grabbing the first line but seems to miss the rest of the data.</p> <p>Adjusting the timeout of the serial port doesn't seem to have any effect on cpu usage, nor does putting the listening function into it's own thread (not that I really expected a difference but it was worth trying).</p> <ul> <li>Should python/pyserial be using this much cpu? (this seems like overkill)</li> <li>Am I wasting my time on this quest / Should I just bite the bullet and schedule the script to sleep for the periods that I know no data will be coming?</li> </ul>
9
2009-08-25T14:20:37Z
1,328,675
<p>Maybe you could issue a blocking <code>read(1)</code> call, and when it succeeds use <code>read(inWaiting())</code> to get the right number of remaining bytes.</p>
9
2009-08-25T14:31:57Z
[ "python", "cpu-usage", "pyserial" ]
How do I use colour with Windows command prompt using Python?
1,328,643
<p>I'm trying to patch a <a href="http://code.google.com/p/waf/issues/detail?id=243">waf issue</a>, where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me in right direction?</p> <h3>Update 1</h3> <p>Please don't suggest anything that requires Cygwin.</p>
10
2009-08-25T14:26:47Z
1,328,952
<p>If you're keen on using normal cmd.exe consoles for the Python interactive interpreter, see <a href="http://code.activestate.com/recipes/496901/" rel="nofollow">this recipe</a>. If you're OK with using special windows simulating a console, for example because you also need more advanced curses functionality anyway, then @TheLobster's suggestion of wcurses is just fine.</p>
3
2009-08-25T15:16:30Z
[ "python", "windows", "command-prompt", "waf" ]
How do I use colour with Windows command prompt using Python?
1,328,643
<p>I'm trying to patch a <a href="http://code.google.com/p/waf/issues/detail?id=243">waf issue</a>, where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me in right direction?</p> <h3>Update 1</h3> <p>Please don't suggest anything that requires Cygwin.</p>
10
2009-08-25T14:26:47Z
1,328,961
<p>It is possible thanks to ctypes and <a href="http://msdn.microsoft.com/en-us/library/ms686047%28VS.85%29.aspx" rel="nofollow">SetConsoleTextAttribute</a></p> <p>Here is an example</p> <pre class="lang-py prettyprint-override"><code>from ctypes import * STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5) windll.Kernel32.GetStdHandle.restype = c_ulong std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID) for color in xrange(16): windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, color) print "hello" </code></pre>
21
2009-08-25T15:17:23Z
[ "python", "windows", "command-prompt", "waf" ]
How to freeze/grayish window in pygtk?
1,329,076
<p>I want main window to "gray, freeze, stop working", when some other window is opened. Is there some default way to do it? Pretty much the same as gtk.Dialog is working.</p> <p><strong>EDIT:</strong> Currently I'm just replacing all contents by a text line, but I guess there should be better way.</p>
0
2009-08-25T15:33:23Z
1,329,140
<p>You really shouldn't try to make a program become unresponsive. If what you want to do is stop the user from using the window, make the dialog modal: <code>gtk.Dialog.set_modal(True)</code></p>
2
2009-08-25T15:44:12Z
[ "python", "window", "pygtk", "freeze" ]
How to create probability density function graph using csv dictreader, matplotlib and numpy?
1,329,105
<p>I'm trying to create a simple probability density function(pdf) graph using data from one column of a csv file using csv dictreader, matplotlib and numpy...</p> <p>Is there an easy way to use CSV DictReader combined with numpy arrays? Below is code that doesn't work. The error message is TypeError: len() of unsized object, which I'm guessing is related to the fact that my data is not in numpy array format? Also my data has negative and positive numbers. Thanks in advance!</p> <pre><code>import easygui import csv import scipy.stats from numpy import* from pylab import* filename= easygui.fileopenbox(msg='Altitude outlier graph', title='select file', filetypes=['*.csv'], default='X:\\') alt_file=open(filename) x=[] for row in csv.DictReader(alt_file): x.append(float(row['Dist_90m(nmi)'])) a=scipy.stats.pdf_moments(x) prob, bins, patches= hist(a, 10,align='left',facecolor='green') ylabel('probability density function') show() </code></pre>
4
2009-08-25T15:38:18Z
1,329,513
<p>The line</p> <pre><code>a=scipy.stats.pdf_moments(x) </code></pre> <p><a href="http://www.scipy.org/doc/api_docs/SciPy.stats.morestats.html#pdf_moments" rel="nofollow">"Return[s] the Gaussian expanded pdf function given the list of central moments (first one is mean)."</a></p> <p>That is to say, <code>a</code> is a function, and you must take its value somehow.</p> <p>So I modified the line:</p> <pre><code>prob, bins, patches= hist([a(i/100.0) for i in xrange(0,100,1)], 10, align='left', facecolor='green') </code></pre> <p>And produced this graph with my sample data.</p> <p>Now my statistics are pretty rusty, and I am not sure if you normally take a pdf over 0-1, but you can figure it out from there.</p> <p>If you do need to go over a range of floating points, <code>range</code> and <code>xrange</code> do not produce floats, so one easy way around that is to generate large numbers and divide down; hence <code>a(i/100.0)</code> instead of <code>a(i) for i in xrange(0, 1, 0.01)</code>.</p> <p><img src="http://i.stack.imgur.com/BsHrt.png" alt="sample"></p>
4
2009-08-25T16:48:25Z
[ "python", "csv", "numpy", "matplotlib", "scipy" ]
How to create probability density function graph using csv dictreader, matplotlib and numpy?
1,329,105
<p>I'm trying to create a simple probability density function(pdf) graph using data from one column of a csv file using csv dictreader, matplotlib and numpy...</p> <p>Is there an easy way to use CSV DictReader combined with numpy arrays? Below is code that doesn't work. The error message is TypeError: len() of unsized object, which I'm guessing is related to the fact that my data is not in numpy array format? Also my data has negative and positive numbers. Thanks in advance!</p> <pre><code>import easygui import csv import scipy.stats from numpy import* from pylab import* filename= easygui.fileopenbox(msg='Altitude outlier graph', title='select file', filetypes=['*.csv'], default='X:\\') alt_file=open(filename) x=[] for row in csv.DictReader(alt_file): x.append(float(row['Dist_90m(nmi)'])) a=scipy.stats.pdf_moments(x) prob, bins, patches= hist(a, 10,align='left',facecolor='green') ylabel('probability density function') show() </code></pre>
4
2009-08-25T15:38:18Z
1,331,382
<p>Thanks for all the help!! The following code produces a graph of the probability density function: I'm still having some issues formating it but I think this is a good start.</p> <pre><code>import easygui import csv import scipy.stats import numpy from pylab import* filename= easygui.fileopenbox(msg='Altitude outlier graph', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\') alt_file=open(filename) a=[] for row in csv.DictReader(alt_file): a.append(row['Dist_90m(nmi)']) y= numpy.array(a, float) pdf, bins, patches=hist(y, bins=6, align='left',range=None, normed=True) ylabel('probability density function') xlabel('Distance from 90m contour line(nm)') ylim([0,1]) show() </code></pre>
0
2009-08-25T22:29:56Z
[ "python", "csv", "numpy", "matplotlib", "scipy" ]
Gender problem in a django i18n translation
1,329,115
<p>I need to solve a gender translation problem, and Django doesn't seem to have <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Contexts" rel="nofollow">gettext contexts</a> implemented yet...</p> <p>I need to translate from english:</p> <pre><code>&lt;p&gt;Welcome, {{ username }}&lt;/p&gt; </code></pre> <p>In two forms of spanish, one for each gender. If user is a male:</p> <pre><code>&lt;p&gt;Bienvenido, {{ username }}&lt;/p&gt; </code></pre> <p>and if is a female:</p> <pre><code>&lt;p&gt;Bienvenida, {{ username }}&lt;/p&gt; </code></pre> <p>note the difference (bienvenido/bienvenida)</p> <p>Is there any way of getting this done?</p> <p>Thanks,</p> <p>H.</p>
10
2009-08-25T15:39:26Z
1,329,157
<p>Django is just Python so you can use the Python gettext bindings directly if you need to, I don't see any reason you couldn't write a {% gender_trans [gender] %} tag.</p>
4
2009-08-25T15:47:13Z
[ "python", "django", "localization", "internationalization" ]
Gender problem in a django i18n translation
1,329,115
<p>I need to solve a gender translation problem, and Django doesn't seem to have <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Contexts" rel="nofollow">gettext contexts</a> implemented yet...</p> <p>I need to translate from english:</p> <pre><code>&lt;p&gt;Welcome, {{ username }}&lt;/p&gt; </code></pre> <p>In two forms of spanish, one for each gender. If user is a male:</p> <pre><code>&lt;p&gt;Bienvenido, {{ username }}&lt;/p&gt; </code></pre> <p>and if is a female:</p> <pre><code>&lt;p&gt;Bienvenida, {{ username }}&lt;/p&gt; </code></pre> <p>note the difference (bienvenido/bienvenida)</p> <p>Is there any way of getting this done?</p> <p>Thanks,</p> <p>H.</p>
10
2009-08-25T15:39:26Z
1,335,968
<p>While waiting for contexts to be supported, an easy alternative would be to slightly change the Spanish sentence and use a greeting that does not vary according to a person's gender. For example, you could use "hola", or some other equivalent term.</p>
2
2009-08-26T16:27:53Z
[ "python", "django", "localization", "internationalization" ]
Gender problem in a django i18n translation
1,329,115
<p>I need to solve a gender translation problem, and Django doesn't seem to have <a href="http://www.gnu.org/software/gettext/manual/gettext.html#Contexts" rel="nofollow">gettext contexts</a> implemented yet...</p> <p>I need to translate from english:</p> <pre><code>&lt;p&gt;Welcome, {{ username }}&lt;/p&gt; </code></pre> <p>In two forms of spanish, one for each gender. If user is a male:</p> <pre><code>&lt;p&gt;Bienvenido, {{ username }}&lt;/p&gt; </code></pre> <p>and if is a female:</p> <pre><code>&lt;p&gt;Bienvenida, {{ username }}&lt;/p&gt; </code></pre> <p>note the difference (bienvenido/bienvenida)</p> <p>Is there any way of getting this done?</p> <p>Thanks,</p> <p>H.</p>
10
2009-08-25T15:39:26Z
3,436,409
<p>The way that I've solved this is:</p> <pre><code>{% if profile.male %} {% blocktrans with profile.name as male %}Welcome, {{ male }}{% endblocktrans %} {% else %} {% blocktrans with profile.name as female %}Welcome, {{ female }}{% endblocktrans %} {% endif %} </code></pre>
9
2010-08-08T22:57:34Z
[ "python", "django", "localization", "internationalization" ]
Python/Suds: Type not found: 'xs:complexType'
1,329,190
<p>I have the following simple python test script that uses <a href="https://fedorahosted.org/suds/">Suds</a> to call a SOAP web service (the service is written in ASP.net):</p> <pre><code>from suds.client import Client url = 'http://someURL.asmx?WSDL' client = Client( url ) result = client.service.GetPackageDetails( "MyPackage" ) print result </code></pre> <p>When I run this test script I am getting the following error (used code markup as it doesn't wrap):</p> <pre><code>No handlers could be found for logger "suds.bindings.unmarshaller" Traceback (most recent call last): File "sudsTest.py", line 9, in &lt;module&gt; result = client.service.GetPackageDetails( "t3db" ) File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 240, in __call__ File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 379, in call File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 240, in __call__ File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 422, in call File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 480, in invoke File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 505, in send File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 537, in succeeded File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/binding.py", line 149, in get_reply File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 303, in process File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 88, in process File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 102, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 324, in start suds.TypeNotFound: Type not found: 'xs:complexType' </code></pre> <p>Looking at the source for the WSDL file's header (reformatted to fit):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://http://someInternalURL/webservices.asmx" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://someURL.asmx" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"&gt; </code></pre> <p>I am guessing based on the last line of output:</p> <pre><code>suds.TypeNotFound: Type not found: 'xs:complexType' </code></pre> <p>That I need to use Sud's <a href="https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs">doctor class</a> to fix the schema but being a SOAP newbie I don't know what exactly needs fixed in my case. Does anyone here have any experience using Suds to fix/correct schema?</p>
9
2009-08-25T15:53:16Z
1,360,535
<p><strong>Ewall</strong>'s resource is a good one. If you try to search in suds trac tickets, you could see that other people have problems <a href="https://fedorahosted.org/suds/ticket/220">similar to yours</a>, but with different object types. It can be a good way to learn from it's examples and how they import their namespaces.</p> <blockquote> <p>The problem is that your wsdl contains a schema definition that references the (...) but fails to import the "http://schemas.xmlsoap.org/soap/encoding/" namespace (and associated schema) properly. The schema can be patched at runtime using the schema ImportDoctor as discussed here: <a href="https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs">https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs</a>.</p> <p><strong>This is a fairly common problem.</strong></p> <p>A commonly referenced schema <strong>(that is not imported)</strong> is the SOAP section 5 encoding schema. This can now be fixed as follows:</p> </blockquote> <p>(all emphasis were mine).</p> <p>You could try the lines that these documentations provide adding the namespaces presented in your WSDL. This can be a try-and-error aproach.</p> <pre><code>imp = Import('http://schemas.xmlsoap.org/soap/encoding/') # Below is your targetNamespace presented in WSDL. Remember # that you can add more namespaces by appending more imp.filter.add imp.filter.add('http://someURL.asmx') doctor = ImportDoctor(imp) client = Client(url, doctor=doctor) </code></pre> <p>You didn't provide the WSDL you're working with, I suppose you have reasons to not showing to us... so I think you have to try these possibilities by yourself. Good luck!</p>
14
2009-09-01T04:33:49Z
[ "python", "soap", "suds" ]
Using settings.LANGUAGES with properly translated names using gettext()
1,329,278
<p>From Django Documentation:</p> <blockquote> <p>If you define a custom <code>LANGUAGES</code> setting, it's OK to mark the languages as translation strings (as in the default value displayed above) -- but use a "dummy" <code>gettext()</code> function, not the one in <code>django.utils.translation</code>. You should never import <code>django.utils.translation</code> from within your settings file, because that module in itself depends on the settings, and that would cause a circular import. The solution is to use a "dummy" <code>gettext()</code> function. Here's a sample settings file:</p> <p><code>gettext = lambda s: s LANGUAGES = (</code> <code>('de', gettext('German')),</code> <code>('en', gettext('English')),</code> <code>)</code> </p> <p>With this arrangement, <code>django-admin.py makemessages</code> will still find and mark these strings for translation, but the translation won't happen at runtime -- so you'll have to remember to wrap the languages in the real <code>gettext()</code> in any code that uses <code>LANGUAGES</code> at runtime.</p> </blockquote> <p>What does it exactly mean to wrap languages in real <code>gettext()</code>? How it should be called in the code?</p>
5
2009-08-25T16:07:20Z
1,330,166
<p>Exactly what it says: call gettext() on the language names when you actually use them or show them to the user:</p> <pre><code>from django.utils.translation import ugettext for lang_code, lang_name in settings.LANGUAGES: translated_name = ugettext(lang_name) ... </code></pre> <p>(You should generally use ugettext rather than gettext, since all text in Django is unicode.)</p> <p>To do the equivalent in a template, just use the {% blocktrans %} tag, which just calls ugettext behind the scenes:</p> <pre><code>{% for lang in LANGUAGES %} {% blocktrans %}{{ lang.1 }}{% endblocktrans %} {% endfor %} </code></pre>
3
2009-08-25T18:37:27Z
[ "python", "django", "translation", "gettext" ]
Using settings.LANGUAGES with properly translated names using gettext()
1,329,278
<p>From Django Documentation:</p> <blockquote> <p>If you define a custom <code>LANGUAGES</code> setting, it's OK to mark the languages as translation strings (as in the default value displayed above) -- but use a "dummy" <code>gettext()</code> function, not the one in <code>django.utils.translation</code>. You should never import <code>django.utils.translation</code> from within your settings file, because that module in itself depends on the settings, and that would cause a circular import. The solution is to use a "dummy" <code>gettext()</code> function. Here's a sample settings file:</p> <p><code>gettext = lambda s: s LANGUAGES = (</code> <code>('de', gettext('German')),</code> <code>('en', gettext('English')),</code> <code>)</code> </p> <p>With this arrangement, <code>django-admin.py makemessages</code> will still find and mark these strings for translation, but the translation won't happen at runtime -- so you'll have to remember to wrap the languages in the real <code>gettext()</code> in any code that uses <code>LANGUAGES</code> at runtime.</p> </blockquote> <p>What does it exactly mean to wrap languages in real <code>gettext()</code>? How it should be called in the code?</p>
5
2009-08-25T16:07:20Z
11,484,962
<p>This is really a comment and further explanation on the above Q&amp;A. I could not get my translations to work, read and re-read the docs, searched for hours online, and after reading this post I realized it came down to this:</p> <p>I originally had:</p> <pre><code>LANGUAGES = ( ('en', 'English'), ('nl', 'Dutch'), ) </code></pre> <p>Which would not work, then after reading this tried</p> <pre><code>ugettext = lambda s: s LANGUAGES = ( ('en', ugettext('English')), ('nl', ugettext('Dutch')), ) </code></pre> <p>Which made everything work... and I just searched for this and it is in the doc's at <a href="https://docs.djangoproject.com/en/1.4/topics/i18n/translation/#how-django-discovers-language-preference" rel="nofollow">https://docs.djangoproject.com/en/1.4/topics/i18n/translation/#how-django-discovers-language-preference</a>, toward the bottom of this section...</p>
0
2012-07-14T15:26:54Z
[ "python", "django", "translation", "gettext" ]
Using settings.LANGUAGES with properly translated names using gettext()
1,329,278
<p>From Django Documentation:</p> <blockquote> <p>If you define a custom <code>LANGUAGES</code> setting, it's OK to mark the languages as translation strings (as in the default value displayed above) -- but use a "dummy" <code>gettext()</code> function, not the one in <code>django.utils.translation</code>. You should never import <code>django.utils.translation</code> from within your settings file, because that module in itself depends on the settings, and that would cause a circular import. The solution is to use a "dummy" <code>gettext()</code> function. Here's a sample settings file:</p> <p><code>gettext = lambda s: s LANGUAGES = (</code> <code>('de', gettext('German')),</code> <code>('en', gettext('English')),</code> <code>)</code> </p> <p>With this arrangement, <code>django-admin.py makemessages</code> will still find and mark these strings for translation, but the translation won't happen at runtime -- so you'll have to remember to wrap the languages in the real <code>gettext()</code> in any code that uses <code>LANGUAGES</code> at runtime.</p> </blockquote> <p>What does it exactly mean to wrap languages in real <code>gettext()</code>? How it should be called in the code?</p>
5
2009-08-25T16:07:20Z
19,221,697
<p>in Template you could just do the following:</p> <pre><code>{% for lang in LANGUAGES %} {% trans lang.1 %} {% endfor %} </code></pre>
0
2013-10-07T09:52:58Z
[ "python", "django", "translation", "gettext" ]
How do I efficiently do a bulk insert-or-update with SQLAlchemy?
1,330,475
<p>I'm using SQLAlchemy with a Postgres backend to do a bulk insert-or-update. To try to improve performance, I'm attempting to commit only once every thousand rows or so:</p> <pre><code>trans = engine.begin() for i, rec in enumerate(records): if i % 1000 == 0: trans.commit() trans = engine.begin() try: inserter.execute(...) except sa.exceptions.SQLError: my_table.update(...).execute() trans.commit() </code></pre> <p>However, this isn't working. It seems that when the INSERT fails, it leaves things in a weird state that prevents the UPDATE from happening. Is it automatically rolling back the transaction? If so, can this be stopped? I don't want my entire transaction rolled back in the event of a problem, which is why I'm trying to catch the exception in the first place.</p> <p>The error message I'm getting, BTW, is "sqlalchemy.exc.InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block", and it happens on the update().execute() call.</p>
8
2009-08-25T19:38:02Z
1,330,718
<p>This error is from PostgreSQL. PostgreSQL doesn't allow you to execute commands in the same transaction if one command creates an error. To fix this you can use nested transactions (implemented using SQL savepoints) via <code>conn.begin_nested()</code>. Heres something that might work. I made the code use explicit connections, factored out the chunking part and made the code use the context manager to manage transactions correctly.</p> <pre><code>from itertools import chain, islice def chunked(seq, chunksize): """Yields items from an iterator in chunks.""" it = iter(seq) while True: yield chain([it.next()], islice(it, chunksize-1)) conn = engine.commit() for chunk in chunked(records, 1000): with conn.begin(): for rec in chunk: try: with conn.begin_nested(): conn.execute(inserter, ...) except sa.exceptions.SQLError: conn.execute(my_table.update(...)) </code></pre> <p>This still won't have stellar performance though due to nested transaction overhead. If you want better performance try to detect which rows will create errors beforehand with a select query and use executemany support (execute can take a list of dicts if all inserts use the same columns). If you need to handle concurrent updates, you'll still need to do error handling either via retrying or falling back to one by one inserts.</p>
4
2009-08-25T20:17:47Z
[ "python", "sqlalchemy" ]
How do I efficiently do a bulk insert-or-update with SQLAlchemy?
1,330,475
<p>I'm using SQLAlchemy with a Postgres backend to do a bulk insert-or-update. To try to improve performance, I'm attempting to commit only once every thousand rows or so:</p> <pre><code>trans = engine.begin() for i, rec in enumerate(records): if i % 1000 == 0: trans.commit() trans = engine.begin() try: inserter.execute(...) except sa.exceptions.SQLError: my_table.update(...).execute() trans.commit() </code></pre> <p>However, this isn't working. It seems that when the INSERT fails, it leaves things in a weird state that prevents the UPDATE from happening. Is it automatically rolling back the transaction? If so, can this be stopped? I don't want my entire transaction rolled back in the event of a problem, which is why I'm trying to catch the exception in the first place.</p> <p>The error message I'm getting, BTW, is "sqlalchemy.exc.InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block", and it happens on the update().execute() call.</p>
8
2009-08-25T19:38:02Z
1,330,779
<p>You're hitting some weird Postgresql-specific behavior: if an error happens in a transaction, it forces the whole transaction to be rolled back. I consider this a Postgres design bug; it takes quite a bit of SQL contortionism to work around in some cases.</p> <p>One workaround is to do the UPDATE first. Detect if it actually modified a row by looking at cursor.rowcount; if it didn't modify any rows, it didn't exist, so do the INSERT. (This will be faster if you update more frequently than you insert, of course.)</p> <p>Another workaround is to use savepoints:</p> <pre><code>SAVEPOINT a; INSERT INTO ....; -- on error: ROLLBACK TO SAVEPOINT a; UPDATE ...; -- on success: RELEASE SAVEPOINT a; </code></pre> <p>This has a serious problem for production-quality code: you have to detect the error accurately. Presumably you're expecting to hit a unique constraint check, but you may hit something unexpected, and it may be next to impossible to reliably distinguish the expected error from the unexpected one. If this hits the error condition incorrectly, it'll lead to obscure problems where nothing will be updated or inserted and no error will be seen. Be very careful with this. You can narrow down the error case by looking at Postgresql's error code to make sure it's the error type you're expecting, but the potential problem is still there.</p> <p>Finally, if you really want to do batch-insert-or-update, you actually want to do many of them in a few commands, not one item per command. This requires trickier SQL: SELECT nested inside an INSERT, filtering out the right items to insert and update.</p>
5
2009-08-25T20:29:00Z
[ "python", "sqlalchemy" ]
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
1,330,498
<p><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">https://developer.mozilla.org/en/New_in_JavaScript_1.7</a></p> <p>A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed</p> <pre><code>for (i = 0; i &lt; arr.length; i++) { /* ... */ } </code></pre> <p>for really simple operations? Wouldn't this be easier:</p> <pre><code>[/* ... */ for each (i in arr)] </code></pre> <p>I think brevity is a great thing. Basically, it all comes down to IE in the end, though.</p> <p>Does IE support these new features? What about other browsers?</p>
16
2009-08-25T19:41:34Z
1,330,566
<p>No, when they say "JavaScript", they mean it literally: the ECMAScript engine used by Gecko. JScript and other engines (AFAIK) don't support these features.</p> <p>EDIT: According to <a href="http://en.wikipedia.org/wiki/ECMAScript#Version%5Fcorrespondence">wikipedia</a>, JavaScript 1.7 implements ECMAScript "Edition 3 plus all JavaScript 1.6 enhancements, plus Pythonic generators and array comprehensions ([a*a for (a in iter)]), block scope with let, destructuring assignment (var [a,b]=[1,2])". So these features are not part of ECMAScript.</p>
9
2009-08-25T19:54:28Z
[ "javascript", "python", "arrays", "internet-explorer", "cross-browser" ]
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
1,330,498
<p><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">https://developer.mozilla.org/en/New_in_JavaScript_1.7</a></p> <p>A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed</p> <pre><code>for (i = 0; i &lt; arr.length; i++) { /* ... */ } </code></pre> <p>for really simple operations? Wouldn't this be easier:</p> <pre><code>[/* ... */ for each (i in arr)] </code></pre> <p>I think brevity is a great thing. Basically, it all comes down to IE in the end, though.</p> <p>Does IE support these new features? What about other browsers?</p>
16
2009-08-25T19:41:34Z
1,588,472
<p>In addition to IE not supporting it, it seems like the webkit based browsers (Safari, Chrome), despite claiming to have JS 1.7 support (actually executing script tags declared as being in JS 1.7), do not actually support any of these features which means that for now, JS 1.7 with its very nice features is limited to Geko browsers alone.</p> <p>And because Webkit still executes scripts tagged as 1.7 only, this also means that we can't even fail gracefully but we'll just produce syntax errors on these browsers when we are using any of the new keywords or syntax.</p>
1
2009-10-19T12:40:29Z
[ "javascript", "python", "arrays", "internet-explorer", "cross-browser" ]
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
1,330,498
<p><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">https://developer.mozilla.org/en/New_in_JavaScript_1.7</a></p> <p>A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed</p> <pre><code>for (i = 0; i &lt; arr.length; i++) { /* ... */ } </code></pre> <p>for really simple operations? Wouldn't this be easier:</p> <pre><code>[/* ... */ for each (i in arr)] </code></pre> <p>I think brevity is a great thing. Basically, it all comes down to IE in the end, though.</p> <p>Does IE support these new features? What about other browsers?</p>
16
2009-08-25T19:41:34Z
2,209,743
<p>While this question is a bit old, and is marked "answered" - I found it on Google and the answers given are possibly inaccurate, or if not, definitely incomplete.</p> <p>It's very important to note that Javascript is NOT A STANDARD. Ken correctly mentioned that ECMAScript is the cross-browser standard that all browsers aim to comply with, but what he didn't clarify is that Javascript is NOT ECMAScript.</p> <p>To say Javascript "implements" ECMAScript means that Javascript includes ECMAScript, plus it's own proprietary extra non-cross-browser features. The <code>for each</code> example given by nicholas is an example of a proprietary feature added by Mozilla that is not in any standard, and therefore unlikely to be adopted by any other browsers.</p> <p>Javascript 1.7 and 1.8 features are useful for extension development in XUL, but should never be used for cross-browser development - that's what standards are for.</p>
33
2010-02-05T19:20:40Z
[ "javascript", "python", "arrays", "internet-explorer", "cross-browser" ]
How Can I Empty the Used Memory With Python?
1,331,033
<p>I have just written a .psf file in Python for executing an optimization algorithm for Abaqus package, but after some analysis it stops. Could you please help me and write Python code to free the memory?</p> <p>Thanks </p>
1
2009-08-25T21:14:19Z
1,331,164
<p>by stopping using it when you do not need, python has garbage collector. Set the attributes, and variables to None when you are done with them.</p>
0
2009-08-25T21:39:27Z
[ "python", "memory", "memory-management" ]
How Can I Empty the Used Memory With Python?
1,331,033
<p>I have just written a .psf file in Python for executing an optimization algorithm for Abaqus package, but after some analysis it stops. Could you please help me and write Python code to free the memory?</p> <p>Thanks </p>
1
2009-08-25T21:14:19Z
1,331,177
<p>There are really only two python options. You can ask the <a href="http://docs.python.org/library/gc.html#module-gc" rel="nofollow">garbage collector</a> to please run. That may or may not do anything useful. Or you can delete a large container. </p> <pre><code>del my_var_name </code></pre> <p>If the memory is not really allocated by Python, you will need to use the interfaces of whatever module you are using to free it up.</p>
1
2009-08-25T21:41:11Z
[ "python", "memory", "memory-management" ]
How Can I Empty the Used Memory With Python?
1,331,033
<p>I have just written a .psf file in Python for executing an optimization algorithm for Abaqus package, but after some analysis it stops. Could you please help me and write Python code to free the memory?</p> <p>Thanks </p>
1
2009-08-25T21:14:19Z
1,331,258
<p>You don't really explicitly free memory in Python. What you do is stop referencing it, and it gets freed automatically. Although <code>del</code> does this, it's very rare that you really need to use it in a well designed application.</p> <p>So this is really a question of how not to use so much memory in Python. I'd say the main hint there is to try to refactor your program to use generators, so that you don't have to hold all the data in memory at once.</p>
2
2009-08-25T21:58:11Z
[ "python", "memory", "memory-management" ]
Converting list of integers into a binary "string" in python
1,331,187
<p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p> <p>As an example, i start off with the following list:</p> <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188] </code></pre> <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p> <pre><code> hexdata = ''.join([chr(item) for item in data]) </code></pre> <p>So if ALPHA is 101, this would return the following string:</p> <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188] &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data]) &gt;&gt;&gt; hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc' </code></pre> <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p> <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc' </code></pre> <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT 1</strong></p> <blockquote> <p>What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago</p> </blockquote> <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc' </code></pre> <p>Does this make sense? </p> <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p> <p><strong>EDIT 2</strong></p> <p>The string i send out is always fixed length. For simplicity, I think its better to represent the list as follows:</p> <pre><code>ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01' </code></pre> <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p> <p>If ALPHA &lt; 256, alpha1 = 0.</p>
3
2009-08-25T21:42:35Z
1,331,222
<p>You can use python <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a></p> <pre><code>import array a = array.array('i') a.extend([2,25,0,0,101,0,23,18,188]) output = a.tostring() </code></pre>
2
2009-08-25T21:49:36Z
[ "python", "string", "list", "binary" ]
Converting list of integers into a binary "string" in python
1,331,187
<p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p> <p>As an example, i start off with the following list:</p> <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188] </code></pre> <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p> <pre><code> hexdata = ''.join([chr(item) for item in data]) </code></pre> <p>So if ALPHA is 101, this would return the following string:</p> <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188] &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data]) &gt;&gt;&gt; hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc' </code></pre> <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p> <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc' </code></pre> <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT 1</strong></p> <blockquote> <p>What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago</p> </blockquote> <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc' </code></pre> <p>Does this make sense? </p> <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p> <p><strong>EDIT 2</strong></p> <p>The string i send out is always fixed length. For simplicity, I think its better to represent the list as follows:</p> <pre><code>ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01' </code></pre> <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p> <p>If ALPHA &lt; 256, alpha1 = 0.</p>
3
2009-08-25T21:42:35Z
1,331,227
<p>You want to send a single byte for ALPHA if it's &lt; 256, but two bytes if >= 256? This seems weird -- how is the receiver going to know which is the case...???</p> <p>But, if this IS what you want, then</p> <pre><code>x = struct.pack(4*'B' + 'HB'[ALPHA&lt;256] + 4*'B', *data) </code></pre> <p>is one way to achieve this.</p>
9
2009-08-25T21:50:56Z
[ "python", "string", "list", "binary" ]
Converting list of integers into a binary "string" in python
1,331,187
<p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p> <p>As an example, i start off with the following list:</p> <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188] </code></pre> <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p> <pre><code> hexdata = ''.join([chr(item) for item in data]) </code></pre> <p>So if ALPHA is 101, this would return the following string:</p> <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188] &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data]) &gt;&gt;&gt; hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc' </code></pre> <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p> <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc' </code></pre> <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT 1</strong></p> <blockquote> <p>What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago</p> </blockquote> <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc' </code></pre> <p>Does this make sense? </p> <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p> <p><strong>EDIT 2</strong></p> <p>The string i send out is always fixed length. For simplicity, I think its better to represent the list as follows:</p> <pre><code>ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01' </code></pre> <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p> <p>If ALPHA &lt; 256, alpha1 = 0.</p>
3
2009-08-25T21:42:35Z
1,331,238
<p>Bytes can not have a value over 255, so with ALPHA being over 255 you are going to somehow have to split it into two bytes. This can be done like so:</p> <pre><code>high, low = divmod(ALPHA, 255) </code></pre> <p>Then you can stick the high and low into the list of values.</p> <p>There are other variations like using bytearray (in 2.6) or struct.pack, etc, but in the end you will have to convert that number two two bytes somehow.</p>
1
2009-08-25T21:53:12Z
[ "python", "string", "list", "binary" ]
Converting list of integers into a binary "string" in python
1,331,187
<p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p> <p>As an example, i start off with the following list:</p> <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188] </code></pre> <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p> <pre><code> hexdata = ''.join([chr(item) for item in data]) </code></pre> <p>So if ALPHA is 101, this would return the following string:</p> <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188] &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data]) &gt;&gt;&gt; hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc' </code></pre> <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p> <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc' </code></pre> <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT 1</strong></p> <blockquote> <p>What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago</p> </blockquote> <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc' </code></pre> <p>Does this make sense? </p> <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p> <p><strong>EDIT 2</strong></p> <p>The string i send out is always fixed length. For simplicity, I think its better to represent the list as follows:</p> <pre><code>ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01' </code></pre> <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p> <p>If ALPHA &lt; 256, alpha1 = 0.</p>
3
2009-08-25T21:42:35Z
1,331,355
<p>If you know the data and ALPHA position beforehand, it would be best to use struct.pack with a big endian short for that position and omit the 0 that might be overwritten:</p> <pre><code>def output(ALPHA): data = [2,25,0,ALPHA,0,23,18,188] format = "&gt;BBBHBBBB" return struct.pack(format, *data) output(101) # result: '\x02\x19\x00\x00e\x00\x17\x12\xbc' output(999) # result: '\x02\x19\x00\x03\xe7\x00\x17\x12\xbc' </code></pre>
5
2009-08-25T22:19:55Z
[ "python", "string", "list", "binary" ]
Converting list of integers into a binary "string" in python
1,331,187
<p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p> <p>As an example, i start off with the following list:</p> <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188] </code></pre> <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p> <pre><code> hexdata = ''.join([chr(item) for item in data]) </code></pre> <p>So if ALPHA is 101, this would return the following string:</p> <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188] &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data]) &gt;&gt;&gt; hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc' </code></pre> <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p> <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc' </code></pre> <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT 1</strong></p> <blockquote> <p>What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago</p> </blockquote> <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p> <pre><code>data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc' </code></pre> <p>Does this make sense? </p> <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p> <p><strong>EDIT 2</strong></p> <p>The string i send out is always fixed length. For simplicity, I think its better to represent the list as follows:</p> <pre><code>ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01' </code></pre> <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p> <p>If ALPHA &lt; 256, alpha1 = 0.</p>
3
2009-08-25T21:42:35Z
16,967,412
<blockquote> <p>You want to send a single byte for ALPHA if it's &lt; 256, but two bytes if >= 256? </p> </blockquote> <p>another (perhaps more generic) way would be:</p> <pre><code>x = reduce(lambda x, y: x + y, map(lambda x: struct.pack('B', x), data)) </code></pre>
0
2013-06-06T16:31:22Z
[ "python", "string", "list", "binary" ]
Prevent python imports compiling
1,331,235
<p>I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?</p>
1
2009-08-25T21:52:55Z
1,331,250
<p>I don't think that's possible - its the way Python works. The best you could do, I think, is to have some kind of automated script which deletes <code>*.pyc</code> files at first. Or you could have a development module which automatically compiles all imports - try the <code>compile</code> module.</p> <p>I've personally not had this trouble before, but try checking the timestamps on the files. You could try running <code>touch</code> on all the Python files in the directory. (<code>find -name \\*.py -exec touch \\{\\} \\;</code>)</p>
2
2009-08-25T21:56:00Z
[ "python", "import", "compilation" ]