title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,074
<p>wow, you guys are fast :) If you want all attributes of a list (and the ordering is known), then you can use something like this:</p> <pre><code>import re print re.findall('"(.+?)"',INPUT) </code></pre> <p>INPUT is a line like:</p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/&gt; </code></pre> <p>and the printed list is:</p> <pre><code>['8', 'hibernis', 'hibernus1', 'n-p---nb-', '7', 'ADV'] </code></pre>
0
2009-06-08T14:05:42Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <code>postag</code> information. e.g. for above I need <code>hibernis</code>, <code>hibernus1</code> and <code>n-p---nb-</code>.</p> <p>How do I tell python to read until it reaches form, to read forward until it reaches the quote mark <code>"</code> and then read the information between the quote marks <code>"hibernis"</code>? Really struggling with this. </p> <p>My attempts so far have been to remove the punctuation, split the sentence and then pull the info I need from a list. Having trouble getting python to iterate over whole file though, I can only get this working for 1 line. My code is below:</p> <pre><code>f=open('blank.txt','r') quotes=f.read() noquotes=quotes.replace('"','') f.close() rf=open('blank.txt','w') rf.write(noquotes) rf.close() f=open('blank.txt','r') finished = False postag=[] while not finished: line=f.readline() words=line.split() postag.append(words[4]) postag.append(words[6]) postag.append(words[8]) finished=True </code></pre> <p>Would appreciate any feedback/criticisms</p> <p>thanks</p>
4
2009-06-08T13:44:32Z
965,140
<p>If it's XML, use <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a> to parse it:</p> <pre><code>from xml.etree import ElementTree line = '&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/&gt;' element = ElementTree.fromstring(line) </code></pre> <p>For each XML element you can easily extract the name and all the attributes:</p> <pre><code>&gt;&gt;&gt; element.tag 'word' &gt;&gt;&gt; element.attrib {'head': '7', 'form': 'hibernis', 'postag': 'n-p---nb-', 'lemma': 'hibernus1', 'relation': 'ADV', 'id': '8'} </code></pre> <p>So if you have a document with a bunch of <code>word</code> XML elements, something like this will extract the information you want from each one:</p> <pre><code>from xml.etree import ElementTree XML = ''' &lt;words&gt; &lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/&gt; &lt;/words&gt;''' root = ElementTree.fromstring(XML) for element in root.findall('word'): form = element.attrib['form'] lemma = element.attrib['lemma'] postag = element.attrib['postag'] print form, lemma, postag </code></pre> <p>Use <code>parse()</code> instead of <code>fromstring()</code> if you only have a filename.</p>
5
2009-06-08T14:21:16Z
[ "python" ]
<option> Level control of Select inputs using Django Forms API
965,082
<p>I'm wanting to add a label= attribute to an option element of a Select form input using the Django Forms API without overwriting the Select widget's render_options method. Is this possible, if so, how?</p> <p>Note: I'm wanting to add a label directly to the option (this <em>is</em> valid in the XHTML Strict standard) not an optgroup.</p>
1
2009-06-08T14:07:53Z
965,545
<p>I'm afraid this isn't possible without subclassing the <code>Select</code> widget to provide your own rendering, as you've guessed. The <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py#L409" rel="nofollow">code for Select</a> doesn't include any attributes for each <code>&lt;option&gt;</code> item. It covers the option value, the "selected" status, and the label... that's all, I'm afraid:</p> <pre><code>def render_option(option_value, option_label): option_value = force_unicode(option_value) selected_html = (option_value in selected_choices) and u' selected="selected"' or '' return u'&lt;option value="%s"%s&gt;%s&lt;/option&gt;' % ( escape(option_value), selected_html, conditional_escape(force_unicode(option_label))) </code></pre>
1
2009-06-08T15:39:19Z
[ "python", "django", "django-forms" ]
<option> Level control of Select inputs using Django Forms API
965,082
<p>I'm wanting to add a label= attribute to an option element of a Select form input using the Django Forms API without overwriting the Select widget's render_options method. Is this possible, if so, how?</p> <p>Note: I'm wanting to add a label directly to the option (this <em>is</em> valid in the XHTML Strict standard) not an optgroup.</p>
1
2009-06-08T14:07:53Z
967,798
<p>I just wrote a class to do that:</p> <pre><code>from django.forms.widgets import Select from django.utils.encoding import force_unicode from itertools import chain from django.utils.html import escape, conditional_escape class ExtendedSelect(Select): """ A subclass of Select that adds the possibility to define additional properties on options. It works as Select, except that the ``choices`` parameter takes a list of 3 elements tuples containing ``(value, label, attrs)``, where ``attrs`` is a dict containing the additional attributes of the option. """ def render_options(self, choices, selected_choices): def render_option(option_value, option_label, attrs): option_value = force_unicode(option_value) selected_html = (option_value in selected_choices) and u' selected="selected"' or '' attrs_html = [] for k, v in attrs.items(): attrs_html.append('%s="%s"' % (k, escape(v))) if attrs_html: attrs_html = " " + " ".join(attrs_html) else: attrs_html = "" return u'&lt;option value="%s"%s%s&gt;%s&lt;/option&gt;' % ( escape(option_value), selected_html, attrs_html, conditional_escape(force_unicode(option_label))) # Normalize to strings. selected_choices = set([force_unicode(v) for v in selected_choices]) output = [] for option_value, option_label, option_attrs in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): output.append(u'&lt;optgroup label="%s"&gt;' % escape(force_unicode(option_value))) for option in option_label: output.append(render_option(*option)) output.append(u'&lt;/optgroup&gt;') else: output.append(render_option(option_value, option_label, option_attrs)) return u'\n'.join(output) </code></pre> <p>Example:</p> <pre><code>select = ExtendedSelect(choices=( (1, "option 1", {"label": "label 1"}), (2, "option 2", {"label": "label 2"}), )) </code></pre>
2
2009-06-09T01:46:06Z
[ "python", "django", "django-forms" ]
Python - simple reading lines from a pipe
965,210
<p>I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this:</p> <p>producer.py</p> <pre><code>import time while True: print 'Data' time.sleep(1) </code></pre> <p>The consumer just needs to check for lines periodically:</p> <p>consumer.py</p> <pre><code>import sys, time while True: line = sys.stdin.readline() if line: print 'Got data:', line else: time.sleep(1) </code></pre> <p>When I run this in the Windows shell as <code>python producer.py | python consumer.py</code>, it just sleeps forever (never seems to get data?) It seems that maybe the problem is that the producer never terminates, since if I send a finite amount of data then it works fine.</p> <p>How can I get the data to be received and show up for the consumer? In the real application, the producer is a C++ program I have no control over.</p>
16
2009-06-08T14:38:32Z
965,226
<p>Some old versions of Windows simulated pipes through files (so they were prone to such problems), but that hasn't been a problem in 10+ years. Try adding a</p> <pre><code> sys.stdout.flush() </code></pre> <p>to the producer after the <code>print</code>, and also try to make the producer's stdout unbuffered (by using <code>python -u</code>).</p> <p>Of course this doesn't help if you have no control over the producer -- if it buffers too much of its output you're still going to wait a long time.</p> <p>Unfortunately - while there are many approaches to solve that problem on Unix-like operating systems, such as pyexpect, <a href="http://sourceforge.net/projects/pexpect/">pexpect</a>, <a href="http://code.google.com/p/exscript/">exscript</a>, and <a href="http://www.lag.net/paramiko/">paramiko</a>, I doubt any of them works on Windows; if that's indeed the case, I'd try <a href="http://www.cygwin.com/">Cygwin</a>, which puts enough of a Linux-like veneer on Windows as to often enable the use of Linux-like approaches on a Windows box.</p>
16
2009-06-08T14:42:52Z
[ "python", "pipe", "producer-consumer" ]
Python - simple reading lines from a pipe
965,210
<p>I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this:</p> <p>producer.py</p> <pre><code>import time while True: print 'Data' time.sleep(1) </code></pre> <p>The consumer just needs to check for lines periodically:</p> <p>consumer.py</p> <pre><code>import sys, time while True: line = sys.stdin.readline() if line: print 'Got data:', line else: time.sleep(1) </code></pre> <p>When I run this in the Windows shell as <code>python producer.py | python consumer.py</code>, it just sleeps forever (never seems to get data?) It seems that maybe the problem is that the producer never terminates, since if I send a finite amount of data then it works fine.</p> <p>How can I get the data to be received and show up for the consumer? In the real application, the producer is a C++ program I have no control over.</p>
16
2009-06-08T14:38:32Z
965,247
<p>This is about I/O that is bufferized by default with Python. Pass <code>-u</code> option to the interpreter to disable this behavior:</p> <pre><code>python -u producer.py | python consumer.py </code></pre> <p>It fixes the problem for me.</p>
7
2009-06-08T14:47:28Z
[ "python", "pipe", "producer-consumer" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
965,730
<p>I am not sure that there is an 'official' way (it is not mentioned in the Zen of Python :) )- I tend to use the Config Parser module myself and I think that you will find that pretty common. I prefer that over the python file approach because you can write back to it and dynamically reload if you want.</p>
5
2009-06-08T16:18:49Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
965,733
<p>why would Guido blessed something that is out of his scope? No there is nothing particular blessed.</p>
2
2009-06-08T16:19:31Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
965,742
<p>It is more of convenience. There is no official way per say. But using XML files would make sense as they can be manipulated by various other applications/libraries.</p>
0
2009-06-08T16:21:50Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
965,795
<p>Depends on the predominant intended audience.</p> <p>If it is programmers who change the file anyway, just use python files like settings.py</p> <p>If it is end users then, think about ini files.</p>
22
2009-06-08T16:35:37Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
965,913
<p>It depends largely on how complicated your configuration is. If you're doing a simple key-value mapping and you want the capability to edit the settings with a text editor, I think ConfigParser is the way to go. </p> <p>If your settings are complicated and include lists and nested data structures, I'd use XML or JSON and create a configuration editor. </p> <p>For really complicated things where the end user isn't expected to change the settings much, or is more trusted, just create a set of Python classes and evaluate a Python script to get the configuration.</p>
1
2009-06-08T17:02:11Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
966,043
<p>Don't know if this can be considered "official", but it is in standard library: <a href="http://docs.python.org/library/configparser.html">14.2. ConfigParser — Configuration file parser</a>.</p> <p>This is, obviously, <em>not</em> an universal solution, though. Just use whatever feels most appropriate to the task, without any necessary complexity (and — especially — Turing-completeness! Think about automatic or GUI configurators).</p>
6
2009-06-08T17:39:45Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
966,074
<p>Just one more option, PyQt. Qt has a platform independent way of storing settings with the QSettings class. Underneath the hood, on windows it uses the registry and in linux it stores the settings in a hidden conf file. QSettings works very well and is pretty seemless.</p>
8
2009-06-08T17:50:36Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
967,036
<p>As many have said, there is no "offical" way. There are, however, many choices. There was <a href="http://pyvideo.org/video/190/pycon-2009--data-storage-in-python---an-overview0">a talk at PyCon</a> this year about many of the available options.</p>
25
2009-06-08T21:07:31Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
6,214,590
<p>I use a shelf ( <a href="http://docs.python.org/library/shelve.html">http://docs.python.org/library/shelve.html</a> ):</p> <pre><code>shelf = shelve.open(filename) shelf["users"] = ["David", "Abraham"] shelf.sync() # Save </code></pre>
14
2011-06-02T12:37:19Z
[ "python", "settings" ]
What's the official way of storing settings for python programs?
965,694
<p>Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
38
2009-06-08T16:13:02Z
16,776,259
<p>For web applications I like using OS environment variables: <code>os.environ.get('CONFIG_OPTION')</code></p> <p>This works especially well for settings that vary between deploys. You can read more about the rationale behind using env vars here: <a href="http://www.12factor.net/config" rel="nofollow">http://www.12factor.net/config</a></p> <p>Of course, this only works for read-only values because changes to the environment are usually not persistent. But if you don't need write access they are a very good solution.</p>
0
2013-05-27T15:27:02Z
[ "python", "settings" ]
Unicode Problem with SQLAlchemy
966,352
<p>I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening.</p> <p>I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file using regex.</p> <p>If i print the locations as I find them, they print with the characters so the encoding must be ok:</p> <pre><code>Le Pré-Saint-Gervais, France Hôtel-de-Ville, France </code></pre> <p>I'm storing the data in a SQLite table using SQLAlchemy:</p> <pre><code>Base = declarative_base() class Point(Base): __tablename__ = 'points' id = Column(Integer, primary_key=True) pdate = Column(Date) ptime = Column(Time) location = Column(Unicode(32)) weather = Column(String(16)) high = Column(Float) low = Column(Float) lat = Column(String(16)) lon = Column(String(16)) image = Column(String(64)) caption = Column(String(64)) def __init__(self, filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption): self.filename = filename self.pdate = pdate self.ptime = ptime self.location = location self.weather = weather self.high = high self.low = low self.lat = lat self.lon = lon self.image = image self.caption = caption def __repr__(self): return "&lt;Point('%s','%s','%s')&gt;" % (self.filename, self.pdate, self.ptime) engine = create_engine('sqlite:///:memory:', echo=False) Base.metadata.create_all(engine) Session = sessionmaker(bind = engine) session = Session() </code></pre> <p>I loop through the files and insert the data from each one into the database:</p> <pre><code>for filename in filelist: # open the file and extract the information using regex such as: location_re = re.compile("&lt;h2&gt;(.*)&lt;/h2&gt;",re.M) # extract other data newpoint = Point(filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption) session.add(newpoint) session.commit() </code></pre> <p>I see the following warning on each insert:</p> <pre><code>/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/default.py:230: SAWarning: Unicode type received non-unicode bind param value 'Spitalfields, United Kingdom' param.append(processors[key](compiled_params[key])) </code></pre> <p>And when I try to do anything with the table such as:</p> <pre><code>session.query(Point).all() </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "./extract_trips.py", line 131, in &lt;module&gt; session.query(Point).all() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1193, in all return list(self) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1341, in instances fetch = cursor.fetchall() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 1642, in fetchall self.connection._handle_dbapi_exception(e, None, None, self.cursor, self.context) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 931, in _handle_dbapi_exception raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect) sqlalchemy.exc.OperationalError: (OperationalError) Could not decode to UTF-8 column 'points_location' with text 'Le Pré-Saint-Gervais, France' None None </code></pre> <p>I would like to be able to correctly store and then return the location names with the original characters intact. Any help would be much appreciated.</p>
8
2009-06-08T18:50:08Z
966,423
<p>Try using a column type of Unicode rather than String for the unicode columns:</p> <pre><code>Base = declarative_base() class Point(Base): __tablename__ = 'points' id = Column(Integer, primary_key=True) pdate = Column(Date) ptime = Column(Time) location = Column(Unicode(32)) weather = Column(String(16)) high = Column(Float) low = Column(Float) lat = Column(String(16)) lon = Column(String(16)) image = Column(String(64)) caption = Column(String(64)) </code></pre> <p>Edit: Response to comment:</p> <p>If you're getting warnings about unicode encodings then there are two things you can try:</p> <ol> <li><p>Convert your location to unicode. This would mean having your Point created like this:</p> <p>newpoint = Point(filename, pdate, ptime, unicode(location), weather, high, low, lat, lon, image, caption)</p> <p>The unicode conversion will produce a unicode string when passed either a string or a unicode string, so you don't need to worry about what you pass in.</p></li> <li><p>If that doesn't solve the encoding issues, try calling encode on your unicode objects. That would mean using code like:</p> <p>newpoint = Point(filename, pdate, ptime, unicode(location).encode('utf-8'), weather, high, low, lat, lon, image, caption)</p> <p>This step probably won't be necessary but what it essentially does is converts a unicode object from unicode code-points to a specific byte representation (in this case, utf-8). I'd expect SQLAlchemy to do this for you when you pass in unicode objects but it may not.</p></li> </ol>
7
2009-06-08T19:08:56Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
Unicode Problem with SQLAlchemy
966,352
<p>I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening.</p> <p>I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file using regex.</p> <p>If i print the locations as I find them, they print with the characters so the encoding must be ok:</p> <pre><code>Le Pré-Saint-Gervais, France Hôtel-de-Ville, France </code></pre> <p>I'm storing the data in a SQLite table using SQLAlchemy:</p> <pre><code>Base = declarative_base() class Point(Base): __tablename__ = 'points' id = Column(Integer, primary_key=True) pdate = Column(Date) ptime = Column(Time) location = Column(Unicode(32)) weather = Column(String(16)) high = Column(Float) low = Column(Float) lat = Column(String(16)) lon = Column(String(16)) image = Column(String(64)) caption = Column(String(64)) def __init__(self, filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption): self.filename = filename self.pdate = pdate self.ptime = ptime self.location = location self.weather = weather self.high = high self.low = low self.lat = lat self.lon = lon self.image = image self.caption = caption def __repr__(self): return "&lt;Point('%s','%s','%s')&gt;" % (self.filename, self.pdate, self.ptime) engine = create_engine('sqlite:///:memory:', echo=False) Base.metadata.create_all(engine) Session = sessionmaker(bind = engine) session = Session() </code></pre> <p>I loop through the files and insert the data from each one into the database:</p> <pre><code>for filename in filelist: # open the file and extract the information using regex such as: location_re = re.compile("&lt;h2&gt;(.*)&lt;/h2&gt;",re.M) # extract other data newpoint = Point(filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption) session.add(newpoint) session.commit() </code></pre> <p>I see the following warning on each insert:</p> <pre><code>/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/default.py:230: SAWarning: Unicode type received non-unicode bind param value 'Spitalfields, United Kingdom' param.append(processors[key](compiled_params[key])) </code></pre> <p>And when I try to do anything with the table such as:</p> <pre><code>session.query(Point).all() </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "./extract_trips.py", line 131, in &lt;module&gt; session.query(Point).all() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1193, in all return list(self) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1341, in instances fetch = cursor.fetchall() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 1642, in fetchall self.connection._handle_dbapi_exception(e, None, None, self.cursor, self.context) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 931, in _handle_dbapi_exception raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect) sqlalchemy.exc.OperationalError: (OperationalError) Could not decode to UTF-8 column 'points_location' with text 'Le Pré-Saint-Gervais, France' None None </code></pre> <p>I would like to be able to correctly store and then return the location names with the original characters intact. Any help would be much appreciated.</p>
8
2009-06-08T18:50:08Z
967,144
<p>From <a href="http://www.sqlalchemy.org/CHANGES">sqlalchemy.org</a></p> <p>See section 0.4.2</p> <blockquote> <p>added new flag to String and create_engine(), assert _unicode=(True|False|'warn'|None). Defaults to <code>False</code> or <code>None</code> on create _engine() and String, <code>'warn'</code> on the Unicode type. When <code>True</code>, results in all unicode conversion operations raising an exception when a non-unicode bytestring is passed as a bind parameter. 'warn' results in a warning. It is strongly advised that all unicode-aware applications make proper use of Python unicode objects (i.e. u'hello' and not 'hello') so that data round trips accurately.</p> </blockquote> <p>I think you are trying to input a non-unicode bytestring. Perhaps this might lead you on the right track? Some form of conversion is needed, compare 'hello' and u'hello'.</p> <p>Cheers</p>
7
2009-06-08T21:34:59Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
Unicode Problem with SQLAlchemy
966,352
<p>I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening.</p> <p>I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file using regex.</p> <p>If i print the locations as I find them, they print with the characters so the encoding must be ok:</p> <pre><code>Le Pré-Saint-Gervais, France Hôtel-de-Ville, France </code></pre> <p>I'm storing the data in a SQLite table using SQLAlchemy:</p> <pre><code>Base = declarative_base() class Point(Base): __tablename__ = 'points' id = Column(Integer, primary_key=True) pdate = Column(Date) ptime = Column(Time) location = Column(Unicode(32)) weather = Column(String(16)) high = Column(Float) low = Column(Float) lat = Column(String(16)) lon = Column(String(16)) image = Column(String(64)) caption = Column(String(64)) def __init__(self, filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption): self.filename = filename self.pdate = pdate self.ptime = ptime self.location = location self.weather = weather self.high = high self.low = low self.lat = lat self.lon = lon self.image = image self.caption = caption def __repr__(self): return "&lt;Point('%s','%s','%s')&gt;" % (self.filename, self.pdate, self.ptime) engine = create_engine('sqlite:///:memory:', echo=False) Base.metadata.create_all(engine) Session = sessionmaker(bind = engine) session = Session() </code></pre> <p>I loop through the files and insert the data from each one into the database:</p> <pre><code>for filename in filelist: # open the file and extract the information using regex such as: location_re = re.compile("&lt;h2&gt;(.*)&lt;/h2&gt;",re.M) # extract other data newpoint = Point(filename, pdate, ptime, location, weather, high, low, lat, lon, image, caption) session.add(newpoint) session.commit() </code></pre> <p>I see the following warning on each insert:</p> <pre><code>/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/default.py:230: SAWarning: Unicode type received non-unicode bind param value 'Spitalfields, United Kingdom' param.append(processors[key](compiled_params[key])) </code></pre> <p>And when I try to do anything with the table such as:</p> <pre><code>session.query(Point).all() </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "./extract_trips.py", line 131, in &lt;module&gt; session.query(Point).all() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1193, in all return list(self) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/orm/query.py", line 1341, in instances fetch = cursor.fetchall() File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 1642, in fetchall self.connection._handle_dbapi_exception(e, None, None, self.cursor, self.context) File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.4p2-py2.5.egg/sqlalchemy/engine/base.py", line 931, in _handle_dbapi_exception raise exc.DBAPIError.instance(statement, parameters, e, connection_invalidated=is_disconnect) sqlalchemy.exc.OperationalError: (OperationalError) Could not decode to UTF-8 column 'points_location' with text 'Le Pré-Saint-Gervais, France' None None </code></pre> <p>I would like to be able to correctly store and then return the location names with the original characters intact. Any help would be much appreciated.</p>
8
2009-06-08T18:50:08Z
967,171
<p>I found this article that helped explain my troubles somewhat:</p> <p><a href="http://www.amk.ca/python/howto/unicode#reading-and-writing-unicode-data">http://www.amk.ca/python/howto/unicode#reading-and-writing-unicode-data</a></p> <p>I was able to get the desired results by using the 'codecs' module and then changing my program as follows:</p> <p>When opening the file:</p> <pre><code>infile = codecs.open(filename, 'r', encoding='iso-8859-1') </code></pre> <p>When printing the location:</p> <pre><code>print location.encode('ISO-8859-1') </code></pre> <p>I can now query and manipulate the data from the table without the error from before. I just have to specify the encoding when I output the text.</p> <p><em>(I still don't entirely understand how this is working so I guess it's time to learn more about Python's unicode handling...)</em></p>
10
2009-06-08T21:41:25Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
debug variable in python
966,571
<p>I want to separate the debug outputs from production ones by defining a variable that can be used throughput the module. It cannot be defined in environment. Any suggestions for globals reused across classes in modules? Additionally is there a way to configure this variable flag for telling appengine that dont use this code.</p>
2
2009-06-08T19:35:39Z
966,617
<p>Have a look at the <a href="http://www.python.org/doc/2.5/lib/module-logging.html">logging module</a>, which is fully supported by Google App Engine. You can specify logging levels such as debug, warning, error, etc. They will show up in the dev server console, and will also be stored in the request log.</p> <p>If you're after executing specific code only when running the dev server, you can do this:</p> <pre><code>if os.environ['SERVER_SOFTWARE'].startswith('Development'): print 'Hello world!' </code></pre> <p>The SERVER_SOFTWARE variable is always set by Google App Engine.</p> <p>As for module specific variables; modules are objects and can have values just as any other object:</p> <pre><code>my_module.debug = True </code></pre>
12
2009-06-08T19:44:59Z
[ "python", "google-app-engine" ]
debug variable in python
966,571
<p>I want to separate the debug outputs from production ones by defining a variable that can be used throughput the module. It cannot be defined in environment. Any suggestions for globals reused across classes in modules? Additionally is there a way to configure this variable flag for telling appengine that dont use this code.</p>
2
2009-06-08T19:35:39Z
967,347
<p>All module-level variables are global to all classes in the module.</p> <p>Here's my file: <code>mymodule.py</code></p> <pre><code>import this import that DEBUG = True class Foo( object ): def __init__( self ): if DEBUG: print self.__class__, "__init__" # etc. class Bar( object ): def do_work( self ): if DEBUG: print self.__class__, "do_work" # etc. </code></pre> <p>A single, module-level <code>DEBUG</code> variable will be found by all instances of these two classes. Other modules (e.g,. <code>this.py</code> and <code>that.py</code>) can have their own <code>DEBUG</code> variables. These would be <code>this.DEBUG</code> or <code>that.DEBUG</code>, and are unrelated.</p>
1
2009-06-08T22:31:05Z
[ "python", "google-app-engine" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
966,995
<p>Change this line of code:</p> <pre><code>a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>to this:</p> <pre><code>a.append(a[j-2] + (j+2)*(j+3)/2) </code></pre>
7
2009-06-08T21:00:01Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,011
<p>You're adding new elements, elements that do not exist yet. Hence you need to use <code>append</code>: since the items do not exist yet, you cannot reference them by index. <a href="http://docs.python.org/3.0/library/stdtypes.html#mutable-sequence-types" rel="nofollow">Overview of operations on mutable sequence types</a>.</p> <pre><code>for j in range(2, 23480): a.append(a[j - 2] + (j + 2) * (j + 3) / 2) </code></pre>
6
2009-06-08T21:02:57Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,015
<p>At <code>j=2</code> you're trying to assign to a[2], which doesn't exist yet. You probably want to use append instead.</p>
1
2009-06-08T21:03:38Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,016
<p>Python lists must be pre-initialzed. You need to do a = [0]*23480</p> <p>Or you can append if you are adding one at a time. I think it would probably be faster to preallocate the array.</p>
0
2009-06-08T21:03:51Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,019
<p>Python does not dynamically increase the size of an array when you assign to an element. You have to use a.append(element) to add an element onto the end, or a.insert(i, element) to insert the element at the position before i.</p>
0
2009-06-08T21:04:21Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,021
<p>If you want to debug it, just change your code to print out the current index as you go:</p> <pre><code> a=[] a.append(3) a.append(7) for j in range(2,23480): print j # &lt;-- this line a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>But you'll probably find that it errors out the second you access <code>a[2]</code> or higher; you've only added two values, but you're trying to access the 3rd and onward.</p> <p>Try replacing your list (<code>[]</code>) with a dictionary (<code>{}</code>); that way, you can assign to whatever numbers you like -- or, if you really want a list, initialize it with 23479 items (<code>[0] * 23479</code>).</p>
1
2009-06-08T21:04:52Z
[ "python" ]
Python error
966,983
<pre><code>a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>When I write this code, it gives an error like this:</p> <pre><code>Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in &lt;module&gt; a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range </code></pre> <p>May I know why and how to debug it?</p>
2
2009-06-08T20:57:48Z
967,048
<p>The reason for the error is that you're trying, as the error message says, to access a portion of the list that is currently out of range.</p> <p>For instance, assume you're creating a list of 10 people, and you try to specify who the 11th person on that list is going to be. On your paper-pad, it might be easy to just make room for another person, but runtime objects, like the list in python, isn't that forgiving.</p> <p>Your list starts out empty because of this:</p> <pre><code>a = [] </code></pre> <p>then you add 2 elements to it, with this code:</p> <pre><code>a.append(3) a.append(7) </code></pre> <p>this makes the size of the list just big enough to hold 2 elements, the two you added, which has an index of 0 and 1 (python lists are 0-based).</p> <p>In your code, further down, you then specify the contents of element <code>j</code> which starts at 2, and your code blows up immediately because you're trying to say "for a list of 2 elements, please store the following value as the 3rd element".</p> <p>Again, lists like the one in Python usually aren't that forgiving.</p> <p>Instead, you're going to have to do one of two things:</p> <ol> <li>In some cases, you want to store into an existing element, or add a new element, depending on whether the index you specify is available or not</li> <li>In other cases, you always want to add a new element</li> </ol> <p>In your case, you want to do nbr. 2, which means you want to rewrite this line of code:</p> <pre><code>a[j]=a[j-2]+(j+2)*(j+3)/2 </code></pre> <p>to this:</p> <pre><code>a.append(a[j-2]+(j+2)*(j+3)/2) </code></pre> <p>This will append a new element to the end of the list, which is OK, instead of trying to assign a new value to element N+1, where N is the current length of the list, which isn't OK.</p>
3
2009-06-08T21:09:14Z
[ "python" ]
Form Validation in Admin with Inline formset and Model form
967,045
<p>I have a model, OrderedList, which is intended to be a listing of content objects ordered by the user. The OrderedList has several attributes, including a site which it belongs to.</p> <p>The content objects are attached to it via an OrderedListRow class, which is brought into OrderedList's admin via an inline formset in the admin.</p> <pre><code>class OrderedList(GenericList): objects = models.Manager() published = GenericListManager() class OrderedListRow(models.Model): list = models.ForeignKey(OrderedList) content_type = models.ForeignKey(ContentType) object_id = models.PositiveSmallIntegerField() content_object = generic.GenericForeignKey("content_type", "object_id") order = models.IntegerField('order', blank = True, null = True) </code></pre> <p>(OrderedList inherits the site field from the larger GenericList abstract).</p> <p>Here's my problem; when the user saves the admin form, I want to verify that each content object mapped to by each OrderedListRow belongs to the same site that the OrderedList does (the list can only belong to 1 site; the content objects can belong to multiple).</p> <p>I can override OrderedList's admin form's clean(), but it doesn't include the inline formset which contains the OrderedListRows, so it can't reach that data. I can override the OrderedListRows' inline formset's clean, but it can't reach the list. I need some way within the context of form validation to reach both the OrderedList's form data and the formset's form data so I can check all the sites of the OrderedListRow's content objects against the site of the OrderedList, and throw a validation error if there's a problem. So far I haven't found a function that the cleaned data for both OrderedRow and the OrderedListRows are contained in.</p>
5
2009-06-08T21:08:50Z
969,068
<p>In the inline formset, <code>self.instance</code> should refer to the parent object, ie the OrderedList.</p>
4
2009-06-09T09:28:49Z
[ "python", "django", "django-admin", "django-forms" ]
Form Validation in Admin with Inline formset and Model form
967,045
<p>I have a model, OrderedList, which is intended to be a listing of content objects ordered by the user. The OrderedList has several attributes, including a site which it belongs to.</p> <p>The content objects are attached to it via an OrderedListRow class, which is brought into OrderedList's admin via an inline formset in the admin.</p> <pre><code>class OrderedList(GenericList): objects = models.Manager() published = GenericListManager() class OrderedListRow(models.Model): list = models.ForeignKey(OrderedList) content_type = models.ForeignKey(ContentType) object_id = models.PositiveSmallIntegerField() content_object = generic.GenericForeignKey("content_type", "object_id") order = models.IntegerField('order', blank = True, null = True) </code></pre> <p>(OrderedList inherits the site field from the larger GenericList abstract).</p> <p>Here's my problem; when the user saves the admin form, I want to verify that each content object mapped to by each OrderedListRow belongs to the same site that the OrderedList does (the list can only belong to 1 site; the content objects can belong to multiple).</p> <p>I can override OrderedList's admin form's clean(), but it doesn't include the inline formset which contains the OrderedListRows, so it can't reach that data. I can override the OrderedListRows' inline formset's clean, but it can't reach the list. I need some way within the context of form validation to reach both the OrderedList's form data and the formset's form data so I can check all the sites of the OrderedListRow's content objects against the site of the OrderedList, and throw a validation error if there's a problem. So far I haven't found a function that the cleaned data for both OrderedRow and the OrderedListRows are contained in.</p>
5
2009-06-08T21:08:50Z
1,477,327
<p>I am dealing with the same issue. And unfortunately I don't think the answer above covers things entirely.</p> <p>If there are changes in both the inline formset and the admin form, accessing self.instance will not give accurate data, since you will base the validation on the database and then save the formset which overwrites that data you just used to validate things. Basically this makes your validation one save behind. </p> <p>I suppose the real question here is which gets saved first. After digging int he source code, it seems like the admin site saved the form first. This means that, logically, doing validation on the formset and from there accessing the 'parent' instance <em>should</em> get consistent values.</p>
1
2009-09-25T13:36:34Z
[ "python", "django", "django-admin", "django-forms" ]
python: find out if running in shell or not (e.g. sun grid engine queue)
967,369
<p>is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?</p> <p>the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.</p> <p>thanks!</p> <p>p.</p>
6
2009-06-08T22:36:56Z
967,383
<p>You can use <code>os.getppid()</code> to find out the process id for the parent-process of this one, and then use that process id to determine which program that process is running. More usefully, you could use <code>sys.stdout.isatty()</code> -- that doesn't answer your title question but appears to better solve the actual problem you explain (if you're running under a shell but your output is piped to some other process or redirected to a file you probably don't want to emit "interactive stuff" on it either).</p>
6
2009-06-08T22:39:46Z
[ "python", "shell", "terminal", "stdout" ]
python: find out if running in shell or not (e.g. sun grid engine queue)
967,369
<p>is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?</p> <p>the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.</p> <p>thanks!</p> <p>p.</p>
6
2009-06-08T22:36:56Z
967,384
<p>The standard way is <code>isatty()</code>.</p> <pre><code>import sys if sys.stdout.isatty(): print("Interactive") else: print("Non-interactive") </code></pre>
13
2009-06-08T22:39:50Z
[ "python", "shell", "terminal", "stdout" ]
python: find out if running in shell or not (e.g. sun grid engine queue)
967,369
<p>is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?</p> <p>the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.</p> <p>thanks!</p> <p>p.</p>
6
2009-06-08T22:36:56Z
1,591,429
<p>I have found the following to work on both Linux and Windows, in both the normal Python interpreter and IPython (though I can't say about IronPython):</p> <pre><code>isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter') </code></pre> <p>However, note that when using <strong>ipython</strong>, if the file is specified as a command-line argument it will run before the interpreter becomes interactive. See what I mean below:</p> <pre><code>C:\&gt;cat C:\demo.py import sys, os # ps1=python shell; ipcompleter=ipython shell isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter') print isInteractive and "This is interactive" or "Automated" C:\&gt;python c:\demo.py Automated C:\&gt;python &gt;&gt;&gt; execfile('C:/demo.py') This is interactive C:\&gt;ipython C:\demo.py Automated # NOTE! Then ipython continues to start up... IPython 0.9.1 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object'. ?object also works, ?? prints more. In [2]: run C:/demo.py This is interactive # NOTE! </code></pre> <p>HTH</p>
1
2009-10-19T22:14:47Z
[ "python", "shell", "terminal", "stdout" ]
python: find out if running in shell or not (e.g. sun grid engine queue)
967,369
<p>is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?</p> <p>the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.</p> <p>thanks!</p> <p>p.</p>
6
2009-06-08T22:36:56Z
8,499,846
<p>Slightly shorter:</p> <pre><code>import sys sys.stdout.isatty() </code></pre>
3
2011-12-14T05:26:44Z
[ "python", "shell", "terminal", "stdout" ]
Curious about differences in vtkMassProperties for VTK 5.04 and VTK 5.4.2
967,468
<p>I have a small python <a href="http://vtk.org" rel="nofollow"><code>VTK</code></a> function that calculates the volume and surface area of an object embedded in a stack of <code>TIFF</code> images. To read the <code>TIFF's</code> into <code>VTK</code>, I have used <code>vtkTIFFReader</code> and processed the result using <code>vtkImageThreshold</code>. I then use <code>vtkMassProperties</code> to extract the volume and surface area of the object identified after thresholding. </p> <p>With <code>VTK-5.04</code>, this function returns the correct value for a test stack (3902 pixels). However, using <code>VTK-5.4.2</code> the same function returns a different value (422 pixels). Can someone explain this? <hr /></p> <h3>Code</h3> <pre><code>def testvtk(): # read 36 TIFF images. Each TIFF is 27x27 pixels v16=vtk.vtkTIFFReader() v16.SetFilePrefix("d:/test/slice") v16.SetDataExtent(0,27,0,27,1,36) v16.SetFilePattern("%s%04d.tif") v16.SetDataSpacing (1,1,1) v16.Update() # Threshold level for seperating background/foreground pixels maxthres=81 # Threshold the image stack thres=vtk.vtkImageThreshold() thres.SetInputConnection(v16.GetOutputPort()) thres.ThresholdByLower(0) thres.ThresholdByUpper(maxthres) # create ISO surface from thresholded images iso=vtk.vtkImageMarchingCubes() iso.SetInputConnection(thres.GetOutputPort()) # Have VTK calculate the Mass (volume) and surface area Mass = vtk.vtkMassProperties() Mass.SetInputConnection(iso.GetOutputPort()) Mass.Update() # just print the results print "Volume = ", Mass.GetVolume() print "Surface = ", Mass.GetSurfaceArea() </code></pre> <p><hr /></p> <h3>Note</h3> <p>By testing both VTK-5.4.2 and VTK-5.2.1, I narrowed things down a bit and believe this behaviour was introduced between versions 5.0.4 and 5.2.1.</p> <h3>Update</h3> <p>It seems that in VTK-5.4.2, vtkTIFFReader ignores the <em>x</em> and <em>y</em> values set in the <em>SetDataSpacing</em> method. Instead vtkTIFFReader is calculating the <em>x</em> and <em>y</em> dataspacing from the resolution reported by the TIFF files.</p>
4
2009-06-08T23:06:31Z
990,274
<p>I have never heard of <a href="http://www.vtk.org/" rel="nofollow">VTK</a> before, but here it goes.</p> <p>Good thing about opensource software is that you can check the source code directly. Better yet, if there's web-based version control browser, we can talk about it online like this.</p> <p>Let's see <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Graphics/vtkMassProperties.cxx?view=log" rel="nofollow"><code>vtkMassProperties</code></a> in question. 5.0.4 uses r1.28 and 5.4.2 uses r1.30. Here's the <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Graphics/vtkMassProperties.cxx?r1=1.30&amp;r2=1.28" rel="nofollow">diff between r1.28 and r.30</a>. The part that may affect volume calculations are</p> <pre><code>vol[2] += (area * (double)u[2] * (double)zavg); // 5.0.4 vol[2] += (area * u[2] * zavg); // 5.4.2 </code></pre> <p>and </p> <pre><code>kxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /(double)(numCells); // 5.0.4 kxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /numCells; // 5.4.2 </code></pre> <p>but all changes look ok to me.</p> <p>Next suspicious are the <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Graphics/vtkMarchingCubes.cxx?view=log" rel="nofollow"><code>vtkMarchingCubes</code></a>. <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Graphics/vtkMarchingCubes.cxx?r1=1.1.6.1&amp;r2=1.5" rel="nofollow">Diff between r1.1.6.1 and 1.5</a>.</p> <pre><code>self-&gt;UpdateProgress ((double) k / ((double) dims[2] - 1)); // 5.0.4 self-&gt;UpdateProgress (k / static_cast&lt;double&gt;(dims[2] - 1)); // 5.4.2 </code></pre> <p>and </p> <pre><code>estimatedSize = (int) pow ((double) (dims[0] * dims[1] * dims[2]), .75); // 5.0.4 estimatedSize = static_cast&lt;int&gt;( pow(static_cast&lt;double&gt;(dims[0]*dims[1]*dims[2]),0.75)); // 5.4.2 </code></pre> <p>Again, they are fixing stuff on casting, but it looks ok.</p> <p>Might as well see <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Imaging/vtkImageThreshold.cxx?view=log" rel="nofollow"><code>vtkImageThreshold</code></a> too. <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/Imaging/vtkImageThreshold.cxx?r1=1.50&amp;r2=1.52" rel="nofollow">Diff between r1.50 and r1.52</a>.</p> <pre><code>lowerThreshold = (IT) inData-&gt;GetScalarTypeMin(); // 5.0.4 lowerThreshold = static_cast&lt;IT&gt;(inData-&gt;GetScalarTypeMin()); // 5.4.2 </code></pre> <p>There are bunch more, but they are all casting stuff.</p> <p>It gets more interesting with <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/IO/vtkTIFFReader.cxx?view=log" rel="nofollow"><code>vtkTIFFReader</code></a>. <a href="http://public.kitware.com/cgi-bin/viewcvs.cgi/IO/vtkTIFFReader.cxx?r1=1.63&amp;r2=1.51" rel="nofollow">Diff between 1.51 and 1.63</a>. As you can see by the difference in the revision numbers, there has been some development in this class compared to others. Here are the checkin comments:</p> <ul> <li>ENH: Add an name for scalars. Visible in Paraview.</li> <li>ENH: vtkDataArray now has a new superclass-vtkAbstractArray...</li> <li>ENH: Set default number of sampels per pixel for files that are missing this meta data.</li> <li>ENH: Read only what you need.</li> <li>ENH: add multipage TIFF file support</li> <li>ENH: print ivars</li> <li>BUG: TIFF Reader did not properly account for RLE encoded data. Also, ExecuteInformation overwrote user specified spacing and origin.</li> <li>BUG: when reading beach.tif (from current CVS VTKData), the image would be loaded upside down.</li> <li>STYLE: s/OrientationTypeSpecifiedFlag/OriginSpecifiedFlag/g and s/OrientationTypeSpecifiedFlag/SpacingSpecifiedFlag/g</li> <li>BUG: Reader was not handling extents properly.</li> <li>COMP: Fixing a warning.</li> <li>COMP: Getting rid of a warning. </li> </ul> <p>From the amount of changes that was made in vtkTIFFReader, I would guess that the difference in behavior is coming from there. For example, it may have started to recognize your Tiff as different format and changed the internal pixel values. Try printing out pixel values and see if there is any difference. If the pixel values have changed <code>maxthres=81</code> may be too high.</p>
4
2009-06-13T08:03:05Z
[ "python", "3d", "vtk" ]
Binary file IO in python, where to start?
967,652
<p>As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats?</p> <p>I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger project that I'm working on). </p> <p>There is already an awesome open-source project for managing ebook libraries : <a href="http://calibre.kovidgoyal.net/">Calibre</a>. I wanted to try implementing this on my own as a learning/self-teaching exercise. I started looking at their <a href="http://bazaar.launchpad.net/~kovid/calibre/trunk/files/head%3A/src/calibre/ebooks/mobi/">python source code</a> and realized that I have no idea what is going on. Of course, the big danger in being self-taught at anything is not knowing what you don't know. </p> <p>In this case, I know that I don't know much about these binary files and how to work with them in python code (<a href="http://www.python.org/doc/2.6/library/struct.html#module-struct">struct</a>?). But I think I'm probably missing a lot of knowledge about binary files in general and I'd like some help understanding how to work with them. <a href="http://wiki.mobileread.com/wiki/MOBI">Here is a detailed overview</a> of the mobi/palmdoc headers. Thanks!</p> <p>Edit: No question, good point! Do you have any tips on how to gain a basic knowledge of working with binary files? Python-specific would be helpful but other approaches could also be useful.</p> <p>TOM:Edited as question, added intro / better title</p>
10
2009-06-09T00:25:36Z
967,884
<p>You should probably start with the <a href="http://docs.python.org/library/struct.html">struct</a> module, as you pointed to in your question, and of course, open the file as a binary.</p> <p>Basically you just start at the beginning of the file and pick it apart piece by piece. It's a hassle, but not a huge problem. If the files are compressed or encrypted, things can get more difficult. It's helpful if you start with a file that you know the contents of so you're not guessing all the time.</p> <p>Try it a bit, and maybe you'll evolve more specific questions. </p>
9
2009-06-09T02:19:37Z
[ "python", "binary", "io", "epub", "mobipocket" ]
Binary file IO in python, where to start?
967,652
<p>As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats?</p> <p>I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger project that I'm working on). </p> <p>There is already an awesome open-source project for managing ebook libraries : <a href="http://calibre.kovidgoyal.net/">Calibre</a>. I wanted to try implementing this on my own as a learning/self-teaching exercise. I started looking at their <a href="http://bazaar.launchpad.net/~kovid/calibre/trunk/files/head%3A/src/calibre/ebooks/mobi/">python source code</a> and realized that I have no idea what is going on. Of course, the big danger in being self-taught at anything is not knowing what you don't know. </p> <p>In this case, I know that I don't know much about these binary files and how to work with them in python code (<a href="http://www.python.org/doc/2.6/library/struct.html#module-struct">struct</a>?). But I think I'm probably missing a lot of knowledge about binary files in general and I'd like some help understanding how to work with them. <a href="http://wiki.mobileread.com/wiki/MOBI">Here is a detailed overview</a> of the mobi/palmdoc headers. Thanks!</p> <p>Edit: No question, good point! Do you have any tips on how to gain a basic knowledge of working with binary files? Python-specific would be helpful but other approaches could also be useful.</p> <p>TOM:Edited as question, added intro / better title</p>
10
2009-06-09T00:25:36Z
970,191
<p>For teaching yourself python tools that work with binary files, <a href="http://www.pythonchallenge.com/" rel="nofollow">this will get you going</a>. Fun too. Exercises with binaries, zips, images... lots more.</p>
0
2009-06-09T13:50:12Z
[ "python", "binary", "io", "epub", "mobipocket" ]
Binary file IO in python, where to start?
967,652
<p>As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats?</p> <p>I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger project that I'm working on). </p> <p>There is already an awesome open-source project for managing ebook libraries : <a href="http://calibre.kovidgoyal.net/">Calibre</a>. I wanted to try implementing this on my own as a learning/self-teaching exercise. I started looking at their <a href="http://bazaar.launchpad.net/~kovid/calibre/trunk/files/head%3A/src/calibre/ebooks/mobi/">python source code</a> and realized that I have no idea what is going on. Of course, the big danger in being self-taught at anything is not knowing what you don't know. </p> <p>In this case, I know that I don't know much about these binary files and how to work with them in python code (<a href="http://www.python.org/doc/2.6/library/struct.html#module-struct">struct</a>?). But I think I'm probably missing a lot of knowledge about binary files in general and I'd like some help understanding how to work with them. <a href="http://wiki.mobileread.com/wiki/MOBI">Here is a detailed overview</a> of the mobi/palmdoc headers. Thanks!</p> <p>Edit: No question, good point! Do you have any tips on how to gain a basic knowledge of working with binary files? Python-specific would be helpful but other approaches could also be useful.</p> <p>TOM:Edited as question, added intro / better title</p>
10
2009-06-09T00:25:36Z
970,282
<p>If you want to construct and analyse binary files the struct module will give you the basic tools, but it isn't very friendly, especially if you want to look at things that aren't a whole number of bytes.</p> <p>There are a few modules that can help, such as <a href="http://pypi.python.org/pypi/BitVector" rel="nofollow">BitVector</a>, <a href="http://pypi.python.org/pypi/bitarray/" rel="nofollow">bitarray</a> and <a href="http://code.google.com/p/python-bitstring/" rel="nofollow">bitstring</a>. (I favour <a href="http://code.google.com/p/python-bitstring/" rel="nofollow">bitstring</a>, but I wrote it and so may be biased). </p> <p>For parsing binary formats the <a href="http://hachoir.org/" rel="nofollow">hachoir</a> module is very good, but I suspect it's too high-level for your current needs.</p>
2
2009-06-09T14:08:27Z
[ "python", "binary", "io", "epub", "mobipocket" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
967,666
<p>String formatting under python 2.x should do it for you:</p> <pre><code>&gt;&gt;&gt; print '%.2f' % 315.15321531321 315.15 </code></pre> <p>This limits the string representation to just 2 decimal places. Note that if you use <code>round(315.153215, 2)</code>, you'll end up with another float value, which is naturally imprecise (or overprecise, depending on how you look at it):</p> <pre><code>&gt;&gt;&gt; round(315.15321531321, 2) 315.14999999999998 </code></pre> <p>Technically, <code>round()</code> is correct, but it doesn't "truncate" the results as you requested at <code>315.15</code>. In addition, if you round a value like 315.157, it will produce something closer to 315.16... not sure if that's what you mean by "truncate".</p>
12
2009-06-09T00:32:27Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
967,670
<p>If you just want to display it shortened, you can use the <code>"%f"</code> formating flag:</p> <pre><code>value = 315.123123123 print "Value is: %.2f" % value </code></pre> <p>If you want to really cut off the "additional" digits, do something like:</p> <pre><code>from math import trunc value = trunc(value*100)/100 </code></pre>
2
2009-06-09T00:33:23Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
967,671
<p>Built-in function <code>round()</code>:</p> <pre><code>&gt;&gt;&gt; num = 315.1532153132 &gt;&gt;&gt; round(num, 2) 3.1499999999999998 </code></pre>
1
2009-06-09T00:33:44Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
967,676
<p>You have several options - you can round the number using round(), however this can introduce some inaccuracies (315.15 might round to 315.150000003 for example). If you're just looking to truncate the value of the float when you're displaying it, you can specify the width of the output using printf("%.2f", mynumber). This is probably a better solution, since without knowing more about your specific application it's a good idea in general to keep the entire length of the number for calculation.</p>
1
2009-06-09T00:34:52Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
967,702
<p>If you're working with currency amounts, I strongly recommend that you use Python's decimal class instead: <a href="http://docs.python.org/library/decimal.html" rel="nofollow">http://docs.python.org/library/decimal.html</a></p>
5
2009-06-09T00:50:08Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
22,250,876
<p>Looks like print "%.2f" does rounding as well. Here is Python code that rounds and truncates </p> <pre><code>num = 315.15627 print "rounded = %.2f" % num print "truncated = %.2f" % (int(num*100)/float(100)) rounded = 315.16 truncated = 315.15 </code></pre>
3
2014-03-07T13:04:33Z
[ "python", "truncate" ]
python truncate after a hundreds?
967,661
<p>How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15</p> <p>how do i do that?</p>
8
2009-06-09T00:29:59Z
27,807,216
<p>When working with <code>Decimal</code> types and currency, where the amount needs to be precise, here is what I came up with for truncating to cents (hundredths):</p> <pre><code>amount = Decimal(long(amount * 100)) / Decimal(100) </code></pre> <p><strong>A little history</strong>: I tried <code>quantize</code> but it tends to round rather than truncate. And I couldn't in good conscience use expensive string formatters for something so simple. And finally I didn't want any precision problems a la <code>float</code> so I use very specific casting that is probably overkill.</p>
0
2015-01-06T21:09:36Z
[ "python", "truncate" ]
Image distortion after sending through a WSGI app in Python
967,826
<p>A lot of the time when I send image data over WSGI (using <code>wsgiref</code>), the image comes out distorted. As an example, examine the following:</p> <p><img src="http://evanfosmark.com/files/goog.gif" alt="distorted Google logo" /></p>
1
2009-06-09T01:55:14Z
967,895
<p>Maybe the result is getting truncated? Try <code>wget</code> or <code>curl</code> to fetch the file directly and <code>cmp</code> it to the original image; that should help debug it. Beyond that, post your full code and environment details even if it's simple.</p>
0
2009-06-09T02:28:37Z
[ "python", "wsgi" ]
Image distortion after sending through a WSGI app in Python
967,826
<p>A lot of the time when I send image data over WSGI (using <code>wsgiref</code>), the image comes out distorted. As an example, examine the following:</p> <p><img src="http://evanfosmark.com/files/goog.gif" alt="distorted Google logo" /></p>
1
2009-06-09T01:55:14Z
968,042
<p>As you haven't posted the code, here is a simple code which correctly works with python 2.5 on windows</p> <pre><code>from wsgiref.simple_server import make_server def serveImage(environ, start_response): status = '200 OK' headers = [('Content-type', 'image/png')] start_response(status, headers) return open("about.png", "rb").read() httpd = make_server('', 8000, serveImage) httpd.serve_forever() </code></pre> <p>may be instead of "rb" you are using "r"</p>
3
2009-06-09T03:44:22Z
[ "python", "wsgi" ]
Image distortion after sending through a WSGI app in Python
967,826
<p>A lot of the time when I send image data over WSGI (using <code>wsgiref</code>), the image comes out distorted. As an example, examine the following:</p> <p><img src="http://evanfosmark.com/files/goog.gif" alt="distorted Google logo" /></p>
1
2009-06-09T01:55:14Z
968,045
<p>It had to do with <code>\n</code> not being converted properly. I'd like to thank Alex Martelli for pointing me in the right direction.</p>
1
2009-06-09T03:45:18Z
[ "python", "wsgi" ]
Installed apps in Django - what about versions?
967,855
<p>After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages. </p> <p>What I don't understand is what happens when the version of one of those installed apps changes. If I update one of the apps that's installed to site-packages, then won't that break all my current projects that use it? I never noticed anything in settings.py that let's you specify the version of the app you're importing.</p> <p>I think in Ruby/Rails, they're able to freeze gems for this sort of situation. But what are we supposed to do in Python/Django?</p>
1
2009-06-09T02:08:14Z
967,885
<p>Having multiple versions of the same package gets messy (setuptools can do it, though).</p> <p>I've found it cleaner to put each project in its own <code>virtualenv</code>. We use <code>virtualevwrapper</code> to manage the virtualenvs easily, and the <code>--no-site-packages</code> option to make every project really self-contained and portable across machines.</p> <p>This is the <a href="http://code.google.com/p/modwsgi/wiki/VirtualEnvironments" rel="nofollow">recommended setup for mod_wsgi servers</a>.</p>
5
2009-06-09T02:19:49Z
[ "python", "django", "version-control" ]
Installed apps in Django - what about versions?
967,855
<p>After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages. </p> <p>What I don't understand is what happens when the version of one of those installed apps changes. If I update one of the apps that's installed to site-packages, then won't that break all my current projects that use it? I never noticed anything in settings.py that let's you specify the version of the app you're importing.</p> <p>I think in Ruby/Rails, they're able to freeze gems for this sort of situation. But what are we supposed to do in Python/Django?</p>
1
2009-06-09T02:08:14Z
968,244
<p>You definitely don't want to put your Django apps into site-packages if you have more than one Django site.</p> <p>The best way, as Ken Arnold answered, is to use Ian Bicking's <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> (Virtual Python Environment Builder). This is especially true if you have to run multiple versions of Django.</p> <p>However, if you can run a single version of Python and Django then it might be a little easier to just install the apps into your project directory. This way if an external app gets updated you can upgrade each of your projects one at a time as you see fit. This is the structure <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> used for external Django apps at one time, but I think it's using virtualenv + <a href="http://pypi.python.org/pypi/pip" rel="nofollow">pip</a> (instead of setuptools/distutils) now.</p>
0
2009-06-09T05:11:28Z
[ "python", "django", "version-control" ]
Installed apps in Django - what about versions?
967,855
<p>After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages. </p> <p>What I don't understand is what happens when the version of one of those installed apps changes. If I update one of the apps that's installed to site-packages, then won't that break all my current projects that use it? I never noticed anything in settings.py that let's you specify the version of the app you're importing.</p> <p>I think in Ruby/Rails, they're able to freeze gems for this sort of situation. But what are we supposed to do in Python/Django?</p>
1
2009-06-09T02:08:14Z
969,345
<p>What we do.</p> <p>We put only "3rd-party" stuff in site-packages. Django, XLRD, PIL, etc.</p> <p>We keep our overall project structured as a collection of packages and Django projects. Each project is a portion of the overall site. We have two separate behaviors for port 80 and port 443 (SSL).</p> <pre><code>OverallProject/ aPackage/ anotherPackage/ djangoProject80/ settings.py logging.ini app_a_1/ models.py # app a, version 1 schema app_a_2/ models.py # app a, version 2 schema app_b_2/ models.py app_c_1/ models.py djangoProject443/ test/ tool/ </code></pre> <p>We use a version number as part of the app name. This is the major version number, and is tied to the schema, since "uses-the-same-schema" is one definition of major release compatibility.</p> <p>You have to migrated the data and prove that things work in the new version. Then you can delete the old version and remove the schema from the database. Migrating the data is challenging because you can't run both apps side-by-side.</p> <p>Most applications have just one current version installed.</p>
0
2009-06-09T10:51:21Z
[ "python", "django", "version-control" ]
Python Advice for a beginner. Regex, Dictionaries etc?
968,018
<p>I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.</p> <p>Example: My config file looks like this.</p> <pre><code>Job { Name = "host.domain.com-foo" Client = host.domain.com-fd JobDefs = "DefaultJob" FileSet = "local" Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr" Pool = storage-disk1 } </code></pre> <p>Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? </p>
3
2009-06-09T03:34:33Z
968,029
<p>I don't think a regex is adequate for parsing something like this. You could look at a true parser, such as <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a>. Or if the file format is within your control, you might consider XML. There are standard Python libraries for parsing that.</p>
2
2009-06-09T03:40:27Z
[ "python", "regex", "dictionary", "configuration-files" ]
Python Advice for a beginner. Regex, Dictionaries etc?
968,018
<p>I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.</p> <p>Example: My config file looks like this.</p> <pre><code>Job { Name = "host.domain.com-foo" Client = host.domain.com-fd JobDefs = "DefaultJob" FileSet = "local" Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr" Pool = storage-disk1 } </code></pre> <p>Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? </p>
3
2009-06-09T03:34:33Z
968,066
<p>There are numorous existing alternatives for this task, json, pickle and yaml to name 3. Unless you really want to implement this yourself, you should use one of these. Even if you do roll your own, following the format of one of the above is still a good idea. </p> <p>Also, it's a much better idea to use a parser/generator or similar tool to do the parsing, regex's are going to be harder to maintain and more inefficient for this type of task.</p>
5
2009-06-09T03:51:14Z
[ "python", "regex", "dictionary", "configuration-files" ]
Python Advice for a beginner. Regex, Dictionaries etc?
968,018
<p>I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.</p> <p>Example: My config file looks like this.</p> <pre><code>Job { Name = "host.domain.com-foo" Client = host.domain.com-fd JobDefs = "DefaultJob" FileSet = "local" Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr" Pool = storage-disk1 } </code></pre> <p>Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? </p>
3
2009-06-09T03:34:33Z
968,115
<p><a href="http://docs.python.org/library/configparser.html" rel="nofollow">ConfigParser</a> module from the standard library is probably the most Pythonic and staight-forward way to parse a configuration file that your python script is using.</p> <p>If you are restricted to using the particular format you have outlined, then using pyparsing is pretty good.</p>
4
2009-06-09T04:21:11Z
[ "python", "regex", "dictionary", "configuration-files" ]
Python Advice for a beginner. Regex, Dictionaries etc?
968,018
<p>I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.</p> <p>Example: My config file looks like this.</p> <pre><code>Job { Name = "host.domain.com-foo" Client = host.domain.com-fd JobDefs = "DefaultJob" FileSet = "local" Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr" Pool = storage-disk1 } </code></pre> <p>Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? </p>
3
2009-06-09T03:34:33Z
968,304
<p>If you can change the configuration file format, you can directly write your file as a Python file.</p> <h3>config.py</h3> <pre><code>job = { 'Name' : "host.domain.com-foo", 'Client' : "host.domain.com-fd", 'JobDefs' : "DefaultJob", 'FileSet' : "local", 'Write Bootstrap' : "/etc/foo/host.domain.com-foo.bsr", 'Pool' : 'storage-disk1' } </code></pre> <h3>yourscript.py</h3> <pre><code>from config import job print job['Name'] </code></pre>
8
2009-06-09T05:32:10Z
[ "python", "regex", "dictionary", "configuration-files" ]
Python Advice for a beginner. Regex, Dictionaries etc?
968,018
<p>I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for the code just a push in the right direction.</p> <p>Example: My config file looks like this.</p> <pre><code>Job { Name = "host.domain.com-foo" Client = host.domain.com-fd JobDefs = "DefaultJob" FileSet = "local" Write Bootstrap = "/etc/foo/host.domain.com-foo.bsr" Pool = storage-disk1 } </code></pre> <p>Should I used regex, line splitting or maybe a module? If I had multiple jobs in my config file would I use a dictionary to correlate a job to a pool? </p>
3
2009-06-09T03:34:33Z
968,307
<p>If your config file can be turned into a python file, just make it a dictionary and import the module.</p> <pre><code>Job = { "Name" : "host.domain.com-foo", "Client" : "host.domain.com-fd", "JobDefs" : "DefaultJob", "FileSet" : "local", "Write BootStrap" : "/etc/foo/host.domain.com-foo.bsr", "Pool" : "storage-disk1" } </code></pre> <p>You can access the options by simply calling Job["Name"]..etc.</p> <p>The ConfigParser is easy to use as well. You can create a text file that looks like this:</p> <pre><code>[Job] Name=host.domain.com-foo Client=host.domain.com-fd JobDefs=DefaultJob FileSet=local Write BootStrap=/etc/foo/host.domain.com-foo.bsr Pool=storage-disk1 </code></pre> <p>Just keep it simple like one of the above.</p>
5
2009-06-09T05:32:44Z
[ "python", "regex", "dictionary", "configuration-files" ]
installing python libraries
968,116
<p>Ok, so i've downloaded the following library: <a href="http://www.lag.net/paramiko/" rel="nofollow">http://www.lag.net/paramiko/</a></p> <p>and i can't seem to figure out how to install on my local machine: Mac OS X 10.4.11</p>
1
2009-06-09T04:21:27Z
968,137
<p>To use the package that you got from the web-site: "python setup.py install "</p> <p>My advice is to use easy_install instead of downloading packages straight from the project web-site.</p> <p>To do this, you must first install <a href="http://pypi.python.org/pypi/setuptools">setuptools</a>.</p> <p>Then just use the command "easy_install paramiko".</p> <p>As you use lots of different packages, this ends up saving you lots of hassle.</p>
6
2009-06-09T04:31:10Z
[ "python", "package-management" ]
How to isolate a single color in an image
968,317
<p>I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish. </p> <p>I tried to take only the red color channel but this includes the white spaces in the Image too. </p> <p>What is a good way to do that?</p>
1
2009-06-09T05:36:01Z
968,336
<p>Use a different color space: <a href="http://en.wikipedia.org/wiki/HSL_color_space" rel="nofollow">http://en.wikipedia.org/wiki/HSL_color_space</a></p>
4
2009-06-09T05:41:02Z
[ "python", "image-processing", "opencv", "color-space" ]
How to isolate a single color in an image
968,317
<p>I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish. </p> <p>I tried to take only the red color channel but this includes the white spaces in the Image too. </p> <p>What is a good way to do that?</p>
1
2009-06-09T05:36:01Z
968,351
<p>How about using a formular like r' = r-(g+b)?</p>
0
2009-06-09T05:45:06Z
[ "python", "image-processing", "opencv", "color-space" ]
How to isolate a single color in an image
968,317
<p>I'm using the python OpenCV bindings and at the moment I try to isolate a colorrange. That means I want to filter out everything that is not reddish. </p> <p>I tried to take only the red color channel but this includes the white spaces in the Image too. </p> <p>What is a good way to do that?</p>
1
2009-06-09T05:36:01Z
2,204,755
<p>Use the HSV colorspace. Select pixels that have an H value in the range that you consider to contain "red," and an S value large enough that you do not consider it to be neutral, maroon, brown, or pink. You might also need to throw out pixels with low V's. The H dimension is a circle, and red is right where the circle is split, so your H range will be in two parts, one near 255, the other near 0.</p>
1
2010-02-05T02:56:26Z
[ "python", "image-processing", "opencv", "color-space" ]
Calculate the center of a contour/Area
968,332
<p>I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object. </p> <p>How do I calculate the center of a contour or area with OpenCV?</p> <p>Opencv links:</p> <ul> <li><a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">http://opencv.willowgarage.com/wiki/</a></li> <li><a href="http://en.wikipedia.org/wiki/OpenCV" rel="nofollow">http://en.wikipedia.org/wiki/OpenCV</a></li> </ul>
4
2009-06-09T05:39:21Z
968,984
<p>I don't exactly know what OpenCV is, but I would suggest this:</p> <p>The Selected cluster of pixels has a maximum width at one point - w - so lets say the area has w vertical columns of pixels. Now I would weight the columns according to how many pixels the column contains, and use these column-wights to determine the Horizontal Center Point.</p> <p>The Same Algorithm could also work for the X Center.</p>
-2
2009-06-09T09:06:02Z
[ "python", "image-processing", "opencv", "contour" ]
Calculate the center of a contour/Area
968,332
<p>I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object. </p> <p>How do I calculate the center of a contour or area with OpenCV?</p> <p>Opencv links:</p> <ul> <li><a href="http://opencv.willowgarage.com/wiki/" rel="nofollow">http://opencv.willowgarage.com/wiki/</a></li> <li><a href="http://en.wikipedia.org/wiki/OpenCV" rel="nofollow">http://en.wikipedia.org/wiki/OpenCV</a></li> </ul>
4
2009-06-09T05:39:21Z
969,506
<p>You can get the center of mass in the y direction by first calculating the <a href="http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/ref/OpenCVRef%5FCv.htm#decl%5FcvMoments">Moments</a>. Then the center of mass is given by <code>yc = M01 / M00</code>, where M01 and M00 are fields in the structure returned by the Moments call.</p> <p>If you just want the center of the bounding rectangle, that is also easy to do with <a href="http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/ref/OpenCVRef%5FCv.htm#decl%5FcvBoundingRect">BoundingRect</a>. This returns you a CvRect and you can just take half of the height.</p> <p>Let me know if this isn't precise enough, I have sample code somewhere I can dig up for you.</p>
10
2009-06-09T11:31:19Z
[ "python", "image-processing", "opencv", "contour" ]
Python regex for alphanumerics not working
968,553
<pre><code>from django import forms class ActonForm(forms.Form): creator = forms.RegexField('^[a-zA-Z0-9\-' ]$',max_length=30, min_length=3) data = {'creator': 'hello' } f = ActonForm(data) print f.is_valid() </code></pre> <p>Why doesn't this work? have i made a wrong regular expression? I wanted a name field with provision for single quotes and a hyphen</p>
-1
2009-06-09T06:55:22Z
968,564
<p>It kind of shows in the syntax highlighting. The apostrophe in the regex isn't escaped, it should be like this:</p> <pre><code>forms.RegexField('^[a-zA-Z0-9\\-\' ]$',max_length=30, min_length=3) </code></pre> <p><strong>Edit:</strong> When escaping things in the regular expression, you need double backslashes. I doubled the backslash before the hyphen (not that it has to be escaped in this particular case.)</p> <p>Secondly, your regular expression only allows for a single character. You need to use a quantifier. + means one or more, * means 0 or more, {2,} means two or more, {3,6} means three to six. You probably want this:</p> <pre><code>forms.RegexField('^[a-zA-Z0-9\\-\' ]+$',max_length=30, min_length=3) </code></pre> <p>Do take care that the above regular expression will allow spaces in the start and end of the field as well. To avoid that you need a more complex regex.</p>
1
2009-06-09T06:57:53Z
[ "python", "regex", "google-app-engine" ]
breakpoint in eclipse for appengine
968,701
<p>I have pydev on eclipse and would like to debug handlers. I put breakpoint on a handler and start project in debug mode. When I click on the hyperlink corresponding to handler the control does not come back to breakpoint. Am I missing something here? Also the launch is for google app engine application in python.</p>
3
2009-06-09T07:45:09Z
969,003
<p>The simplest way to debug is to use the builtin python module <code>pdb</code> and debug from the shell.</p> <p>Just set the trace in the handler you want to debug.</p> <pre><code>import pdb pdb.set_trace() </code></pre> <p>How do U run the server, from within the eclipse or from the shell. If it is from the shell, then how does eclipse know you are even running the application;</p> <p>You could use an user friendly version of <code>pdb</code>, <code>ipdb</code> that also includes user friendly options like auto complete.</p>
0
2009-06-09T09:11:18Z
[ "python", "eclipse", "debugging", "google-app-engine", "pydev" ]
breakpoint in eclipse for appengine
968,701
<p>I have pydev on eclipse and would like to debug handlers. I put breakpoint on a handler and start project in debug mode. When I click on the hyperlink corresponding to handler the control does not come back to breakpoint. Am I missing something here? Also the launch is for google app engine application in python.</p>
3
2009-06-09T07:45:09Z
969,586
<p>I'm using eclipse with PyDev with appengine and I debug all the time, it's completely possible !</p> <p>What you have to do is start the program in debug, but you have to start the dev_appserver in debug, not the handler directly. The main module you have to debug is:</p> <pre><code>&lt;path_to_gae&gt;/dev_appserver.py </code></pre> <p>With program arguments:</p> <pre><code>--datastore_path=/tmp/myapp_datastore &lt;your_app&gt; </code></pre> <p>I hope it help</p>
4
2009-06-09T11:49:27Z
[ "python", "eclipse", "debugging", "google-app-engine", "pydev" ]
fetching row numbers in a database-independent way - django
969,074
<p>Let's say that I have a <strong>'Scores'</strong> table with fields <strong>'User'</strong>,<strong>'ScoreA'</strong>, <strong>'ScoreB'</strong>, <strong>'ScoreC'</strong>. In a leaderboard view I fetch and order a queryset by any one of these score fields that the visitor selects. The template paginates the queryset. The table is updated by a job on regular periods (a django command triggered by cron). </p> <p>I want to add a <strong>'rank'</strong> field to the queryset so that I will have <strong>'rank'</strong>, <strong>'User'</strong>, <strong>'ScoreA'</strong>, <strong>'ScoreB'</strong>, <strong>'ScoreC'</strong>. Moreover I want to remain database-independent (postgre is an option and for the time being it does not support <strong>row_number</strong>).</p> <p>A solution may be that I can modify the job, so that it also computes and writes three different ranks in three new fields (<strong>'rankA'</strong>, <strong>'rankB'</strong>, <strong>'rankC'</strong>).</p> <p>I hope there is a (much) better solution?</p>
0
2009-06-09T09:31:18Z
969,233
<p>Why can't you compute the rank in the template?</p> <pre><code>{% for row in results_to_display %} &lt;tr&gt;&lt;td&gt;{{forloop.counter}}&lt;/td&gt;&lt;td&gt;{{row.scorea}}&lt;/td&gt;... {% endfor %} </code></pre> <p>Or, you can compute the rank in the view function.</p> <pre><code>def fetch_ranked_scores( request ): query = Score.objects.filter( ... ).orderby( scorea ) scores = [ r, s.scorea for r, s in enumerate(query) ] return render_to_response ( template, { 'results_to_display':scores } ) </code></pre> <p>Or, you can compute the ranking in the model.</p> <pre><code> class Score( models.Model ): ScoreA = models.IntegerField( ... ) def ranked_by_a( self ): return enumerate( self.objects.filter(...).orderby( scorea ) ) </code></pre> <p>I think there are many, many ways to do this.</p>
2
2009-06-09T10:20:35Z
[ "python", "django", "django-orm" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
969,141
<p>Try <code>help()</code> or <code>dir()</code>. AFAIR there's no builtin support for pdf-related tasks in plain Python installation. Another way to find help for Python modules is to google ;)</p> <p>Docs: </p> <p><a href="http://docs.python.org/library/functions.html#help" rel="nofollow">http://docs.python.org/library/functions.html#help</a></p> <p><a href="http://docs.python.org/library/functions.html#dir" rel="nofollow">http://docs.python.org/library/functions.html#dir</a></p> <p>EDIT:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; def search_help(keyword): ... os.system('python Lib/pydoc.py -k %s' % keyword) ... &gt;&gt;&gt; search_help('math') cmath - This module is always available. It provides access to mathematical math - This module is always available. It provides access to the test.test_cmath test.test_math &gt;&gt;&gt; search_help('pdf') &gt;&gt;&gt; _ </code></pre> <p>You have to have main python dir in your path. And it won't work under IDLE. HTH.</p>
0
2009-06-09T09:48:11Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
969,283
<p>In console type help(object):</p> <pre><code>Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; help(dir) Help on built-in function dir in module __builtin__: dir(...) dir([object]) -&gt; list of strings .... </code></pre> <p>Unfortunatelly there is no help for pdf:</p> <pre><code>&gt;&gt;&gt; help(pdf) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'pdf' is not defined &gt;&gt;&gt; </code></pre> <p>As paffnucy said try searching internet (SO works wery well :)</p> <p>This site can be helpful as well: <a href="http://www.gotapi.com/python" rel="nofollow">http://www.gotapi.com/python</a></p>
1
2009-06-09T10:36:05Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
969,323
<p>You can use help to access the docstrings of the different modules you have imported, e.g., try the following:</p> <pre><code>help(math) </code></pre> <p>and you'll get an error,</p> <pre><code>import math help(math) </code></pre> <p>and you will get a list of the available methods in the module, but only AFTER you have imported it. It also works with individual functions, e.g. after importing math try:</p> <pre><code>help(math.sin) </code></pre> <p>To deal with pdf you will probably have to install a third party module. A quick search has led me to this result, which I haven't tried:</p> <p><a href="http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/" rel="nofollow">http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/</a></p>
4
2009-06-09T10:45:55Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
970,043
<p>help( "modules")</p> <pre><code>&gt;&gt;&gt; help( "modules" ) Please wait a moment while I gather a list of all available modules... C:\Program Files\Python26\lib\pkgutil.py:110: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon __import__(name) ArgImagePlugin WmfImagePlugin dbhash pyclbr BaseHTTPServer XVThumbImagePlugin decimal pydoc Bastion XbmImagePlugin difflib pydoc_topics BdfFontFile XpmImagePlugin dircache pyexpat BmpImagePlugin _LWPCookieJar dis quopri BufrStubImagePlugin _MozillaCookieJar distutils random CGIHTTPServer __builtin__ doctest re Canvas __future__ dumbdbm repr ConfigParser _abcoll dummy_thread rexec ContainerIO _ast dummy_threading rfc822 Cookie _bisect email rlcompleter CurImagePlugin _bsddb encodings robotparser DcxImagePlugin _bytesio errno runpy Dialog _codecs exceptions sched DocXMLRPCServer _codecs_cn filecmp select EpsImagePlugin _codecs_hk fileinput sets ExifTags _codecs_iso2022 fnmatch sgmllib FileDialog _codecs_jp formatter sha FitsStubImagePlugin _codecs_kr fpformat shelve FixTk _codecs_tw fractions shlex FliImagePlugin _collections ftplib shutil FontFile _csv functools signal FpxImagePlugin _ctypes future_builtins site GbrImagePlugin _ctypes_test gc smtpd GdImageFile _elementtree genericpath smtplib GifImagePlugin _fileio getopt sndhdr GimpGradientFile _functools getpass socket GimpPaletteFile _hashlib gettext sqlite3 GribStubImagePlugin _heapq glob sre HTMLParser _hotshot gzip sre_compile Hdf5StubImagePlugin _imaging hashlib sre_constants IcnsImagePlugin _imagingft heapq sre_parse IcoImagePlugin _imagingmath hmac ssl ImImagePlugin _imagingtk hotshot stat Image _json htmlentitydefs statvfs ImageChops _locale htmllib string ImageColor _lsprof httplib stringold ImageDraw _md5 idlelib stringprep ImageDraw2 _msi ihooks strop ImageEnhance _multibytecodec imageop struct ImageFile _multiprocessing imaplib subprocess ImageFileIO _random imghdr sunau ImageFilter _sha imp sunaudio ImageFont _sha256 imputil symbol ImageGL _sha512 inspect symtable ImageGrab _socket io sys ImageMath _sqlite3 itertools tabnanny ImageMode _sre json tarfile ImageOps _ssl keyword telnetlib ImagePalette _strptime lib2to3 tempfile ImagePath _struct linecache test ImageQt _subprocess locale textwrap ImageSequence _symtable logging this ImageStat _testcapi macpath thread ImageTk _threading_local macurl2path threading ImageTransform _tkinter mailbox time ImageWin _warnings mailcap timeit ImtImagePlugin _weakref markupbase tkColorChooser IptcImagePlugin _winreg marshal tkCommonDialog JpegImagePlugin abc math tkFileDialog McIdasImagePlugin aifc md5 tkFont MicImagePlugin anydbm mhlib tkMessageBox MimeWriter array mimetools tkSimpleDialog MpegImagePlugin ast mimetypes toaiff MspImagePlugin asynchat mimify token OleFileIO asyncore mmap tokenize PIL atexit modulefinder trace PSDraw audiodev msilib traceback PaletteFile audioop msvcrt tty PalmImagePlugin base64 multifile turtle PcdImagePlugin bdb multiprocessing types PcfFontFile binascii mutex unicodedata PcxImagePlugin binhex netrc unittest PdfImagePlugin bisect new update_manifest PixarImagePlugin bsddb nntplib urllib PngImagePlugin bz2 nt urllib2 PpmImagePlugin cPickle ntpath urlparse PsdImagePlugin cProfile nturl2path user Queue cStringIO numbers uu ScrolledText calendar opcode uuid SgiImagePlugin cgi operator warnings SimpleDialog cgitb optparse wave SimpleHTTPServer chunk os weakref SimpleXMLRPCServer cmath os2emxpath webbrowser SocketServer cmd parser whichdb SpiderImagePlugin code pdb winsound StringIO codecs pickle wsgiref SunImagePlugin codeop pickletools wx TarIO collections pipes wxPython TgaImagePlugin colorsys pkgutil wxversion TiffImagePlugin commands platform xdrlib TiffTags compileall plistlib xml Tix compiler popen2 xmllib Tkconstants contextlib poplib xmlrpclib Tkdnd cookielib posixfile xxsubtype Tkinter copy posixpath zipfile UserDict copy_reg pprint zipimport UserList csv profile zlib UserString ctypes pstats WalImageFile curses pty WbmpImagePlugin datetime py_compile Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". &gt;&gt;&gt; </code></pre>
4
2009-06-09T13:20:43Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
970,106
<p>The <code>pydoc -k</code> flag searches the documentation.</p> <pre><code>pydoc -k &lt;keyword&gt; Search for a keyword in the synopsis lines of all available modules. </code></pre> <p>From a terminal, run..</p> <pre><code>$ pydoc -k pdf </code></pre> <p>..for example:</p> <pre><code>$ pydoc -k pdf PdfImagePlugin wx.lib.pdfwin PIL.PdfImagePlugin </code></pre> <p>It doesn't search the contents of the documentation, but it searches all module names - if that's not enough, I'd suggest using Google or StackOverflow to search for "Python PDF module" or similar</p>
7
2009-06-09T13:30:28Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
970,501
<p>(Years later) I now use <a href="https://pip.pypa.io/en/stable/reference/pip_search/" rel="nofollow">pip search</a><br> and <a href="https://pypi.python.org/pypi/yolk/0.4.3" rel="nofollow">yolk</a> -M or -H packagename: -M for metadata, -H to browse to its web page .</p> <hr> <p>To search PyPI (Python Package Index) package info locally, try <code>pypi-grep</code>. An example: <code>pypi-grep 'pyqt'</code> --></p> <pre><code># day status packagename version homepage summary 2009-06-07 3 "pydee" 0.4.11 http://code.google.com/p/pydee/ Pydee development environment and its PyQt4-based IDE tools: ... 2009-06-05 4 "Sandbox" 0.9.5 http://www.qtrac.eu/sandbox.html A PyQt4-based alternative to IDLE ... </code></pre> <p><code>pypi-grep</code> is just a file with one long line per PyPI package, with the info you see above, plus a trivial bash script to egrep the file.<br> Why ? Grepping a local file is very fast and very simple, for old Unix guys and simple searches: "what's XYZ ?"</p> <p><code>hg clone http://bitbucket.org/denisb/pypi-grep/</code> should download <code>pypi-grep</code> and <code>pypi-grepfile-2009-06-08</code> or the like; move them to a directory in your PATH. (First <code>easy_install hg</code> if you don't have <code>hg</code>.)</p> <p>Notes:</p> <p>the pypi-grepfile has only one version per package, the newest; multiline summaries are folded to one long line (which I chop with <code>pypi-grep | less -iS</code>).</p> <p><code>pypi-grep -h</code> lists a few options </p> <p>The data comes from <a href="http://pypi.python.org/pypi" rel="nofollow">http://pypi.python.org/pypi</a> xmlrpc, but beware: some packages in list_packages have no package_releases or no releasedata, and a few releasedatas timeout (timeout_xmlrpclib); what you see is All you get.</p> <p>Feedback is welcome.</p>
2
2009-06-09T14:48:35Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
4,670,427
<p>You can search for modules containing "pdf" in their description by running the command <code>help("modules pdf")</code>.</p>
4
2011-01-12T15:20:34Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
24,565,848
<p>Thinking recursively:</p> <pre><code>&gt;&gt;&gt; help(help) Help on _Helper in module site object: class _Helper(builtins.object) | Define the builtin 'help'. | This is a wrapper around **pydoc.help** (with a twist). | ... </code></pre> <p>from here:</p> <pre><code>&gt;&gt;&gt; import pydoc &gt;&gt;&gt; help(pydoc) Help on module pydoc: .... </code></pre> <p>lots of essential info on search in python docs there.</p>
1
2014-07-04T02:24:08Z
[ "python" ]
How to search help using python console
969,093
<p>Is there any way to search for a particular package/function using keywords in the Python console?</p> <p>For example, I may want to search "pdf" for pdf related tasks.</p>
6
2009-06-09T09:37:17Z
26,696,112
<p>pip is an excellent resource. If pip is installed (if you don't have it, instructions are <a href="http://pip.readthedocs.org/en/latest/installing.html" rel="nofollow">here</a>), then using the Windows command shell you can do the following:</p> <pre><code>pip search pdf </code></pre> <p>It returns a plethora of options.</p> <pre><code>C:\Python27\Scripts&gt;pip search pdf mwlib.rl - generate pdfs from mediawiki markup slc.publications - A content type to store and parse pdf publications PyPDFLite - Simple PDF Writer. pdfminer - PDF parser and analyzer zopyx.convert - A Python interface to XSL-FO libraries (Conversion HTML to PDF, RTF, DOCX, WML and ODT) WeasyPrint - WeasyPrint converts web documents to PDF. zopyx.convert2 - A Python interface for the conversion of HTML to PDF, RTF, DOCX, WML and ODT) - belongs to zopyx.smartprintng.core collective.pdfpeek - A Plone 4 product that generates image thumbnail previews of PDF files stored on ATFile based objects. pisa - PDF generator using HTML and CSS </code></pre> <p>etc.</p>
3
2014-11-02T04:35:09Z
[ "python" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
969,134
<p>If you don't mind a switch to Subversion, Eclipse has its SubClipse plugin.</p>
1
2009-06-09T09:46:01Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
969,176
<p>I believe Eclipse does have CVS support built in - or at least it did have when I last used it a couple of years ago.</p> <p>For further information on how to use CVS with Eclipse see the <a href="http://wiki.eclipse.org/index.php/CVS%5FFAQ" rel="nofollow">Eclipse CVS FAQ</a></p>
0
2009-06-09T09:59:04Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
969,236
<p>I tried Eclipse+Subclipse and Eclipse+Bazaar plugin. Both work very well, but I have found that Tortoise versions of those version source control tools are so good that I resigned from Eclipse plugins. On Windows Tortoise XXX are my choice. They integrate with shell (Explorer or TotalCommander), changes icon overlay if file is changed, shows log, compare revisions etc. etc.</p>
1
2009-06-09T10:20:47Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
969,541
<p>As others have indicated, there are plugins available for Eclipse for SVN, Bazar, Mercurial and Git.</p> <p>Even so, despite their presence, I find using the command line the most comfortable.</p> <pre><code>svn commit -m 'now committing' </code></pre> <p>Assuming you are not committing for more than several times a day, this should work well enough. Is there anything specific that is preventing you from using the command line?</p>
1
2009-06-09T11:41:24Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
969,642
<p>Last time I tried this, Eclipse did not support direct access to local repositories in the same way that command line cvs does because command line cvs has both client and server functionality whereas Eclipse only has client functionality and needs to go through (e.g.) pserver, so you would probably need to have a cvs server running.</p> <p>Turns out that I didn't really need it anyway as Eclipse keeps its own history of all changes so I only needed to do an occasional manual update to cvs at major milestones.</p> <p>[Eventually I decided not to use cvs at all with Eclipse under Linux as it got confused by symlinks and started deleting my include files when it "synchronised" with the repository.]</p>
4
2009-06-09T11:56:44Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
976,961
<blockquote> <p>I recently moved my house and don't have yet an access to internet.</p> </blockquote> <p>CVS and SVN are the Centralized Version control systems. Rather than having to install them on your local system just for single version control, you could use DVCS like Mercurial or Git.</p> <p>When you clone a Mercurial Repository, you have literally all versions of all the repo files available locally.</p>
0
2009-06-10T17:12:59Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
976,996
<p>I would definitely recommend switching over to a different VCS—I prefer <a href="http://selenic.com/mercurial/" rel="nofollow">Mercurial</a>, along with a lot of the Python community. That way, you'll be able to work locally, but still have the ability to publish your changes to the world later.</p> <p>You can install <a href="http://bitbucket.org/tortoisehg/stable/wiki/Home" rel="nofollow">TortoiseHg</a> for Windows Explorer, and the <a href="http://www.vectrace.com/mercurialeclipse/" rel="nofollow">MercurialEclipse</a> plugin for Eclipse.</p> <p>There's even a <a href="http://www.selenic.com/mercurial/wiki/CvsConcepts" rel="nofollow">Mercurial for CVS users</a> document to help you change over, and a <a href="http://www.selenic.com/mercurial/wiki/CvsCommands" rel="nofollow">list of mostly-equivalent commands</a>.</p>
1
2009-06-10T17:21:03Z
[ "python", "eclipse", "cvs", "pydev" ]
Eclipse + local CVS + PyDev
969,121
<p>I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)</p> <p>It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?</p> <p>Regards and thanks in advance for any clues. Please forgive my English ;)</p>
4
2009-06-09T09:43:21Z
977,044
<p>I use Eclipse with a local CVS repository without issue. The only catch is that you cannot use the ":local:" CVS protocol. Since you're on Windows, I recommend installing <a href="http://tortoisecvs.org/" rel="nofollow">TortoiseCVS</a> and then configuring the included CVSNT server as follows:</p> <ul> <li>Control Panel: CVSNT <ul> <li>Repository configuration: create a repository and publish it</li> <li>Note the Server Name and make sure it matches your hostname</li> </ul></li> <li>Eclipse: Create a new repository location using the :pserver: connection type and point it to your local hostname</li> </ul> <p>This (or any actual source control system) has the advantage over the Eclipse Local History of being able to associate checkin comments with changes, group changes into change sets, etc. You can use the Eclipse Local History to recover from minor mistakes, but it's no replacement for source control (and expires as well: see Window->Preferences General->Workspace->Local History).</p>
0
2009-06-10T17:29:56Z
[ "python", "eclipse", "cvs", "pydev" ]
How to agnostically link any object/Model from another Django Model?
969,211
<p>I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.</p> <p>The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.</p> <p>I <em>could</em> build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.</p> <p>Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.</p> <p>I've had the idea that perhaps I could dump custom template tags on the page like this:</p> <pre><code>{% block unique_object "unique placeholder name" %} </code></pre> <p>And that would find a "block" based on the two arguments passed in. An example:</p> <pre><code>&lt;h1&gt;{{ product_instance.name }}&lt;/h1&gt; {% block product_instance "detail: product short description" %} {% block product_instance "detail: product video" %} {% block product_instance "detail: product long description" %} </code></pre> <p>Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat<code>&lt;/fg&gt;</code>).</p> <p>Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.</p> <p>So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?</p> <p>Note: Editing will be done <em>on-the-page</em> so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them!</p>
1
2009-06-09T10:11:28Z
969,300
<p>django-tagging uses Django's <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/" rel="nofollow">contenttypes</a> framework. The docs do a much better job of explaining it than I can, but the simplest description of it would be "generic foreign key that can point to any other model."</p> <p>This may be what you are looking for, but from your description it also sounds like you want to do something very similar to some other existing projects:</p> <ul> <li><p><strong><a href="http://pypi.python.org/pypi/django-flatblocks/0.3.1" rel="nofollow">django-flatblocks</a></strong> ("... acts like django.contrib.flatpages but for parts of a page; like an editable help box you want show alongside the main content.")</p></li> <li><p><strong><a href="http://bitbucket.org/hakanw/django-better-chunks/wiki/Home" rel="nofollow">django-better-chunks</a></strong> ("Think of it as flatpages for small bits of reusable content you might want to insert into your templates and manage from the admin interface.")</p></li> </ul> <p>and so on. If these are similar then they'll make a good starting point for you.</p>
6
2009-06-09T10:39:50Z
[ "python", "django", "django-models", "content-management-system" ]
How to agnostically link any object/Model from another Django Model?
969,211
<p>I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.</p> <p>The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.</p> <p>I <em>could</em> build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.</p> <p>Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.</p> <p>I've had the idea that perhaps I could dump custom template tags on the page like this:</p> <pre><code>{% block unique_object "unique placeholder name" %} </code></pre> <p>And that would find a "block" based on the two arguments passed in. An example:</p> <pre><code>&lt;h1&gt;{{ product_instance.name }}&lt;/h1&gt; {% block product_instance "detail: product short description" %} {% block product_instance "detail: product video" %} {% block product_instance "detail: product long description" %} </code></pre> <p>Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat<code>&lt;/fg&gt;</code>).</p> <p>Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.</p> <p>So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?</p> <p>Note: Editing will be done <em>on-the-page</em> so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them!</p>
1
2009-06-09T10:11:28Z
1,201,454
<p>You want a way to display some object-specific content on a generic template, given a specific object, correct?</p> <p>In order to support both models and other objects, we need two intermediate models; one to handle strings, and one to handle models. We could do it with one model, but this is less performant. These models will provide the link between content and string/model.</p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic CONTENT_TYPE_CHOICES = ( ("video", "Video"), ("text", "Text"), ("image", "Image"), ) def _get_template(name, type): "Returns a list of templates to load given a name and a type" return ["%s_%s.html" % (type, name), "%s.html" % name, "%s.html" % type] class ModelContentLink(models.Model): key = models.CharField(max_length=255) # Or whatever you find appropriate type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') def get_template(self): model_name = self.object.__class__.__name__.lower() return _get_template(model_name, self.type) class StringContentLink(models.Model): key = models.CharField(max_length=255) # Or whatever length you find appropriate type = models.CharField(max_length=31, choices= CONTENT_TYPE_CHOICES) content = models.TextField() def get_template(self): return _get_template(self.content, self.type) </code></pre> <p>Now, all we need is a template tag to grab these, and then try to load the templates given by the models' get_template() method. I'm a bit pressed on time so I'll leave it at this and update it in ~1 hour. Let me know if you think this approach seems fine.</p>
2
2009-07-29T16:24:58Z
[ "python", "django", "django-models", "content-management-system" ]
How to agnostically link any object/Model from another Django Model?
969,211
<p>I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL.</p> <p>The problem comes when you're no longer dealing with "pages" (be those FlatPages pages, or something else), but rather instances from another Model. For example if I have a Model of products, I may wish to create a detail page that has multiple editable regions within.</p> <p>I <em>could</em> build those regions into the Model but in my case, there are several Models and is a lot of variance in how much data I want to show.</p> <p>Therefore, I want to build the CMS at template level and specify what a block (an editable region) is based on the instance of "page" or the model it uses.</p> <p>I've had the idea that perhaps I could dump custom template tags on the page like this:</p> <pre><code>{% block unique_object "unique placeholder name" %} </code></pre> <p>And that would find a "block" based on the two arguments passed in. An example:</p> <pre><code>&lt;h1&gt;{{ product_instance.name }}&lt;/h1&gt; {% block product_instance "detail: product short description" %} {% block product_instance "detail: product video" %} {% block product_instance "detail: product long description" %} </code></pre> <p>Sounds spiffy, right? Well the problem I'm running into is how do I create a "key" for a zone so I can pull the correct block out? I'll be dealing with a completely unknown object (it could be a "page" object, a URL, a model instance, anything - it could even be a boat<code>&lt;/fg&gt;</code>).</p> <p>Other Django micro-applications must do this. You can tag anything with django-tagging, right? I've tried to understand how that works but I'm drawing blanks.</p> <p>So, firstly, am I mad? And assuming I not, and this looks like a relatively sane idea to persue, how should I go about linking an object+string to a block/editable-region?</p> <p>Note: Editing will be done <em>on-the-page</em> so there's no real issue in letting the users edit the zones. I won't have to do any reverse-mumbo-jumbo in the admin. My eventual dream is to allow a third argument to specify what sort of content area this is (text, image, video, etc). If you have any comments on any of this, I'm happy to read them!</p>
1
2009-06-09T10:11:28Z
1,223,361
<p>It's pretty straightforward to use the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes" rel="nofollow">contenttypes</a> framework to implement the lookup strategy you are describing:</p> <pre><code>class Block(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey() # not actually used here, but may be handy key = models.CharField(max_length=255) ... other fields ... class Meta: unique_together = ('content_type', 'object_id', 'key') def lookup_block(object, key): return Block.objects.get(content_type=ContentType.objects.get_for_model(object), object_id=object.pk, key=key) @register.simple_tag def block(object, key) block = lookup_block(object, key) ... generate template content using 'block' ... </code></pre> <p>One gotcha to be aware of is that you can't use the <code>object</code> field in the <code>Block.objects.get</code> call, because it's not a real database field. You must use <code>content_type</code> and <code>object_id</code>.</p> <p>I called the model <code>Block</code>, but if you have some cases where more than one unique <code>(object, key)</code> tuple maps to the same block, it may in fact be an intermediate model that itself has a <code>ForeignKey</code> to your actual <code>Block</code> model or to the appropriate model in a helper app like the ones Van Gale has mentioned.</p>
2
2009-08-03T16:43:19Z
[ "python", "django", "django-models", "content-management-system" ]
Function parameters hint Eclipse with PyDev
969,466
<p>Seems like newbie's question, but I just can't find the answer. Can I somehow see function parameters hint like in Visual Studio by pressing Ctrl+Shift+Space when cursor is in function call like this:</p> <pre><code>someObj.doSomething("Test", "hello, wold", 4|) </code></pre> <p>where | is my cursor position. Ctrl+Spase shows me that information when I start typing function name, but I want to see function's parameters list at any time I want. I'm using latest available Eclipse and PyDev</p>
6
2009-06-09T11:20:50Z
969,483
<p>Try "<code>CTRL+space</code>" after a '<code>,</code>', not after a parameter.<br /> The function parameters are displayed just after the '<code>(</code>' or after a '<code>,</code>' + "<code>CTRL+space</code>".</p>
10
2009-06-09T11:26:06Z
[ "python", "eclipse", "pydev" ]
Function parameters hint Eclipse with PyDev
969,466
<p>Seems like newbie's question, but I just can't find the answer. Can I somehow see function parameters hint like in Visual Studio by pressing Ctrl+Shift+Space when cursor is in function call like this:</p> <pre><code>someObj.doSomething("Test", "hello, wold", 4|) </code></pre> <p>where | is my cursor position. Ctrl+Spase shows me that information when I start typing function name, but I want to see function's parameters list at any time I want. I'm using latest available Eclipse and PyDev</p>
6
2009-06-09T11:20:50Z
1,606,937
<p>Parameters will show up just after a '(', which is how I re-displayed mine for ages. I recently discovered that 'CTRL + Shift + Space' will show the parameters anywhere in a function call. Saved me some valuable seconds.</p>
3
2009-10-22T12:40:02Z
[ "python", "eclipse", "pydev" ]
Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv?
969,553
<p>I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the <code>bin/activate</code> file, is there a better/more standard way?</p>
13
2009-06-09T11:44:14Z
969,703
<p>Here is the hacked version of <code>bin/activate</code> for reference. It sets the PYTHONPATH correctly, but unsetting does not work. </p> <pre><code> # This file must be used with "source bin/activate" *from bash* # you cannot run it directly deactivate () { if [ -n "$_OLD_VIRTUAL_PATH" ] ; then PATH="$_OLD_VIRTUAL_PATH" export PATH unset _OLD_VIRTUAL_PATH fi # This should detect bash and zsh, which have a hash command that must # be called to get it to forget past commands. Without forgetting # past commands the $PATH changes we made may not be respected if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then hash -r fi if [ -n "$_OLD_VIRTUAL_PS1" ] ; then PS1="$_OLD_VIRTUAL_PS1" export PS1 unset _OLD_VIRTUAL_PS1 fi if [ -n "$_OLD_PYTHONPATH" ] ; then PYTHONPATH="$_OLD_PYTHONPATH" export PYTHONPATH unset _OLD_PYTHONPATH fi unset VIRTUAL_ENV if [ ! "$1" = "nondestructive" ] ; then # Self destruct! unset deactivate fi } # unset irrelavent variables deactivate nondestructive VIRTUAL_ENV="env_location" # Anonymized export VIRTUAL_ENV _OLD_VIRTUAL_PATH="$PATH" PATH="$VIRTUAL_ENV/bin:$PATH" export PATH _OLD_VIRTUAL_PS1="$PS1" if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then # special case for Aspen magic directories # see http://www.zetadev.com/software/aspen/ PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1" else PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1" fi export PS1 # This should detect bash and zsh, which have a hash command that must # be called to get it to forget past commands. Without forgetting # past commands the $PATH changes we made may not be respected if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then hash -r fi _OLD_PYTHONPATH="$PYTHONPATH" PYTHONPATH="new_pythonpath" #Anonymized export PYTHONPATH </code></pre>
1
2009-06-09T12:09:29Z
[ "python", "virtualenv" ]
Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv?
969,553
<p>I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the <code>bin/activate</code> file, is there a better/more standard way?</p>
13
2009-06-09T11:44:14Z
969,727
<p>This <a href="http://groups.google.com/group/django-users/msg/5316bd02d34b7544">django-users post</a> is probably going to help you a lot. It suggests using <a href="http://www.doughellmann.com/projects/virtualenvwrapper/">virtualenvwrapper</a> to wrap virtualenv, to use the <a href="http://www.doughellmann.com/docs/virtualenvwrapper/command%5Fref.html#path-management">add2virtualenv</a> command. Using this, when the environment is active, you can just call:</p> <pre><code>add2virtualenv directory1 directory2 ... </code></pre> <p>to add the directories to your pythonpath for the current environment. </p> <p>It handles autonomously the PATH changes on environment switches. No black magic required. Et voila!</p>
19
2009-06-09T12:15:34Z
[ "python", "virtualenv" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
969,758
<pre><code>def postings(posts): sets = (set(l) for l in posts) return sorted(reduce(set.intersection, sets)) </code></pre> <p>... you could try and take advantage of the fact that the lists are ordered, but since reduce, generator expressions and set are all implemented in C, you'll probably have a hard time doing better than the above with logic implemented in python.</p>
6
2009-06-09T12:22:43Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
969,823
<p>If these are really long (or even infinite) sequences, and you don't want to load everything into a set in advance, you can implement this with a 1-item lookahead on each iterator.</p> <pre><code>EndOfIter = object() # Sentinel value class PeekableIterator(object): def __init__(self, it): self.it = it self._peek = None self.next() # pump iterator to get first value def __iter__(self): return self def next(self): cur = self._peek if cur is EndOfIter: raise StopIteration() try: self._peek = self.it.next() except StopIteration: self._peek = EndOfIter return cur def peek(self): return self._peek def contained_in_all(seqs): if not seqs: return # No items iterators = [PeekableIterator(iter(seq)) for seq in seqs] first, rest = iterators[0], iterators[1:] for item in first: candidates = list(rest) while candidates: if any(c.peek() is EndOfIter for c in candidates): return # Exhausted an iterator candidates = [c for c in candidates if c.peek() &lt; item] for c in candidates: c.next() # Out of loop if first item in remaining iterator are all &gt;= item. if all(it.peek() == item for it in rest): yield item </code></pre> <p>Usage:</p> <pre><code>&gt;&gt;&gt; print list(contained_in_all(postings)) [100, 322] </code></pre>
3
2009-06-09T12:35:22Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
969,967
<p>What about this:</p> <pre><code>import heapq def inalliters(iterators): heap=[(iterator.next(),iterator) for iterator in iterators] heapq.heapify(heap) maximal = max(heap)[0] while True: value,iterator = heapq.heappop(heap) if maximal==value: yield value nextvalue=iterator.next() heapq.heappush(heap,(nextvalue,iterator)) maximal=max(maximal,nextvalue) postings = [iter([1, 100, 142, 322, 12312]), iter([2, 100, 101, 322, 1221]), iter([100, 142, 322, 956, 1222])] print [x for x in inalliters(postings)] </code></pre> <p>I haven't tested it very thoroughly (just ran your example), but I believe the basic idea is sound.</p>
2
2009-06-09T13:09:15Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
969,987
<p>This solution will compute the intersection of your iterators. It works by advancing the iterators one step at a time and looking for the same value in all of them. When found, such values are yielded -- this makes the <code>intersect</code> function a generator itself.</p> <pre><code>import operator def intersect(sequences): """Compute intersection of sequences of increasing integers. &gt;&gt;&gt; list(intersect([[1, 100, 142, 322, 12312], ... [2, 100, 101, 322, 1221], ... [100, 142, 322, 956, 1222]])) [100, 322] """ iterators = [iter(seq) for seq in sequences] last = [iterator.next() for iterator in iterators] indices = range(len(iterators) - 1) while True: # The while loop stops when StopIteration is raised. The # exception will also stop the iteration by our caller. if reduce(operator.and_, [l == last[0] for l in last]): # All iterators contain last[0] yield last[0] last = [iterator.next() for iterator in iterators] # Now go over the iterators once and advance them as # necessary. To stop as soon as the smallest iterator is # exhausted we advance each iterator only once per iteration # in the while loop. for i in indices: if last[i] &lt; last[i+1]: last[i] = iterators[i].next() if last[i] &gt; last[i+1]: last[i+1] = iterators[i+1].next() </code></pre>
6
2009-06-09T13:11:37Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
970,062
<p>I want to show that there's an elegant solution, which <strong>only iterates forward once</strong>. Sorry, I don't know the Python well enough, so I use fictional classes. This one reads <code>input</code>, an array of iterators, and writes to <code>output</code> on-the-fly without ever going back or using any array function!.</p> <pre><code> def intersect (input, output) do: min = input[0] bingo = True for i in input: if (i.cur &lt; min.cur): bingo = False min = i if bingo: output.push(min.cur) while (min.step()) </code></pre>
1
2009-06-09T13:23:02Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
978,816
<pre><code>import heapq, itertools def intersect(*its): for key, values in itertools.groupby(heapq.merge(*its)): if len(list(values)) == len(its): yield key &gt;&gt;&gt; list(intersect(*postings)) [100, 322] </code></pre>
15
2009-06-11T00:49:14Z
[ "python", "join", "code-golf", "iterator", "generator" ]
Joining a set of ordered-integer yielding Python iterators
969,709
<p>Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.</p> <p>After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, <a href="http://code.google.com/p/ghetto-fts/" rel="nofollow">as seen here</a> (though that version is quite old now).</p> <p>My problem is with the <code>search()</code> function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible.</p> <p><b>Example</b>:</p> <pre><code>postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] </code></pre> <p>Should yield:</p> <pre><code>[100, 322] </code></pre> <p>There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, <code>itertools</code> abuse, or any other kind of code golf is more than welcome. :-)</p> <p>It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM.</p> <p>For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!</p>
16
2009-06-09T12:11:00Z
18,188,205
<p>This one runs in <code>O(n*m)</code> where <code>n</code> is the sum of all iterator lengths, and <code>m</code> is the number of lists. It can be made <code>O(n*logm)</code> by using a heap in line 6.</p> <pre><code>def intersection(its): if not its: return vs = [next(it) for it in its] m = max(vs) while True: v, i = min((v,i) for i,v in enumerate(vs)) if v == m: yield m vs[i] = next(its[i]) m = max(m, vs[i]) </code></pre>
0
2013-08-12T13:26:36Z
[ "python", "join", "code-golf", "iterator", "generator" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
969,860
<p>wrap the calling of your python app in a .bat file and put a shortcut to that .bat file in startup. </p>
1
2009-06-09T12:42:34Z
[ "python", "authentication" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
969,863
<p>If you use firefox, just install the <a href="https://addons.mozilla.org/en-US/firefox/addon/115" rel="nofollow">ReloadEvery</a> extension.</p>
1
2009-06-09T12:43:46Z
[ "python", "authentication" ]
automatic keystroke to stay logged in
969,849
<p>I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm not too worried about needing to be logged out.</p> <p>I have written a small python script to ping an ip and then sleep for 9 minutes, and this works dandy, but I would like something that I could include in my startup applications. I don't know if this means I need to compile something into an exe, or can I add this python script to startup apps?</p>
1
2009-06-09T12:40:42Z
969,870
<p>Assuming you use Windows, you can add a bat file containing the python run command in the Startup folder.</p> <p>Example keeploggedin.bat</p> <pre><code>C:\Steve\Projects\Python&gt; python pytest.py </code></pre>
3
2009-06-09T12:45:44Z
[ "python", "authentication" ]