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> ...
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__ =...
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> ...
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__= ...
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> ...
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.__cl...
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> ...
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...
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> ...
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...
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> ...
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 =...
-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> ...
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, Fo...
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> ...
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...
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> ...
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...
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> ...
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' ...
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...
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 ...
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...
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(infil...
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...
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 applicati...
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="h...
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 applicati...
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 ...
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 memo...
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 ...
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 ...
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...
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 ...
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(SessionExtensio...
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...
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...
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...
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...
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 So...
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>...
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 learn...
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 <c...
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) ...
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 <c...
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 = mode...
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 Pyt...
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 Pyt...
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) ...
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) ...
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) ...
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...
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...
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, pa...
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...
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 "u...
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...
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...
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...
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: ...
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...
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 ...
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...
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) foo...
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...
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" ques...
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 expres...
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 expres...
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 expres...
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;', htm...
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 expres...
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 expres...
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 expres...
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></...
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 expres...
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 fre...
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 expres...
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 expres...
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 ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãä...
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 'st...
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...
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 attri...
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...
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%5Fmo...
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...
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 clu...
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...
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. ...
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 someho...
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...
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 someho...
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_searc...
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...
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/...
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...
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 level...
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...
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 ...
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...
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...
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 b...
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 i...
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 automo...
-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 i...
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 i...
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...
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 i...
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...
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 i...
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>I...
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-...
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,...
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-...
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-...
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 ...
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 ...
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 ...
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'...
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 tr...
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'...
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...
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 ...
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 j...
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 poll...
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 j...
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...
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, ...
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...
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.Get...
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 unsize...
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...
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 unsize...
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 outl...
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><...
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><...
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><...
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.GetPackageDetail...
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 thei...
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>...
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 ...
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>...
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',...
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>...
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() ...
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 c...
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() ...
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...
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 ...
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 "Edit...
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 ...
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...
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 ...
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 brow...
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...
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...
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...
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...
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 ach...
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...
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 ...
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...
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...
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...
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 perso...
2
2009-08-25T21:56:00Z
[ "python", "import", "compilation" ]